45381 lines
1.7 MiB
Plaintext
45381 lines
1.7 MiB
Plaintext
var __create = Object.create;
|
|
var __defProp = Object.defineProperty;
|
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
var __getProtoOf = Object.getPrototypeOf;
|
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
}) : x)(function(x) {
|
|
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
});
|
|
var __esm = (fn, res, err) => function __init() {
|
|
if (err) throw err[0];
|
|
try {
|
|
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
} catch (e) {
|
|
throw err = [e], e;
|
|
}
|
|
};
|
|
var __commonJS = (cb, mod) => function __require2() {
|
|
try {
|
|
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
} catch (e) {
|
|
throw mod = 0, e;
|
|
}
|
|
};
|
|
var __export = (target, all) => {
|
|
for (var name in all)
|
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
};
|
|
var __copyProps = (to, from, except, desc) => {
|
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
for (let key of __getOwnPropNames(from))
|
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
}
|
|
return to;
|
|
};
|
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
// If the importer is in node compatibility mode or this is not an ESM
|
|
// file that has been converted to a CommonJS file using a Babel-
|
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
mod
|
|
));
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js
|
|
var FifoQueue, EventStream, AssistantMessageEventStream;
|
|
var init_event_stream = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js"() {
|
|
FifoQueue = class {
|
|
incoming = [];
|
|
outgoing = [];
|
|
get length() {
|
|
return this.incoming.length + this.outgoing.length;
|
|
}
|
|
enqueue(value) {
|
|
this.incoming.push(value);
|
|
}
|
|
dequeue() {
|
|
if (this.outgoing.length === 0) {
|
|
while (this.incoming.length > 0) {
|
|
this.outgoing.push(this.incoming.pop());
|
|
}
|
|
}
|
|
return this.outgoing.pop();
|
|
}
|
|
};
|
|
EventStream = class {
|
|
queue = new FifoQueue();
|
|
waiting = new FifoQueue();
|
|
done = false;
|
|
finalResultPromise;
|
|
resolveFinalResult;
|
|
isComplete;
|
|
extractResult;
|
|
constructor(isComplete, extractResult) {
|
|
this.isComplete = isComplete;
|
|
this.extractResult = extractResult;
|
|
this.finalResultPromise = new Promise((resolve) => {
|
|
this.resolveFinalResult = resolve;
|
|
});
|
|
}
|
|
push(event) {
|
|
if (this.done)
|
|
return;
|
|
if (this.isComplete(event)) {
|
|
this.done = true;
|
|
this.resolveFinalResult(this.extractResult(event));
|
|
}
|
|
const waiter = this.waiting.dequeue();
|
|
if (waiter) {
|
|
waiter({ value: event, done: false });
|
|
} else {
|
|
this.queue.enqueue(event);
|
|
}
|
|
}
|
|
end(result) {
|
|
this.done = true;
|
|
if (result !== void 0) {
|
|
this.resolveFinalResult(result);
|
|
}
|
|
while (this.waiting.length > 0) {
|
|
const waiter = this.waiting.dequeue();
|
|
waiter({ value: void 0, done: true });
|
|
}
|
|
}
|
|
async *[Symbol.asyncIterator]() {
|
|
while (true) {
|
|
if (this.queue.length > 0) {
|
|
yield this.queue.dequeue();
|
|
} else if (this.done) {
|
|
return;
|
|
} else {
|
|
const result = await new Promise((resolve) => this.waiting.enqueue(resolve));
|
|
if (result.done)
|
|
return;
|
|
yield result.value;
|
|
}
|
|
}
|
|
}
|
|
result() {
|
|
return this.finalResultPromise;
|
|
}
|
|
};
|
|
AssistantMessageEventStream = class extends EventStream {
|
|
#startedAt = Date.now();
|
|
#startedAtMonotonic = performance.now();
|
|
constructor() {
|
|
super((event) => event.type === "done" || event.type === "error", (event) => {
|
|
if (event.type === "done") {
|
|
return event.message;
|
|
} else if (event.type === "error") {
|
|
return event.error;
|
|
}
|
|
throw new Error("Unexpected event type for final result");
|
|
});
|
|
}
|
|
push(event) {
|
|
if (event.type === "done")
|
|
this.#time(event.message);
|
|
else if (event.type === "error")
|
|
this.#time(event.error);
|
|
super.push(event);
|
|
}
|
|
end(result) {
|
|
if (result !== void 0)
|
|
this.#time(result);
|
|
super.end(result);
|
|
}
|
|
#time(message) {
|
|
if (this.done || message.durationMs !== void 0 || message.timestamp < this.#startedAt)
|
|
return;
|
|
message.durationMs = Math.max(0, Math.round(performance.now() - this.#startedAtMonotonic));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/lazy.js
|
|
function createSetupErrorMessage(model2, error, timestamp2) {
|
|
return {
|
|
role: "assistant",
|
|
content: [],
|
|
api: model2.api,
|
|
provider: model2.provider,
|
|
model: model2.id,
|
|
usage: {
|
|
input: 0,
|
|
output: 0,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
totalTokens: 0,
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
},
|
|
stopReason: "error",
|
|
errorMessage: error instanceof Error ? error.message : String(error),
|
|
timestamp: timestamp2
|
|
};
|
|
}
|
|
function hasResult(source) {
|
|
return typeof source.result === "function";
|
|
}
|
|
async function forwardStream(target, source, observer, observeResult) {
|
|
let result;
|
|
for await (const event of source) {
|
|
target.push(event);
|
|
observer?.onEvent?.(event);
|
|
if (event.type === "done")
|
|
result = event.message;
|
|
else if (event.type === "error")
|
|
result = event.error;
|
|
}
|
|
if (hasResult(source))
|
|
result = await source.result();
|
|
target.end(result);
|
|
observeResult(result);
|
|
}
|
|
function lazyStream(model2, setup, observer) {
|
|
const startedAt = Date.now();
|
|
const outer = new AssistantMessageEventStream();
|
|
let observedResult = false;
|
|
const observeResult = (result) => {
|
|
if (observedResult)
|
|
return;
|
|
observedResult = true;
|
|
observer?.onResult?.(result);
|
|
};
|
|
setup().then((inner) => forwardStream(outer, inner, observer, observeResult)).catch((error) => {
|
|
const message = createSetupErrorMessage(model2, error, startedAt);
|
|
const event = { type: "error", reason: "error", error: message };
|
|
outer.push(event);
|
|
observer?.onEvent?.(event);
|
|
outer.end(message);
|
|
observeResult(message);
|
|
});
|
|
return outer;
|
|
}
|
|
function lazyApi(load, capabilities) {
|
|
const api = {
|
|
stream: (model2, context, options) => lazyStream(model2, async () => (await load()).stream(model2, context, options)),
|
|
streamSimple: (model2, context, options) => lazyStream(model2, async () => (await load()).streamSimple(model2, context, options))
|
|
};
|
|
if (capabilities?.fetchDeferred) {
|
|
api.fetchDeferred = (model2, handle, options) => lazyStream(model2, async () => {
|
|
const implementation = await load();
|
|
if (!implementation.fetchDeferred)
|
|
throw new Error("API does not support deferred responses");
|
|
return implementation.fetchDeferred(model2, handle, options);
|
|
});
|
|
}
|
|
if (capabilities?.cancelDeferred) {
|
|
api.cancelDeferred = async (model2, handle, options) => {
|
|
const implementation = await load();
|
|
if (!implementation.cancelDeferred)
|
|
throw new Error("API cannot cancel deferred responses");
|
|
await implementation.cancelDeferred(model2, handle, options);
|
|
};
|
|
}
|
|
return api;
|
|
}
|
|
var init_lazy = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/lazy.js"() {
|
|
init_event_stream();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/auth/context.js
|
|
function getProcessEnv() {
|
|
const proc = globalThis.process;
|
|
return proc?.env;
|
|
}
|
|
function defaultProviderAuthContext() {
|
|
return {
|
|
async env(name) {
|
|
const value = getProcessEnv()?.[name];
|
|
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
},
|
|
async fileExists(path4) {
|
|
try {
|
|
const fs3 = await importNodeModule("node:fs/promises");
|
|
let resolved = path4;
|
|
if (resolved.startsWith("~")) {
|
|
const os2 = await importNodeModule("node:os");
|
|
resolved = os2.homedir() + resolved.slice(1);
|
|
}
|
|
await fs3.access(resolved);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
};
|
|
}
|
|
var __rewriteRelativeImportExtension, importNodeModule;
|
|
var init_context = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/auth/context.js"() {
|
|
__rewriteRelativeImportExtension = function(path4, preserveJsx) {
|
|
if (typeof path4 === "string" && /^\.\.?\//.test(path4)) {
|
|
return path4.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
|
|
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
|
|
});
|
|
}
|
|
return path4;
|
|
};
|
|
importNodeModule = (specifier) => import(__rewriteRelativeImportExtension(specifier));
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/abort.js
|
|
function abortReason(signal) {
|
|
if (signal.reason !== void 0)
|
|
return signal.reason;
|
|
const error = new Error("The operation was aborted");
|
|
error.name = "AbortError";
|
|
return error;
|
|
}
|
|
function operationSignal(signal) {
|
|
return signal ?? new AbortController().signal;
|
|
}
|
|
function raceWithAbortSignal(operation, signal) {
|
|
if (signal.aborted) {
|
|
void operation.catch(() => {
|
|
});
|
|
return Promise.reject(abortReason(signal));
|
|
}
|
|
return new Promise((resolve, reject) => {
|
|
let settled = false;
|
|
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
const onAbort = () => {
|
|
if (settled)
|
|
return;
|
|
settled = true;
|
|
cleanup();
|
|
reject(abortReason(signal));
|
|
};
|
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
void operation.then((value) => {
|
|
if (settled)
|
|
return;
|
|
settled = true;
|
|
cleanup();
|
|
resolve(value);
|
|
}, (error) => {
|
|
if (settled)
|
|
return;
|
|
settled = true;
|
|
cleanup();
|
|
reject(error);
|
|
});
|
|
if (signal.aborted)
|
|
onAbort();
|
|
});
|
|
}
|
|
var init_abort = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/abort.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js
|
|
var InMemoryCredentialStore;
|
|
var init_credential_store = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/auth/credential-store.js"() {
|
|
init_abort();
|
|
InMemoryCredentialStore = class {
|
|
credentials = /* @__PURE__ */ new Map();
|
|
chains = /* @__PURE__ */ new Map();
|
|
/** Serialize tasks per provider id without releasing the chain before active work settles. */
|
|
enqueue(providerId, task, options) {
|
|
const signal = operationSignal(options?.signal);
|
|
const previous = this.chains.get(providerId) ?? Promise.resolve();
|
|
const queued = (async () => {
|
|
await previous.catch(() => {
|
|
});
|
|
signal.throwIfAborted();
|
|
return task();
|
|
})();
|
|
const tail = queued.catch(() => {
|
|
});
|
|
this.chains.set(providerId, tail);
|
|
void tail.then(() => {
|
|
if (this.chains.get(providerId) === tail)
|
|
this.chains.delete(providerId);
|
|
});
|
|
return raceWithAbortSignal(queued, signal);
|
|
}
|
|
async read(providerId, options) {
|
|
options?.signal?.throwIfAborted();
|
|
return this.credentials.get(providerId);
|
|
}
|
|
async list(options) {
|
|
options?.signal?.throwIfAborted();
|
|
return [...this.credentials].map(([providerId, credential]) => ({ providerId, type: credential.type }));
|
|
}
|
|
modify(providerId, fn, options) {
|
|
return this.enqueue(providerId, async () => {
|
|
const current = this.credentials.get(providerId);
|
|
const next = await fn(current);
|
|
options?.signal?.throwIfAborted();
|
|
if (next !== void 0)
|
|
this.credentials.set(providerId, next);
|
|
return next ?? current;
|
|
}, options);
|
|
}
|
|
delete(providerId, options) {
|
|
return this.enqueue(providerId, async () => {
|
|
this.credentials.delete(providerId);
|
|
}, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js
|
|
function formatThrownValue(value) {
|
|
if (value instanceof Error)
|
|
return value.message || value.name;
|
|
if (typeof value === "string")
|
|
return value;
|
|
return String(value);
|
|
}
|
|
function appendAssistantMessageDiagnostic(message, diagnostic) {
|
|
message.diagnostics = [...message.diagnostics ?? [], diagnostic];
|
|
}
|
|
var init_diagnostics = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/diagnostics.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/models-error.js
|
|
function withCauseDetail(message, cause) {
|
|
if (cause === void 0 || cause === null)
|
|
return message;
|
|
const detail = formatThrownValue(cause).trim();
|
|
if (!detail || message.includes(detail))
|
|
return message;
|
|
return `${message}: ${detail}`;
|
|
}
|
|
var ModelsError;
|
|
var init_models_error = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/models-error.js"() {
|
|
init_diagnostics();
|
|
ModelsError = class extends Error {
|
|
code;
|
|
constructor(code, message, options) {
|
|
super(withCauseDetail(message, options?.cause), options);
|
|
this.name = "ModelsError";
|
|
this.code = code;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/auth/resolve.js
|
|
function resolveProviderAuth(provider2, credentials, authContext, overrides) {
|
|
const signal = operationSignal(overrides?.signal);
|
|
return raceWithAbortSignal(resolveProviderAuthWithSignal(provider2, credentials, authContext, overrides, signal), signal);
|
|
}
|
|
async function resolveProviderAuthWithSignal(provider2, credentials, authContext, overrides, signal) {
|
|
signal.throwIfAborted();
|
|
const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
|
|
if (overrides?.apiKey !== void 0 && provider2.auth.apiKey) {
|
|
return resolveApiKey(requestAuthContext, provider2.auth.apiKey, provider2.id, {
|
|
type: "api_key",
|
|
key: overrides.apiKey,
|
|
env: overrides.env
|
|
}, signal);
|
|
}
|
|
const stored = await readCredential(credentials, provider2.id, signal);
|
|
if (stored) {
|
|
if (stored.type === "oauth" && provider2.auth.oauth) {
|
|
return resolveStoredOAuth(credentials, provider2.id, provider2.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);
|
|
}
|
|
if (stored.type === "api_key" && provider2.auth.apiKey) {
|
|
const credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;
|
|
return resolveApiKey(requestAuthContext, provider2.auth.apiKey, provider2.id, credential, signal);
|
|
}
|
|
return void 0;
|
|
}
|
|
return provider2.auth.apiKey ? resolveApiKey(requestAuthContext, provider2.auth.apiKey, provider2.id, void 0, signal) : void 0;
|
|
}
|
|
function overlayEnvAuthContext(base, env) {
|
|
return {
|
|
env: async (name) => env[name] || await base.env(name),
|
|
fileExists: (path4) => base.fileExists(path4)
|
|
};
|
|
}
|
|
async function refreshStoredOAuthCredential(credentials, providerId, oauth, needsRefresh, signal) {
|
|
let post;
|
|
const lockWait = new AbortController();
|
|
const cancelLockWait = () => lockWait.abort(signal.reason);
|
|
signal.addEventListener("abort", cancelLockWait, { once: true });
|
|
if (signal.aborted)
|
|
cancelLockWait();
|
|
try {
|
|
post = await credentials.modify(providerId, async (current) => {
|
|
signal.removeEventListener("abort", cancelLockWait);
|
|
signal.throwIfAborted();
|
|
if (current?.type !== "oauth")
|
|
return void 0;
|
|
if (!needsRefresh(current))
|
|
return void 0;
|
|
try {
|
|
return await oauth.refresh(current, AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS));
|
|
} catch (error) {
|
|
throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
|
|
}
|
|
}, { signal: lockWait.signal });
|
|
} catch (error) {
|
|
if (error instanceof ModelsError)
|
|
throw error;
|
|
signal.throwIfAborted();
|
|
throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
|
|
} finally {
|
|
signal.removeEventListener("abort", cancelLockWait);
|
|
}
|
|
return post?.type === "oauth" ? post : void 0;
|
|
}
|
|
async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {
|
|
const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);
|
|
const expiresSoon = (credential2) => Date.now() + minimumValidityMs >= credential2.expires;
|
|
let credential = stored;
|
|
if (expiresSoon(credential)) {
|
|
const post = await refreshStoredOAuthCredential(credentials, providerId, oauth, expiresSoon, signal);
|
|
if (!post)
|
|
return void 0;
|
|
credential = post;
|
|
if (minOAuthValidityMs !== void 0 && expiresSoon(credential)) {
|
|
throw new ModelsError("oauth", `OAuth refresh returned a token that expires too soon for ${providerId}`);
|
|
}
|
|
}
|
|
try {
|
|
return { auth: await oauth.toAuth(credential), source: "OAuth" };
|
|
} catch (error) {
|
|
throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
|
|
}
|
|
}
|
|
async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {
|
|
try {
|
|
return await apiKey.resolve({ ctx: authContext, credential, signal });
|
|
} catch (error) {
|
|
throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
|
|
}
|
|
}
|
|
async function readCredential(credentials, providerId, signal) {
|
|
try {
|
|
return await credentials.read(providerId, { signal });
|
|
} catch (error) {
|
|
throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
|
|
}
|
|
}
|
|
var DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, DEFAULT_OAUTH_REFRESH_TIMEOUT_MS;
|
|
var init_resolve = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/auth/resolve.js"() {
|
|
init_abort();
|
|
init_models_error();
|
|
init_models_error();
|
|
DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1e3;
|
|
DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15e3;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/models-store.js
|
|
var InMemoryModelsStore;
|
|
var init_models_store = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/models-store.js"() {
|
|
InMemoryModelsStore = class {
|
|
entries = /* @__PURE__ */ new Map();
|
|
async read(providerId, options) {
|
|
options?.signal?.throwIfAborted();
|
|
const entry = this.entries.get(providerId);
|
|
return entry ? structuredClone(entry) : void 0;
|
|
}
|
|
async write(providerId, entry, options) {
|
|
options?.signal?.throwIfAborted();
|
|
this.entries.set(providerId, structuredClone(entry));
|
|
}
|
|
async delete(providerId, options) {
|
|
options?.signal?.throwIfAborted();
|
|
this.entries.delete(providerId);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-telemetry/dist/metrics.js
|
|
function createTypedMetrics(metrics, schemas) {
|
|
const definitions = /* @__PURE__ */ new Map();
|
|
for (const schema4 of schemas) {
|
|
for (const [name, definition] of Object.entries(schema4.metrics ?? {}))
|
|
definitions.set(name, definition);
|
|
}
|
|
return {
|
|
counter: (name) => metrics.counter(name, definitions.get(name)),
|
|
upDownCounter: (name) => metrics.upDownCounter(name, definitions.get(name)),
|
|
histogram: (name) => metrics.histogram(name, definitions.get(name))
|
|
};
|
|
}
|
|
var init_metrics = __esm({
|
|
"node_modules/@earendil-works/pi-telemetry/dist/metrics.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-telemetry/dist/noop.js
|
|
async function startNoopSpan(_options, callback) {
|
|
return callback(noopTelemetrySpan);
|
|
}
|
|
var noopCounter, noopUpDownCounter, noopHistogram, NOOP_TELEMETRY_METRICS, NOOP_TELEMETRY_PROPAGATION, noopTelemetrySpan, NOOP_TELEMETRY_CONTEXT;
|
|
var init_noop = __esm({
|
|
"node_modules/@earendil-works/pi-telemetry/dist/noop.js"() {
|
|
noopCounter = Object.freeze({ add: () => {
|
|
} });
|
|
noopUpDownCounter = Object.freeze({ add: () => {
|
|
} });
|
|
noopHistogram = Object.freeze({ record: () => {
|
|
} });
|
|
NOOP_TELEMETRY_METRICS = Object.freeze({
|
|
counter: () => noopCounter,
|
|
upDownCounter: () => noopUpDownCounter,
|
|
histogram: () => noopHistogram
|
|
});
|
|
NOOP_TELEMETRY_PROPAGATION = Object.freeze({
|
|
inject: () => void 0,
|
|
extract: () => NOOP_TELEMETRY_CONTEXT
|
|
});
|
|
noopTelemetrySpan = {
|
|
metrics: NOOP_TELEMETRY_METRICS,
|
|
propagation: NOOP_TELEMETRY_PROPAGATION,
|
|
startSpan: startNoopSpan,
|
|
addLink: () => {
|
|
},
|
|
addEvent: () => {
|
|
},
|
|
setAttributes: () => {
|
|
},
|
|
setStatus: () => {
|
|
}
|
|
};
|
|
Object.freeze(noopTelemetrySpan);
|
|
NOOP_TELEMETRY_CONTEXT = noopTelemetrySpan;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-telemetry/dist/memory.js
|
|
var init_memory = __esm({
|
|
"node_modules/@earendil-works/pi-telemetry/dist/memory.js"() {
|
|
init_noop();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-telemetry/dist/index.js
|
|
function defineTelemetrySchema(schema4) {
|
|
return schema4;
|
|
}
|
|
function bindTypedSpanStarter(telemetryContext) {
|
|
const startSpan = (name, attributes, callback) => telemetryContext.startSpan({ name, attributes }, (span) => callback(span, bindTypedSpanStarter(span)));
|
|
return startSpan;
|
|
}
|
|
function createTypedSpanStarter(telemetryContext, _schemas) {
|
|
return bindTypedSpanStarter(telemetryContext);
|
|
}
|
|
var init_dist = __esm({
|
|
"node_modules/@earendil-works/pi-telemetry/dist/index.js"() {
|
|
init_metrics();
|
|
init_noop();
|
|
init_memory();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/text.js
|
|
function contentText(content, separator = "\n") {
|
|
if (typeof content === "string")
|
|
return content;
|
|
return content.filter((block) => block.type === "text").map((block) => block.text).join(separator);
|
|
}
|
|
function getSystemMessageText(message) {
|
|
const parts = [contentText(message.content)];
|
|
for (const text of Object.values(message.sections ?? {})) {
|
|
if (text !== null)
|
|
parts.push(text);
|
|
}
|
|
return parts.filter((part) => part.length > 0).join("\n\n");
|
|
}
|
|
function renderSystemMessageUpdate(message) {
|
|
const parts = [];
|
|
const text = contentText(message.content);
|
|
if (text.length > 0)
|
|
parts.push(text);
|
|
for (const [name, value] of Object.entries(message.sections ?? {})) {
|
|
parts.push(value === null ? `Removed system prompt section "${name}".` : `Updated system prompt section "${name}":
|
|
|
|
${value}`);
|
|
}
|
|
return parts.join("\n\n");
|
|
}
|
|
function ownedSlice(text, start, end = text.length) {
|
|
return `${text.slice(start, end)} `.slice(0, -1);
|
|
}
|
|
var init_text = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/text.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/telemetry.js
|
|
function createInstruments(adapter) {
|
|
const metrics = createTypedMetrics(adapter, [AI_TELEMETRY_SCHEMA]);
|
|
return {
|
|
requestDuration: metrics.histogram("pi.ai.request.duration"),
|
|
firstChunkDuration: metrics.histogram("pi.ai.first_chunk.duration"),
|
|
tokens: metrics.counter("pi.ai.tokens"),
|
|
cost: metrics.counter("pi.ai.cost")
|
|
};
|
|
}
|
|
function observeModelRequest(requestedModel, options, poll) {
|
|
const started = performance.now();
|
|
const attributes = { provider: requestedModel.provider, model: requestedModel.id };
|
|
const adapter = options?.telemetry?.metrics ?? NOOP_TELEMETRY_METRICS;
|
|
let instruments = instrumentCache.get(adapter);
|
|
if (!instruments) {
|
|
instruments = createInstruments(adapter);
|
|
instrumentCache.set(adapter, instruments);
|
|
}
|
|
const { requestDuration, firstChunkDuration, tokens, cost } = instruments;
|
|
let span;
|
|
let finish;
|
|
let first = true;
|
|
const toolChars = /* @__PURE__ */ new Map();
|
|
const finished = new Promise((resolve) => {
|
|
finish = resolve;
|
|
});
|
|
const run = (activeSpan) => {
|
|
span = activeSpan;
|
|
return finished;
|
|
};
|
|
const startAttributes = {
|
|
...attributes,
|
|
api: requestedModel.api,
|
|
...typeof options?.reasoning === "string" ? { reasoning: options.reasoning } : {}
|
|
};
|
|
const start = createTypedSpanStarter(options?.telemetry ?? NOOP_TELEMETRY_CONTEXT, [AI_TELEMETRY_SCHEMA]);
|
|
if (poll)
|
|
void start("pi.ai.poll", startAttributes, run);
|
|
else
|
|
void start("pi.ai.request", startAttributes, run);
|
|
return {
|
|
onEvent(event) {
|
|
if (first) {
|
|
first = false;
|
|
span.addEvent("pi.ai.first_chunk");
|
|
firstChunkDuration.record(performance.now() - started, attributes, span);
|
|
}
|
|
if (event.type === "toolcall_delta") {
|
|
toolChars.set(event.contentIndex, (toolChars.get(event.contentIndex) ?? 0) + event.delta.length);
|
|
} else if (event.type === "text_end" || event.type === "thinking_end") {
|
|
span.addEvent("pi.ai.block", {
|
|
type: event.type === "text_end" ? "text" : "thinking",
|
|
index: event.contentIndex,
|
|
chars: event.content.length
|
|
});
|
|
} else if (event.type === "toolcall_end") {
|
|
const chars = toolChars.get(event.contentIndex) ?? 0;
|
|
toolChars.delete(event.contentIndex);
|
|
span.addEvent("pi.ai.block", {
|
|
type: "tool_call",
|
|
index: event.contentIndex,
|
|
chars,
|
|
tool: event.toolCall.name
|
|
});
|
|
}
|
|
},
|
|
onResult(message) {
|
|
if (message) {
|
|
span.setAttributes({
|
|
stop: message.stopReason,
|
|
"usage.input": message.usage.input,
|
|
"usage.output": message.usage.output,
|
|
"usage.cache_read": message.usage.cacheRead,
|
|
"usage.cache_write": message.usage.cacheWrite,
|
|
"cost.total": message.usage.cost.total,
|
|
"response.id": message.responseId
|
|
});
|
|
if (message.stopReason === "error") {
|
|
span.setStatus({
|
|
status: "error",
|
|
error: { name: "provider_error", message: ownedSlice(message.errorMessage ?? "", 0, 500) }
|
|
});
|
|
}
|
|
requestDuration.record(performance.now() - started, { ...attributes, stop: message.stopReason }, span);
|
|
if (!poll || message.stopReason !== "pending" && message.stopReason !== "deferred") {
|
|
tokens.add(message.usage.input, { ...attributes, kind: "input" });
|
|
tokens.add(message.usage.output, { ...attributes, kind: "output" });
|
|
tokens.add(message.usage.cacheRead, { ...attributes, kind: "cache_read" });
|
|
tokens.add(message.usage.cacheWrite, { ...attributes, kind: "cache_write" });
|
|
cost.add(message.usage.cost.total, attributes);
|
|
}
|
|
}
|
|
finish();
|
|
}
|
|
};
|
|
}
|
|
var provider, model, stop, request, AI_TELEMETRY_SCHEMA, instrumentCache;
|
|
var init_telemetry = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/telemetry.js"() {
|
|
init_dist();
|
|
init_text();
|
|
provider = { type: "string", description: "Provider identifier.", required: true };
|
|
model = { type: "string", description: "Requested model identifier.", required: true };
|
|
stop = {
|
|
type: "string",
|
|
description: "Normalized stop reason.",
|
|
values: ["pending", "stop", "length", "toolUse", "error", "aborted", "deferred"]
|
|
};
|
|
request = {
|
|
description: "One logical model request, including authentication and provider setup.",
|
|
parents: { kind: "any" },
|
|
startAttributes: {
|
|
provider,
|
|
api: { type: "string", description: "API identifier.", required: true },
|
|
model,
|
|
reasoning: { type: "string", description: "Scalar requested reasoning level.", required: false }
|
|
},
|
|
endAttributes: {
|
|
stop,
|
|
"usage.input": { type: "number", description: "Uncached input tokens." },
|
|
"usage.output": { type: "number", description: "Output tokens." },
|
|
"usage.cache_read": { type: "number", description: "Cache-read tokens." },
|
|
"usage.cache_write": { type: "number", description: "Cache-write tokens." },
|
|
"cost.total": { type: "number", description: "Total request cost in USD." },
|
|
"response.id": { type: "string", description: "Provider response identifier.", cardinality: "high" }
|
|
},
|
|
events: {
|
|
"pi.ai.first_chunk": { description: "First normalized stream event delivered.", attributes: {} },
|
|
"pi.ai.block": {
|
|
description: "A completed content block; content is never recorded.",
|
|
attributes: {
|
|
type: {
|
|
type: "string",
|
|
description: "Block kind.",
|
|
values: ["text", "thinking", "tool_call"],
|
|
required: true
|
|
},
|
|
index: { type: "number", description: "Content block index.", required: true },
|
|
chars: { type: "number", description: "UTF-16 character count.", required: true },
|
|
tool: { type: "string", description: "Tool name, for tool-call blocks only.", required: false }
|
|
}
|
|
}
|
|
},
|
|
status: {
|
|
default: "ok",
|
|
errorWhen: "Stop reason is error: provider_error with at most 500 error-message characters. Aborted stays ok."
|
|
}
|
|
};
|
|
AI_TELEMETRY_SCHEMA = defineTelemetrySchema({
|
|
version: 1,
|
|
spans: {
|
|
"pi.ai.request": request,
|
|
"pi.ai.poll": { ...request, description: "One deferred-response poll, not the deferred request's lifetime." }
|
|
},
|
|
metrics: {
|
|
"pi.ai.request.duration": {
|
|
kind: "histogram",
|
|
description: "Logical request or poll duration.",
|
|
unit: "ms",
|
|
attributes: { provider, model, stop: { ...stop, required: true } }
|
|
},
|
|
"pi.ai.first_chunk.duration": {
|
|
kind: "histogram",
|
|
description: "Time to the first normalized stream event.",
|
|
unit: "ms",
|
|
attributes: { provider, model }
|
|
},
|
|
"pi.ai.tokens": {
|
|
kind: "counter",
|
|
description: "Reported model token usage; pending and deferred polls are excluded.",
|
|
unit: "token",
|
|
attributes: {
|
|
provider,
|
|
model,
|
|
kind: {
|
|
type: "string",
|
|
description: "Token usage category.",
|
|
values: ["input", "output", "cache_read", "cache_write"],
|
|
required: true
|
|
}
|
|
}
|
|
},
|
|
"pi.ai.cost": {
|
|
kind: "counter",
|
|
description: "Reported model cost; pending and deferred polls are excluded.",
|
|
unit: "USD",
|
|
attributes: { provider, model }
|
|
}
|
|
}
|
|
});
|
|
instrumentCache = /* @__PURE__ */ new WeakMap();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/version.js
|
|
var PI_AI_VERSION;
|
|
var init_version = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/version.js"() {
|
|
PI_AI_VERSION = "1.5.0";
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/identity.js
|
|
function mergeClientIdentity(...sources) {
|
|
let merged;
|
|
for (const source of sources) {
|
|
if (!source)
|
|
continue;
|
|
merged = { ...merged };
|
|
if (source.userAgent !== void 0)
|
|
merged.userAgent = source.userAgent;
|
|
if (source.attribution !== void 0)
|
|
merged.attribution = source.attribution;
|
|
if (source.version !== void 0)
|
|
merged.version = source.version;
|
|
}
|
|
return merged;
|
|
}
|
|
function getClientVersion(identity) {
|
|
return identity?.version ?? PI_AI_VERSION;
|
|
}
|
|
function runtimeDescription() {
|
|
if (typeof process === "undefined")
|
|
return void 0;
|
|
const versions = process.versions;
|
|
if (versions?.bun)
|
|
return `bun/${versions.bun}`;
|
|
if (versions?.node)
|
|
return `node/${process.version}`;
|
|
return void 0;
|
|
}
|
|
function formatUserAgent(identity) {
|
|
const mode = identity?.userAgent ?? "detailed";
|
|
if (typeof mode === "object")
|
|
return mode.custom;
|
|
if (mode === "short")
|
|
return "pi";
|
|
const product = `pi/${getClientVersion(identity)}`;
|
|
const runtime = runtimeDescription();
|
|
return runtime ? `${product} (${process.platform}; ${runtime}; ${process.arch})` : `${product} (browser)`;
|
|
}
|
|
function matchesHost(baseUrl, expectedHost) {
|
|
try {
|
|
return new URL(baseUrl).hostname === expectedHost;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
function isOpenRouter(target) {
|
|
return target.provider === "openrouter" || target.baseUrl.includes("openrouter.ai");
|
|
}
|
|
function isNvidiaNim(target) {
|
|
return target.provider === "nvidia" || matchesHost(target.baseUrl, NVIDIA_NIM_HOST);
|
|
}
|
|
function isOpenCode(target) {
|
|
return target.provider === "opencode" || target.provider === "opencode-go" || matchesHost(target.baseUrl, OPENCODE_HOST);
|
|
}
|
|
function getAttributionHeaders(target, identity) {
|
|
const attribution = identity?.attribution;
|
|
if (!attribution)
|
|
return {};
|
|
const { name, url, categories } = attribution;
|
|
if (isOpenRouter(target)) {
|
|
return {
|
|
"HTTP-Referer": url,
|
|
"X-OpenRouter-Title": name,
|
|
...categories === void 0 || categories.length === 0 ? {} : { "X-OpenRouter-Categories": categories.join(",") }
|
|
};
|
|
}
|
|
if (isNvidiaNim(target))
|
|
return { "X-BILLING-INVOKE-ORIGIN": name.charAt(0).toUpperCase() + name.slice(1) };
|
|
if (isOpenCode(target))
|
|
return { "x-opencode-client": name };
|
|
return {};
|
|
}
|
|
function getOpenCodeSessionHeaders(target, sessionId) {
|
|
return sessionId && isOpenCode(target) ? { "x-opencode-session": sessionId } : void 0;
|
|
}
|
|
function getIdentityHeaders(target, identity) {
|
|
return { "User-Agent": formatUserAgent(identity), ...getAttributionHeaders(target, identity) };
|
|
}
|
|
var NVIDIA_NIM_HOST, OPENCODE_HOST;
|
|
var init_identity = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/identity.js"() {
|
|
init_version();
|
|
NVIDIA_NIM_HOST = "integrate.api.nvidia.com";
|
|
OPENCODE_HOST = "opencode.ai";
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js
|
|
function getModelType(model2) {
|
|
return model2.type ?? "chat";
|
|
}
|
|
function isModelType(model2, type) {
|
|
return getModelType(model2) === type;
|
|
}
|
|
function assertChatModel(model2) {
|
|
if (!isModelType(model2, "chat")) {
|
|
throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} is not a chat model`);
|
|
}
|
|
}
|
|
function assertImageModel(model2) {
|
|
if (!isModelType(model2, "image")) {
|
|
throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} is not an image model`);
|
|
}
|
|
}
|
|
function assertClassifierModel(model2) {
|
|
if (!isModelType(model2, "classifier")) {
|
|
throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} is not a classifier model`);
|
|
}
|
|
}
|
|
function assertClassifierInputSupported(model2, context) {
|
|
if (context.images?.length && !model2.input.includes("image")) {
|
|
throw new ModelsError("provider", `Model ${model2.provider}/${model2.id} does not accept image input`);
|
|
}
|
|
}
|
|
function imageErrorResult(model2, error, aborted = false) {
|
|
return {
|
|
api: model2.api,
|
|
provider: model2.provider,
|
|
model: model2.id,
|
|
output: [],
|
|
stopReason: aborted ? "aborted" : "error",
|
|
errorMessage: error instanceof Error ? error.message : String(error),
|
|
timestamp: Date.now()
|
|
};
|
|
}
|
|
function classifierErrorResult(model2, error, aborted = false) {
|
|
return {
|
|
api: model2.api,
|
|
provider: model2.provider,
|
|
model: model2.id,
|
|
answers: {},
|
|
stopReason: aborted ? "aborted" : "error",
|
|
errorMessage: error instanceof Error ? error.message : String(error),
|
|
timestamp: Date.now()
|
|
};
|
|
}
|
|
var init_model_operations = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/model-operations.js"() {
|
|
init_models_error();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/transcript.js
|
|
function createInitialSystemMessage(systemPrompt, tools) {
|
|
const hasSystemPrompt = systemPrompt !== void 0 && systemPrompt.length > 0;
|
|
const hasTools = tools !== void 0 && tools.length > 0;
|
|
if (!hasSystemPrompt && !hasTools)
|
|
return void 0;
|
|
return {
|
|
role: "system",
|
|
content: systemPrompt ?? "",
|
|
...hasTools ? { toolsAdded: tools } : {},
|
|
timestamp: 0
|
|
};
|
|
}
|
|
function normalizeContext(context) {
|
|
const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
|
|
const messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;
|
|
return { messages };
|
|
}
|
|
function isSystemMessage(message) {
|
|
return message.role === "system";
|
|
}
|
|
function getInitialSystemMessage(messages) {
|
|
const first = messages[0];
|
|
return first && isSystemMessage(first) ? first : void 0;
|
|
}
|
|
function getCurrentTools(messages) {
|
|
const tools = /* @__PURE__ */ new Map();
|
|
for (const message of messages) {
|
|
if (!isSystemMessage(message))
|
|
continue;
|
|
for (const tool of message.toolsRemoved ?? [])
|
|
tools.delete(tool.name);
|
|
for (const tool of message.toolsAdded ?? [])
|
|
tools.set(tool.name, tool);
|
|
}
|
|
return [...tools.values()];
|
|
}
|
|
function getCurrentSystemMessage(messages) {
|
|
const content = [];
|
|
const sections = /* @__PURE__ */ new Map();
|
|
let timestamp2;
|
|
for (const message of messages) {
|
|
if (!isSystemMessage(message))
|
|
continue;
|
|
timestamp2 ??= message.timestamp;
|
|
const text = contentText(message.content);
|
|
if (text.length > 0)
|
|
content.push(text);
|
|
for (const [name, value] of Object.entries(message.sections ?? {})) {
|
|
if (value === null)
|
|
sections.delete(name);
|
|
else
|
|
sections.set(name, value);
|
|
}
|
|
}
|
|
const tools = getCurrentTools(messages);
|
|
if (timestamp2 === void 0 && tools.length === 0)
|
|
return void 0;
|
|
return {
|
|
role: "system",
|
|
content: content.join("\n\n"),
|
|
...sections.size > 0 ? { sections: Object.fromEntries(sections) } : {},
|
|
...tools.length > 0 ? { toolsAdded: tools } : {},
|
|
timestamp: timestamp2 ?? 0
|
|
};
|
|
}
|
|
function collapseSystemMessages(context) {
|
|
const head = getCurrentSystemMessage(context.messages);
|
|
const messages = context.messages.filter((message) => message.role !== "system");
|
|
return { messages: head ? [head, ...messages] : messages };
|
|
}
|
|
function resolveTranscript(context, supportsMidConvoSystemMessages) {
|
|
return supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);
|
|
}
|
|
function getDeclaredTools(messages) {
|
|
const definitions = /* @__PURE__ */ new Map();
|
|
for (const message of messages) {
|
|
if (!isSystemMessage(message))
|
|
continue;
|
|
for (const tool of message.toolsAdded ?? [])
|
|
definitions.set(tool.name, tool);
|
|
}
|
|
return [...definitions.values()];
|
|
}
|
|
function findLastNonAdditiveToolChange(systemMessages) {
|
|
const declared = /* @__PURE__ */ new Set();
|
|
let last = -1;
|
|
for (let index = 0; index < systemMessages.length; index++) {
|
|
const message = systemMessages[index];
|
|
if ((message.toolsRemoved?.length ?? 0) > 0)
|
|
last = index;
|
|
for (const tool of message.toolsAdded ?? []) {
|
|
if (declared.has(tool.name))
|
|
last = index;
|
|
declared.add(tool.name);
|
|
}
|
|
}
|
|
return last;
|
|
}
|
|
function resolveTranscriptTools(messages, support) {
|
|
const systemMessages = messages.filter(isSystemMessage);
|
|
if (support === "none") {
|
|
return { requestTools: getCurrentTools(systemMessages), foldedSystemMessages: systemMessages.length };
|
|
}
|
|
if (support === "changes")
|
|
return { requestTools: [], foldedSystemMessages: 0 };
|
|
const folded = Math.max(getInitialSystemMessage(messages) ? 1 : 0, findLastNonAdditiveToolChange(systemMessages) + 1);
|
|
return { requestTools: getCurrentTools(systemMessages.slice(0, folded)), foldedSystemMessages: folded };
|
|
}
|
|
var init_transcript = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/transcript.js"() {
|
|
init_text();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/models.js
|
|
function hasKnownModelType(model2) {
|
|
return Object.hasOwn(KNOWN_MODEL_TYPES, getModelType(model2));
|
|
}
|
|
function withKnownModelTypes(entry) {
|
|
return { ...entry, models: entry.models.filter(hasKnownModelType) };
|
|
}
|
|
function mergeHeaders(base, override) {
|
|
if (!base && !override)
|
|
return void 0;
|
|
const merged = { ...base };
|
|
for (const [name, value] of Object.entries(override ?? {})) {
|
|
const lowerName = name.toLowerCase();
|
|
for (const existingName of Object.keys(merged)) {
|
|
if (existingName.toLowerCase() === lowerName)
|
|
delete merged[existingName];
|
|
}
|
|
merged[name] = value;
|
|
}
|
|
return merged;
|
|
}
|
|
function createModels(options) {
|
|
return new ModelsImpl(options);
|
|
}
|
|
function createProvider(input) {
|
|
const single = input.api && typeof input.api.stream === "function" ? input.api : void 0;
|
|
const byApi = single || !input.api ? void 0 : input.api;
|
|
const images = input.images;
|
|
const classifiers = input.classifiers;
|
|
const streams = single ? [single] : Object.values(byApi ?? {}).filter((entry) => entry !== void 0);
|
|
const imageImplementations = Object.values(images ?? {}).filter((entry) => entry !== void 0);
|
|
const classifierImplementations = Object.values(classifiers ?? {}).filter((entry) => entry !== void 0);
|
|
if (streams.length === 0 && imageImplementations.length === 0 && classifierImplementations.length === 0) {
|
|
throw new Error(`Provider ${input.id}: at least one of "api", "images", or "classifiers" is required.`);
|
|
}
|
|
const baselineModels = input.models;
|
|
let dynamicModels = [];
|
|
const fetchModels = input.fetchModels;
|
|
const currentModels = () => {
|
|
const merged = [...baselineModels];
|
|
for (const model2 of dynamicModels) {
|
|
const index = merged.findIndex((entry) => getModelType(entry) === getModelType(model2) && entry.id === model2.id);
|
|
if (index >= 0)
|
|
merged[index] = model2;
|
|
else
|
|
merged.push(model2);
|
|
}
|
|
return merged;
|
|
};
|
|
const apiFor = (model2) => single ?? byApi?.[model2.api];
|
|
const dispatch = (model2, run) => {
|
|
const streams2 = apiFor(model2);
|
|
if (!streams2) {
|
|
return lazyStream(model2, async () => {
|
|
throw new ModelsError("stream", `Provider ${input.id} has no API implementation for "${model2.api}"`);
|
|
});
|
|
}
|
|
return run(streams2);
|
|
};
|
|
const provider2 = {
|
|
id: input.id,
|
|
name: input.name ?? input.id,
|
|
baseUrl: input.baseUrl,
|
|
headers: input.headers,
|
|
auth: input.auth,
|
|
getModels: () => currentModels().filter((model2) => isModelType(model2, "chat")),
|
|
getAllModels: currentModels,
|
|
refreshModels: fetchModels ? async (context) => {
|
|
if (context.stored) {
|
|
const restored = context.stored.models.filter((model2) => model2.provider === input.id).map((model2) => model2);
|
|
if (!await context.publish({
|
|
update: () => {
|
|
dynamicModels = restored;
|
|
}
|
|
})) {
|
|
return;
|
|
}
|
|
}
|
|
if (!context.allowNetwork || context.signal.aborted)
|
|
return;
|
|
const fetched = await fetchModels(context);
|
|
if (context.signal.aborted)
|
|
return;
|
|
const refreshed = fetched.filter(hasKnownModelType);
|
|
await context.publish({
|
|
persist: { models: refreshed, checkedAt: Date.now() },
|
|
update: () => {
|
|
dynamicModels = refreshed;
|
|
}
|
|
});
|
|
} : void 0,
|
|
filterModels: input.filterModels,
|
|
filterAllModels: input.filterAllModels,
|
|
stream: (model2, context, options) => dispatch(model2, (streams2) => streams2.stream(model2, context, options)),
|
|
streamSimple: (model2, context, options) => dispatch(model2, (streams2) => streams2.streamSimple(model2, context, options))
|
|
};
|
|
if (streams.some((entry) => entry.fetchDeferred !== void 0)) {
|
|
provider2.fetchDeferred = (model2, handle, options) => lazyStream(model2, async () => {
|
|
const implementation = apiFor(model2);
|
|
if (!implementation?.fetchDeferred) {
|
|
throw new ModelsError("provider", `Provider ${input.id} does not support deferred responses for "${model2.api}"`);
|
|
}
|
|
return implementation.fetchDeferred(model2, handle, options);
|
|
});
|
|
}
|
|
if (streams.some((entry) => entry.cancelDeferred !== void 0)) {
|
|
provider2.cancelDeferred = async (model2, handle, options) => {
|
|
const implementation = apiFor(model2);
|
|
if (!implementation?.cancelDeferred) {
|
|
throw new ModelsError("provider", `Provider ${input.id} cannot cancel deferred responses for "${model2.api}"`);
|
|
}
|
|
await implementation.cancelDeferred(model2, handle, options);
|
|
};
|
|
}
|
|
if (images && imageImplementations.length > 0) {
|
|
provider2.generateImages = async (model2, context, options) => {
|
|
const implementation = images[model2.api];
|
|
if (!implementation) {
|
|
return imageErrorResult(model2, new ModelsError("provider", `Provider ${input.id} has no image generation implementation for "${model2.api}"`));
|
|
}
|
|
return implementation.generateImages(model2, context, options);
|
|
};
|
|
}
|
|
if (classifiers && classifierImplementations.length > 0) {
|
|
provider2.classify = async (model2, context, options) => {
|
|
const implementation = classifiers[model2.api];
|
|
if (!implementation) {
|
|
return classifierErrorResult(model2, new ModelsError("provider", `Provider ${input.id} has no classifier implementation for "${model2.api}"`));
|
|
}
|
|
return implementation.classify(model2, context, options);
|
|
};
|
|
}
|
|
return provider2;
|
|
}
|
|
function calculateCost(model2, usage) {
|
|
const inputTokens = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
let rates = model2.cost;
|
|
let matchedThreshold = -1;
|
|
for (const tier of model2.cost.tiers ?? []) {
|
|
if (inputTokens > tier.inputTokensAbove && tier.inputTokensAbove > matchedThreshold) {
|
|
rates = tier;
|
|
matchedThreshold = tier.inputTokensAbove;
|
|
}
|
|
}
|
|
const longWrite = usage.cacheWrite1h ?? 0;
|
|
const shortWrite = usage.cacheWrite - longWrite;
|
|
usage.cost.input = rates.input / 1e6 * usage.input;
|
|
usage.cost.output = rates.output / 1e6 * usage.output;
|
|
usage.cost.cacheRead = rates.cacheRead / 1e6 * usage.cacheRead;
|
|
usage.cost.cacheWrite = (rates.cacheWrite * shortWrite + rates.input * 2 * longWrite) / 1e6;
|
|
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
usage.cost.totalFromProvider = false;
|
|
return usage.cost;
|
|
}
|
|
function getSupportedThinkingLevels(model2) {
|
|
if (!model2.reasoning)
|
|
return ["off"];
|
|
return EXTENDED_THINKING_LEVELS.filter((level) => {
|
|
const mapped = model2.thinkingLevelMap?.[level];
|
|
if (mapped === null)
|
|
return false;
|
|
if (level === "xhigh" || level === "max")
|
|
return mapped !== void 0;
|
|
return true;
|
|
});
|
|
}
|
|
function clampThinkingLevel(model2, level) {
|
|
const availableLevels = getSupportedThinkingLevels(model2);
|
|
if (availableLevels.includes(level))
|
|
return level;
|
|
const requestedIndex = EXTENDED_THINKING_LEVELS.indexOf(level);
|
|
if (requestedIndex === -1)
|
|
return availableLevels[0] ?? "off";
|
|
for (let i = requestedIndex; i < EXTENDED_THINKING_LEVELS.length; i++) {
|
|
const candidate = EXTENDED_THINKING_LEVELS[i];
|
|
if (availableLevels.includes(candidate))
|
|
return candidate;
|
|
}
|
|
for (let i = requestedIndex - 1; i >= 0; i--) {
|
|
const candidate = EXTENDED_THINKING_LEVELS[i];
|
|
if (availableLevels.includes(candidate))
|
|
return candidate;
|
|
}
|
|
return availableLevels[0] ?? "off";
|
|
}
|
|
var KNOWN_MODEL_TYPES, ModelsImpl, EXTENDED_THINKING_LEVELS;
|
|
var init_models = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/models.js"() {
|
|
init_lazy();
|
|
init_context();
|
|
init_credential_store();
|
|
init_resolve();
|
|
init_models_store();
|
|
init_telemetry();
|
|
init_abort();
|
|
init_identity();
|
|
init_model_operations();
|
|
init_transcript();
|
|
init_model_operations();
|
|
KNOWN_MODEL_TYPES = { chat: true, image: true, classifier: true };
|
|
ModelsImpl = class {
|
|
providers = /* @__PURE__ */ new Map();
|
|
credentials;
|
|
modelsStore;
|
|
authContext;
|
|
identity;
|
|
refreshGenerations = /* @__PURE__ */ new Map();
|
|
refreshControllers = /* @__PURE__ */ new Map();
|
|
publicationChains = /* @__PURE__ */ new Map();
|
|
constructor(options) {
|
|
this.credentials = options?.credentials ?? new InMemoryCredentialStore();
|
|
this.modelsStore = options?.modelsStore ?? new InMemoryModelsStore();
|
|
this.authContext = options?.authContext ?? defaultProviderAuthContext();
|
|
this.identity = options?.identity;
|
|
}
|
|
setProvider(provider2) {
|
|
this.supersedeProviderRefresh(provider2.id);
|
|
this.providers.set(provider2.id, provider2);
|
|
}
|
|
deleteProvider(id) {
|
|
this.supersedeProviderRefresh(id);
|
|
this.providers.delete(id);
|
|
}
|
|
clearProviders() {
|
|
for (const id of /* @__PURE__ */ new Set([...this.providers.keys(), ...this.refreshControllers.keys()])) {
|
|
this.supersedeProviderRefresh(id);
|
|
}
|
|
this.providers.clear();
|
|
}
|
|
getProviders() {
|
|
return Array.from(this.providers.values());
|
|
}
|
|
getProvider(id) {
|
|
return this.providers.get(id);
|
|
}
|
|
getModels(provider2) {
|
|
if (provider2 !== void 0) {
|
|
const entry = this.providers.get(provider2);
|
|
if (!entry)
|
|
return [];
|
|
try {
|
|
return entry.getModels();
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
const models2 = [];
|
|
for (const entry of this.providers.values()) {
|
|
try {
|
|
models2.push(...entry.getModels());
|
|
} catch {
|
|
}
|
|
}
|
|
return models2;
|
|
}
|
|
getAllModels(provider2) {
|
|
if (provider2 !== void 0) {
|
|
const entry = this.providers.get(provider2);
|
|
if (!entry)
|
|
return [];
|
|
try {
|
|
return entry.getAllModels?.() ?? entry.getModels();
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
const models2 = [];
|
|
for (const entry of this.providers.values()) {
|
|
try {
|
|
models2.push(...entry.getAllModels?.() ?? entry.getModels());
|
|
} catch {
|
|
}
|
|
}
|
|
return models2;
|
|
}
|
|
getModelsOfType(type, provider2) {
|
|
return this.getAllModels(provider2).filter((model2) => isModelType(model2, type));
|
|
}
|
|
getModel(provider2, id) {
|
|
return this.getModels(provider2).find((model2) => model2.id === id);
|
|
}
|
|
getModelOfType(type, provider2, id) {
|
|
return this.getModelsOfType(type, provider2).find((model2) => model2.id === id);
|
|
}
|
|
supersedeProviderRefresh(providerId) {
|
|
const generation = (this.refreshGenerations.get(providerId) ?? 0) + 1;
|
|
this.refreshGenerations.set(providerId, generation);
|
|
const previous = this.refreshControllers.get(providerId);
|
|
if (previous) {
|
|
this.refreshControllers.delete(providerId);
|
|
previous.abort();
|
|
}
|
|
return generation;
|
|
}
|
|
beginProviderRefresh(providerId) {
|
|
const generation = this.supersedeProviderRefresh(providerId);
|
|
const controller = new AbortController();
|
|
this.refreshControllers.set(providerId, controller);
|
|
return { generation, controller };
|
|
}
|
|
publishProviderModels(providerId, generation, signal, publication) {
|
|
const previous = this.publicationChains.get(providerId) ?? Promise.resolve();
|
|
const queued = (async () => {
|
|
await previous.catch(() => {
|
|
});
|
|
if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)
|
|
return false;
|
|
if (publication.persist === null) {
|
|
await this.modelsStore.delete(providerId, { signal });
|
|
} else if (publication.persist !== void 0) {
|
|
await this.modelsStore.write(providerId, structuredClone(publication.persist), { signal });
|
|
}
|
|
if (signal.aborted || this.refreshGenerations.get(providerId) !== generation)
|
|
return false;
|
|
publication.update?.();
|
|
return true;
|
|
})();
|
|
const tail = queued.catch(() => {
|
|
});
|
|
this.publicationChains.set(providerId, tail);
|
|
void tail.then(() => {
|
|
if (this.publicationChains.get(providerId) === tail)
|
|
this.publicationChains.delete(providerId);
|
|
});
|
|
return raceWithAbortSignal(queued, signal);
|
|
}
|
|
async runProviderRefreshPhase(provider2, credential, allowNetwork, force, generation, signal) {
|
|
const stored = await this.modelsStore.read(provider2.id, { signal });
|
|
await provider2.refreshModels({
|
|
credential,
|
|
stored: stored ? withKnownModelTypes(structuredClone(stored)) : void 0,
|
|
publish: (publication) => this.publishProviderModels(provider2.id, generation, signal, publication),
|
|
allowNetwork,
|
|
force: allowNetwork ? force : void 0,
|
|
signal,
|
|
baseUrl: provider2.baseUrl
|
|
});
|
|
}
|
|
async refresh(options = {}) {
|
|
const allowNetwork = options.allowNetwork ?? true;
|
|
const callerSignal = operationSignal(options.signal);
|
|
const errors = /* @__PURE__ */ new Map();
|
|
if (callerSignal.aborted)
|
|
return { aborted: true, errors };
|
|
const selected = options.providers ? new Set(options.providers) : void 0;
|
|
const refreshable = Array.from(this.providers.values()).filter((provider2) => provider2.refreshModels !== void 0 && (!selected || selected.has(provider2.id)));
|
|
const refresh = Promise.all(refreshable.map(async (provider2) => {
|
|
const { generation, controller } = this.beginProviderRefresh(provider2.id);
|
|
const signal = AbortSignal.any([callerSignal, controller.signal]);
|
|
const operation = (async () => {
|
|
let storedCredential;
|
|
let credentialError;
|
|
try {
|
|
storedCredential = await this.readCredential(provider2.id, signal);
|
|
} catch (error) {
|
|
credentialError = error;
|
|
}
|
|
await this.runProviderRefreshPhase(provider2, storedCredential, false, void 0, generation, signal);
|
|
if (credentialError !== void 0)
|
|
throw credentialError;
|
|
if (!allowNetwork || signal.aborted)
|
|
return;
|
|
const credential = await this.resolveRefreshCredential(provider2, storedCredential, signal);
|
|
if (!credential)
|
|
return;
|
|
await this.runProviderRefreshPhase(provider2, credential, true, options.force, generation, signal);
|
|
})();
|
|
try {
|
|
await raceWithAbortSignal(operation, signal);
|
|
} catch (error) {
|
|
if (!signal.aborted) {
|
|
errors.set(provider2.id, error instanceof Error ? error : new ModelsError("model_source", `Model refresh failed for ${provider2.id}`, { cause: error }));
|
|
}
|
|
} finally {
|
|
if (this.refreshControllers.get(provider2.id) === controller) {
|
|
this.refreshControllers.delete(provider2.id);
|
|
}
|
|
}
|
|
}));
|
|
try {
|
|
await raceWithAbortSignal(refresh, callerSignal);
|
|
} catch (error) {
|
|
if (!callerSignal.aborted)
|
|
throw error;
|
|
}
|
|
return { aborted: callerSignal.aborted, errors: new Map(errors) };
|
|
}
|
|
async resolveRefreshCredential(provider2, stored, signal) {
|
|
if (stored?.type === "oauth") {
|
|
const oauth = provider2.auth.oauth;
|
|
if (!oauth)
|
|
return void 0;
|
|
if (Date.now() < stored.expires)
|
|
return stored;
|
|
if (signal.aborted)
|
|
return void 0;
|
|
return refreshStoredOAuthCredential(this.credentials, provider2.id, oauth, (current) => Date.now() >= current.expires, signal);
|
|
}
|
|
const apiKey = provider2.auth.apiKey;
|
|
if (!apiKey)
|
|
return void 0;
|
|
const credential = stored?.type === "api_key" ? stored : void 0;
|
|
const result = await apiKey.resolve({ ctx: this.authContext, credential, signal });
|
|
if (!result)
|
|
return void 0;
|
|
return { type: "api_key", key: result.auth.apiKey, env: result.env };
|
|
}
|
|
async readCredential(providerId, signal) {
|
|
try {
|
|
return await this.credentials.read(providerId, { signal });
|
|
} catch (error) {
|
|
throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
|
|
}
|
|
}
|
|
async checkProviderAuth(provider2, credential, signal) {
|
|
if (credential?.type === "oauth") {
|
|
return provider2.auth.oauth ? { source: "OAuth", type: "oauth" } : void 0;
|
|
}
|
|
const apiKey = provider2.auth.apiKey;
|
|
if (!apiKey)
|
|
return void 0;
|
|
if (apiKey.check) {
|
|
try {
|
|
return await apiKey.check({
|
|
ctx: this.authContext,
|
|
credential: credential?.type === "api_key" ? credential : void 0,
|
|
signal
|
|
});
|
|
} catch (error) {
|
|
throw new ModelsError("auth", `API key auth check failed for provider ${provider2.id}`, { cause: error });
|
|
}
|
|
}
|
|
const resolution = await resolveProviderAuth(provider2, this.credentials, this.authContext, { signal });
|
|
return resolution ? { source: resolution.source, type: "api_key" } : void 0;
|
|
}
|
|
checkAuth(providerId, options) {
|
|
const signal = operationSignal(options?.signal);
|
|
const check = (async () => {
|
|
signal.throwIfAborted();
|
|
const provider2 = this.providers.get(providerId);
|
|
if (!provider2)
|
|
return void 0;
|
|
return this.checkProviderAuth(provider2, await this.readCredential(providerId, signal), signal);
|
|
})();
|
|
return raceWithAbortSignal(check, signal);
|
|
}
|
|
async getAuthenticatedProviders(providerId, signal) {
|
|
signal.throwIfAborted();
|
|
const providers = providerId ? [this.providers.get(providerId)].filter((entry) => entry !== void 0) : this.getProviders();
|
|
const checks = await Promise.all(providers.map(async (provider2) => {
|
|
const credential = await this.readCredential(provider2.id, signal);
|
|
return { provider: provider2, credential, auth: await this.checkProviderAuth(provider2, credential, signal) };
|
|
}));
|
|
return checks.filter((entry) => entry.auth !== void 0);
|
|
}
|
|
getAvailable(providerId, options) {
|
|
const signal = operationSignal(options?.signal);
|
|
const available = (async () => {
|
|
const providers = await this.getAuthenticatedProviders(providerId, signal);
|
|
return providers.flatMap(({ provider: provider2, credential }) => {
|
|
const models2 = provider2.getModels();
|
|
return provider2.filterModels?.(models2, credential) ?? models2;
|
|
});
|
|
})();
|
|
return raceWithAbortSignal(available, signal);
|
|
}
|
|
async getAvailableOfType(type, providerId, options) {
|
|
return (await this.getAllAvailable(providerId, options)).filter((model2) => isModelType(model2, type));
|
|
}
|
|
getAllAvailable(providerId, options) {
|
|
const signal = operationSignal(options?.signal);
|
|
const available = (async () => {
|
|
const providers = await this.getAuthenticatedProviders(providerId, signal);
|
|
return providers.flatMap(({ provider: provider2, credential }) => {
|
|
const models2 = provider2.getAllModels?.() ?? provider2.getModels();
|
|
if (provider2.filterAllModels)
|
|
return provider2.filterAllModels(models2, credential);
|
|
if (!provider2.filterModels)
|
|
return models2;
|
|
const availableChatIds = new Set(provider2.filterModels(provider2.getModels(), credential).map((model2) => model2.id));
|
|
return models2.filter((model2) => !isModelType(model2, "chat") || availableChatIds.has(model2.id));
|
|
});
|
|
})();
|
|
return raceWithAbortSignal(available, signal);
|
|
}
|
|
async getAuth(providerOrModel, overrides) {
|
|
const signal = operationSignal(overrides?.signal);
|
|
const providerId = typeof providerOrModel === "string" ? providerOrModel : providerOrModel.provider;
|
|
const provider2 = this.providers.get(providerId);
|
|
if (!provider2)
|
|
return void 0;
|
|
const result = await resolveProviderAuth(provider2, this.credentials, this.authContext, { ...overrides, signal });
|
|
if (!result || typeof providerOrModel === "string" || !providerOrModel.headers)
|
|
return result;
|
|
return {
|
|
...result,
|
|
auth: {
|
|
...result.auth,
|
|
headers: mergeHeaders(result.auth.headers, providerOrModel.headers)
|
|
}
|
|
};
|
|
}
|
|
async login(providerId, type, interaction, options) {
|
|
const signal = operationSignal(interaction.signal);
|
|
signal.throwIfAborted();
|
|
const provider2 = this.providers.get(providerId);
|
|
if (!provider2)
|
|
throw new ModelsError("provider", `Unknown provider: ${providerId}`);
|
|
const method = type === "oauth" ? provider2.auth.oauth : provider2.auth.apiKey;
|
|
if (!method?.login) {
|
|
throw new ModelsError("auth", `${provider2.name} does not support ${type} login`);
|
|
}
|
|
const loginOperation = method.login({ ...interaction, signal }, options);
|
|
const credential = await raceWithAbortSignal(loginOperation, signal);
|
|
let mutationStarted = false;
|
|
let markMutationStarted;
|
|
const started = new Promise((resolve) => {
|
|
markMutationStarted = resolve;
|
|
});
|
|
const mutation = this.credentials.modify(providerId, async () => {
|
|
mutationStarted = true;
|
|
markMutationStarted?.();
|
|
return credential;
|
|
}, { signal });
|
|
void mutation.catch(() => {
|
|
});
|
|
try {
|
|
await new Promise((resolve, reject) => {
|
|
const onAbort = () => {
|
|
if (!mutationStarted)
|
|
reject(signal.reason);
|
|
};
|
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
void Promise.race([started, mutation]).then(() => {
|
|
signal.removeEventListener("abort", onAbort);
|
|
resolve();
|
|
}, (error) => {
|
|
signal.removeEventListener("abort", onAbort);
|
|
reject(error);
|
|
});
|
|
if (signal.aborted)
|
|
onAbort();
|
|
});
|
|
await mutation;
|
|
} catch (error) {
|
|
signal.throwIfAborted();
|
|
throw new ModelsError("auth", `Credential store modify failed for ${providerId}`, { cause: error });
|
|
}
|
|
return credential;
|
|
}
|
|
async logout(providerId, options) {
|
|
const signal = operationSignal(options?.signal);
|
|
signal.throwIfAborted();
|
|
try {
|
|
await this.credentials.delete(providerId, { signal });
|
|
} catch (error) {
|
|
signal.throwIfAborted();
|
|
throw new ModelsError("auth", `Credential store delete failed for ${providerId}`, { cause: error });
|
|
}
|
|
}
|
|
requireProvider(model2) {
|
|
const provider2 = this.providers.get(model2.provider);
|
|
if (!provider2) {
|
|
throw new ModelsError("provider", `Unknown provider: ${model2.provider}`);
|
|
}
|
|
return provider2;
|
|
}
|
|
requireChatProvider(model2) {
|
|
assertChatModel(model2);
|
|
return this.requireProvider(model2);
|
|
}
|
|
async applyAuth(model2, options) {
|
|
this.requireProvider(model2);
|
|
const resolution = await this.getAuth(model2, {
|
|
apiKey: options?.apiKey,
|
|
env: options?.env,
|
|
signal: options?.signal
|
|
});
|
|
if (!resolution) {
|
|
throw new ModelsError("auth", `Provider is not configured: ${model2.provider}`);
|
|
}
|
|
const auth2 = resolution.auth;
|
|
const apiKey = options?.apiKey ?? auth2.apiKey;
|
|
const requestModel = auth2.baseUrl ? { ...model2, baseUrl: auth2.baseUrl } : model2;
|
|
const sessionId = options && "sessionId" in options && typeof options.sessionId === "string" ? options.sessionId : void 0;
|
|
let headers = mergeHeaders(mergeHeaders(getOpenCodeSessionHeaders(requestModel, sessionId), auth2.headers), options?.headers);
|
|
if (options?.transformHeaders)
|
|
headers = await options.transformHeaders(headers ?? {});
|
|
const env = resolution.env || options?.env ? { ...resolution.env ?? {}, ...options?.env ?? {} } : void 0;
|
|
const identity = mergeClientIdentity(this.identity, options?.identity);
|
|
const { transformHeaders: _transformHeaders, ...providerOptions } = options ?? {};
|
|
const requestOptions = {
|
|
...providerOptions,
|
|
apiKey,
|
|
headers,
|
|
env,
|
|
...identity === void 0 ? {} : { identity }
|
|
};
|
|
return { requestModel, requestOptions };
|
|
}
|
|
stream(model2, context, options) {
|
|
const transcript = normalizeContext(context);
|
|
return lazyStream(model2, async () => {
|
|
const provider2 = this.requireChatProvider(model2);
|
|
const { requestModel, requestOptions } = await this.applyAuth(model2, options);
|
|
return provider2.stream(requestModel, transcript, requestOptions);
|
|
}, observeModelRequest(model2, options, false));
|
|
}
|
|
async complete(model2, context, options) {
|
|
return this.stream(model2, context, options).result();
|
|
}
|
|
streamSimple(model2, context, options) {
|
|
const transcript = normalizeContext(context);
|
|
return lazyStream(model2, async () => {
|
|
const provider2 = this.requireChatProvider(model2);
|
|
const { requestModel, requestOptions } = await this.applyAuth(model2, options);
|
|
return provider2.streamSimple(requestModel, transcript, requestOptions);
|
|
}, observeModelRequest(model2, options, false));
|
|
}
|
|
async completeSimple(model2, context, options) {
|
|
return this.streamSimple(model2, context, options).result();
|
|
}
|
|
streamDeferred(model2, handle, options) {
|
|
return lazyStream(model2, async () => {
|
|
const provider2 = this.requireChatProvider(model2);
|
|
if (!provider2.fetchDeferred) {
|
|
throw new ModelsError("provider", `Provider ${model2.provider} does not support deferred responses`);
|
|
}
|
|
const { requestModel, requestOptions } = await this.applyAuth(model2, options);
|
|
return provider2.fetchDeferred(requestModel, handle, requestOptions);
|
|
}, observeModelRequest(model2, options, true));
|
|
}
|
|
async fetchDeferred(model2, handle, options) {
|
|
return this.streamDeferred(model2, handle, options).result();
|
|
}
|
|
async cancelDeferred(model2, handle, options) {
|
|
const provider2 = this.requireChatProvider(model2);
|
|
if (!provider2.cancelDeferred) {
|
|
throw new ModelsError("provider", `Provider ${model2.provider} does not support deferred responses`);
|
|
}
|
|
const { requestModel, requestOptions } = await this.applyAuth(model2, options);
|
|
await provider2.cancelDeferred(requestModel, handle, requestOptions);
|
|
}
|
|
async generateImages(model2, context, options) {
|
|
try {
|
|
assertImageModel(model2);
|
|
const provider2 = this.requireProvider(model2);
|
|
if (!provider2.generateImages) {
|
|
throw new ModelsError("provider", `Provider ${model2.provider} does not support image generation`);
|
|
}
|
|
const { requestModel, requestOptions } = await this.applyAuth(model2, options);
|
|
return await provider2.generateImages(requestModel, context, requestOptions);
|
|
} catch (error) {
|
|
return imageErrorResult(model2, error, options?.signal?.aborted);
|
|
}
|
|
}
|
|
async classify(model2, context, options) {
|
|
try {
|
|
assertClassifierModel(model2);
|
|
assertClassifierInputSupported(model2, context);
|
|
const provider2 = this.requireProvider(model2);
|
|
if (!provider2.classify) {
|
|
throw new ModelsError("provider", `Provider ${model2.provider} does not support classification`);
|
|
}
|
|
const { requestModel, requestOptions } = await this.applyAuth(model2, options);
|
|
return await provider2.classify(requestModel, context, requestOptions);
|
|
} catch (error) {
|
|
return classifierErrorResult(model2, error, options?.signal?.aborted);
|
|
}
|
|
}
|
|
};
|
|
EXTENDED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/error-body.js
|
|
function normalizeProviderError(error) {
|
|
if (!(error instanceof Error)) {
|
|
return { message: safeJsonStringify(error), messageCarriesBody: false };
|
|
}
|
|
const sdkError = error;
|
|
const status = extractStatus(sdkError);
|
|
const body = extractBody(sdkError);
|
|
const messageCarriesBody = body === void 0 || error.message.includes(body);
|
|
return {
|
|
status,
|
|
body,
|
|
message: error.message,
|
|
messageCarriesBody
|
|
};
|
|
}
|
|
function extractStatus(error) {
|
|
if (typeof error.statusCode === "number")
|
|
return error.statusCode;
|
|
if (typeof error.status === "number")
|
|
return error.status;
|
|
if (typeof error.$metadata?.httpStatusCode === "number")
|
|
return error.$metadata.httpStatusCode;
|
|
if (typeof error.$response?.statusCode === "number")
|
|
return error.$response.statusCode;
|
|
return void 0;
|
|
}
|
|
function extractBody(error) {
|
|
const bodyText = pickBodyText(error);
|
|
if (bodyText === void 0)
|
|
return void 0;
|
|
const trimmed = bodyText.trim();
|
|
if (trimmed.length === 0)
|
|
return void 0;
|
|
return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);
|
|
}
|
|
function pickBodyText(error) {
|
|
if (typeof error.body === "string")
|
|
return error.body;
|
|
if (isPlainNonEmptyObject(error.error))
|
|
return safeJsonStringify(error.error);
|
|
const responseBody = error.$response?.body;
|
|
if (typeof responseBody === "string")
|
|
return responseBody;
|
|
if (isReadableStreamLike(responseBody))
|
|
return void 0;
|
|
if (isPlainNonEmptyObject(responseBody))
|
|
return safeJsonStringify(responseBody);
|
|
return void 0;
|
|
}
|
|
function isReadableStreamLike(value) {
|
|
return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function";
|
|
}
|
|
function isPlainNonEmptyObject(value) {
|
|
if (typeof value !== "object" || value === null)
|
|
return false;
|
|
const proto = Object.getPrototypeOf(value);
|
|
if (proto !== Object.prototype && proto !== null)
|
|
return false;
|
|
return Object.keys(value).length > 0;
|
|
}
|
|
function formatProviderError(norm, prefix) {
|
|
if (norm.messageCarriesBody || norm.status === void 0 || norm.body === void 0) {
|
|
return prefix !== void 0 && norm.status !== void 0 ? `${prefix} (${norm.status}): ${norm.message}` : norm.message;
|
|
}
|
|
return prefix !== void 0 ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;
|
|
}
|
|
function truncateErrorText(text, maxChars) {
|
|
if (text.length <= maxChars)
|
|
return text;
|
|
return `${ownedSlice(text, 0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
|
|
}
|
|
function safeJsonStringify(value) {
|
|
try {
|
|
const serialized = JSON.stringify(value);
|
|
return serialized === void 0 ? String(value) : serialized;
|
|
} catch {
|
|
return String(value);
|
|
}
|
|
}
|
|
var MAX_PROVIDER_ERROR_BODY_CHARS;
|
|
var init_error_body = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/error-body.js"() {
|
|
init_text();
|
|
MAX_PROVIDER_ERROR_BODY_CHARS = 4e3;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/headers.js
|
|
function headersToRecord(headers) {
|
|
const result = {};
|
|
for (const [key, value] of headers.entries()) {
|
|
result[key] = value;
|
|
}
|
|
return result;
|
|
}
|
|
function providerHeadersToRecord(...headerSources) {
|
|
const merged = /* @__PURE__ */ new Map();
|
|
for (const source of headerSources) {
|
|
for (const [name, value] of Object.entries(source ?? {})) {
|
|
const normalizedName = name.toLowerCase();
|
|
merged.delete(normalizedName);
|
|
if (value !== null)
|
|
merged.set(normalizedName, [name, value]);
|
|
}
|
|
}
|
|
return merged.size > 0 ? Object.fromEntries(merged.values()) : void 0;
|
|
}
|
|
var init_headers = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/headers.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js
|
|
function isProviderError(error) {
|
|
if (!(error instanceof Error) || !("status" in error) || !("headers" in error))
|
|
return false;
|
|
return (error.status === void 0 || typeof error.status === "number") && (error.headers === void 0 || error.headers instanceof Headers);
|
|
}
|
|
function isRetryableProviderError(error) {
|
|
const shouldRetry = error.headers?.get("x-should-retry");
|
|
if (shouldRetry === "true")
|
|
return true;
|
|
if (shouldRetry === "false")
|
|
return false;
|
|
if (error.status === void 0)
|
|
return true;
|
|
return error.status === 408 || error.status === 409 || error.status === 429 || typeof error.status === "number" && error.status >= 500;
|
|
}
|
|
function validateServerRetryDelayMs(delayMs, maxRetryDelayMs, providerErrorMessage) {
|
|
const maxDelayMs = maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
|
|
if (maxDelayMs > 0 && delayMs > maxDelayMs) {
|
|
throw new Error(`Server requested ${Math.ceil(delayMs / 1e3)}s retry delay (max: ${Math.ceil(maxDelayMs / 1e3)}s). ${providerErrorMessage}`);
|
|
}
|
|
return delayMs;
|
|
}
|
|
function getRetryDelayMs(error, retryIndex, maxRetryDelayMs) {
|
|
const retryAfterMs = error.headers?.get("retry-after-ms");
|
|
if (retryAfterMs) {
|
|
const value = Number.parseFloat(retryAfterMs);
|
|
if (Number.isFinite(value))
|
|
return validateServerRetryDelayMs(value, maxRetryDelayMs, error.message);
|
|
}
|
|
const retryAfter = error.headers?.get("retry-after");
|
|
if (retryAfter) {
|
|
const seconds = Number.parseFloat(retryAfter);
|
|
const delayMs = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1e3;
|
|
if (Number.isFinite(delayMs))
|
|
return validateServerRetryDelayMs(delayMs, maxRetryDelayMs, error.message);
|
|
}
|
|
const exponentialDelay = Math.min(0.5 * 2 ** retryIndex, 8) * 1e3;
|
|
return exponentialDelay * (1 - Math.random() * 0.25);
|
|
}
|
|
function createAbortError() {
|
|
const error = new Error("Request aborted");
|
|
error.name = "AbortError";
|
|
return error;
|
|
}
|
|
function abortableSleep(ms, signal) {
|
|
return new Promise((resolve, reject) => {
|
|
if (signal?.aborted) {
|
|
reject(createAbortError());
|
|
return;
|
|
}
|
|
const onAbort = () => {
|
|
clearTimeout(timeout);
|
|
reject(createAbortError());
|
|
};
|
|
const timeout = setTimeout(() => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
resolve();
|
|
}, Math.max(0, ms));
|
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
}
|
|
async function retryProviderRequest(request2, options = {}) {
|
|
const maxRetries = options.maxRetries ?? 0;
|
|
let retriesRemaining = maxRetries;
|
|
for (; ; ) {
|
|
try {
|
|
return await request2();
|
|
} catch (error) {
|
|
if (options.signal?.aborted)
|
|
throw createAbortError();
|
|
if (retriesRemaining <= 0 || !isProviderError(error) || !isRetryableProviderError(error))
|
|
throw error;
|
|
if (error.status !== void 0 && options.noRetryStatuses?.includes(error.status))
|
|
throw error;
|
|
const retryIndex = maxRetries - retriesRemaining;
|
|
retriesRemaining--;
|
|
await abortableSleep(getRetryDelayMs(error, retryIndex, options.maxRetryDelayMs), options.signal);
|
|
}
|
|
}
|
|
}
|
|
var DEFAULT_MAX_RETRY_DELAY_MS;
|
|
var init_provider_retry = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/provider-retry.js"() {
|
|
DEFAULT_MAX_RETRY_DELAY_MS = 6e4;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/classifier-shared.js
|
|
function httpError(label, response, body) {
|
|
const error = new Error(`${label} returned ${response.status}`);
|
|
error.status = response.status;
|
|
error.headers = response.headers;
|
|
error.body = body;
|
|
return error;
|
|
}
|
|
function timeoutError(timeoutMs) {
|
|
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
error.name = "TimeoutError";
|
|
error.status = void 0;
|
|
error.headers = void 0;
|
|
error.body = "";
|
|
return error;
|
|
}
|
|
function isRecord(value) {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
function requiredNumber(label, value, field) {
|
|
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
throw new Error(`${label} returned an invalid ${field}`);
|
|
}
|
|
return value;
|
|
}
|
|
function requestHeaders(model2, apiKey, optionsHeaders, identity) {
|
|
return providerHeadersToRecord(getIdentityHeaders(model2, identity), { authorization: `Bearer ${apiKey}`, "content-type": "application/json" }, model2.headers, optionsHeaders) ?? {};
|
|
}
|
|
async function postClassifierRequest(label, url, model2, body, options, noRetryStatuses) {
|
|
if (!options?.apiKey)
|
|
throw new Error(`No API key for provider: ${model2.provider}`);
|
|
const apiKey = options.apiKey;
|
|
let payload = body;
|
|
const transformed = await options.onPayload?.(payload, model2);
|
|
if (transformed !== void 0)
|
|
payload = transformed;
|
|
const requestFetch = options.fetch ?? globalThis.fetch;
|
|
const { response, json } = await retryProviderRequest(async () => {
|
|
const timeoutSignal = options.timeoutMs !== void 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
|
|
const signal = options.signal && timeoutSignal ? AbortSignal.any([options.signal, timeoutSignal]) : options.signal ?? timeoutSignal;
|
|
try {
|
|
const next = await requestFetch(url, {
|
|
method: "POST",
|
|
headers: requestHeaders(model2, apiKey, options.headers, options.identity),
|
|
body: JSON.stringify(payload),
|
|
signal
|
|
});
|
|
if (!next.ok)
|
|
throw httpError(label, next, await next.text());
|
|
return { response: next, json: await next.json() };
|
|
} catch (error) {
|
|
if (timeoutSignal?.aborted && !options.signal?.aborted)
|
|
throw timeoutError(options.timeoutMs);
|
|
throw error;
|
|
}
|
|
}, {
|
|
maxRetries: options.maxRetries ?? 2,
|
|
maxRetryDelayMs: options.maxRetryDelayMs,
|
|
signal: options.signal,
|
|
noRetryStatuses
|
|
});
|
|
await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model2);
|
|
return json;
|
|
}
|
|
function tokenCount(value) {
|
|
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
}
|
|
function parseClassifierUsage(value, model2) {
|
|
if (!isRecord(value) || value.input_tokens === void 0 && value.output_tokens === void 0)
|
|
return void 0;
|
|
const input = tokenCount(value.input_tokens);
|
|
const output = tokenCount(value.output_tokens);
|
|
const usage = {
|
|
input,
|
|
output,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
totalTokens: input + output,
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
};
|
|
calculateCost(model2, usage);
|
|
return usage;
|
|
}
|
|
var init_classifier_shared = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/classifier-shared.js"() {
|
|
init_models();
|
|
init_headers();
|
|
init_identity();
|
|
init_provider_retry();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/openai-decisions.js
|
|
var openai_decisions_exports = {};
|
|
__export(openai_decisions_exports, {
|
|
classify: () => classify
|
|
});
|
|
function predicateInstructions(question) {
|
|
const meanings = [
|
|
question.criteria.true ? `True means: ${question.criteria.true}` : "",
|
|
question.criteria.false ? `False means: ${question.criteria.false}` : ""
|
|
].filter(Boolean);
|
|
return meanings.length > 0 ? `${question.instructions}
|
|
|
|
${meanings.join("\n")}` : question.instructions;
|
|
}
|
|
function wireQuestion(name, question) {
|
|
if (question.type === "choice") {
|
|
return {
|
|
type: "choice",
|
|
name,
|
|
instructions: question.instructions,
|
|
choices: Object.entries(question.criteria).map(([value, description]) => description ? { value, description } : { value })
|
|
};
|
|
}
|
|
if (question.type === "score") {
|
|
return {
|
|
type: "score",
|
|
name,
|
|
instructions: question.instructions,
|
|
levels: question.criteria.map((label) => ({ label }))
|
|
};
|
|
}
|
|
return { type: "predicate", name, instructions: predicateInstructions(question) };
|
|
}
|
|
function wireInput(context) {
|
|
const state2 = JSON.stringify(context.state);
|
|
const images = context.images ?? [];
|
|
if (images.length === 0)
|
|
return state2;
|
|
if (images.length > MAX_IMAGES) {
|
|
throw new Error(`${LABEL} accepts at most ${MAX_IMAGES} images, got ${images.length}`);
|
|
}
|
|
return [
|
|
{
|
|
role: "user",
|
|
content: [
|
|
{ type: "input_text", text: state2 },
|
|
...images.map((image) => ({
|
|
type: "input_image",
|
|
image_url: `data:${image.mimeType};base64,${image.data}`
|
|
}))
|
|
]
|
|
}
|
|
];
|
|
}
|
|
function choiceProbabilities(value, id) {
|
|
if (!Array.isArray(value))
|
|
throw new Error(`${LABEL} returned invalid probabilities for ${id}`);
|
|
return Object.fromEntries(value.map((entry) => {
|
|
if (!isRecord(entry) || typeof entry.value !== "string") {
|
|
throw new Error(`${LABEL} returned invalid probabilities for ${id}`);
|
|
}
|
|
return [entry.value, requiredNumber(LABEL, entry.probability, `probability for ${id}.${entry.value}`)];
|
|
}));
|
|
}
|
|
function parseAnswer(id, question, answer) {
|
|
if (answer.type === "refusal")
|
|
throw new Error(`${LABEL} refused to answer ${id}`);
|
|
if (question.type === "choice") {
|
|
if (answer.type !== "choice" || typeof answer.choice !== "string") {
|
|
throw new Error(`${LABEL} did not return a choice answer for ${id}`);
|
|
}
|
|
return {
|
|
type: "choice",
|
|
choice: answer.choice,
|
|
probabilities: choiceProbabilities(answer.probabilities, id),
|
|
confidence: requiredNumber(LABEL, answer.confidence, `confidence for ${id}`)
|
|
};
|
|
}
|
|
if (question.type === "score") {
|
|
if (answer.type !== "score")
|
|
throw new Error(`${LABEL} did not return a score answer for ${id}`);
|
|
return {
|
|
type: "score",
|
|
score: requiredNumber(LABEL, answer.score, `score for ${id}`),
|
|
confidence: requiredNumber(LABEL, answer.confidence, `confidence for ${id}`)
|
|
};
|
|
}
|
|
if (answer.type !== "predicate")
|
|
throw new Error(`${LABEL} did not return a predicate answer for ${id}`);
|
|
return { type: "bool", probability: requiredNumber(LABEL, answer.probability, `probability for ${id}`) };
|
|
}
|
|
function parseAnswers(value, context) {
|
|
if (!Array.isArray(value))
|
|
throw new Error(`${LABEL} returned an unexpected response`);
|
|
const byName = /* @__PURE__ */ new Map();
|
|
for (const answer of value) {
|
|
if (isRecord(answer) && typeof answer.name === "string")
|
|
byName.set(answer.name, answer);
|
|
}
|
|
return Object.fromEntries(Object.entries(context.questions).map(([id, question]) => {
|
|
const answer = byName.get(id);
|
|
if (!answer)
|
|
throw new Error(`${LABEL} did not return an answer for ${id}`);
|
|
return [id, parseAnswer(id, question, answer)];
|
|
}));
|
|
}
|
|
function errorMessage(error) {
|
|
if (error.status === 504) {
|
|
return `${LABEL} error (504): the request timed out at the gateway. Very large inputs (above roughly 600K tokens) currently exceed its time limit.`;
|
|
}
|
|
return formatProviderError(normalizeProviderError(error), `${LABEL} error`);
|
|
}
|
|
var LABEL, MAX_IMAGES, NO_RETRY_STATUSES, classify;
|
|
var init_openai_decisions = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/openai-decisions.js"() {
|
|
init_error_body();
|
|
init_classifier_shared();
|
|
LABEL = "OpenAI Decisions";
|
|
MAX_IMAGES = 128;
|
|
NO_RETRY_STATUSES = [504];
|
|
classify = async (model2, context, options) => {
|
|
const output = {
|
|
api: model2.api,
|
|
provider: model2.provider,
|
|
model: model2.id,
|
|
answers: {},
|
|
stopReason: "stop",
|
|
timestamp: Date.now()
|
|
};
|
|
try {
|
|
if (model2.api !== "openai-decisions")
|
|
throw new Error(`Unsupported classifier API: ${model2.api}`);
|
|
const body = await postClassifierRequest(LABEL, new URL("decisions", `${model2.baseUrl.replace(/\/+$/u, "")}/`), model2, {
|
|
model: model2.id,
|
|
input: wireInput(context),
|
|
questions: Object.entries(context.questions).map(([id, question]) => wireQuestion(id, question))
|
|
}, options, NO_RETRY_STATUSES);
|
|
if (!isRecord(body))
|
|
throw new Error(`${LABEL} returned an unexpected response`);
|
|
const usage = parseClassifierUsage(body.usage, model2);
|
|
if (usage)
|
|
output.usage = usage;
|
|
output.answers = parseAnswers(body.answers, context);
|
|
return output;
|
|
} catch (error) {
|
|
output.answers = {};
|
|
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
output.errorMessage = errorMessage(error);
|
|
return output;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/tslib.mjs
|
|
function __classPrivateFieldSet(receiver, state2, value, kind, f) {
|
|
if (kind === "m")
|
|
throw new TypeError("Private method is not writable");
|
|
if (kind === "a" && !f)
|
|
throw new TypeError("Private accessor was defined without a setter");
|
|
if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver))
|
|
throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state2.set(receiver, value), value;
|
|
}
|
|
function __classPrivateFieldGet(receiver, state2, kind, f) {
|
|
if (kind === "a" && !f)
|
|
throw new TypeError("Private accessor was defined without a getter");
|
|
if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver))
|
|
throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state2.get(receiver);
|
|
}
|
|
var init_tslib = __esm({
|
|
"node_modules/openai/internal/tslib.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/uuid.mjs
|
|
var uuid4;
|
|
var init_uuid = __esm({
|
|
"node_modules/openai/internal/utils/uuid.mjs"() {
|
|
uuid4 = function() {
|
|
const { crypto: crypto3 } = globalThis;
|
|
if (crypto3?.randomUUID) {
|
|
uuid4 = crypto3.randomUUID.bind(crypto3);
|
|
return crypto3.randomUUID();
|
|
}
|
|
const u8 = new Uint8Array(1);
|
|
const randomByte = crypto3 ? () => crypto3.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
|
|
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/errors.mjs
|
|
function isAbortError(err) {
|
|
return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
|
|
("name" in err && err.name === "AbortError" || // Expo fetch
|
|
"message" in err && String(err.message).includes("FetchRequestCanceledException"));
|
|
}
|
|
var castToError;
|
|
var init_errors = __esm({
|
|
"node_modules/openai/internal/errors.mjs"() {
|
|
castToError = (err) => {
|
|
if (err instanceof Error)
|
|
return err;
|
|
if (typeof err === "object" && err !== null) {
|
|
try {
|
|
if (Object.prototype.toString.call(err) === "[object Error]") {
|
|
const hasCause = "cause" in err;
|
|
const error = new Error(err.message, hasCause ? { cause: err.cause } : {});
|
|
if (err.stack)
|
|
error.stack = err.stack;
|
|
if (hasCause && !Object.prototype.hasOwnProperty.call(error, "cause"))
|
|
error.cause = err.cause;
|
|
if (err.name)
|
|
error.name = err.name;
|
|
return error;
|
|
}
|
|
} catch {
|
|
}
|
|
try {
|
|
return new Error(JSON.stringify(err));
|
|
} catch {
|
|
}
|
|
}
|
|
return new Error(err);
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/core/error.mjs
|
|
var OpenAIError, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, LengthFinishReasonError, ContentFilterFinishReasonError, InvalidWebhookSignatureError, OAuthError, SubjectTokenProviderError;
|
|
var init_error = __esm({
|
|
"node_modules/openai/core/error.mjs"() {
|
|
init_errors();
|
|
OpenAIError = class extends Error {
|
|
};
|
|
APIError = class _APIError extends OpenAIError {
|
|
constructor(status, error, message, headers) {
|
|
super(`${_APIError.makeMessage(status, error, message)}`);
|
|
this.status = status;
|
|
this.headers = headers;
|
|
this.requestID = headers?.get("x-request-id");
|
|
this.error = error;
|
|
const data = error;
|
|
this.code = data?.["code"];
|
|
this.param = data?.["param"];
|
|
this.type = data?.["type"];
|
|
}
|
|
static makeMessage(status, error, message) {
|
|
const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
|
|
if (status && msg) {
|
|
return `${status} ${msg}`;
|
|
}
|
|
if (status) {
|
|
return `${status} status code (no body)`;
|
|
}
|
|
if (msg) {
|
|
return msg;
|
|
}
|
|
return "(no status code or body)";
|
|
}
|
|
static generate(status, errorResponse, message, headers) {
|
|
if (!status || !headers) {
|
|
return new APIConnectionError({ message, cause: castToError(errorResponse) });
|
|
}
|
|
const error = errorResponse?.["error"];
|
|
if (status === 400) {
|
|
return new BadRequestError(status, error, message, headers);
|
|
}
|
|
if (status === 401) {
|
|
return new AuthenticationError(status, error, message, headers);
|
|
}
|
|
if (status === 403) {
|
|
return new PermissionDeniedError(status, error, message, headers);
|
|
}
|
|
if (status === 404) {
|
|
return new NotFoundError(status, error, message, headers);
|
|
}
|
|
if (status === 409) {
|
|
return new ConflictError(status, error, message, headers);
|
|
}
|
|
if (status === 422) {
|
|
return new UnprocessableEntityError(status, error, message, headers);
|
|
}
|
|
if (status === 429) {
|
|
return new RateLimitError(status, error, message, headers);
|
|
}
|
|
if (status >= 500) {
|
|
return new InternalServerError(status, error, message, headers);
|
|
}
|
|
return new _APIError(status, error, message, headers);
|
|
}
|
|
};
|
|
APIUserAbortError = class extends APIError {
|
|
constructor({ message } = {}) {
|
|
super(void 0, void 0, message || "Request was aborted.", void 0);
|
|
}
|
|
};
|
|
APIConnectionError = class extends APIError {
|
|
constructor({ message, cause }) {
|
|
super(void 0, void 0, message || "Connection error.", void 0);
|
|
if (cause)
|
|
this.cause = cause;
|
|
}
|
|
};
|
|
APIConnectionTimeoutError = class extends APIConnectionError {
|
|
constructor({ message } = {}) {
|
|
super({ message: message ?? "Request timed out." });
|
|
}
|
|
};
|
|
BadRequestError = class extends APIError {
|
|
};
|
|
AuthenticationError = class extends APIError {
|
|
};
|
|
PermissionDeniedError = class extends APIError {
|
|
};
|
|
NotFoundError = class extends APIError {
|
|
};
|
|
ConflictError = class extends APIError {
|
|
};
|
|
UnprocessableEntityError = class extends APIError {
|
|
};
|
|
RateLimitError = class extends APIError {
|
|
};
|
|
InternalServerError = class extends APIError {
|
|
};
|
|
LengthFinishReasonError = class extends OpenAIError {
|
|
constructor() {
|
|
super(`Could not parse response content as the length limit was reached`);
|
|
}
|
|
};
|
|
ContentFilterFinishReasonError = class extends OpenAIError {
|
|
constructor() {
|
|
super(`Could not parse response content as the request was rejected by the content filter`);
|
|
}
|
|
};
|
|
InvalidWebhookSignatureError = class extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
}
|
|
};
|
|
OAuthError = class extends APIError {
|
|
constructor(status, error, headers) {
|
|
let finalMessage = "OAuth2 authentication error";
|
|
let error_code = void 0;
|
|
if (error && typeof error === "object") {
|
|
const errorData = error;
|
|
error_code = errorData["error"];
|
|
const description = errorData["error_description"];
|
|
if (description && typeof description === "string") {
|
|
finalMessage = description;
|
|
} else if (error_code) {
|
|
finalMessage = error_code;
|
|
}
|
|
}
|
|
super(status, error, finalMessage, headers);
|
|
this.error_code = error_code;
|
|
}
|
|
};
|
|
SubjectTokenProviderError = class extends OpenAIError {
|
|
constructor(message, provider2, cause) {
|
|
super(message);
|
|
this.provider = provider2;
|
|
this.cause = cause;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/values.mjs
|
|
function maybeObj(x) {
|
|
if (typeof x !== "object") {
|
|
return {};
|
|
}
|
|
return x ?? {};
|
|
}
|
|
function isEmptyObj(obj2) {
|
|
if (!obj2)
|
|
return true;
|
|
for (const _k in obj2)
|
|
return false;
|
|
return true;
|
|
}
|
|
function hasOwn(obj2, key) {
|
|
return Object.prototype.hasOwnProperty.call(obj2, key);
|
|
}
|
|
function isObj(obj2) {
|
|
return obj2 != null && typeof obj2 === "object" && !Array.isArray(obj2);
|
|
}
|
|
var startsWithSchemeRegexp, isAbsoluteURL, isArray, isReadonlyArray, validatePositiveInteger, safeJSON;
|
|
var init_values = __esm({
|
|
"node_modules/openai/internal/utils/values.mjs"() {
|
|
init_error();
|
|
startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
|
isAbsoluteURL = (url) => {
|
|
return startsWithSchemeRegexp.test(url);
|
|
};
|
|
isArray = (val) => (isArray = Array.isArray, isArray(val));
|
|
isReadonlyArray = isArray;
|
|
validatePositiveInteger = (name, n) => {
|
|
if (typeof n !== "number" || !Number.isInteger(n)) {
|
|
throw new OpenAIError(`${name} must be an integer`);
|
|
}
|
|
if (n < 0) {
|
|
throw new OpenAIError(`${name} must be a positive integer`);
|
|
}
|
|
return n;
|
|
};
|
|
safeJSON = (text) => {
|
|
try {
|
|
return JSON.parse(text);
|
|
} catch (err) {
|
|
return void 0;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/sleep.mjs
|
|
var sleep;
|
|
var init_sleep = __esm({
|
|
"node_modules/openai/internal/utils/sleep.mjs"() {
|
|
sleep = (ms, ...signals) => new Promise((resolve, reject) => {
|
|
const activeSignals = [...new Set(signals.filter((signal) => signal != null))];
|
|
let timeout;
|
|
let settled = false;
|
|
const cleanup = () => {
|
|
for (const signal of activeSignals) {
|
|
try {
|
|
signal.removeEventListener("abort", abort);
|
|
} catch {
|
|
}
|
|
}
|
|
};
|
|
const settle = (callback) => {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
if (timeout !== void 0) {
|
|
clearTimeout(timeout);
|
|
timeout = void 0;
|
|
}
|
|
cleanup();
|
|
callback();
|
|
};
|
|
const abort = () => {
|
|
settle(() => reject());
|
|
};
|
|
if (activeSignals.some((signal) => signal.aborted)) {
|
|
abort();
|
|
return;
|
|
}
|
|
timeout = setTimeout(() => {
|
|
settle(resolve);
|
|
}, ms);
|
|
for (const signal of activeSignals) {
|
|
if (settled) {
|
|
break;
|
|
}
|
|
try {
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
} catch (error) {
|
|
settle(() => reject(error));
|
|
}
|
|
}
|
|
if (activeSignals.some((signal) => signal.aborted)) {
|
|
abort();
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/abort.mjs
|
|
function subscribeWeakly(signal, reference, registry2) {
|
|
let subscription = subscriptions.get(signal);
|
|
if (!subscription) {
|
|
const callbacks = /* @__PURE__ */ new Set();
|
|
const abort = () => {
|
|
subscriptions.delete(signal);
|
|
for (const callback of callbacks) {
|
|
registry2.unregister(callback);
|
|
callback.deref()?.();
|
|
}
|
|
callbacks.clear();
|
|
};
|
|
subscription = { callbacks, abort };
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
subscriptions.set(signal, subscription);
|
|
}
|
|
const owner = subscription;
|
|
owner.callbacks.add(reference);
|
|
return () => {
|
|
owner.callbacks.delete(reference);
|
|
registry2.unregister(reference);
|
|
if (owner.callbacks.size === 0) {
|
|
if (subscriptions.get(signal) === owner) {
|
|
subscriptions.delete(signal);
|
|
}
|
|
signal.removeEventListener("abort", owner.abort);
|
|
}
|
|
};
|
|
}
|
|
function releaseOnAbort(signal, callbacks, abort) {
|
|
signal.addEventListener("abort", () => callbacks.deref()?.delete(abort), { once: true });
|
|
}
|
|
function retainRequestAbortCallback(owner, abort, requestSignal) {
|
|
if (typeof weakGlobals.WeakRef === "function" && finalizer && !requestSignal.aborted) {
|
|
let callbacks = callbackOwners.get(owner);
|
|
if (!callbacks) {
|
|
callbacks = /* @__PURE__ */ new Set();
|
|
callbackOwners.set(owner, callbacks);
|
|
}
|
|
callbacks.add(abort);
|
|
releaseOnAbort(requestSignal, new weakGlobals.WeakRef(callbacks), abort);
|
|
}
|
|
}
|
|
function addRequestAbortListener(signal, abort, requestSignal) {
|
|
if (signal.aborted) {
|
|
abort();
|
|
return () => {
|
|
};
|
|
}
|
|
if (typeof weakGlobals.WeakRef !== "function" || !finalizer) {
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
return () => signal.removeEventListener("abort", abort);
|
|
}
|
|
const reference = new weakGlobals.WeakRef(abort);
|
|
const cleanup = subscribeWeakly(signal, reference, finalizer);
|
|
finalizer.register(abort, cleanup, reference);
|
|
retainRequestAbortCallback(requestSignal, abort, requestSignal);
|
|
return cleanup;
|
|
}
|
|
var weakGlobals, finalizer, callbackOwners, subscriptions;
|
|
var init_abort2 = __esm({
|
|
"node_modules/openai/internal/utils/abort.mjs"() {
|
|
weakGlobals = globalThis;
|
|
finalizer = // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Weak references and finalizers are optional host capabilities, so probe them before constructing either.
|
|
typeof weakGlobals.FinalizationRegistry === "function" ? new weakGlobals.FinalizationRegistry((cleanup) => {
|
|
try {
|
|
cleanup();
|
|
} catch {
|
|
}
|
|
}) : void 0;
|
|
callbackOwners = /* @__PURE__ */ new WeakMap();
|
|
subscriptions = /* @__PURE__ */ new WeakMap();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/shims.mjs
|
|
function getDefaultFetch() {
|
|
if (typeof fetch !== "undefined") {
|
|
return fetch;
|
|
}
|
|
throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
|
|
}
|
|
function makeReadableStream(...args) {
|
|
const ReadableStream2 = globalThis.ReadableStream;
|
|
if (typeof ReadableStream2 === "undefined") {
|
|
throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
|
|
}
|
|
return new ReadableStream2(...args);
|
|
}
|
|
function ReadableStreamFrom(iterable) {
|
|
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
return makeReadableStream({
|
|
start() {
|
|
},
|
|
async pull(controller) {
|
|
const { done, value } = await iter.next();
|
|
if (done) {
|
|
controller.close();
|
|
} else {
|
|
controller.enqueue(value);
|
|
}
|
|
},
|
|
async cancel() {
|
|
await iter.return?.();
|
|
}
|
|
});
|
|
}
|
|
function ReadableStreamToAsyncIterable(stream4) {
|
|
if (stream4[Symbol.asyncIterator])
|
|
return stream4;
|
|
const reader = stream4.getReader();
|
|
return {
|
|
async next() {
|
|
try {
|
|
const result = await reader.read();
|
|
if (result?.done)
|
|
reader.releaseLock();
|
|
return result;
|
|
} catch (e) {
|
|
reader.releaseLock();
|
|
throw e;
|
|
}
|
|
},
|
|
async return() {
|
|
const cancelPromise = reader.cancel();
|
|
reader.releaseLock();
|
|
await cancelPromise;
|
|
return { done: true, value: void 0 };
|
|
},
|
|
[Symbol.asyncIterator]() {
|
|
return this;
|
|
}
|
|
};
|
|
}
|
|
async function CancelReadableStream(stream4) {
|
|
if (stream4 === null || typeof stream4 !== "object")
|
|
return;
|
|
if (stream4[Symbol.asyncIterator]) {
|
|
await stream4[Symbol.asyncIterator]().return?.();
|
|
return;
|
|
}
|
|
const reader = stream4.getReader();
|
|
const cancelPromise = reader.cancel();
|
|
reader.releaseLock();
|
|
await cancelPromise;
|
|
}
|
|
var init_shims = __esm({
|
|
"node_modules/openai/internal/shims.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/bytes.mjs
|
|
function encodeUTF8(str2) {
|
|
let encoder3;
|
|
return (encodeUTF8_ ?? (encoder3 = new globalThis.TextEncoder(), encodeUTF8_ = encoder3.encode.bind(encoder3)))(str2);
|
|
}
|
|
function decodeUTF8(bytes2) {
|
|
let decoder3;
|
|
return (decodeUTF8_ ?? (decoder3 = new globalThis.TextDecoder(), decodeUTF8_ = decoder3.decode.bind(decoder3)))(bytes2);
|
|
}
|
|
var encodeUTF8_, decodeUTF8_;
|
|
var init_bytes = __esm({
|
|
"node_modules/openai/internal/utils/bytes.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/decoders/line.mjs
|
|
function findNewlineIndex(buffer, start, end) {
|
|
const newline = 10;
|
|
const carriage = 13;
|
|
for (let i = start; i < end; i++) {
|
|
if (buffer[i] === newline) {
|
|
return { preceding: i, index: i + 1, carriage: false };
|
|
}
|
|
if (buffer[i] === carriage) {
|
|
return { preceding: i, index: i + 1, carriage: true };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
function findDoubleNewlineIndex(buffer) {
|
|
for (let i = 0; i < buffer.length - 1; i++) {
|
|
const firstEndingLength = lineEndingLength(buffer, i);
|
|
if (firstEndingLength > 0) {
|
|
const secondEndingIndex = i + firstEndingLength;
|
|
const secondEndingLength = lineEndingLength(buffer, secondEndingIndex);
|
|
if (secondEndingLength > 0) {
|
|
return secondEndingIndex + secondEndingLength;
|
|
}
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
function lineEndingLength(buffer, index) {
|
|
const newline = 10;
|
|
const carriage = 13;
|
|
if (buffer[index] === newline) {
|
|
return 1;
|
|
}
|
|
if (buffer[index] === carriage) {
|
|
return buffer[index + 1] === newline ? 2 : 1;
|
|
}
|
|
return 0;
|
|
}
|
|
var _LineDecoder_instances, _LineDecoder_buffer, _LineDecoder_start, _LineDecoder_end, _LineDecoder_searchIndex, _LineDecoder_skipLeadingLF, _LineDecoder_append, MAX_RETAINED_BUFFER_BYTES, LineDecoder;
|
|
var init_line = __esm({
|
|
"node_modules/openai/internal/decoders/line.mjs"() {
|
|
init_tslib();
|
|
init_bytes();
|
|
MAX_RETAINED_BUFFER_BYTES = 64 * 1024;
|
|
LineDecoder = class {
|
|
/** Creates a decoder with no buffered bytes or pending newline continuation. */
|
|
constructor() {
|
|
_LineDecoder_instances.add(this);
|
|
_LineDecoder_buffer.set(this, void 0);
|
|
_LineDecoder_start.set(this, void 0);
|
|
_LineDecoder_end.set(this, void 0);
|
|
_LineDecoder_searchIndex.set(this, void 0);
|
|
_LineDecoder_skipLeadingLF.set(this, void 0);
|
|
__classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
}
|
|
/**
|
|
* Appends a text or UTF-8 byte chunk and returns every newly completed line.
|
|
*
|
|
* Incomplete lines remain buffered for the next call. A trailing `\r`
|
|
* completes its line immediately, and a following `\n` is consumed as its
|
|
* continuation. `null` and `undefined` are ignored and do not flush buffered
|
|
* content.
|
|
*/
|
|
decode(chunk) {
|
|
if (chunk == null) {
|
|
return [];
|
|
}
|
|
let binaryChunk;
|
|
if (chunk instanceof ArrayBuffer) {
|
|
binaryChunk = new Uint8Array(chunk);
|
|
} else if (typeof chunk === "string") {
|
|
binaryChunk = encodeUTF8(chunk);
|
|
} else {
|
|
binaryChunk = chunk;
|
|
}
|
|
if (binaryChunk.length === 0) {
|
|
return [];
|
|
}
|
|
if (__classPrivateFieldGet(this, _LineDecoder_skipLeadingLF, "f")) {
|
|
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
if (binaryChunk[0] === 10) {
|
|
binaryChunk = binaryChunk.subarray(1);
|
|
}
|
|
if (binaryChunk.length === 0) {
|
|
return [];
|
|
}
|
|
}
|
|
__classPrivateFieldGet(this, _LineDecoder_instances, "m", _LineDecoder_append).call(this, binaryChunk);
|
|
const lines = [];
|
|
let patternIndex;
|
|
while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"))) != null) {
|
|
const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), patternIndex.preceding));
|
|
lines.push(line);
|
|
__classPrivateFieldSet(this, _LineDecoder_start, patternIndex.index, "f");
|
|
if (patternIndex.carriage) {
|
|
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") < __classPrivateFieldGet(this, _LineDecoder_end, "f") && __classPrivateFieldGet(this, _LineDecoder_buffer, "f")[__classPrivateFieldGet(this, _LineDecoder_start, "f")] === 10) {
|
|
__classPrivateFieldSet(this, _LineDecoder_start, __classPrivateFieldGet(this, _LineDecoder_start, "f") + 1, "f");
|
|
} else if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
|
|
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, true, "f");
|
|
}
|
|
}
|
|
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
|
|
}
|
|
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_end, "f"), "f");
|
|
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
|
|
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
|
|
if (__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) {
|
|
__classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f");
|
|
}
|
|
} else if (lines.length > 0 && __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) {
|
|
const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
|
|
if (length <= MAX_RETAINED_BUFFER_BYTES || __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > length * 4) {
|
|
const capacity = length <= MAX_RETAINED_BUFFER_BYTES ? Math.min(Math.max(length * 2, 256), MAX_RETAINED_BUFFER_BYTES) : length * 2;
|
|
const buffer = new Uint8Array(capacity);
|
|
buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
|
|
__classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_end, length, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_searchIndex, length, "f");
|
|
}
|
|
}
|
|
return lines;
|
|
}
|
|
/** Emits the remaining unterminated line, or returns an empty array when idle. */
|
|
flush() {
|
|
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
|
|
return [];
|
|
}
|
|
return this.decode("\n");
|
|
}
|
|
};
|
|
_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_start = /* @__PURE__ */ new WeakMap(), _LineDecoder_end = /* @__PURE__ */ new WeakMap(), _LineDecoder_searchIndex = /* @__PURE__ */ new WeakMap(), _LineDecoder_skipLeadingLF = /* @__PURE__ */ new WeakMap(), _LineDecoder_instances = /* @__PURE__ */ new WeakSet(), _LineDecoder_append = function _LineDecoder_append2(chunk) {
|
|
if (__classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length > __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
|
|
const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
|
|
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") >= __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length / 2 && length + chunk.length <= __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
|
|
__classPrivateFieldGet(this, _LineDecoder_buffer, "f").copyWithin(0, __classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"));
|
|
} else {
|
|
const capacity = Math.max(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length * 2, length + chunk.length, 256);
|
|
const buffer = new Uint8Array(capacity);
|
|
buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
|
|
__classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
|
|
}
|
|
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_end, length, "f");
|
|
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
}
|
|
__classPrivateFieldGet(this, _LineDecoder_buffer, "f").set(chunk, __classPrivateFieldGet(this, _LineDecoder_end, "f"));
|
|
__classPrivateFieldSet(this, _LineDecoder_end, __classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length, "f");
|
|
};
|
|
LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
|
|
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/log.mjs
|
|
function noop() {
|
|
}
|
|
function makeLogFn(fnLevel, logger, logLevel) {
|
|
if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
|
|
return noop;
|
|
} else {
|
|
return logger[fnLevel].bind(logger);
|
|
}
|
|
}
|
|
function loggerFor(client) {
|
|
const logger = client.logger;
|
|
const logLevel = client.logLevel ?? "off";
|
|
if (!logger) {
|
|
return noopLogger;
|
|
}
|
|
const cachedLogger = cachedLoggers.get(logger);
|
|
if (cachedLogger && cachedLogger[0] === logLevel) {
|
|
return cachedLogger[1];
|
|
}
|
|
const levelLogger = {
|
|
error: makeLogFn("error", logger, logLevel),
|
|
warn: makeLogFn("warn", logger, logLevel),
|
|
info: makeLogFn("info", logger, logLevel),
|
|
debug: makeLogFn("debug", logger, logLevel)
|
|
};
|
|
cachedLoggers.set(logger, [logLevel, levelLogger]);
|
|
return levelLogger;
|
|
}
|
|
function isSensitiveQueryParameter(name) {
|
|
const normalized = name.toLowerCase().replace(/[-_]/gu, "");
|
|
return sensitiveQueryNames.has(normalized) || sensitiveQueryNames.has(normalized.replace(/^x/u, ""));
|
|
}
|
|
function isSensitiveHeader(name) {
|
|
return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu, "-")) || isSensitiveQueryParameter(name);
|
|
}
|
|
function redactURL(value) {
|
|
const url = new URL(value);
|
|
url.username = "";
|
|
url.password = "";
|
|
url.hash = "";
|
|
for (const name of url.searchParams.keys()) {
|
|
if (isSensitiveQueryParameter(name)) {
|
|
url.searchParams.set(name, "***");
|
|
}
|
|
}
|
|
return url.href;
|
|
}
|
|
var levelNumbers, parseLogLevel, noopLogger, cachedLoggers, sensitiveQueryNames, sensitiveHeaderNames, formatRequestDetails;
|
|
var init_log = __esm({
|
|
"node_modules/openai/internal/utils/log.mjs"() {
|
|
init_values();
|
|
levelNumbers = {
|
|
off: 0,
|
|
error: 200,
|
|
warn: 300,
|
|
info: 400,
|
|
debug: 500
|
|
};
|
|
parseLogLevel = (maybeLevel, sourceName, client) => {
|
|
if (!maybeLevel) {
|
|
return void 0;
|
|
}
|
|
if (hasOwn(levelNumbers, maybeLevel)) {
|
|
return maybeLevel;
|
|
}
|
|
loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
|
|
return void 0;
|
|
};
|
|
noopLogger = {
|
|
error: noop,
|
|
warn: noop,
|
|
info: noop,
|
|
debug: noop
|
|
};
|
|
cachedLoggers = /* @__PURE__ */ new WeakMap();
|
|
sensitiveQueryNames = /* @__PURE__ */ new Set([
|
|
"apikey",
|
|
"accesstoken",
|
|
"refreshtoken",
|
|
"sessiontoken",
|
|
"sessionid",
|
|
"idtoken",
|
|
"authtoken",
|
|
"authorization",
|
|
"token",
|
|
"password",
|
|
"clientsecret",
|
|
"signingsecret",
|
|
"xamzsecuritytoken",
|
|
"xamzsignature",
|
|
"xamzcredential"
|
|
]);
|
|
sensitiveHeaderNames = /* @__PURE__ */ new Set([
|
|
"authorization",
|
|
"proxy-authorization",
|
|
"api-key",
|
|
"x-api-key",
|
|
"x-amz-security-token",
|
|
"cookie",
|
|
"set-cookie",
|
|
"x-session-token",
|
|
"x-session-id",
|
|
"x-auth-token",
|
|
"x-id-token"
|
|
]);
|
|
formatRequestDetails = (details) => {
|
|
if (details.options) {
|
|
details.options = { ...details.options };
|
|
delete details.options["headers"];
|
|
if (details.options.path) {
|
|
const path4 = details.options.path;
|
|
const redacted = new URL(redactURL(new URL(path4, "https://redacted.invalid").href));
|
|
details.options.path = redacted.origin === "https://redacted.invalid" ? `${path4.startsWith("/") ? "/" : ""}${redacted.pathname.slice(1)}${redacted.search}` : redacted.href;
|
|
}
|
|
if (details.options.query) {
|
|
details.options.query = Object.fromEntries(Object.entries(details.options.query).map(([name, value]) => [
|
|
name,
|
|
isSensitiveQueryParameter(name) ? "***" : value
|
|
]));
|
|
}
|
|
}
|
|
if (details.url) {
|
|
details.url = redactURL(details.url);
|
|
}
|
|
if (details.headers) {
|
|
details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, isSensitiveHeader(name) ? "***" : value]));
|
|
}
|
|
if ("retryOfRequestLogID" in details) {
|
|
if (details.retryOfRequestLogID) {
|
|
details.retryOf = details.retryOfRequestLogID;
|
|
}
|
|
delete details.retryOfRequestLogID;
|
|
}
|
|
return details;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/core/streaming.mjs
|
|
function isTransportAbortError(error) {
|
|
return !(error instanceof APIError) && isAbortError(error);
|
|
}
|
|
function createStreamTeeQueue() {
|
|
let entries = [];
|
|
let head = 0;
|
|
let canceled = false;
|
|
return {
|
|
get length() {
|
|
return entries.length - head;
|
|
},
|
|
get canceled() {
|
|
return canceled;
|
|
},
|
|
enqueue(value) {
|
|
if (!canceled) {
|
|
entries.push(value);
|
|
}
|
|
},
|
|
dequeue() {
|
|
if (head === entries.length) {
|
|
return void 0;
|
|
}
|
|
const value = entries[head];
|
|
entries[head] = void 0;
|
|
head += 1;
|
|
if (head === entries.length) {
|
|
entries = [];
|
|
head = 0;
|
|
} else if (head >= 1024 && head * 2 >= entries.length) {
|
|
entries = entries.slice(head);
|
|
head = 0;
|
|
}
|
|
return value;
|
|
},
|
|
cancel() {
|
|
canceled = true;
|
|
entries.length = 0;
|
|
head = 0;
|
|
}
|
|
};
|
|
}
|
|
function createAbortableSSESource(body, signal) {
|
|
const reader = typeof body.getReader === "function" ? body.getReader() : void 0;
|
|
const source = reader ? {
|
|
next: () => reader.read(),
|
|
return: () => reader.cancel()
|
|
} : ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator]();
|
|
const ended = { value: void 0, done: true };
|
|
let closed = false;
|
|
let canceled = false;
|
|
let cancellation;
|
|
let interrupt;
|
|
const waitForAbort = () => (
|
|
// oxlint-disable-next-line promise/avoid-new -- AbortSignal callbacks need a portable Promise bridge.
|
|
new Promise((resolve) => {
|
|
interrupt = resolve;
|
|
})
|
|
);
|
|
const cancel = () => {
|
|
if (canceled || closed) {
|
|
return cancellation;
|
|
}
|
|
canceled = true;
|
|
try {
|
|
cancellation = Promise.resolve(source.return?.());
|
|
} catch (error) {
|
|
cancellation = Promise.reject(error);
|
|
}
|
|
cancellation.catch(() => void 0);
|
|
return cancellation;
|
|
};
|
|
const abort = () => {
|
|
queueMicrotask(() => {
|
|
interrupt?.();
|
|
cancel();
|
|
});
|
|
};
|
|
const iterator = {
|
|
async next() {
|
|
if (signal.aborted) {
|
|
return ended;
|
|
}
|
|
const aborted = waitForAbort().then(() => ended);
|
|
try {
|
|
const result = await Promise.race([source.next(), aborted]);
|
|
if (signal.aborted) {
|
|
return ended;
|
|
}
|
|
if (result.done) {
|
|
closed = true;
|
|
return ended;
|
|
}
|
|
return { value: result.value, done: false };
|
|
} catch (error) {
|
|
if (signal.aborted && (isAbortError(error) || error === signal.reason)) {
|
|
return ended;
|
|
}
|
|
throw error;
|
|
} finally {
|
|
interrupt = void 0;
|
|
}
|
|
},
|
|
async return() {
|
|
const pending = cancel();
|
|
if (pending && !signal.aborted) {
|
|
const aborted = waitForAbort();
|
|
try {
|
|
if (!signal.aborted) {
|
|
await Promise.race([pending, aborted]);
|
|
}
|
|
} finally {
|
|
interrupt = void 0;
|
|
}
|
|
}
|
|
return ended;
|
|
},
|
|
[Symbol.asyncIterator]() {
|
|
return this;
|
|
}
|
|
};
|
|
return {
|
|
iterator,
|
|
start() {
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
if (signal.aborted) {
|
|
abort();
|
|
}
|
|
},
|
|
async cleanup(failed) {
|
|
let cleanupError;
|
|
try {
|
|
signal.removeEventListener("abort", abort);
|
|
} catch (error) {
|
|
cleanupError = error;
|
|
}
|
|
if (!closed) {
|
|
const pending = cancel();
|
|
if (pending && !failed && !signal.aborted) {
|
|
try {
|
|
await pending;
|
|
} catch (error) {
|
|
cleanupError ?? (cleanupError = error);
|
|
}
|
|
}
|
|
}
|
|
if (reader) {
|
|
try {
|
|
reader.releaseLock();
|
|
} catch (error) {
|
|
cleanupError ?? (cleanupError = error);
|
|
}
|
|
}
|
|
if (cleanupError !== void 0 && !failed && !signal.aborted) {
|
|
throw cleanupError;
|
|
}
|
|
}
|
|
};
|
|
}
|
|
async function* _iterSSEMessages(response, controller) {
|
|
if (!response.body) {
|
|
controller.abort();
|
|
if (globalThis.navigator !== void 0 && globalThis.navigator.product === "ReactNative") {
|
|
throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
|
|
}
|
|
throw new OpenAIError(`Attempted to iterate over a response with no body`);
|
|
}
|
|
const sseDecoder = new SSEDecoder();
|
|
const lineDecoder = new LineDecoder();
|
|
const { signal } = controller;
|
|
const source = createAbortableSSESource(response.body, signal);
|
|
let failed = false;
|
|
try {
|
|
source.start();
|
|
for await (const sseChunk of iterSSEChunks(source.iterator)) {
|
|
if (signal.aborted) {
|
|
return;
|
|
}
|
|
for (const line of lineDecoder.decode(sseChunk)) {
|
|
if (signal.aborted) {
|
|
return;
|
|
}
|
|
const sse = sseDecoder.decode(line);
|
|
if (sse) {
|
|
yield sse;
|
|
}
|
|
}
|
|
}
|
|
if (signal.aborted) {
|
|
return;
|
|
}
|
|
for (const line of lineDecoder.flush()) {
|
|
if (signal.aborted) {
|
|
return;
|
|
}
|
|
const sse = sseDecoder.decode(line);
|
|
if (sse) {
|
|
yield sse;
|
|
}
|
|
}
|
|
if (signal.aborted) {
|
|
return;
|
|
}
|
|
const pending = sseDecoder.flush();
|
|
if (pending) {
|
|
yield pending;
|
|
}
|
|
} catch (error) {
|
|
failed = true;
|
|
if (!signal.aborted || !isAbortError(error) && error !== signal.reason) {
|
|
throw error;
|
|
}
|
|
} finally {
|
|
await source.cleanup(failed);
|
|
}
|
|
}
|
|
async function* iterSSEChunks(iterator) {
|
|
let data = new Uint8Array();
|
|
let dataStart = 0;
|
|
let dataEnd = 0;
|
|
let searchStartIndex = 0;
|
|
for await (const chunk of iterator) {
|
|
if (chunk == null) {
|
|
continue;
|
|
}
|
|
let binaryChunk;
|
|
if (chunk instanceof ArrayBuffer) {
|
|
binaryChunk = new Uint8Array(chunk);
|
|
} else if (typeof chunk === "string") {
|
|
binaryChunk = encodeUTF8(chunk);
|
|
} else {
|
|
binaryChunk = chunk;
|
|
}
|
|
if (dataEnd + binaryChunk.length > data.length) {
|
|
const bufferedLength = dataEnd - dataStart;
|
|
if (dataStart >= data.length / 2 && bufferedLength + binaryChunk.length <= data.length) {
|
|
data.copyWithin(0, dataStart, dataEnd);
|
|
} else {
|
|
const newData = new Uint8Array(Math.max(data.length * 2, bufferedLength + binaryChunk.length));
|
|
newData.set(data.subarray(dataStart, dataEnd));
|
|
data = newData;
|
|
}
|
|
searchStartIndex -= dataStart;
|
|
dataStart = 0;
|
|
dataEnd = bufferedLength;
|
|
}
|
|
data.set(binaryChunk, dataEnd);
|
|
dataEnd += binaryChunk.length;
|
|
let patternIndex;
|
|
while ((patternIndex = findDoubleNewlineIndex(data.subarray(searchStartIndex, dataEnd))) !== -1) {
|
|
patternIndex += searchStartIndex;
|
|
yield data.slice(dataStart, patternIndex);
|
|
dataStart = patternIndex;
|
|
searchStartIndex = dataStart;
|
|
}
|
|
searchStartIndex = Math.max(dataStart, dataEnd - DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES);
|
|
}
|
|
if (dataEnd > dataStart) {
|
|
yield data.slice(dataStart, dataEnd);
|
|
}
|
|
}
|
|
function partition(str2, delimiter) {
|
|
const index = str2.indexOf(delimiter);
|
|
if (index !== -1) {
|
|
return [str2.slice(0, index), delimiter, str2.slice(index + delimiter.length)];
|
|
}
|
|
return [str2, "", ""];
|
|
}
|
|
var _Stream_instances, _Stream_client, _Stream_isTeeBranch, _Stream_cancelIterator, Stream, DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES, SSEDecoder;
|
|
var init_streaming = __esm({
|
|
"node_modules/openai/core/streaming.mjs"() {
|
|
init_tslib();
|
|
init_error();
|
|
init_shims();
|
|
init_line();
|
|
init_errors();
|
|
init_bytes();
|
|
init_log();
|
|
Stream = class _Stream {
|
|
/** Wraps an asynchronous event iterator and the controller that owns its request. */
|
|
constructor(iterator, controller, client) {
|
|
_Stream_instances.add(this);
|
|
_Stream_client.set(this, void 0);
|
|
_Stream_isTeeBranch.set(this, false);
|
|
this.iterator = iterator;
|
|
this.controller = controller;
|
|
__classPrivateFieldSet(this, _Stream_client, client, "f");
|
|
}
|
|
/**
|
|
* Decodes an SSE response into parsed JSON events.
|
|
*
|
|
* The resulting stream can be consumed only once, ignores events after `[DONE]`, and
|
|
* surfaces API error payloads as `APIError` instances. When
|
|
* `synthesizeEventData` is enabled, each item also includes its SSE event name.
|
|
*/
|
|
static fromSSEResponse(response, controller, client, synthesizeEventData) {
|
|
let consumed = false;
|
|
const logger = client ? loggerFor(client) : console;
|
|
async function* iterator() {
|
|
if (consumed) {
|
|
throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
}
|
|
consumed = true;
|
|
let done = false;
|
|
let receivedCompletionSentinel = false;
|
|
const messages = _iterSSEMessages(response, controller);
|
|
const closeMessages = messages.return.bind(messages);
|
|
messages.return = (value) => {
|
|
if (!receivedCompletionSentinel) {
|
|
controller.abort();
|
|
}
|
|
return closeMessages(value);
|
|
};
|
|
try {
|
|
for await (const sse of messages) {
|
|
if (sse.data === "[DONE]") {
|
|
receivedCompletionSentinel = true;
|
|
break;
|
|
}
|
|
if (sse.event === null || !sse.event.startsWith("thread.")) {
|
|
let data;
|
|
try {
|
|
data = JSON.parse(sse.data);
|
|
} catch {
|
|
logger.error(`Could not parse message into JSON:`);
|
|
logger.error(`From chunk:`);
|
|
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
}
|
|
if (sse.event === "error") {
|
|
throw new APIError(void 0, data?.error ?? data, void 0, response.headers);
|
|
}
|
|
if (data && data.error) {
|
|
throw new APIError(void 0, data.error, void 0, response.headers);
|
|
}
|
|
yield synthesizeEventData ? { event: sse.event, data } : data;
|
|
} else {
|
|
let data;
|
|
try {
|
|
data = JSON.parse(sse.data);
|
|
} catch {
|
|
logger.error(`Could not parse message into JSON:`);
|
|
logger.error(`From chunk:`);
|
|
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
}
|
|
yield { event: sse.event, data };
|
|
}
|
|
}
|
|
done = true;
|
|
} catch (e) {
|
|
if (receivedCompletionSentinel || isTransportAbortError(e) || controller.signal.aborted && e === controller.signal.reason) {
|
|
return;
|
|
}
|
|
throw e;
|
|
} finally {
|
|
if (!done) {
|
|
controller.abort();
|
|
}
|
|
}
|
|
}
|
|
return new _Stream(iterator, controller, client);
|
|
}
|
|
/**
|
|
* Generates a Stream from a newline-separated ReadableStream
|
|
* where each item is a JSON value.
|
|
*/
|
|
static fromReadableStream(readableStream, controller, client) {
|
|
let consumed = false;
|
|
async function* iterLines() {
|
|
const lineDecoder = new LineDecoder();
|
|
const reader = readableStream.getReader();
|
|
let closed = false;
|
|
let cancelPromise;
|
|
const cancel = () => {
|
|
cancelPromise ?? (cancelPromise = reader.cancel());
|
|
cancelPromise.catch(() => void 0);
|
|
};
|
|
controller.signal.addEventListener("abort", cancel, { once: true });
|
|
try {
|
|
if (controller.signal.aborted) {
|
|
cancel();
|
|
return;
|
|
}
|
|
while (true) {
|
|
const { value: chunk, done } = await reader.read();
|
|
if (done) {
|
|
closed = true;
|
|
break;
|
|
}
|
|
if (controller.signal.aborted) {
|
|
return;
|
|
}
|
|
for (const line of lineDecoder.decode(chunk)) {
|
|
if (controller.signal.aborted) {
|
|
return;
|
|
}
|
|
yield line;
|
|
}
|
|
}
|
|
if (controller.signal.aborted) {
|
|
return;
|
|
}
|
|
for (const line of lineDecoder.flush()) {
|
|
if (controller.signal.aborted) {
|
|
return;
|
|
}
|
|
yield line;
|
|
}
|
|
} finally {
|
|
controller.signal.removeEventListener("abort", cancel);
|
|
if (!closed) {
|
|
cancel();
|
|
}
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
async function* iterator() {
|
|
if (consumed) {
|
|
throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
}
|
|
consumed = true;
|
|
let done = false;
|
|
try {
|
|
for await (const line of iterLines()) {
|
|
if (line) {
|
|
let data;
|
|
try {
|
|
data = JSON.parse(line);
|
|
} catch (error) {
|
|
if (error instanceof SyntaxError) {
|
|
throw new SyntaxError("Error reading response: malformed newline-delimited JSON.");
|
|
}
|
|
throw error;
|
|
}
|
|
yield data;
|
|
}
|
|
}
|
|
done = true;
|
|
} catch (e) {
|
|
if (controller.signal.aborted || isAbortError(e)) {
|
|
return;
|
|
}
|
|
throw e;
|
|
} finally {
|
|
if (!done) {
|
|
controller.abort();
|
|
}
|
|
}
|
|
}
|
|
return new _Stream(iterator, controller, client);
|
|
}
|
|
/** Starts consuming this stream; attempting to consume it again throws. */
|
|
[(_Stream_client = /* @__PURE__ */ new WeakMap(), _Stream_isTeeBranch = /* @__PURE__ */ new WeakMap(), _Stream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
return this.iterator();
|
|
}
|
|
/**
|
|
* Splits the stream into two streams which can be
|
|
* independently read from at different speeds.
|
|
* Closing a branch discards its buffered events without stopping its sibling.
|
|
* Future reads on that branch finish immediately; previously issued `next()`
|
|
* promises remain shared with its sibling and may still resolve with events.
|
|
* Closing both branches invokes the source iterator's `return()` when available.
|
|
* For {@link Stream.fromReadableStream}, closing both branches before iteration
|
|
* starts does not cancel the supplied readable; cancel that readable directly.
|
|
*/
|
|
tee() {
|
|
const { controller } = this;
|
|
const left = createStreamTeeQueue();
|
|
const right = createStreamTeeQueue();
|
|
const iterator = this.iterator();
|
|
const teeIterator = (queue) => ({
|
|
next: () => {
|
|
if (queue.canceled) {
|
|
return Promise.resolve({ value: void 0, done: true });
|
|
}
|
|
if (queue.length === 0) {
|
|
const result = iterator.next();
|
|
left.enqueue(result);
|
|
right.enqueue(result);
|
|
}
|
|
return queue.dequeue();
|
|
},
|
|
return: async () => {
|
|
if (!queue.canceled) {
|
|
queue.cancel();
|
|
if (left.canceled && right.canceled) {
|
|
await __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iterator, controller);
|
|
}
|
|
}
|
|
return { value: void 0, done: true };
|
|
}
|
|
});
|
|
const branch = (queue) => {
|
|
const stream4 = new _Stream(() => teeIterator(queue), controller, __classPrivateFieldGet(this, _Stream_client, "f"));
|
|
__classPrivateFieldSet(stream4, _Stream_isTeeBranch, true, "f");
|
|
return stream4;
|
|
};
|
|
return [branch(left), branch(right)];
|
|
}
|
|
/**
|
|
* Converts this stream to a newline-separated ReadableStream of
|
|
* JSON stringified values in the stream
|
|
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
* Canceling a response-backed readable aborts its request. Canceling a tee
|
|
* branch discards its buffered events and leaves sibling consumers running.
|
|
* Read or serialization failures also release the iterator without replacing the original error.
|
|
*/
|
|
toReadableStream() {
|
|
const { controller } = this;
|
|
let iter;
|
|
let cancellation;
|
|
const cancel = () => cancellation ?? (cancellation = __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iter, controller));
|
|
return makeReadableStream({
|
|
start: async () => {
|
|
iter = this[Symbol.asyncIterator]();
|
|
},
|
|
async pull(ctrl) {
|
|
try {
|
|
const { value, done } = await iter.next();
|
|
if (done) {
|
|
return ctrl.close();
|
|
}
|
|
const bytes2 = encodeUTF8(JSON.stringify(value) + "\n");
|
|
ctrl.enqueue(bytes2);
|
|
} catch (err) {
|
|
ctrl.error(err);
|
|
void cancel().catch(() => void 0);
|
|
}
|
|
},
|
|
cancel
|
|
});
|
|
}
|
|
};
|
|
_Stream_cancelIterator = async function _Stream_cancelIterator2(iterator, controller) {
|
|
const returnMethod = iterator.return;
|
|
if (returnMethod) {
|
|
if (!__classPrivateFieldGet(this, _Stream_isTeeBranch, "f")) {
|
|
controller.abort();
|
|
}
|
|
await Reflect.apply(returnMethod, iterator, []);
|
|
}
|
|
};
|
|
DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES = 3;
|
|
SSEDecoder = class {
|
|
constructor() {
|
|
this.event = null;
|
|
this.data = [];
|
|
this.chunks = [];
|
|
}
|
|
decode(line) {
|
|
if (line.endsWith("\r")) {
|
|
line = line.slice(0, -1);
|
|
}
|
|
if (!line) {
|
|
if (!this.event && !this.data.length) {
|
|
return null;
|
|
}
|
|
const sse = {
|
|
event: this.event,
|
|
data: this.data.join("\n"),
|
|
raw: this.chunks
|
|
};
|
|
this.event = null;
|
|
this.data = [];
|
|
this.chunks = [];
|
|
return sse;
|
|
}
|
|
this.chunks.push(line);
|
|
if (line.startsWith(":")) {
|
|
return null;
|
|
}
|
|
const [fieldname, , initialValue] = partition(line, ":");
|
|
let value = initialValue;
|
|
if (value.startsWith(" ")) {
|
|
value = value.slice(1);
|
|
}
|
|
if (fieldname === "event") {
|
|
this.event = value;
|
|
} else if (fieldname === "data") {
|
|
this.data.push(value);
|
|
}
|
|
return null;
|
|
}
|
|
/**
|
|
* Emits a pending event at EOF when the stream omitted the trailing blank
|
|
* line. Returns `null` when no event is in progress so a record that already
|
|
* ended with a blank line is not delivered twice.
|
|
*/
|
|
flush() {
|
|
return this.decode("");
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/parse.mjs
|
|
async function defaultParseResponse(client, props) {
|
|
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
|
|
let jsonBodyLength;
|
|
const body = await (async () => {
|
|
if (props.options.stream) {
|
|
loggerFor(client).debug("response", response.status, response.url, response.headers, response.body);
|
|
if (props.options.__streamClass) {
|
|
return props.options.__streamClass.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
|
|
}
|
|
return Stream.fromSSEResponse(response, props.controller, client, props.options.__synthesizeEventData);
|
|
}
|
|
if (response.status === 204) {
|
|
return null;
|
|
}
|
|
if (props.options.__binaryResponse) {
|
|
return response;
|
|
}
|
|
const contentType = response.headers.get("content-type");
|
|
const mediaType = contentType?.split(";")[0]?.trim().toLowerCase();
|
|
const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
|
|
if (isJSON) {
|
|
const contentLength = response.headers.get("content-length");
|
|
if (contentLength === "0") {
|
|
return void 0;
|
|
}
|
|
const bodyText = await response.text();
|
|
if (!bodyText) {
|
|
return void 0;
|
|
}
|
|
const json = JSON.parse(bodyText);
|
|
jsonBodyLength = bodyText.length;
|
|
return addRequestID(json, response);
|
|
}
|
|
const text = await response.text();
|
|
return text;
|
|
})().catch((error) => {
|
|
throw asAbortError(error, props.controller.signal);
|
|
});
|
|
if (client.logLevel === "debug") {
|
|
loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
body: jsonBodyLength === void 0 ? body : { type: "json", length: jsonBodyLength },
|
|
durationMs: Date.now() - startTime
|
|
}));
|
|
}
|
|
return body;
|
|
}
|
|
function asAbortError(error, signal) {
|
|
if (!signal.aborted || error !== signal.reason || isAbortError(error)) {
|
|
return error;
|
|
}
|
|
const message = "This operation was aborted";
|
|
const DOMExceptionConstructor = globalThis.DOMException;
|
|
return typeof DOMExceptionConstructor === "function" ? new DOMExceptionConstructor(message, "AbortError") : Object.assign(new Error(message), { name: "AbortError" });
|
|
}
|
|
function addRequestID(value, response) {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
return value;
|
|
}
|
|
return Object.defineProperty(value, "_request_id", {
|
|
value: response.headers.get("x-request-id"),
|
|
enumerable: false
|
|
});
|
|
}
|
|
var init_parse = __esm({
|
|
"node_modules/openai/internal/parse.mjs"() {
|
|
init_streaming();
|
|
init_errors();
|
|
init_log();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/version.mjs
|
|
var VERSION;
|
|
var init_version2 = __esm({
|
|
"node_modules/openai/version.mjs"() {
|
|
VERSION = "7.19.0";
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/detect-platform.mjs
|
|
function getDetectedPlatform() {
|
|
if (typeof Deno !== "undefined" && Deno.build != null) {
|
|
return "deno";
|
|
}
|
|
if (typeof EdgeRuntime !== "undefined") {
|
|
return "edge";
|
|
}
|
|
if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
|
|
return "node";
|
|
}
|
|
return "unknown";
|
|
}
|
|
function getBrowserInfo() {
|
|
if (typeof navigator === "undefined" || !navigator) {
|
|
return null;
|
|
}
|
|
const browserPatterns = [
|
|
{ key: "edge", pattern: /\bEdg(?:e|A|iOS)?\b(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
|
|
];
|
|
for (const { key, pattern } of browserPatterns) {
|
|
const match = pattern.exec(navigator.userAgent);
|
|
if (match) {
|
|
const major = match[1] || 0;
|
|
const minor = match[2] || 0;
|
|
const patch = match[3] || 0;
|
|
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
var isRunningInBrowser, getPlatformProperties, normalizeArch, normalizePlatform, _platformHeaders, getPlatformHeaders;
|
|
var init_detect_platform = __esm({
|
|
"node_modules/openai/internal/detect-platform.mjs"() {
|
|
init_version2();
|
|
isRunningInBrowser = () => {
|
|
return (
|
|
// @ts-ignore
|
|
typeof window !== "undefined" && // @ts-ignore
|
|
typeof window.document !== "undefined" && // @ts-ignore
|
|
typeof navigator !== "undefined"
|
|
);
|
|
};
|
|
getPlatformProperties = () => {
|
|
const detectedPlatform = getDetectedPlatform();
|
|
if (detectedPlatform === "deno") {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION,
|
|
"X-Stainless-OS": normalizePlatform(Deno.build.os),
|
|
"X-Stainless-Arch": normalizeArch(Deno.build.arch),
|
|
"X-Stainless-Runtime": "deno",
|
|
"X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
|
|
};
|
|
}
|
|
if (typeof EdgeRuntime !== "undefined") {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION,
|
|
"X-Stainless-OS": "Unknown",
|
|
"X-Stainless-Arch": `other:${EdgeRuntime}`,
|
|
"X-Stainless-Runtime": "edge",
|
|
"X-Stainless-Runtime-Version": globalThis.process?.version ?? "unknown"
|
|
};
|
|
}
|
|
if (detectedPlatform === "node") {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION,
|
|
"X-Stainless-OS": normalizePlatform(globalThis.process.platform ?? "unknown"),
|
|
"X-Stainless-Arch": normalizeArch(globalThis.process.arch ?? "unknown"),
|
|
"X-Stainless-Runtime": "node",
|
|
"X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
|
|
};
|
|
}
|
|
const browserInfo = getBrowserInfo();
|
|
if (browserInfo) {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION,
|
|
"X-Stainless-OS": "Unknown",
|
|
"X-Stainless-Arch": "unknown",
|
|
"X-Stainless-Runtime": `browser:${browserInfo.browser}`,
|
|
"X-Stainless-Runtime-Version": browserInfo.version
|
|
};
|
|
}
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION,
|
|
"X-Stainless-OS": "Unknown",
|
|
"X-Stainless-Arch": "unknown",
|
|
"X-Stainless-Runtime": "unknown",
|
|
"X-Stainless-Runtime-Version": "unknown"
|
|
};
|
|
};
|
|
normalizeArch = (arch) => {
|
|
if (arch === "x32")
|
|
return "x32";
|
|
if (arch === "x86_64" || arch === "x64")
|
|
return "x64";
|
|
if (arch === "arm")
|
|
return "arm";
|
|
if (arch === "aarch64" || arch === "arm64")
|
|
return "arm64";
|
|
if (arch)
|
|
return `other:${arch}`;
|
|
return "unknown";
|
|
};
|
|
normalizePlatform = (platform) => {
|
|
platform = platform.toLowerCase();
|
|
if (platform.includes("ios"))
|
|
return "iOS";
|
|
if (platform === "android")
|
|
return "Android";
|
|
if (platform === "darwin")
|
|
return "MacOS";
|
|
if (platform === "win32")
|
|
return "Windows";
|
|
if (platform === "freebsd")
|
|
return "FreeBSD";
|
|
if (platform === "openbsd")
|
|
return "OpenBSD";
|
|
if (platform === "linux")
|
|
return "Linux";
|
|
if (platform)
|
|
return `Other:${platform}`;
|
|
return "Unknown";
|
|
};
|
|
getPlatformHeaders = () => {
|
|
return _platformHeaders ?? (_platformHeaders = getPlatformProperties());
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/request-options.mjs
|
|
function observeJSONRequestBody(body, observer) {
|
|
let observers = jsonRequestBodyObservers.get(body);
|
|
if (!observers) {
|
|
observers = /* @__PURE__ */ new Set();
|
|
jsonRequestBodyObservers.set(body, observers);
|
|
}
|
|
observers.add(observer);
|
|
return () => {
|
|
const active = jsonRequestBodyObservers.get(body);
|
|
if (!active) {
|
|
return;
|
|
}
|
|
active.delete(observer);
|
|
if (active.size === 0) {
|
|
jsonRequestBodyObservers.delete(body);
|
|
}
|
|
};
|
|
}
|
|
var jsonRequestBodyObservers, FallbackEncoder;
|
|
var init_request_options = __esm({
|
|
"node_modules/openai/internal/request-options.mjs"() {
|
|
jsonRequestBodyObservers = /* @__PURE__ */ new WeakMap();
|
|
FallbackEncoder = ({ headers, body }) => {
|
|
const observers = typeof body === "object" && body !== null ? jsonRequestBodyObservers.get(body) : void 0;
|
|
let encoded;
|
|
if (!observers || observers.size === 0) {
|
|
encoded = JSON.stringify(body);
|
|
} else {
|
|
const active = [...observers];
|
|
encoded = JSON.stringify(body, function(key, value) {
|
|
let observed = value;
|
|
for (const observer of active) {
|
|
const replacement = observer.value(this, key, observed);
|
|
if (replacement !== void 0) {
|
|
observed = replacement;
|
|
}
|
|
}
|
|
return observed;
|
|
});
|
|
for (const observer of active) {
|
|
observer.complete();
|
|
}
|
|
}
|
|
return {
|
|
bodyHeaders: {
|
|
"content-type": "application/json"
|
|
},
|
|
body: encoded
|
|
};
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/qs/formats.mjs
|
|
var default_format, default_formatter, formatters, RFC1738;
|
|
var init_formats = __esm({
|
|
"node_modules/openai/internal/qs/formats.mjs"() {
|
|
default_format = "RFC3986";
|
|
default_formatter = String;
|
|
formatters = {
|
|
RFC1738: (v) => String(v).replace(/%20/g, "+"),
|
|
RFC3986: default_formatter
|
|
};
|
|
RFC1738 = "RFC1738";
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/qs/utils.mjs
|
|
function is_buffer(obj2) {
|
|
if (!obj2 || typeof obj2 !== "object") {
|
|
return false;
|
|
}
|
|
return !!(obj2.constructor && obj2.constructor.isBuffer && obj2.constructor.isBuffer(obj2));
|
|
}
|
|
function maybe_map(val, fn) {
|
|
if (isArray(val)) {
|
|
const mapped = [];
|
|
for (const item of val) {
|
|
mapped.push(fn(item));
|
|
}
|
|
return mapped;
|
|
}
|
|
return fn(val);
|
|
}
|
|
var cachedHas, has, hex_table, limit, encode;
|
|
var init_utils = __esm({
|
|
"node_modules/openai/internal/qs/utils.mjs"() {
|
|
init_formats();
|
|
init_values();
|
|
has = (obj2, key) => {
|
|
const resolvedHas = cachedHas ?? Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty);
|
|
cachedHas = resolvedHas;
|
|
return resolvedHas(obj2, key);
|
|
};
|
|
hex_table = /* @__PURE__ */ (() => {
|
|
const array = [];
|
|
for (let i = 0; i < 256; ++i) {
|
|
array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
|
|
}
|
|
return array;
|
|
})();
|
|
limit = 1024;
|
|
encode = (str2, _defaultEncoder, charset, _kind, format) => {
|
|
if (str2.length === 0) {
|
|
return str2;
|
|
}
|
|
let string2 = str2;
|
|
if (typeof str2 === "symbol") {
|
|
string2 = Symbol.prototype.toString.call(str2);
|
|
} else if (typeof str2 !== "string") {
|
|
string2 = String(str2);
|
|
}
|
|
if (charset === "iso-8859-1") {
|
|
return escape(string2).replace(/%u[0-9a-f]{4}/gi, ($0) => "%26%23" + Number.parseInt($0.slice(2), 16) + "%3B");
|
|
}
|
|
let out = "";
|
|
for (let j = 0; j < string2.length; ) {
|
|
let segmentEnd = Math.min((Math.floor(j / limit) + 1) * limit, string2.length);
|
|
if (segmentEnd < string2.length && string2.codePointAt(segmentEnd - 1) > 65535) {
|
|
segmentEnd += 1;
|
|
}
|
|
const segment = string2.length >= limit ? string2.slice(j, segmentEnd) : string2;
|
|
const arr2 = [];
|
|
for (let i = 0; i < segment.length; ++i) {
|
|
let c = segment.charCodeAt(i);
|
|
if (c === 45 || // -
|
|
c === 46 || // .
|
|
c === 95 || // _
|
|
c === 126 || // ~
|
|
c >= 48 && c <= 57 || // 0-9
|
|
c >= 65 && c <= 90 || // a-z
|
|
c >= 97 && c <= 122 || // A-Z
|
|
format === RFC1738 && (c === 40 || c === 41)) {
|
|
arr2[arr2.length] = segment.charAt(i);
|
|
continue;
|
|
}
|
|
if (c < 128) {
|
|
arr2[arr2.length] = hex_table[c];
|
|
continue;
|
|
}
|
|
if (c < 2048) {
|
|
arr2[arr2.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63];
|
|
continue;
|
|
}
|
|
if (c < 55296 || c >= 57344) {
|
|
arr2[arr2.length] = hex_table[224 | c >> 12] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
|
|
continue;
|
|
}
|
|
i += 1;
|
|
c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
|
|
arr2[arr2.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63];
|
|
}
|
|
out += arr2.join("");
|
|
j = segmentEnd;
|
|
}
|
|
return out;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/qs/stringify.mjs
|
|
function is_non_nullish_primitive(v) {
|
|
return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
|
|
}
|
|
function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder3, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
|
|
let obj2 = object;
|
|
let tmp_sc = sideChannel;
|
|
let step = 0;
|
|
let find_flag = false;
|
|
while ((tmp_sc = tmp_sc.get(sentinel)) !== void 0 && !find_flag) {
|
|
const pos = tmp_sc.get(object);
|
|
step += 1;
|
|
if (pos !== void 0) {
|
|
if (pos === step) {
|
|
throw new RangeError("Cyclic object value");
|
|
} else {
|
|
find_flag = true;
|
|
}
|
|
}
|
|
if (tmp_sc.get(sentinel) === void 0) {
|
|
step = 0;
|
|
}
|
|
}
|
|
if (typeof filter === "function") {
|
|
obj2 = filter(prefix, obj2);
|
|
} else if (obj2 instanceof Date) {
|
|
obj2 = serializeDate?.(obj2);
|
|
} else if (generateArrayPrefix === "comma" && isArray(obj2)) {
|
|
obj2 = maybe_map(obj2, (value) => {
|
|
if (value instanceof Date) {
|
|
return serializeDate?.(value);
|
|
}
|
|
return value;
|
|
});
|
|
}
|
|
if (obj2 === null) {
|
|
if (strictNullHandling) {
|
|
return encoder3 && !encodeValuesOnly ? (
|
|
// @ts-expect-error
|
|
encoder3(prefix, defaults.encoder, charset, "key", format)
|
|
) : prefix;
|
|
}
|
|
obj2 = "";
|
|
}
|
|
if (is_non_nullish_primitive(obj2) || is_buffer(obj2)) {
|
|
if (encoder3) {
|
|
const key_value = encodeValuesOnly ? prefix : (
|
|
// @ts-expect-error
|
|
encoder3(prefix, defaults.encoder, charset, "key", format)
|
|
);
|
|
return [
|
|
formatter?.(key_value) + "=" + // @ts-expect-error
|
|
formatter?.(encoder3(obj2, defaults.encoder, charset, "value", format))
|
|
];
|
|
}
|
|
return [formatter?.(prefix) + "=" + formatter?.(String(obj2))];
|
|
}
|
|
const values = [];
|
|
if (obj2 === void 0) {
|
|
return values;
|
|
}
|
|
let obj_keys;
|
|
if (generateArrayPrefix === "comma" && isArray(obj2)) {
|
|
if (encodeValuesOnly && encoder3) {
|
|
obj2 = maybe_map(obj2, encoder3);
|
|
}
|
|
obj_keys = [{ value: obj2.length > 0 ? obj2.join(",") || null : void 0 }];
|
|
} else if (isArray(filter)) {
|
|
obj_keys = filter;
|
|
} else {
|
|
const keys = Object.keys(obj2);
|
|
if (sort) {
|
|
keys.sort(sort);
|
|
}
|
|
obj_keys = keys;
|
|
}
|
|
const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
|
|
const adjusted_prefix = commaRoundTrip && isArray(obj2) && obj2.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
|
|
if (allowEmptyArrays && isArray(obj2) && obj2.length === 0) {
|
|
return adjusted_prefix + "[]";
|
|
}
|
|
for (const key of obj_keys) {
|
|
const value = (
|
|
// @ts-ignore
|
|
typeof key === "object" && key.value !== void 0 ? key.value : obj2[key]
|
|
);
|
|
if (skipNulls && value === null) {
|
|
continue;
|
|
}
|
|
const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
|
|
let key_prefix;
|
|
if (isArray(obj2)) {
|
|
key_prefix = typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix;
|
|
} else {
|
|
key_prefix = adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
|
|
}
|
|
sideChannel.set(object, step);
|
|
const valueSideChannel = new WeakMap([[sentinel, sideChannel]]);
|
|
push_to_array(values, inner_stringify(
|
|
value,
|
|
key_prefix,
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
allowEmptyArrays,
|
|
strictNullHandling,
|
|
skipNulls,
|
|
encodeDotInKeys,
|
|
// @ts-ignore
|
|
generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj2) ? null : encoder3,
|
|
filter,
|
|
sort,
|
|
allowDots,
|
|
serializeDate,
|
|
format,
|
|
formatter,
|
|
encodeValuesOnly,
|
|
charset,
|
|
valueSideChannel
|
|
));
|
|
}
|
|
return values;
|
|
}
|
|
function normalize_stringify_options(opts = defaults) {
|
|
if (opts.allowEmptyArrays !== void 0 && typeof opts.allowEmptyArrays !== "boolean") {
|
|
throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
|
|
}
|
|
if (opts.encodeDotInKeys !== void 0 && typeof opts.encodeDotInKeys !== "boolean") {
|
|
throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
|
|
}
|
|
if (opts.encoder !== null && opts.encoder !== void 0 && typeof opts.encoder !== "function") {
|
|
throw new TypeError("Encoder has to be a function.");
|
|
}
|
|
const charset = opts.charset || defaults.charset;
|
|
if (opts.charset !== void 0 && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
|
|
throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
|
|
}
|
|
let format = default_format;
|
|
if (opts.format !== void 0) {
|
|
if (!has(formatters, opts.format)) {
|
|
throw new TypeError("Unknown format option provided.");
|
|
}
|
|
format = opts.format;
|
|
}
|
|
const formatter = formatters[format];
|
|
let filter = defaults.filter;
|
|
if (typeof opts.filter === "function" || isArray(opts.filter)) {
|
|
filter = opts.filter;
|
|
}
|
|
let arrayFormat;
|
|
if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
|
|
arrayFormat = opts.arrayFormat;
|
|
} else if ("indices" in opts) {
|
|
arrayFormat = opts.indices ? "indices" : "repeat";
|
|
} else {
|
|
arrayFormat = defaults.arrayFormat;
|
|
}
|
|
if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
|
|
throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
|
|
}
|
|
let allowDots;
|
|
if (opts.allowDots === void 0) {
|
|
allowDots = !!opts.encodeDotInKeys === true ? true : defaults.allowDots;
|
|
} else {
|
|
allowDots = !!opts.allowDots;
|
|
}
|
|
return {
|
|
addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix,
|
|
// @ts-ignore
|
|
allowDots,
|
|
allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
|
|
arrayFormat,
|
|
charset,
|
|
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults.charsetSentinel,
|
|
commaRoundTrip: !!opts.commaRoundTrip,
|
|
delimiter: opts.delimiter === void 0 ? defaults.delimiter : opts.delimiter,
|
|
encode: typeof opts.encode === "boolean" ? opts.encode : defaults.encode,
|
|
encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
|
|
encoder: typeof opts.encoder === "function" ? opts.encoder : defaults.encoder,
|
|
encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
|
|
filter,
|
|
format,
|
|
formatter,
|
|
serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults.serializeDate,
|
|
skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults.skipNulls,
|
|
// @ts-ignore
|
|
sort: typeof opts.sort === "function" ? opts.sort : null,
|
|
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling
|
|
};
|
|
}
|
|
function stringify(object, opts = {}) {
|
|
let obj2 = object;
|
|
const options = normalize_stringify_options(opts);
|
|
let obj_keys;
|
|
let filter;
|
|
if (typeof options.filter === "function") {
|
|
filter = options.filter;
|
|
obj2 = filter("", obj2);
|
|
} else if (isArray(options.filter)) {
|
|
filter = options.filter;
|
|
obj_keys = filter;
|
|
}
|
|
const keys = [];
|
|
if (typeof obj2 !== "object" || obj2 === null) {
|
|
return "";
|
|
}
|
|
const generateArrayPrefix = array_prefix_generators[options.arrayFormat];
|
|
const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
|
|
if (!obj_keys) {
|
|
obj_keys = Object.keys(obj2);
|
|
}
|
|
if (options.sort) {
|
|
obj_keys.sort(options.sort);
|
|
}
|
|
const sideChannel = /* @__PURE__ */ new WeakMap();
|
|
for (const key of obj_keys) {
|
|
if (options.skipNulls && obj2[key] === null) {
|
|
continue;
|
|
}
|
|
push_to_array(keys, inner_stringify(
|
|
obj2[key],
|
|
key,
|
|
// @ts-expect-error
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
options.allowEmptyArrays,
|
|
options.strictNullHandling,
|
|
options.skipNulls,
|
|
options.encodeDotInKeys,
|
|
options.encode ? options.encoder : null,
|
|
options.filter,
|
|
options.sort,
|
|
options.allowDots,
|
|
options.serializeDate,
|
|
options.format,
|
|
options.formatter,
|
|
options.encodeValuesOnly,
|
|
options.charset,
|
|
sideChannel
|
|
));
|
|
}
|
|
const joined = keys.join(options.delimiter);
|
|
let prefix = options.addQueryPrefix === true ? "?" : "";
|
|
if (options.charsetSentinel) {
|
|
prefix += options.charset === "iso-8859-1" ? (
|
|
// encodeURIComponent('✓'), the "numeric entity" representation of a checkmark
|
|
"utf8=%26%2310003%3B&"
|
|
) : (
|
|
// encodeURIComponent('✓')
|
|
"utf8=%E2%9C%93&"
|
|
);
|
|
}
|
|
return joined.length > 0 ? prefix + joined : "";
|
|
}
|
|
var array_prefix_generators, push_to_array, toISOString, defaults, sentinel;
|
|
var init_stringify = __esm({
|
|
"node_modules/openai/internal/qs/stringify.mjs"() {
|
|
init_utils();
|
|
init_formats();
|
|
init_values();
|
|
array_prefix_generators = {
|
|
brackets(prefix) {
|
|
return String(prefix) + "[]";
|
|
},
|
|
comma: "comma",
|
|
indices(prefix, key) {
|
|
return String(prefix) + "[" + key + "]";
|
|
},
|
|
repeat(prefix) {
|
|
return String(prefix);
|
|
}
|
|
};
|
|
push_to_array = function push_to_array2(arr2, value_or_array) {
|
|
Array.prototype.push.apply(arr2, isArray(value_or_array) ? value_or_array : [value_or_array]);
|
|
};
|
|
defaults = {
|
|
addQueryPrefix: false,
|
|
allowDots: false,
|
|
allowEmptyArrays: false,
|
|
arrayFormat: "indices",
|
|
charset: "utf-8",
|
|
charsetSentinel: false,
|
|
delimiter: "&",
|
|
encode: true,
|
|
encodeDotInKeys: false,
|
|
encoder: encode,
|
|
encodeValuesOnly: false,
|
|
format: default_format,
|
|
formatter: default_formatter,
|
|
/** @deprecated */
|
|
indices: false,
|
|
serializeDate(date) {
|
|
return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date);
|
|
},
|
|
skipNulls: false,
|
|
strictNullHandling: false
|
|
};
|
|
sentinel = {};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/query.mjs
|
|
function stringifyQuery(query) {
|
|
return stringify(query, { arrayFormat: "brackets" });
|
|
}
|
|
var init_query = __esm({
|
|
"node_modules/openai/internal/utils/query.mjs"() {
|
|
init_stringify();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/data-residency.mjs
|
|
function resolveDataResidency(options) {
|
|
if (options.dataResidency === null || options.dataResidency === void 0) {
|
|
return void 0;
|
|
}
|
|
if (hasOwn(options, "baseURL")) {
|
|
throw new OpenAIError("The `dataResidency` and `baseURL` options are mutually exclusive.");
|
|
}
|
|
const endpoint = endpoints.get(options.dataResidency);
|
|
if (endpoint === void 0) {
|
|
throw new OpenAIError("Invalid `dataResidency`; expected one of: global, us, eu, ae.");
|
|
}
|
|
return endpoint;
|
|
}
|
|
var endpoints;
|
|
var init_data_residency = __esm({
|
|
"node_modules/openai/internal/data-residency.mjs"() {
|
|
init_error();
|
|
init_values();
|
|
endpoints = /* @__PURE__ */ new Map([
|
|
["global", "https://api.openai.com/v1"],
|
|
["us", "https://us.api.openai.com/v1"],
|
|
["eu", "https://eu.api.openai.com/v1"],
|
|
["ae", "https://ae.api.openai.com/v1"]
|
|
]);
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/core/api-promise.mjs
|
|
var _APIPromise_client, APIPromise;
|
|
var init_api_promise = __esm({
|
|
"node_modules/openai/core/api-promise.mjs"() {
|
|
init_tslib();
|
|
init_parse();
|
|
APIPromise = class _APIPromise extends Promise {
|
|
constructor(client, responsePromise, parseResponse2 = defaultParseResponse) {
|
|
super((resolve) => {
|
|
resolve(null);
|
|
});
|
|
this.responsePromise = responsePromise;
|
|
this.parseResponse = parseResponse2;
|
|
_APIPromise_client.set(this, void 0);
|
|
__classPrivateFieldSet(this, _APIPromise_client, client, "f");
|
|
}
|
|
_thenUnwrap(transform) {
|
|
return new _APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
|
|
}
|
|
/**
|
|
* Gets the raw `Response` instance instead of parsing the response
|
|
* data.
|
|
*
|
|
* If you want to parse the response body but still get the `Response`
|
|
* instance, you can use {@link withResponse()}.
|
|
*
|
|
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
* to your `tsconfig.json`.
|
|
*/
|
|
asResponse() {
|
|
return this.responsePromise.then((p) => p.response);
|
|
}
|
|
/**
|
|
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
|
|
* returned via the X-Request-ID header which is useful for debugging requests and reporting
|
|
* issues to OpenAI.
|
|
*
|
|
* If you just want to get the raw `Response` instance without parsing it,
|
|
* you can use {@link asResponse()}.
|
|
*
|
|
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
* to your `tsconfig.json`.
|
|
*/
|
|
async withResponse() {
|
|
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
return { data, response, request_id: response.headers.get("x-request-id") };
|
|
}
|
|
parse() {
|
|
if (!this.parsedPromise) {
|
|
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
|
|
}
|
|
return this.parsedPromise;
|
|
}
|
|
then(onfulfilled, onrejected) {
|
|
return this.parse().then(onfulfilled, onrejected);
|
|
}
|
|
catch(onrejected) {
|
|
return this.parse().catch(onrejected);
|
|
}
|
|
finally(onfinally) {
|
|
return this.parse().finally(onfinally);
|
|
}
|
|
};
|
|
_APIPromise_client = /* @__PURE__ */ new WeakMap();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/core/pagination.mjs
|
|
var _AbstractPage_client, AbstractPage, PagePromise, Page, CursorPage, ConversationCursorPage, NextCursorPage, TokenPage;
|
|
var init_pagination = __esm({
|
|
"node_modules/openai/core/pagination.mjs"() {
|
|
init_tslib();
|
|
init_error();
|
|
init_parse();
|
|
init_api_promise();
|
|
init_values();
|
|
AbstractPage = class {
|
|
constructor(client, response, body, options) {
|
|
_AbstractPage_client.set(this, void 0);
|
|
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
|
|
this.options = options;
|
|
this.response = response;
|
|
this.body = body;
|
|
}
|
|
hasNextPage() {
|
|
const items = this.getPaginatedItems();
|
|
if (!items.length)
|
|
return false;
|
|
return this.nextPageRequestOptions() != null;
|
|
}
|
|
async getNextPage() {
|
|
const nextOptions = this.nextPageRequestOptions();
|
|
if (!nextOptions) {
|
|
throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
|
|
}
|
|
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
|
|
}
|
|
async *iterPages() {
|
|
let page = this;
|
|
yield page;
|
|
while (page.hasNextPage()) {
|
|
page = await page.getNextPage();
|
|
yield page;
|
|
}
|
|
}
|
|
async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
|
|
for await (const page of this.iterPages()) {
|
|
for (const item of page.getPaginatedItems()) {
|
|
yield item;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
PagePromise = class extends APIPromise {
|
|
constructor(client, request2, Page3) {
|
|
super(client, request2, async (client2, props) => new Page3(client2, props.response, await defaultParseResponse(client2, props), props.options));
|
|
}
|
|
/**
|
|
* Allow auto-paginating iteration on an unawaited list call, eg:
|
|
*
|
|
* for await (const item of client.items.list()) {
|
|
* console.log(item)
|
|
* }
|
|
*/
|
|
async *[Symbol.asyncIterator]() {
|
|
const page = await this;
|
|
for await (const item of page) {
|
|
yield item;
|
|
}
|
|
}
|
|
};
|
|
Page = class extends AbstractPage {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.object = body.object;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
nextPageRequestOptions() {
|
|
return null;
|
|
}
|
|
};
|
|
CursorPage = class extends AbstractPage {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.has_more = body.has_more || false;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
hasNextPage() {
|
|
if (this.has_more === false) {
|
|
return false;
|
|
}
|
|
return super.hasNextPage();
|
|
}
|
|
nextPageRequestOptions() {
|
|
const data = this.getPaginatedItems();
|
|
const id = data[data.length - 1]?.id;
|
|
if (!id) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj(this.options.query),
|
|
after: id
|
|
}
|
|
};
|
|
}
|
|
};
|
|
ConversationCursorPage = class extends AbstractPage {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.has_more = body.has_more || false;
|
|
this.last_id = body.last_id || "";
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
hasNextPage() {
|
|
if (this.has_more === false) {
|
|
return false;
|
|
}
|
|
return super.hasNextPage();
|
|
}
|
|
nextPageRequestOptions() {
|
|
const cursor = this.last_id;
|
|
if (!cursor) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj(this.options.query),
|
|
after: cursor
|
|
}
|
|
};
|
|
}
|
|
};
|
|
NextCursorPage = class extends AbstractPage {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.has_more = body.has_more || false;
|
|
this.next = body.next || null;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
hasNextPage() {
|
|
if (this.has_more === false) {
|
|
return false;
|
|
}
|
|
return this.nextPageRequestOptions() != null;
|
|
}
|
|
nextPageRequestOptions() {
|
|
const cursor = this.next;
|
|
if (!cursor) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj(this.options.query),
|
|
after: cursor
|
|
}
|
|
};
|
|
}
|
|
};
|
|
TokenPage = class extends AbstractPage {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.has_more = body.has_more || false;
|
|
this.next = body.next || null;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
hasNextPage() {
|
|
if (this.has_more === false) {
|
|
return false;
|
|
}
|
|
return this.nextPageRequestOptions() != null;
|
|
}
|
|
nextPageRequestOptions() {
|
|
const cursor = this.next;
|
|
if (!cursor) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj(this.options.query),
|
|
page: cursor
|
|
}
|
|
};
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/auth/workload-identity-auth.mjs
|
|
function calculateExpiresAt(expiresIn, exchangeStartedAt) {
|
|
if (typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0) {
|
|
throw new OpenAIError("Token exchange response has invalid 'expires_in' field");
|
|
}
|
|
const now = Date.now();
|
|
const fullLifetimeDeadline = now + expiresIn * 1e3;
|
|
if (!Number.isSafeInteger(fullLifetimeDeadline) || fullLifetimeDeadline <= now) {
|
|
throw new OpenAIError("Token exchange response has invalid 'expires_in' field");
|
|
}
|
|
const expiresAt = fullLifetimeDeadline - (performance.now() - exchangeStartedAt);
|
|
if (expiresAt <= now) {
|
|
throw new OpenAIError("Workload identity token expired before its exchange completed.");
|
|
}
|
|
return expiresAt;
|
|
}
|
|
function calculateRefreshAt(expiresAt, lifetimeSeconds, refreshBufferSeconds) {
|
|
const configuredBufferMs = (refreshBufferSeconds ?? 1200) * 1e3;
|
|
const effectiveBufferMs = Math.min(configuredBufferMs, lifetimeSeconds * 1e3 * MAX_REFRESH_BUFFER_FRACTION);
|
|
return expiresAt - effectiveBufferMs;
|
|
}
|
|
function isResponsePrototype(response, prototype) {
|
|
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
if (prototype === response || typeof constructor !== "function" || Object.getOwnPropertyDescriptor(constructor, "name")?.value !== "Response" || Object.getOwnPropertyDescriptor(constructor, "prototype")?.value !== prototype) {
|
|
return false;
|
|
}
|
|
const tag = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
|
|
return (tag?.value === "Response" || typeof tag?.get === "function") && typeof Object.getOwnPropertyDescriptor(prototype, "headers")?.get === "function" && typeof Object.getOwnPropertyDescriptor(prototype, "ok")?.get === "function" && typeof Object.getOwnPropertyDescriptor(prototype, "status")?.get === "function";
|
|
}
|
|
function isResponseBodyPrototype(prototype, responsePrototype) {
|
|
if (prototype === responsePrototype) {
|
|
return true;
|
|
}
|
|
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
|
|
return responsePrototype !== null && Object.getPrototypeOf(responsePrototype) === prototype && typeof constructor === "function" && Object.getOwnPropertyDescriptor(constructor, "name")?.value === "Body" && Object.getOwnPropertyDescriptor(constructor, "prototype")?.value === prototype;
|
|
}
|
|
function decodeNativeResponseBody(body) {
|
|
const scope = globalThis;
|
|
return new TextDecoder("utf-8", { ignoreBOM: typeof scope.Bun?.version === "string" }).decode(body);
|
|
}
|
|
async function parseOAuthTokenResponse(response) {
|
|
let readText2;
|
|
let responsePrototype = null;
|
|
for (let depth = 0, prototype = response; prototype !== null && depth < 16; prototype = Object.getPrototypeOf(prototype), depth += 1) {
|
|
if (prototype === NATIVE_RESPONSE_PROTOTYPE) {
|
|
break;
|
|
}
|
|
if (isResponsePrototype(response, prototype)) {
|
|
responsePrototype = prototype;
|
|
}
|
|
const parser = Object.getOwnPropertyDescriptor(prototype, "json");
|
|
if (!parser) {
|
|
continue;
|
|
}
|
|
if (typeof parser.value !== "function") {
|
|
break;
|
|
}
|
|
const bodyReader = Object.getOwnPropertyDescriptor(prototype, "text")?.value;
|
|
if (typeof bodyReader === "function" && isResponseBodyPrototype(prototype, responsePrototype)) {
|
|
readText2 = bodyReader;
|
|
break;
|
|
}
|
|
return parser.value.call(response);
|
|
}
|
|
const body = readText2 === void 0 ? decodeNativeResponseBody(await READ_NATIVE_RESPONSE_BODY.call(response)) : await readText2.call(response);
|
|
try {
|
|
return JSON.parse(body);
|
|
} catch {
|
|
throw new SyntaxError("Token exchange response contains invalid JSON");
|
|
}
|
|
}
|
|
function isUnsafeAccessToken(accessToken) {
|
|
const scope = globalThis;
|
|
if (typeof scope.Bun?.version === "string") {
|
|
return /[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(accessToken);
|
|
}
|
|
return /[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(accessToken);
|
|
}
|
|
var SUBJECT_TOKEN_TYPES, TOKEN_EXCHANGE_GRANT_TYPE, MAX_REFRESH_BUFFER_FRACTION, NATIVE_RESPONSE_PROTOTYPE, READ_NATIVE_RESPONSE_BODY, WorkloadIdentityAuth;
|
|
var init_workload_identity_auth = __esm({
|
|
"node_modules/openai/auth/workload-identity-auth.mjs"() {
|
|
init_shims();
|
|
init_error();
|
|
SUBJECT_TOKEN_TYPES = {
|
|
jwt: "urn:ietf:params:oauth:token-type:jwt",
|
|
id: "urn:ietf:params:oauth:token-type:id_token"
|
|
};
|
|
TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
|
|
MAX_REFRESH_BUFFER_FRACTION = 0.5;
|
|
NATIVE_RESPONSE_PROTOTYPE = Response.prototype;
|
|
READ_NATIVE_RESPONSE_BODY = NATIVE_RESPONSE_PROTOTYPE.arrayBuffer;
|
|
WorkloadIdentityAuth = class _WorkloadIdentityAuth {
|
|
/**
|
|
* Creates a workload-identity token cache and OAuth token-exchange client.
|
|
*
|
|
* @param config External identity provider, OpenAI service account, and refresh settings.
|
|
* @param fetch Optional fetch implementation for calls to the OpenAI token endpoint.
|
|
*/
|
|
constructor(config, fetch2) {
|
|
this.cachedToken = null;
|
|
this.refreshPromise = null;
|
|
this.tokenGeneration = 0;
|
|
this.tokenExchangeUrl = "https://auth.openai.com/oauth/token";
|
|
const { identityProviderId, serviceAccountId, clientId, refreshBufferSeconds, provider: provider2 } = config;
|
|
this.config = {
|
|
identityProviderId,
|
|
serviceAccountId,
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...clientId === void 0 ? {} : { clientId },
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...refreshBufferSeconds === void 0 ? {} : { refreshBufferSeconds },
|
|
provider: {
|
|
tokenType: provider2.tokenType,
|
|
getToken: provider2.getToken.bind(provider2)
|
|
}
|
|
};
|
|
this.fetch = fetch2 ?? getDefaultFetch();
|
|
}
|
|
/**
|
|
* Returns a valid OpenAI access token, exchanging or refreshing credentials as needed.
|
|
*
|
|
* Cached tokens nearing expiration are returned immediately while a background
|
|
* refresh runs. Concurrent callers share the same in-flight token exchange.
|
|
*
|
|
* @throws {OAuthError} When the token endpoint rejects the subject token or identity.
|
|
* @throws {APIError} When another unsuccessful HTTP response prevents token exchange.
|
|
* @throws {OpenAIError} When a successful exchange has an invalid access token or expiration.
|
|
*/
|
|
async getToken() {
|
|
if (!this.cachedToken || _WorkloadIdentityAuth.isTokenExpired(this.cachedToken)) {
|
|
if (this.refreshPromise) {
|
|
return await this.refreshPromise;
|
|
}
|
|
const refreshPromise = this.refreshToken(this.tokenGeneration);
|
|
this.refreshPromise = refreshPromise;
|
|
try {
|
|
return await refreshPromise;
|
|
} finally {
|
|
if (this.refreshPromise === refreshPromise) {
|
|
this.refreshPromise = null;
|
|
}
|
|
}
|
|
}
|
|
if (_WorkloadIdentityAuth.needsRefresh(this.cachedToken) && !this.refreshPromise) {
|
|
const refreshPromise = this.refreshToken(this.tokenGeneration).finally(() => {
|
|
if (this.refreshPromise === refreshPromise) {
|
|
this.refreshPromise = null;
|
|
}
|
|
});
|
|
this.refreshPromise = refreshPromise;
|
|
void refreshPromise.catch(() => null);
|
|
}
|
|
return this.cachedToken.token;
|
|
}
|
|
async refreshToken(generation) {
|
|
const subjectToken = await this.config.provider.getToken();
|
|
const body = {
|
|
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
|
|
subject_token: subjectToken,
|
|
subject_token_type: SUBJECT_TOKEN_TYPES[this.config.provider.tokenType],
|
|
identity_provider_id: this.config.identityProviderId,
|
|
service_account_id: this.config.serviceAccountId
|
|
};
|
|
if (this.config.clientId) {
|
|
body["client_id"] = this.config.clientId;
|
|
}
|
|
const exchangeStartedAt = performance.now();
|
|
const response = await this.fetch(this.tokenExchangeUrl, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json"
|
|
},
|
|
body: JSON.stringify(body),
|
|
redirect: "manual"
|
|
});
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
let body2 = void 0;
|
|
try {
|
|
body2 = JSON.parse(errorText);
|
|
} catch {
|
|
}
|
|
if (response.status === 400 || response.status === 401 || response.status === 403) {
|
|
throw new OAuthError(response.status, body2, response.headers);
|
|
}
|
|
throw APIError.generate(response.status, body2, `Token exchange failed with status ${response.status}`, response.headers);
|
|
}
|
|
const tokenResponse = await parseOAuthTokenResponse(response);
|
|
const accessToken = typeof tokenResponse === "object" && tokenResponse !== null && "access_token" in tokenResponse ? tokenResponse.access_token : void 0;
|
|
if (typeof accessToken !== "string" || accessToken.trim().length === 0 || isUnsafeAccessToken(accessToken)) {
|
|
throw new OpenAIError("Token exchange response missing 'access_token' field");
|
|
}
|
|
const expiresIn = tokenResponse.expires_in ?? 3600;
|
|
const expiresAt = calculateExpiresAt(expiresIn, exchangeStartedAt);
|
|
if (this.tokenGeneration === generation) {
|
|
this.cachedToken = {
|
|
token: accessToken,
|
|
expiresAt,
|
|
refreshAt: calculateRefreshAt(expiresAt, expiresIn, this.config.refreshBufferSeconds)
|
|
};
|
|
}
|
|
return accessToken;
|
|
}
|
|
static isTokenExpired(cachedToken) {
|
|
return Date.now() >= cachedToken.expiresAt;
|
|
}
|
|
static needsRefresh(cachedToken) {
|
|
return Date.now() >= cachedToken.refreshAt;
|
|
}
|
|
/** Discards the cached access token so the next request performs a fresh exchange. */
|
|
invalidateToken() {
|
|
this.tokenGeneration += 1;
|
|
this.cachedToken = null;
|
|
this.refreshPromise = null;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-api-origin.mjs
|
|
function assertX509APIOrigin(value) {
|
|
let target;
|
|
try {
|
|
target = new URL(value);
|
|
} catch {
|
|
throw new OpenAIError("X.509 workload identity requires the approved global mTLS API origin.");
|
|
}
|
|
if (target.origin !== "https://mtls.api.openai.com" || target.username || target.password) {
|
|
throw new OpenAIError("X.509 workload identity requires the approved global mTLS API origin.");
|
|
}
|
|
for (const name of target.searchParams.keys()) {
|
|
if (isSensitiveQueryParameter(name)) {
|
|
throw new OpenAIError("X.509 workload identity cannot send conflicting query authentication credentials.");
|
|
}
|
|
}
|
|
return target;
|
|
}
|
|
var X509_API_BASE_URL;
|
|
var init_x509_api_origin = __esm({
|
|
"node_modules/openai/internal/auth/x509-api-origin.mjs"() {
|
|
init_error();
|
|
init_log();
|
|
X509_API_BASE_URL = "https://mtls.api.openai.com/v1";
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/headers.mjs
|
|
function* iterateHeaders(headers) {
|
|
if (!headers)
|
|
return;
|
|
if (brand_privateNullableHeaders in headers) {
|
|
const { values, nulls } = headers;
|
|
yield* values.entries();
|
|
for (const name of nulls) {
|
|
yield [name, null];
|
|
}
|
|
return;
|
|
}
|
|
let shouldClear = false;
|
|
let iter;
|
|
const iterator = Symbol.iterator in headers ? headers[Symbol.iterator] : void 0;
|
|
if (typeof iterator === "function") {
|
|
iter = { [Symbol.iterator]: () => iterator.call(headers) };
|
|
} else {
|
|
shouldClear = true;
|
|
iter = Object.entries(headers ?? {});
|
|
}
|
|
for (let row of iter) {
|
|
const name = row[0];
|
|
if (typeof name !== "string")
|
|
throw new TypeError("expected header name to be a string");
|
|
const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
|
|
let didClear = false;
|
|
for (const value of values) {
|
|
if (value === void 0)
|
|
continue;
|
|
if (shouldClear && !didClear) {
|
|
didClear = true;
|
|
yield [name, null];
|
|
}
|
|
yield [name, value];
|
|
}
|
|
}
|
|
}
|
|
var brand_privateNullableHeaders, httpTokenHeaderName, buildHeaders;
|
|
var init_headers2 = __esm({
|
|
"node_modules/openai/internal/headers.mjs"() {
|
|
init_values();
|
|
brand_privateNullableHeaders = /* @__PURE__ */ Symbol("brand.privateNullableHeaders");
|
|
httpTokenHeaderName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
buildHeaders = (newHeaders) => {
|
|
const targetHeaders = new Headers();
|
|
const nullHeaders = /* @__PURE__ */ new Set();
|
|
for (const headers of newHeaders) {
|
|
const seenHeaders = /* @__PURE__ */ new Set();
|
|
for (const [name, value] of iterateHeaders(headers)) {
|
|
if (!httpTokenHeaderName.test(name)) {
|
|
throw new TypeError(`Header name must be a valid HTTP token ["${name}"]`);
|
|
}
|
|
const lowerName = name.toLowerCase();
|
|
if (!seenHeaders.has(lowerName)) {
|
|
targetHeaders.delete(lowerName);
|
|
seenHeaders.add(lowerName);
|
|
}
|
|
if (value === null) {
|
|
targetHeaders.delete(lowerName);
|
|
nullHeaders.add(lowerName);
|
|
} else {
|
|
targetHeaders.append(lowerName, value);
|
|
nullHeaders.delete(lowerName);
|
|
}
|
|
}
|
|
}
|
|
return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-transport-state-browser.mjs
|
|
var x509_transport_state_browser_exports = {};
|
|
__export(x509_transport_state_browser_exports, {
|
|
findRegisteredX509Transport: () => findRegisteredX509Transport,
|
|
findX509Credential: () => findX509Credential,
|
|
findX509OAuthError: () => findX509OAuthError,
|
|
isApprovedX509Client: () => isApprovedX509Client,
|
|
isRetryableX509IssuerError: () => isRetryableX509IssuerError,
|
|
isTransientX509ConnectionError: () => isTransientX509ConnectionError,
|
|
markApprovedX509Client: () => markApprovedX509Client,
|
|
markRetryableX509IssuerError: () => markRetryableX509IssuerError,
|
|
markTransientX509ConnectionError: () => markTransientX509ConnectionError,
|
|
rememberRegisteredX509Transport: () => rememberRegisteredX509Transport,
|
|
rememberX509Credential: () => rememberX509Credential,
|
|
rememberX509OAuthError: () => rememberX509OAuthError
|
|
});
|
|
var registeredX509Transports, transientX509ConnectionErrors, retryableX509IssuerErrors, approvedX509Clients, approvedX509OAuthErrors, approvedX509Credentials, findRegisteredX509Transport, rememberRegisteredX509Transport, markTransientX509ConnectionError, isTransientX509ConnectionError, markRetryableX509IssuerError, isRetryableX509IssuerError, markApprovedX509Client, isApprovedX509Client, rememberX509OAuthError, findX509OAuthError, rememberX509Credential, findX509Credential;
|
|
var init_x509_transport_state_browser = __esm({
|
|
"node_modules/openai/internal/auth/x509-transport-state-browser.mjs"() {
|
|
registeredX509Transports = /* @__PURE__ */ new WeakMap();
|
|
transientX509ConnectionErrors = /* @__PURE__ */ new WeakSet();
|
|
retryableX509IssuerErrors = /* @__PURE__ */ new WeakSet();
|
|
approvedX509Clients = /* @__PURE__ */ new WeakSet();
|
|
approvedX509OAuthErrors = /* @__PURE__ */ new WeakMap();
|
|
approvedX509Credentials = /* @__PURE__ */ new WeakMap();
|
|
findRegisteredX509Transport = WeakMap.prototype.get.bind(registeredX509Transports);
|
|
rememberRegisteredX509Transport = WeakMap.prototype.set.bind(registeredX509Transports);
|
|
markTransientX509ConnectionError = WeakSet.prototype.add.bind(transientX509ConnectionErrors);
|
|
isTransientX509ConnectionError = WeakSet.prototype.has.bind(transientX509ConnectionErrors);
|
|
markRetryableX509IssuerError = WeakSet.prototype.add.bind(retryableX509IssuerErrors);
|
|
isRetryableX509IssuerError = WeakSet.prototype.has.bind(retryableX509IssuerErrors);
|
|
markApprovedX509Client = WeakSet.prototype.add.bind(approvedX509Clients);
|
|
isApprovedX509Client = WeakSet.prototype.has.bind(approvedX509Clients);
|
|
rememberX509OAuthError = WeakMap.prototype.set.bind(approvedX509OAuthErrors);
|
|
findX509OAuthError = WeakMap.prototype.get.bind(approvedX509OAuthErrors);
|
|
rememberX509Credential = WeakMap.prototype.set.bind(approvedX509Credentials);
|
|
findX509Credential = WeakMap.prototype.get.bind(approvedX509Credentials);
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-transport-state.js
|
|
var require_x509_transport_state = __commonJS({
|
|
"node_modules/openai/internal/auth/x509-transport-state.js"(exports, module) {
|
|
"use strict";
|
|
if (typeof module !== "undefined" && module !== globalThis.module && typeof exports !== "undefined" && module.exports === exports) {
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.findX509Credential = exports.rememberX509Credential = exports.findX509OAuthError = exports.rememberX509OAuthError = exports.isApprovedX509Client = exports.markApprovedX509Client = exports.isRetryableX509IssuerError = exports.markRetryableX509IssuerError = exports.isTransientX509ConnectionError = exports.markTransientX509ConnectionError = exports.rememberRegisteredX509Transport = exports.findRegisteredX509Transport = void 0;
|
|
const registeredX509Transports2 = /* @__PURE__ */ new WeakMap();
|
|
const transientX509ConnectionErrors2 = /* @__PURE__ */ new WeakSet();
|
|
const retryableX509IssuerErrors2 = /* @__PURE__ */ new WeakSet();
|
|
const approvedX509Clients2 = /* @__PURE__ */ new WeakSet();
|
|
const approvedX509OAuthErrors2 = /* @__PURE__ */ new WeakMap();
|
|
const approvedX509Credentials2 = /* @__PURE__ */ new WeakMap();
|
|
exports.findRegisteredX509Transport = WeakMap.prototype.get.bind(registeredX509Transports2);
|
|
exports.rememberRegisteredX509Transport = WeakMap.prototype.set.bind(registeredX509Transports2);
|
|
exports.markTransientX509ConnectionError = WeakSet.prototype.add.bind(transientX509ConnectionErrors2);
|
|
exports.isTransientX509ConnectionError = WeakSet.prototype.has.bind(transientX509ConnectionErrors2);
|
|
exports.markRetryableX509IssuerError = WeakSet.prototype.add.bind(retryableX509IssuerErrors2);
|
|
exports.isRetryableX509IssuerError = WeakSet.prototype.has.bind(retryableX509IssuerErrors2);
|
|
exports.markApprovedX509Client = WeakSet.prototype.add.bind(approvedX509Clients2);
|
|
exports.isApprovedX509Client = WeakSet.prototype.has.bind(approvedX509Clients2);
|
|
exports.rememberX509OAuthError = WeakMap.prototype.set.bind(approvedX509OAuthErrors2);
|
|
exports.findX509OAuthError = WeakMap.prototype.get.bind(approvedX509OAuthErrors2);
|
|
exports.rememberX509Credential = WeakMap.prototype.set.bind(approvedX509Credentials2);
|
|
exports.findX509Credential = WeakMap.prototype.get.bind(approvedX509Credentials2);
|
|
}
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-transport-state.mjs
|
|
var nodeState, state, findRegisteredX509Transport3, rememberRegisteredX509Transport2, markTransientX509ConnectionError2, isTransientX509ConnectionError2, markRetryableX509IssuerError2, isRetryableX509IssuerError2, markApprovedX509Client2, isApprovedX509Client2, rememberX509OAuthError2, findX509OAuthError2, rememberX509Credential2, findX509Credential2;
|
|
var init_x509_transport_state = __esm({
|
|
"node_modules/openai/internal/auth/x509-transport-state.mjs"() {
|
|
init_x509_transport_state_browser();
|
|
nodeState = __toESM(require_x509_transport_state(), 1);
|
|
state = typeof nodeState.findRegisteredX509Transport === "function" ? nodeState : x509_transport_state_browser_exports;
|
|
({
|
|
findRegisteredX509Transport: findRegisteredX509Transport3,
|
|
rememberRegisteredX509Transport: rememberRegisteredX509Transport2,
|
|
markTransientX509ConnectionError: markTransientX509ConnectionError2,
|
|
isTransientX509ConnectionError: isTransientX509ConnectionError2,
|
|
markRetryableX509IssuerError: markRetryableX509IssuerError2,
|
|
isRetryableX509IssuerError: isRetryableX509IssuerError2,
|
|
markApprovedX509Client: markApprovedX509Client2,
|
|
isApprovedX509Client: isApprovedX509Client2,
|
|
rememberX509OAuthError: rememberX509OAuthError2,
|
|
findX509OAuthError: findX509OAuthError2,
|
|
rememberX509Credential: rememberX509Credential2,
|
|
findX509Credential: findX509Credential2
|
|
} = state);
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-transport-registry.mjs
|
|
function resolveX509Transport(value) {
|
|
if (!value || typeof value !== "object") {
|
|
throw new OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");
|
|
}
|
|
const registered = findRegisteredX509Transport3(value);
|
|
if (!registered) {
|
|
throw new OpenAIError("X.509 workload identity requires an approved X.509 transport capability.");
|
|
}
|
|
return registered;
|
|
}
|
|
var init_x509_transport_registry = __esm({
|
|
"node_modules/openai/internal/auth/x509-transport-registry.mjs"() {
|
|
init_error();
|
|
init_x509_transport_state();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-workload-identity-auth.mjs
|
|
function assertSafeHeaders(headers) {
|
|
for (const name of Headers.prototype.keys.call(headers)) {
|
|
const canonical2 = name.toLowerCase().split("_").join("-");
|
|
if (canonical2 !== "authorization" && isSensitiveHeader(canonical2) || canonical2 === "host") {
|
|
throw new OpenAIError("X.509 workload identity cannot send conflicting authentication credentials.");
|
|
}
|
|
}
|
|
}
|
|
function exchangeDeadline(timeout, callerSignal) {
|
|
const deadline = new AbortController();
|
|
const timer = timeout === void 0 ? void 0 : setTimeout(() => deadline.abort(new APIConnectionTimeoutError()), timeout);
|
|
const timerHandle = timer;
|
|
if (typeof timerHandle === "object" && timerHandle !== null && "unref" in timerHandle && typeof timerHandle.unref === "function") {
|
|
timerHandle.unref();
|
|
}
|
|
const cancel = () => deadline.abort(callerSignal?.reason);
|
|
callerSignal?.addEventListener("abort", cancel, { once: true });
|
|
if (callerSignal?.aborted) {
|
|
cancel();
|
|
}
|
|
return {
|
|
signal: deadline.signal,
|
|
dispose: () => {
|
|
callerSignal?.removeEventListener("abort", cancel);
|
|
if (timer) {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
function waitForRefresh(attempt, signal) {
|
|
let abort;
|
|
const canceled = new Promise((_resolve, reject) => {
|
|
abort = () => reject(signal.reason);
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
if (signal.aborted) {
|
|
abort();
|
|
}
|
|
});
|
|
return {
|
|
result: Promise.race([attempt.promise, canceled]),
|
|
dispose: () => {
|
|
if (abort) {
|
|
signal.removeEventListener("abort", abort);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
function isX509WorkloadIdentity(identity) {
|
|
if (!identity || typeof identity !== "object") {
|
|
return false;
|
|
}
|
|
let providerOwner = identity;
|
|
while (providerOwner !== null && providerOwner !== Object.prototype) {
|
|
const provider2 = Object.getOwnPropertyDescriptor(providerOwner, "provider");
|
|
if (provider2) {
|
|
if (!("value" in provider2) || provider2.value !== void 0) {
|
|
return false;
|
|
}
|
|
break;
|
|
}
|
|
providerOwner = Object.getPrototypeOf(providerOwner);
|
|
}
|
|
let current = identity;
|
|
while (current !== null && current !== Object.prototype) {
|
|
const discriminator = Object.getOwnPropertyDescriptor(current, "type");
|
|
if (discriminator) {
|
|
if (!("value" in discriminator)) {
|
|
throw new OpenAIError("X.509 workload identity type must be a plain data property.");
|
|
}
|
|
return discriminator.value === "x509";
|
|
}
|
|
current = Object.getPrototypeOf(current);
|
|
}
|
|
return false;
|
|
}
|
|
function assertX509FetchOptions(options) {
|
|
if (!options) {
|
|
return;
|
|
}
|
|
for (const name of FORBIDDEN_TRANSPORT_OPTIONS) {
|
|
if (hasOwn(options, name)) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its approved transport capability.");
|
|
}
|
|
}
|
|
const redirect = Object.getOwnPropertyDescriptor(options, "redirect")?.value;
|
|
if (redirect !== void 0 && redirect !== "manual") {
|
|
throw new OpenAIError("X.509 workload identity requests require manual redirects.");
|
|
}
|
|
}
|
|
function assertX509RequestOptions(options) {
|
|
assertX509FetchOptions(options);
|
|
if (options && ["body", "headers", "method", "signal"].some((name) => hasOwn(options, name))) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.");
|
|
}
|
|
}
|
|
function snapshotX509RequestOptions(options) {
|
|
assertX509RequestOptions(options);
|
|
const snapshot = { ...options };
|
|
assertX509RequestOptions(snapshot);
|
|
return snapshot;
|
|
}
|
|
var _X509WorkloadIdentityAuth_instances, _a, _X509WorkloadIdentityAuth_identityProviderId, _X509WorkloadIdentityAuth_serviceAccountId, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, _X509WorkloadIdentityAuth_organization, _X509WorkloadIdentityAuth_project, _X509WorkloadIdentityAuth_transport, _X509WorkloadIdentityAuth_refreshBufferMs, _X509WorkloadIdentityAuth_cachedToken, _X509WorkloadIdentityAuth_refresh, _X509WorkloadIdentityAuth_tokenGeneration, _X509WorkloadIdentityAuth_cancelRequestBody, _X509WorkloadIdentityAuth_assignToken, _X509WorkloadIdentityAuth_recoverRefreshFailure, _X509WorkloadIdentityAuth_fallbackToken, _X509WorkloadIdentityAuth_retireRefresh, _X509WorkloadIdentityAuth_beginRefresh, _X509WorkloadIdentityAuth_refreshToken, _X509WorkloadIdentityAuth_preflight, _X509WorkloadIdentityAuth_scope, _X509WorkloadIdentityAuth_assertTenantHeaders, FORBIDDEN_TRANSPORT_OPTIONS, headerValue, DEFAULT_REFRESH_BUFFER_MS, FAILED_REFRESH_COOLDOWN_MS, userAbortError, X509WorkloadIdentityAuth;
|
|
var init_x509_workload_identity_auth = __esm({
|
|
"node_modules/openai/internal/auth/x509-workload-identity-auth.mjs"() {
|
|
init_tslib();
|
|
init_error();
|
|
init_headers2();
|
|
init_shims();
|
|
init_log();
|
|
init_values();
|
|
init_x509_api_origin();
|
|
init_x509_transport_registry();
|
|
init_x509_transport_state();
|
|
FORBIDDEN_TRANSPORT_OPTIONS = ["dispatcher", "agent", "client", "tls", "proxy"];
|
|
headerValue = (headers, name) => Headers.prototype.get.call(headers, name);
|
|
DEFAULT_REFRESH_BUFFER_MS = 20 * 60 * 1e3;
|
|
FAILED_REFRESH_COOLDOWN_MS = 1e3;
|
|
userAbortError = (signal) => {
|
|
const error = new APIUserAbortError();
|
|
Object.defineProperty(error, "cause", { value: signal.reason, writable: true, configurable: true });
|
|
return error;
|
|
};
|
|
X509WorkloadIdentityAuth = class {
|
|
/** Captures one registered, immutable certificate identity and its enrolled selectors. */
|
|
constructor(identity, transport, organization, project) {
|
|
_X509WorkloadIdentityAuth_instances.add(this);
|
|
_X509WorkloadIdentityAuth_identityProviderId.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_serviceAccountId.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_configuredRefreshBufferMs.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_configuredRefreshBufferSeconds.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_organization.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_project.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_transport.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_refreshBufferMs.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_cachedToken.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_refresh.set(this, void 0);
|
|
_X509WorkloadIdentityAuth_tokenGeneration.set(this, 0);
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_transport, resolveX509Transport(transport), "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_identityProviderId, identity.identityProviderId, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_serviceAccountId, identity.serviceAccountId, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, identity.refreshBufferMs, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, identity.refreshBufferSeconds, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_organization, organization, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_project, project, "f");
|
|
if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") !== void 0 && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") !== void 0) {
|
|
throw new OpenAIError("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");
|
|
}
|
|
if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") !== void 0 && (!Number.isSafeInteger(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f")) || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") < 0)) {
|
|
throw new OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferMs.");
|
|
}
|
|
if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") !== void 0 && (!Number.isSafeInteger(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f")) || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") < 0 || !Number.isSafeInteger(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") * 1e3))) {
|
|
throw new OpenAIError("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");
|
|
}
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refreshBufferMs, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") === void 0 ? __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") ?? DEFAULT_REFRESH_BUFFER_MS : __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") * 1e3, "f");
|
|
}
|
|
/** Reconstructs the immutable selectors captured before caller-owned identity mutation. */
|
|
identitySnapshot() {
|
|
return {
|
|
type: "x509",
|
|
identityProviderId: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_identityProviderId, "f"),
|
|
serviceAccountId: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_serviceAccountId, "f"),
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") === void 0 ? {} : { refreshBufferMs: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferMs, "f") },
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") === void 0 ? {} : { refreshBufferSeconds: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds, "f") }
|
|
};
|
|
}
|
|
/** Preserves explicitly headerless requests without presenting a certificate to the issuer. */
|
|
static shouldAuthenticate(options, defaultHeaders, requestHeaders2 = options.headers) {
|
|
return !buildHeaders([defaultHeaders, requestHeaders2]).nulls.has("authorization");
|
|
}
|
|
/** Snapshots each caller-owned header layer once while preserving nulls and precedence. */
|
|
snapshotHeaders(defaultHeaders, requestHeaders2) {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
scope.defaultHeaders ?? (scope.defaultHeaders = buildHeaders([defaultHeaders]));
|
|
scope.requestHeaders ?? (scope.requestHeaders = buildHeaders([requestHeaders2]));
|
|
return this.headerSnapshots();
|
|
}
|
|
/** Returns the already rendered caller headers without touching mutable inputs again. */
|
|
headerSnapshots() {
|
|
const { defaultHeaders, requestHeaders: requestHeaders2 } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (!defaultHeaders || !requestHeaders2) {
|
|
throw new OpenAIError("X.509 workload identity requires snapshotted request headers.");
|
|
}
|
|
return { defaultHeaders, requestHeaders: requestHeaders2 };
|
|
}
|
|
/** Captures enrolled public tenant selectors once before certificate presentation. */
|
|
snapshotTenant(organization, project) {
|
|
if (organization !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") || project !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f")) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
|
|
}
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
scope.tenant = { organization, project };
|
|
return scope.tenant;
|
|
}
|
|
/** Returns the tenant selectors already approved for this logical request. */
|
|
tenantSnapshot() {
|
|
const { tenant } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (!tenant) {
|
|
throw new OpenAIError("X.509 workload identity requires snapshotted tenant selectors.");
|
|
}
|
|
return tenant;
|
|
}
|
|
/** Validates and retains the exact destination that authenticated dispatch will use. */
|
|
snapshotAPIURL(value) {
|
|
assertX509APIOrigin(value);
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).apiURL = value;
|
|
}
|
|
/** Reads the already-approved destination without rerendering caller-owned request options. */
|
|
requestAPIURL() {
|
|
const { apiURL } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (apiURL === void 0) {
|
|
throw new OpenAIError("X.509 workload identity requires a snapshotted API destination.");
|
|
}
|
|
return apiURL;
|
|
}
|
|
/** Captures the exact caller settings approved for authenticated dispatch. */
|
|
snapshotRequest(signal, timeout, fetchOptions) {
|
|
var _b;
|
|
(_b = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this)).request ?? (_b.request = { signal, timeout, fetchOptions });
|
|
}
|
|
/** Returns immutable request settings without invoking caller-owned accessors again. */
|
|
requestSnapshot() {
|
|
const { request: request2 } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (!request2) {
|
|
throw new OpenAIError("X.509 workload identity requires snapshotted request settings.");
|
|
}
|
|
return request2;
|
|
}
|
|
/** Suspends an already-running network budget during retry-local asynchronous preparation. */
|
|
beginRequestPreparation() {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (scope.deadlineArmed && scope.preparationStartedAt === void 0) {
|
|
scope.preparationStartedAt = performance.now();
|
|
scope.preparationWallStartedAt = Date.now();
|
|
}
|
|
}
|
|
/** Begins local request construction without charging protected hook latency to the network. */
|
|
beginRequestPlanning() {
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).phase = "planning";
|
|
}
|
|
/** Arms one absolute network deadline only after all local request preparation completes. */
|
|
beginRequestNetwork() {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (!scope.deadlineArmed) {
|
|
scope.wallStartedAt = Date.now();
|
|
scope.monotonicStartedAt = performance.now();
|
|
scope.deadlineArmed = true;
|
|
} else if (scope.preparationStartedAt !== void 0) {
|
|
scope.monotonicStartedAt += performance.now() - scope.preparationStartedAt;
|
|
scope.wallStartedAt += Date.now() - (scope.preparationWallStartedAt ?? Date.now());
|
|
delete scope.preparationStartedAt;
|
|
delete scope.preparationWallStartedAt;
|
|
}
|
|
}
|
|
/** Keeps certificate authentication outside overridable request construction. */
|
|
isPlanningRequest() {
|
|
return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).phase === "planning";
|
|
}
|
|
/** Approves the final overridden destination and transport before minting a bearer. */
|
|
authorizePlannedRequest(url, request2, timeout, allowHookSignal = false) {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
const headers = Object.getOwnPropertyDescriptor(request2, "headers");
|
|
const body = Object.getOwnPropertyDescriptor(request2, "body");
|
|
const signal = Object.getOwnPropertyDescriptor(request2, "signal");
|
|
const redirect = Object.getOwnPropertyDescriptor(request2, "redirect");
|
|
if (scope.phase !== "planning" || !headers || !(headers.value instanceof Headers) || !body && "body" in request2 || [body, signal, redirect].some((descriptor) => descriptor && !("value" in descriptor))) {
|
|
throw new OpenAIError("X.509 workload identity requires an approved final request.");
|
|
}
|
|
this.snapshotAPIURL(url);
|
|
assertX509FetchOptions(request2);
|
|
try {
|
|
assertSafeHeaders(headers.value);
|
|
} catch {
|
|
throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.");
|
|
}
|
|
if (headerValue(headers.value, "Authorization") !== null) {
|
|
throw new OpenAIError("X.509 workload identity cannot use caller-supplied authorization credentials.");
|
|
}
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_assertTenantHeaders).call(this, headers.value);
|
|
if (!allowHookSignal && (signal?.value ?? void 0) !== (this.requestSnapshot().signal ?? void 0)) {
|
|
throw new OpenAIError("X.509 workload identity must preserve its approved request signal.");
|
|
}
|
|
const approved = this.requestSnapshot();
|
|
scope.request = { ...approved, timeout: Math.min(approved.timeout, timeout) };
|
|
scope.phase = "authorizing";
|
|
}
|
|
/** Owns only SDK-created iterator adapters until authenticated dispatch takes responsibility. */
|
|
ownRequestBody(body, source) {
|
|
if (body instanceof ReadableStream && body !== source) {
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).materializedBody = body;
|
|
}
|
|
}
|
|
/** Recognizes every one-shot upload before issuer authentication or request replay. */
|
|
static isStreamingRequestBody(body) {
|
|
return globalThis.ReadableStream !== void 0 && body instanceof globalThis.ReadableStream || typeof body === "object" && body !== null && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function");
|
|
}
|
|
/** Retires abandoned upload adapters without masking or blocking their authentication failure. */
|
|
retireRequestBody() {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
const body = scope.materializedBody;
|
|
delete scope.materializedBody;
|
|
if (body) {
|
|
void __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_cancelRequestBody).call(_a, body);
|
|
}
|
|
}
|
|
/** Transfers the dispatched upload while retiring any SDK-owned body replaced by a hook. */
|
|
releaseRequestBody(body) {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
if (scope.materializedBody === body) {
|
|
delete scope.materializedBody;
|
|
} else {
|
|
this.retireRequestBody();
|
|
}
|
|
}
|
|
/** Retains caller-only cancellation separately from SDK-created deadline controllers. */
|
|
setEffectiveSignal(signal) {
|
|
if (signal) {
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).effectiveSignal = signal;
|
|
} else {
|
|
delete __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this).effectiveSignal;
|
|
}
|
|
}
|
|
/** Uses protected-hook cancellation when an authenticated attempt enters retry backoff. */
|
|
effectiveSignal() {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
return scope.effectiveSignal ?? scope.request?.signal;
|
|
}
|
|
/** Establishes an independent scope even when concurrent requests share caller options. */
|
|
// oxlint-disable-next-line anti-slop/no-object-parameters -- Logical request owners are opaque identity tokens; their properties are never read.
|
|
runRequest(operation, requestOwner) {
|
|
return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").run(async () => {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
|
|
if (!scope) {
|
|
throw new OpenAIError("X.509 workload identity requires an active certificate request scope.");
|
|
}
|
|
scope.owner = this;
|
|
scope.requestOwner = requestOwner;
|
|
try {
|
|
return await operation();
|
|
} finally {
|
|
this.retireRequestBody();
|
|
this.releaseRequestCredentials();
|
|
delete scope.requestOwner;
|
|
delete scope.owner;
|
|
}
|
|
});
|
|
}
|
|
/** Reports whether a public request-building call already belongs to an active logical operation. */
|
|
// oxlint-disable-next-line anti-slop/no-object-parameters -- Request scope membership compares the opaque caller token by identity only.
|
|
inRequest(requestOwner) {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
|
|
return scope?.owner === this && scope.requestOwner === requestOwner && scope.phase !== "authorizing";
|
|
}
|
|
/** Shares a cache only when the complete, privately snapshotted credential identity matches. */
|
|
matches(other) {
|
|
return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_transport, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_identityProviderId, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_identityProviderId, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_serviceAccountId, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_serviceAccountId, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_organization, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_project, "f") && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refreshBufferMs, "f") === __classPrivateFieldGet(other, _X509WorkloadIdentityAuth_refreshBufferMs, "f");
|
|
}
|
|
/** Binds deferred response parsing to the original logical request and its unchanged deadline. */
|
|
continuation() {
|
|
const { wallStartedAt, monotonicStartedAt, deadlineArmed, request: request2, requestOwner, effectiveSignal } = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
const scope = {
|
|
wallStartedAt,
|
|
monotonicStartedAt,
|
|
owner: this,
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...deadlineArmed ? { deadlineArmed } : {},
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...request2 ? { request: request2 } : {},
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...effectiveSignal ? { effectiveSignal } : {},
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...requestOwner ? { requestOwner } : {}
|
|
};
|
|
return (operation) => __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").resume(scope, async () => {
|
|
try {
|
|
return await operation();
|
|
} finally {
|
|
this.releaseRequestCredentials();
|
|
delete scope.requestOwner;
|
|
delete scope.owner;
|
|
}
|
|
});
|
|
}
|
|
/** Removes dispatched bearer material before settled request promises can retain their scope. */
|
|
releaseRequestCredentials() {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
delete scope.request;
|
|
delete scope.phase;
|
|
delete scope.deadlineArmed;
|
|
delete scope.preparationStartedAt;
|
|
delete scope.preparationWallStartedAt;
|
|
delete scope.effectiveSignal;
|
|
delete scope.materializedBody;
|
|
delete scope.apiURL;
|
|
delete scope.tenant;
|
|
delete scope.token;
|
|
delete scope.defaultHeaders;
|
|
delete scope.requestHeaders;
|
|
delete scope.tokenGeneration;
|
|
delete scope.headers;
|
|
delete scope.authorization;
|
|
}
|
|
/** Returns the original authentication start so response consumption shares its request deadline. */
|
|
requestStartedAt(_options) {
|
|
return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current()?.wallStartedAt;
|
|
}
|
|
/** Distinguishes issued workload credentials from independent admin or headerless requests. */
|
|
usedWorkloadToken(_options) {
|
|
return __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current()?.token !== void 0;
|
|
}
|
|
/** Returns the budget left after certificate authentication without starting another timeout. */
|
|
remainingTimeout(_options, timeout) {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
|
|
if (scope === void 0) {
|
|
return timeout;
|
|
}
|
|
const remaining = timeout - (performance.now() - scope.monotonicStartedAt);
|
|
if (remaining <= 0) {
|
|
throw new APIConnectionTimeoutError();
|
|
}
|
|
return remaining;
|
|
}
|
|
/** Cancels active retry timers promptly without changing public caller-abort semantics. */
|
|
async waitForRetry(duration, signal) {
|
|
try {
|
|
await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").sleep(duration, signal);
|
|
} catch (error) {
|
|
if (signal?.aborted) {
|
|
throw userAbortError(signal);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
/** Trusts only issuer or connection failures privately branded by the approved transport. */
|
|
static isRetryableFailure(error) {
|
|
return typeof error === "object" && error !== null && (isTransientX509ConnectionError2(error) || isRetryableX509IssuerError2(error));
|
|
}
|
|
/** Reads safe retry hints only from a privately branded, sanitized issuer response. */
|
|
static retryHeaders(error) {
|
|
if (!error || typeof error !== "object" || !isRetryableX509IssuerError2(error)) {
|
|
return void 0;
|
|
}
|
|
const headers = Object.getOwnPropertyDescriptor(error, "headers")?.value;
|
|
return headers instanceof Headers ? headers : void 0;
|
|
}
|
|
/** Exchanges the exact certificate capability selected for the matching API dispatch. */
|
|
async getToken(options, context) {
|
|
const callerSignal = context ? context.signal : options?.signal;
|
|
if (callerSignal?.aborted) {
|
|
throw userAbortError(callerSignal);
|
|
}
|
|
if (options) {
|
|
assertX509RequestOptions(context ? context.fetchOptions : options.fetchOptions);
|
|
}
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_preflight).call(this, context);
|
|
const scope = options ? __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this) : void 0;
|
|
const cached = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f");
|
|
if (cached && performance.now() < cached.refreshAt && Date.now() < cached.wallRefreshAt) {
|
|
return __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_assignToken).call(_a, scope, cached);
|
|
}
|
|
const remaining = context && options ? this.remainingTimeout(options, context.timeout) : context?.timeout;
|
|
const { signal, dispose } = exchangeDeadline(remaining, callerSignal);
|
|
if (callerSignal?.aborted) {
|
|
dispose();
|
|
throw userAbortError(callerSignal);
|
|
}
|
|
const attempt = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f") ?? __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_beginRefresh).call(this);
|
|
attempt.waiters += 1;
|
|
const waiter = waitForRefresh(attempt, signal);
|
|
try {
|
|
const exchanged = await waiter.result;
|
|
const refreshed = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f");
|
|
if (!refreshed || refreshed.accessToken !== exchanged.accessToken) {
|
|
throw new APIUserAbortError();
|
|
}
|
|
return __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_assignToken).call(_a, scope, refreshed);
|
|
} catch (error) {
|
|
return await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_recoverRefreshFailure).call(this, error, attempt, cached, scope, options, context);
|
|
} finally {
|
|
waiter.dispose();
|
|
dispose();
|
|
attempt.waiters -= 1;
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_retireRefresh).call(this, attempt);
|
|
}
|
|
}
|
|
/** Invalidates only the workload-token generation actually rejected by the current request. */
|
|
invalidateToken() {
|
|
const rejected = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
|
|
if (!rejected?.token || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f")?.accessToken !== rejected.token || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f").generation !== rejected.tokenGeneration) {
|
|
return;
|
|
}
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_tokenGeneration, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") + 1, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_cachedToken, void 0, "f");
|
|
const refresh = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, void 0, "f");
|
|
refresh?.controller.abort(new APIUserAbortError());
|
|
}
|
|
/** Binds the minted credential to the original headers before protected request hooks run. */
|
|
bindRequest(options, request2, adminAPIKey) {
|
|
if (!(request2.headers instanceof Headers)) {
|
|
throw new OpenAIError("X.509 workload identity requires the original workload authorization headers.");
|
|
}
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
const { token } = scope;
|
|
const security = options.__security ?? { bearerAuth: true };
|
|
let approvedAuthorization = token ? `Bearer ${token}` : null;
|
|
if (!token && security.adminAPIKeyAuth && adminAPIKey !== null && headerValue(request2.headers, "Authorization") !== null) {
|
|
approvedAuthorization = new Headers({ Authorization: `Bearer ${adminAPIKey}` }).get("Authorization");
|
|
}
|
|
scope.headers = request2.headers;
|
|
scope.authorization = approvedAuthorization;
|
|
this.assertRequest(request2);
|
|
}
|
|
/** Rebinds an equivalent protected-hook container without relaxing final dispatch identity checks. */
|
|
adoptRequestHeaders(request2) {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_scope).call(this);
|
|
const original = scope.headers;
|
|
if (!(original instanceof Headers) || !(request2.headers instanceof Headers)) {
|
|
throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
|
|
}
|
|
scope.headers = request2.headers;
|
|
try {
|
|
this.assertRequest(request2);
|
|
} catch (error) {
|
|
scope.headers = original;
|
|
throw error;
|
|
}
|
|
}
|
|
/** Rejects request hooks that replace the selected bearer or its approved header identity. */
|
|
assertRequest(request2) {
|
|
const { headers } = request2;
|
|
if (!(headers instanceof Headers)) {
|
|
throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
|
|
}
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
|
|
if (!scope || scope.headers !== headers || scope.authorization === void 0 || headerValue(headers, "Authorization") !== scope.authorization) {
|
|
throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
|
|
}
|
|
__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_assertTenantHeaders).call(this, headers);
|
|
assertSafeHeaders(headers);
|
|
}
|
|
/** Returns a guarded final dispatcher while preserving all existing request hook object identities. */
|
|
fetch() {
|
|
return async (input, init = {}) => {
|
|
const target = assertX509APIOrigin(typeof input === "string" || input instanceof URL ? input : input.url);
|
|
assertX509FetchOptions(init);
|
|
this.assertRequest(init);
|
|
const approved = init.headers;
|
|
if (!(approved instanceof Headers)) {
|
|
throw new OpenAIError("X.509 workload identity must preserve its issued workload authorization.");
|
|
}
|
|
const headers = new Headers([...Headers.prototype.entries.call(approved)]);
|
|
assertSafeHeaders(headers);
|
|
init.headers = headers;
|
|
init.redirect = "manual";
|
|
return await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").dispatch(target, init);
|
|
};
|
|
}
|
|
};
|
|
_a = X509WorkloadIdentityAuth, _X509WorkloadIdentityAuth_identityProviderId = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_serviceAccountId = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_configuredRefreshBufferMs = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_configuredRefreshBufferSeconds = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_organization = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_project = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_transport = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_refreshBufferMs = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_cachedToken = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_refresh = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_tokenGeneration = /* @__PURE__ */ new WeakMap(), _X509WorkloadIdentityAuth_instances = /* @__PURE__ */ new WeakSet(), _X509WorkloadIdentityAuth_cancelRequestBody = async function _X509WorkloadIdentityAuth_cancelRequestBody2(body) {
|
|
try {
|
|
await CancelReadableStream(body);
|
|
} catch {
|
|
}
|
|
}, _X509WorkloadIdentityAuth_assignToken = function _X509WorkloadIdentityAuth_assignToken2(scope, token) {
|
|
if (scope) {
|
|
scope.token = token.accessToken;
|
|
scope.tokenGeneration = token.generation;
|
|
}
|
|
return token.accessToken;
|
|
}, _X509WorkloadIdentityAuth_recoverRefreshFailure = async function _X509WorkloadIdentityAuth_recoverRefreshFailure2(error, attempt, cached, scope, options, context) {
|
|
const callerSignal = context ? context.signal : options?.signal;
|
|
if (callerSignal?.aborted) {
|
|
throw userAbortError(callerSignal);
|
|
}
|
|
if (attempt.controller.signal.aborted && attempt.generation !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f")) {
|
|
return await this.getToken(options, context);
|
|
}
|
|
const fallback2 = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_fallbackToken).call(this, error, cached, scope);
|
|
if (fallback2 !== void 0) {
|
|
return fallback2;
|
|
}
|
|
if (error && typeof error === "object" && !(error instanceof OAuthError)) {
|
|
const oauth = findX509OAuthError2(error);
|
|
if (oauth) {
|
|
throw new OAuthError(oauth.status, oauth.error, oauth.headers);
|
|
}
|
|
}
|
|
throw error;
|
|
}, _X509WorkloadIdentityAuth_fallbackToken = function _X509WorkloadIdentityAuth_fallbackToken2(error, cached, scope) {
|
|
if (!cached || cached !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_cachedToken, "f") || performance.now() >= cached.expiresAt || Date.now() >= cached.wallExpiresAt || !_a.isRetryableFailure(error)) {
|
|
return void 0;
|
|
}
|
|
const headers = _a.retryHeaders(error);
|
|
const milliseconds = headers?.get("retry-after-ms");
|
|
let requested = milliseconds ? Number(milliseconds) : void 0;
|
|
const retryAfter = headers?.get("retry-after");
|
|
if (retryAfter && (requested === void 0 || Number.isNaN(requested))) {
|
|
const seconds = Number(retryAfter);
|
|
requested = Number.isNaN(seconds) ? Date.parse(retryAfter) - Date.now() : seconds * 1e3;
|
|
}
|
|
const cooldown = requested !== void 0 && Number.isFinite(requested) && requested >= 0 && requested <= 6e4 ? Math.max(FAILED_REFRESH_COOLDOWN_MS, requested) : FAILED_REFRESH_COOLDOWN_MS;
|
|
cached.refreshAt = Math.min(cached.expiresAt, performance.now() + cooldown);
|
|
cached.wallRefreshAt = Math.min(cached.wallExpiresAt, Date.now() + cooldown);
|
|
return __classPrivateFieldGet(_a, _a, "m", _X509WorkloadIdentityAuth_assignToken).call(_a, scope, cached);
|
|
}, _X509WorkloadIdentityAuth_retireRefresh = function _X509WorkloadIdentityAuth_retireRefresh2(attempt) {
|
|
if (attempt.waiters !== 0 || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f") !== attempt) {
|
|
return;
|
|
}
|
|
queueMicrotask(() => {
|
|
if (attempt.waiters === 0 && __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f") === attempt) {
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, void 0, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_tokenGeneration, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") + 1, "f");
|
|
attempt.controller.abort(new APIUserAbortError());
|
|
}
|
|
});
|
|
}, _X509WorkloadIdentityAuth_beginRefresh = function _X509WorkloadIdentityAuth_beginRefresh2() {
|
|
const controller = new AbortController();
|
|
const generation = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f");
|
|
const attempt = {
|
|
controller,
|
|
generation,
|
|
waiters: 0,
|
|
promise: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_instances, "m", _X509WorkloadIdentityAuth_refreshToken).call(this, controller, generation)
|
|
};
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, attempt, "f");
|
|
return attempt;
|
|
}, _X509WorkloadIdentityAuth_refreshToken = async function _X509WorkloadIdentityAuth_refreshToken2(controller, generation) {
|
|
const startedAt = performance.now();
|
|
const wallStartedAt = Date.now();
|
|
try {
|
|
const token = await __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").exchange(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_identityProviderId, "f"), __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_serviceAccountId, "f"), controller.signal);
|
|
const lifetime = token.expiresIn * 1e3;
|
|
const expiresAt = startedAt + lifetime;
|
|
const wallExpiresAt = wallStartedAt + lifetime;
|
|
if (performance.now() >= expiresAt || Date.now() >= wallExpiresAt) {
|
|
throw new OpenAIError("X.509 workload identity token expired before its exchange completed.");
|
|
}
|
|
if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") !== generation || controller.signal.aborted || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f")?.controller !== controller) {
|
|
throw new APIUserAbortError();
|
|
}
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_tokenGeneration, __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f") + 1, "f");
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_cachedToken, {
|
|
accessToken: token.accessToken,
|
|
generation: __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_tokenGeneration, "f"),
|
|
expiresAt,
|
|
refreshAt: expiresAt - Math.min(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refreshBufferMs, "f"), lifetime / 2),
|
|
wallExpiresAt,
|
|
wallRefreshAt: wallExpiresAt - Math.min(__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refreshBufferMs, "f"), lifetime / 2)
|
|
}, "f");
|
|
return token;
|
|
} finally {
|
|
if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_refresh, "f")?.controller === controller) {
|
|
__classPrivateFieldSet(this, _X509WorkloadIdentityAuth_refresh, void 0, "f");
|
|
}
|
|
}
|
|
}, _X509WorkloadIdentityAuth_preflight = function _X509WorkloadIdentityAuth_preflight2(context) {
|
|
if (!context) {
|
|
return;
|
|
}
|
|
if (context.organization !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") || context.project !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f")) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
|
|
}
|
|
assertX509APIOrigin(context.apiURL);
|
|
const supplied = buildHeaders([context.defaultHeaders, context.requestHeaders]);
|
|
if (__classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") !== null && supplied.nulls.has("openai-organization") || __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f") !== null && supplied.nulls.has("openai-project")) {
|
|
throw new OpenAIError("X.509 workload identity cannot omit its enrolled organization or project.");
|
|
}
|
|
for (const name of supplied.values.keys()) {
|
|
const canonical2 = name.toLowerCase().split("_").join("-");
|
|
if ((canonical2 === "openai-organization" || canonical2 === "openai-project") && (name !== canonical2 || headerValue(supplied.values, name) !== (canonical2 === "openai-organization" ? context.organization : context.project))) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
|
|
}
|
|
if (isSensitiveHeader(canonical2) || canonical2 === "host") {
|
|
throw new OpenAIError("X.509 workload identity cannot use caller-supplied authentication credentials.");
|
|
}
|
|
}
|
|
}, _X509WorkloadIdentityAuth_scope = function _X509WorkloadIdentityAuth_scope2() {
|
|
const scope = __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_transport, "f").current();
|
|
if (!scope || scope.owner !== this) {
|
|
throw new OpenAIError("X.509 workload identity requires an active certificate request scope.");
|
|
}
|
|
return scope;
|
|
}, _X509WorkloadIdentityAuth_assertTenantHeaders = function _X509WorkloadIdentityAuth_assertTenantHeaders2(headers) {
|
|
if (headerValue(headers, "OpenAI-Organization") !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_organization, "f") || headerValue(headers, "OpenAI-Project") !== __classPrivateFieldGet(this, _X509WorkloadIdentityAuth_project, "f")) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
|
|
}
|
|
for (const name of Headers.prototype.keys.call(headers)) {
|
|
const canonical2 = name.toLowerCase().split("_").join("-");
|
|
if ((canonical2 === "openai-organization" || canonical2 === "openai-project") && name !== canonical2) {
|
|
throw new OpenAIError("X.509 workload identity cannot override its enrolled organization or project.");
|
|
}
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/auth/x509-credential-options.mjs
|
|
function normalizeX509CredentialOptions(options) {
|
|
const { credential } = options;
|
|
if (credential === void 0) {
|
|
return { credential, options };
|
|
}
|
|
const registered = findX509Credential2(credential);
|
|
if (!registered) {
|
|
throw new OpenAIError("An X.509 credential must be created by the SDK authentication helper.");
|
|
}
|
|
const conflicting = ["apiKey", "adminAPIKey", "workloadIdentity", "x509Transport"].filter((name) => {
|
|
const value = options[name];
|
|
return value !== null && value !== void 0;
|
|
});
|
|
if (conflicting.length > 0) {
|
|
throw new OpenAIError(`The \`credential\` option cannot be combined with ${conflicting.map((name) => `\`${name}\``).join(", ")}.`);
|
|
}
|
|
return {
|
|
credential,
|
|
options: {
|
|
...options,
|
|
apiKey: null,
|
|
adminAPIKey: null,
|
|
baseURL: options.baseURL ?? null,
|
|
organization: options.organization ?? null,
|
|
project: options.project ?? null,
|
|
workloadIdentity: registered.identity,
|
|
x509Transport: registered.transport
|
|
}
|
|
};
|
|
}
|
|
function overridesOrdinaryAuthentication({ apiKey, adminAPIKey }) {
|
|
return apiKey !== null && apiKey !== void 0 || adminAPIKey !== null && adminAPIKey !== void 0;
|
|
}
|
|
function prepareProviderClone(inherited, overrides) {
|
|
const inheritedProvider = inherited.provider;
|
|
const replacingProvider = overrides.credential ?? overrides.workloadIdentity;
|
|
const provider2 = overrides.provider ?? (replacingProvider ? void 0 : inheritedProvider);
|
|
if (provider2 !== inheritedProvider) {
|
|
delete inherited.baseURL;
|
|
delete inherited.organization;
|
|
delete inherited.project;
|
|
delete inherited.defaultHeaders;
|
|
delete inherited.defaultQuery;
|
|
delete inherited.fetchOptions;
|
|
delete inherited.fetch;
|
|
}
|
|
if (provider2) {
|
|
delete inherited.apiKey;
|
|
delete inherited.adminAPIKey;
|
|
delete inherited.credential;
|
|
delete inherited.workloadIdentity;
|
|
delete inherited.x509Transport;
|
|
delete inherited.baseURL;
|
|
}
|
|
return provider2;
|
|
}
|
|
function prepareX509ClientClone(inherited, overrides, credential, currentlyX509) {
|
|
const nextIdentity = hasOwn(overrides, "workloadIdentity") ? overrides.workloadIdentity : inherited.workloadIdentity;
|
|
const dropping = credential !== void 0 && (overridesOrdinaryAuthentication(overrides) && overrides.workloadIdentity === void 0 || overrides.provider !== void 0);
|
|
if (credential !== void 0 && hasOwn(overrides, "workloadIdentity")) {
|
|
delete inherited.x509Transport;
|
|
}
|
|
const inheritedCredential = credential !== void 0 && !dropping && overrides.credential === void 0 && !hasOwn(overrides, "workloadIdentity") && !hasOwn(overrides, "x509Transport") ? credential : void 0;
|
|
const nextCredential = overrides.credential === void 0 ? inheritedCredential : overrides.credential;
|
|
const nextX509 = nextCredential !== void 0 || !dropping && isX509WorkloadIdentity(nextIdentity);
|
|
if (currentlyX509 !== nextX509) {
|
|
delete inherited.fetch;
|
|
delete inherited.baseURL;
|
|
delete inherited.organization;
|
|
delete inherited.project;
|
|
delete inherited.defaultHeaders;
|
|
delete inherited.defaultQuery;
|
|
delete inherited.fetchOptions;
|
|
if (nextX509) {
|
|
inherited.apiKey = null;
|
|
} else {
|
|
delete inherited.x509Transport;
|
|
if (dropping) {
|
|
delete inherited.workloadIdentity;
|
|
}
|
|
}
|
|
}
|
|
if (nextCredential !== void 0) {
|
|
delete inherited.apiKey;
|
|
delete inherited.adminAPIKey;
|
|
delete inherited.workloadIdentity;
|
|
delete inherited.x509Transport;
|
|
inherited.credential = nextCredential;
|
|
if (overrides.credential !== void 0) {
|
|
delete inherited.organization;
|
|
delete inherited.project;
|
|
delete inherited.defaultHeaders;
|
|
delete inherited.defaultQuery;
|
|
delete inherited.fetchOptions;
|
|
}
|
|
}
|
|
return { credential: nextCredential, provider: prepareProviderClone(inherited, overrides) };
|
|
}
|
|
var init_x509_credential_options = __esm({
|
|
"node_modules/openai/internal/auth/x509-credential-options.mjs"() {
|
|
init_error();
|
|
init_values();
|
|
init_x509_workload_identity_auth();
|
|
init_x509_transport_state();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/uploads.mjs
|
|
function toStreamingFile(data, name, options) {
|
|
if (typeof name !== "string" || !name) {
|
|
throw new TypeError("toStreamingFile requires a non-empty file name");
|
|
}
|
|
const type = options?.type;
|
|
if (type) {
|
|
validateStreamingFileType(type);
|
|
}
|
|
return {
|
|
[brand_privateStreamingFile]: true,
|
|
data,
|
|
name,
|
|
...type ? { type } : {}
|
|
};
|
|
}
|
|
function makeFile(fileBits, fileName, options) {
|
|
checkFileSupport();
|
|
return new File(fileBits, fileName ?? "unknown_file", options);
|
|
}
|
|
function getName(value, options) {
|
|
if (typeof value !== "object" || value === null) {
|
|
return void 0;
|
|
}
|
|
const name = "name" in value ? value.name : void 0;
|
|
const explicitName = name && String(name) || "filename" in value && value.filename && String(value.filename);
|
|
if (explicitName) {
|
|
return options?.stripFilename === false ? normalizeFilenamePath(explicitName) : basename(explicitName);
|
|
}
|
|
const url = "url" in value && value.url && String(value.url);
|
|
if (url) {
|
|
try {
|
|
return basename(new URL(url).pathname);
|
|
} catch {
|
|
return basename(url);
|
|
}
|
|
}
|
|
const path4 = "path" in value && value.path && String(value.path);
|
|
return path4 ? basename(path4) : void 0;
|
|
}
|
|
function basename(value) {
|
|
return value.split(/[\\/]/).pop() || void 0;
|
|
}
|
|
function normalizeFilenamePath(value) {
|
|
const normalized = value.replace(/\\/g, "/");
|
|
if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized) || normalized.split("/").includes("..")) {
|
|
throw new TypeError("Upload file name must be a safe relative path without parent directory segments");
|
|
}
|
|
return normalized;
|
|
}
|
|
function isArrayBuffer(value) {
|
|
try {
|
|
return arrayBufferByteLengthGetter?.call(value) !== void 0;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
function supportsFormData(fetchObject) {
|
|
const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
|
|
const cached = supportsFormDataMap.get(fetch2);
|
|
if (cached) {
|
|
return cached;
|
|
}
|
|
const promise = (async () => {
|
|
try {
|
|
let FetchResponse;
|
|
if ("Response" in fetch2) {
|
|
FetchResponse = fetch2.Response;
|
|
} else {
|
|
const response = await fetch2("data:,");
|
|
await response.arrayBuffer();
|
|
FetchResponse = response.constructor;
|
|
}
|
|
const data = new FormData();
|
|
if (data.toString() === await new FetchResponse(data).text()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
} catch {
|
|
return true;
|
|
}
|
|
})();
|
|
supportsFormDataMap.set(fetch2, promise);
|
|
return promise;
|
|
}
|
|
async function* iterateMultipartBody(entries, boundary, options, preservedFilenames) {
|
|
for await (const { key, value } of entries) {
|
|
if (isUploadable(value)) {
|
|
const filename = preservedFilenames?.get(value) ?? getStreamingFileName(value, options);
|
|
const type = getStreamingFileType(value);
|
|
yield encodeUTF8(`--${boundary}\r
|
|
`);
|
|
yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"; filename="${escapeHeaderValue(filename)}"\r
|
|
Content-Type: ${type}\r
|
|
\r
|
|
`);
|
|
yield* iterateBytes(getStreamingFileData(value));
|
|
} else {
|
|
yield encodeUTF8(`--${boundary}\r
|
|
`);
|
|
yield encodeUTF8(`Content-Disposition: form-data; name="${escapeHeaderValue(key)}"\r
|
|
\r
|
|
${String(value)}`);
|
|
}
|
|
yield encodeUTF8("\r\n");
|
|
}
|
|
yield encodeUTF8(`--${boundary}--\r
|
|
`);
|
|
}
|
|
function* iterateFormEntries(body) {
|
|
if (!body || typeof body !== "object") {
|
|
return;
|
|
}
|
|
for (const [key, value] of Object.entries(body)) {
|
|
yield* iterateFormValue(key, value);
|
|
}
|
|
}
|
|
function* iterateFormValue(key, value) {
|
|
if (value === void 0) {
|
|
return;
|
|
}
|
|
if (value == null) {
|
|
throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
|
|
}
|
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || isUploadable(value)) {
|
|
yield { key, value };
|
|
} else if (Array.isArray(value)) {
|
|
for (const entry of value) {
|
|
yield* iterateFormValue(key + "[]", entry);
|
|
}
|
|
} else if (typeof value === "object") {
|
|
for (const [name, prop] of Object.entries(value)) {
|
|
yield* iterateFormValue(`${key}[${name}]`, prop);
|
|
}
|
|
} else {
|
|
throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
|
|
}
|
|
}
|
|
function getStreamingFileName(value, options) {
|
|
if (isStreamingFile(value)) {
|
|
const { name } = value;
|
|
if (typeof name !== "string" || !name) {
|
|
throw new TypeError("Streaming upload file name must be a non-empty string");
|
|
}
|
|
return options.stripFilenames === false ? normalizeFilenamePath(name) : basename(name) ?? "unknown_file";
|
|
}
|
|
return getName(value, { stripFilename: options.stripFilenames }) ?? "unknown_file";
|
|
}
|
|
function getStreamingFileType(value) {
|
|
let type;
|
|
if (isStreamingFile(value) || isBlob(value)) {
|
|
({ type } = value);
|
|
} else if (value instanceof Response) {
|
|
type = value.headers.get("content-type") ?? void 0;
|
|
}
|
|
return validateStreamingFileType(type || "application/octet-stream");
|
|
}
|
|
function validateStreamingFileType(type) {
|
|
if (typeof type !== "string") {
|
|
throw new TypeError("Streaming upload content type must be a string");
|
|
}
|
|
for (let index = 0; index < type.length; index += 1) {
|
|
const character = type.codePointAt(index) ?? 0;
|
|
if (character <= 31 || character === 127) {
|
|
throw new TypeError("Streaming upload content type must not contain control characters");
|
|
}
|
|
}
|
|
return type;
|
|
}
|
|
function getStreamingFileData(value) {
|
|
if (isStreamingFile(value)) {
|
|
return value.data;
|
|
}
|
|
return value;
|
|
}
|
|
async function* iterateBytes(value) {
|
|
if (typeof value === "string") {
|
|
yield encodeUTF8(value);
|
|
} else if (ArrayBuffer.isView(value)) {
|
|
yield new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
|
|
} else if (isArrayBuffer(value)) {
|
|
yield new Uint8Array(value);
|
|
} else if (value instanceof Response) {
|
|
yield* iterateBytes(value.body || await value.blob());
|
|
} else if (value instanceof Blob) {
|
|
if (typeof value.stream === "function") {
|
|
yield* iterateBytes(value.stream());
|
|
} else {
|
|
yield new Uint8Array(await value.arrayBuffer());
|
|
}
|
|
} else if (isReadableStream(value)) {
|
|
for await (const chunk of ReadableStreamToAsyncIterable(value)) {
|
|
yield* iterateBytes(chunk);
|
|
}
|
|
} else if (isAsyncIterable(value)) {
|
|
for await (const chunk of value) {
|
|
yield* iterateBytes(chunk);
|
|
}
|
|
} else {
|
|
throw new TypeError(`Invalid streaming file chunk: ${String(value)}`);
|
|
}
|
|
}
|
|
function escapeHeaderValue(value) {
|
|
return Array.from(value, (character) => {
|
|
const codePoint = character.codePointAt(0) ?? 0;
|
|
return codePoint <= 31 || codePoint === 127 || character === '"' || character === "\\" ? encodeURIComponent(character) : character;
|
|
}).join("");
|
|
}
|
|
var brand_privateStreamingFile, checkFileSupport, arrayBufferByteLengthGetter, isAsyncIterable, maybeMultipartFormRequestOptions, multipartFormRequestOptions, supportsFormDataMap, createForm, isBlob, isReadableStream, isStreamingFile, isUploadable, hasStreamingUploadableValue, hasUploadableValue, snapshotPreservedUploadEntries, createStreamingFormRequestOptions, addFormValue;
|
|
var init_uploads = __esm({
|
|
"node_modules/openai/internal/uploads.mjs"() {
|
|
init_headers2();
|
|
init_shims();
|
|
init_bytes();
|
|
brand_privateStreamingFile = /* @__PURE__ */ Symbol("brand.privateStreamingFile");
|
|
checkFileSupport = () => {
|
|
if (typeof File === "undefined") {
|
|
const { process: process2 } = globalThis;
|
|
const isOldNode = typeof process2?.versions?.node === "string" && Number.parseInt(process2.versions.node.split("."), 10) < 20;
|
|
throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`." : ""));
|
|
}
|
|
};
|
|
arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get;
|
|
isAsyncIterable = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
|
|
maybeMultipartFormRequestOptions = async (opts, fetch2, formOptions) => {
|
|
if (!hasUploadableValue(opts.body)) {
|
|
return opts;
|
|
}
|
|
if (hasStreamingUploadableValue(opts.body)) {
|
|
return createStreamingFormRequestOptions(opts, formOptions);
|
|
}
|
|
return { ...opts, body: await createForm(opts.body, fetch2, formOptions) };
|
|
};
|
|
multipartFormRequestOptions = async (opts, fetch2, formOptions) => {
|
|
if (hasStreamingUploadableValue(opts.body)) {
|
|
return createStreamingFormRequestOptions(opts, formOptions);
|
|
}
|
|
return { ...opts, body: await createForm(opts.body, fetch2, formOptions) };
|
|
};
|
|
supportsFormDataMap = /* @__PURE__ */ new WeakMap();
|
|
createForm = async (body, fetch2, options = {}) => {
|
|
if (!await supportsFormData(fetch2)) {
|
|
throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
|
|
}
|
|
const form = new FormData();
|
|
await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value, options)));
|
|
return form;
|
|
};
|
|
isBlob = (value) => value instanceof Blob;
|
|
isReadableStream = (value) => typeof value === "object" && value !== null && "getReader" in value && typeof value.getReader === "function";
|
|
isStreamingFile = (value) => typeof value === "object" && value !== null && brand_privateStreamingFile in value;
|
|
isUploadable = (value) => typeof value === "object" && value !== null && (value instanceof Response || isAsyncIterable(value) || isReadableStream(value) || isStreamingFile(value) || isBlob(value));
|
|
hasStreamingUploadableValue = (value) => {
|
|
if (isStreamingFile(value) || isAsyncIterable(value) || isReadableStream(value)) {
|
|
return true;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value.some(hasStreamingUploadableValue);
|
|
}
|
|
if (value && typeof value === "object" && !isBlob(value) && !(value instanceof Response)) {
|
|
for (const k of Object.keys(value)) {
|
|
if (hasStreamingUploadableValue(value[k])) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
};
|
|
hasUploadableValue = (value) => {
|
|
if (isUploadable(value)) {
|
|
return true;
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value.some(hasUploadableValue);
|
|
}
|
|
if (value && typeof value === "object") {
|
|
for (const k of Object.keys(value)) {
|
|
if (hasUploadableValue(value[k])) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
};
|
|
snapshotPreservedUploadEntries = (entries, filenames) => {
|
|
const snapshot = [];
|
|
for (const entry of entries) {
|
|
if (isUploadable(entry.value) && !filenames.has(entry.value)) {
|
|
filenames.set(entry.value, getStreamingFileName(entry.value, { stripFilenames: false }));
|
|
}
|
|
snapshot.push(entry);
|
|
}
|
|
return snapshot;
|
|
};
|
|
createStreamingFormRequestOptions = (opts, options = {}) => {
|
|
const entries = iterateFormEntries(opts.body);
|
|
const preservedFilenames = options.stripFilenames === false ? /* @__PURE__ */ new WeakMap() : void 0;
|
|
const multipartEntries = preservedFilenames ? snapshotPreservedUploadEntries(entries, preservedFilenames) : entries;
|
|
const boundary = `openai-${Math.random().toString(36).slice(2)}`;
|
|
const body = ReadableStreamFrom(iterateMultipartBody(multipartEntries, boundary, options, preservedFilenames));
|
|
return {
|
|
...opts,
|
|
body,
|
|
headers: buildHeaders([{ "content-type": `multipart/form-data; boundary=${boundary}` }, opts.headers])
|
|
};
|
|
};
|
|
addFormValue = async (form, key, value, options) => {
|
|
if (value === void 0) {
|
|
return;
|
|
}
|
|
if (value == null) {
|
|
throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
|
|
}
|
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
form.append(key, String(value));
|
|
} else if (value instanceof Response) {
|
|
const blob = await value.blob();
|
|
form.append(key, makeFile([blob], getName(value, { stripFilename: options.stripFilenames }), { type: blob.type }));
|
|
} else if (isAsyncIterable(value)) {
|
|
form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value, { stripFilename: options.stripFilenames })));
|
|
} else if (isBlob(value)) {
|
|
const filename = getName(value, { stripFilename: options.stripFilenames });
|
|
if (filename === void 0) {
|
|
form.append(key, value);
|
|
} else {
|
|
form.append(key, value, filename);
|
|
}
|
|
} else if (Array.isArray(value)) {
|
|
const entries = await Promise.all(value.map(async (entry) => {
|
|
const entryForm = new FormData();
|
|
await addFormValue(entryForm, key + "[]", entry, options);
|
|
return entryForm;
|
|
}));
|
|
for (const entryForm of entries) {
|
|
if (!entryForm) {
|
|
continue;
|
|
}
|
|
for (const [entryKey, entryValue] of entryForm.entries()) {
|
|
form.append(entryKey, entryValue);
|
|
}
|
|
}
|
|
} else if (typeof value === "object") {
|
|
await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop, options)));
|
|
} else {
|
|
throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/to-file.mjs
|
|
async function toFile(value, name, options) {
|
|
checkFileSupport();
|
|
value = await value;
|
|
if (isFileLike(value)) {
|
|
const fileOptions = {
|
|
...options,
|
|
type: options?.type ?? value.type,
|
|
lastModified: options?.lastModified ?? value.lastModified
|
|
};
|
|
if (value instanceof File) {
|
|
if (canReuseNativeFile(value, name, options)) {
|
|
return value;
|
|
}
|
|
return makeFile([value], name ?? value.name, fileOptions);
|
|
}
|
|
return makeFile([await value.arrayBuffer()], name ?? value.name, fileOptions);
|
|
}
|
|
if (isResponseLike(value)) {
|
|
const blob = await value.blob();
|
|
name ?? (name = getName(value));
|
|
const responseOptions = options?.type === void 0 && blob.type ? { ...options, type: blob.type } : options;
|
|
return makeFile(await getBytes(blob), name, responseOptions);
|
|
}
|
|
const parts = await getBytes(value);
|
|
name ?? (name = getName(value));
|
|
if (options?.type === void 0) {
|
|
const typedPart = parts.find((part) => typeof part === "object" && "type" in part && !!part.type);
|
|
if (typedPart) {
|
|
options = { ...options, type: typedPart.type };
|
|
}
|
|
}
|
|
return makeFile(parts, name, options);
|
|
}
|
|
async function getBytes(value) {
|
|
const parts = [];
|
|
if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
|
|
isArrayBuffer(value)) {
|
|
parts.push(value);
|
|
} else if (isBlobLike(value)) {
|
|
parts.push(value instanceof Blob ? value : new Blob([await value.arrayBuffer()], { type: value.type }));
|
|
} else if (isAsyncIterable(value)) {
|
|
for await (const chunk of value) {
|
|
parts.push(...await getBytes(chunk));
|
|
}
|
|
} else {
|
|
const constructor = value?.constructor?.name;
|
|
throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError(value)}`);
|
|
}
|
|
return parts;
|
|
}
|
|
function propsForError(value) {
|
|
if (typeof value !== "object" || value === null) {
|
|
return "";
|
|
}
|
|
const props = Object.getOwnPropertyNames(value);
|
|
return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`;
|
|
}
|
|
var isBlobLike, isFileLike, isResponseLike, hasFilePropertyOverrides, canReuseNativeFile;
|
|
var init_to_file = __esm({
|
|
"node_modules/openai/internal/to-file.mjs"() {
|
|
init_uploads();
|
|
isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
|
|
isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value);
|
|
isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
|
|
hasFilePropertyOverrides = (value, options) => options?.type != null && options.type !== value.type || options?.lastModified != null && options.lastModified !== value.lastModified || options?.endings != null;
|
|
canReuseNativeFile = (value, name, options) => (name == null || name === value.name) && !hasFilePropertyOverrides(value, options);
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/core/uploads.mjs
|
|
var init_uploads2 = __esm({
|
|
"node_modules/openai/core/uploads.mjs"() {
|
|
init_uploads();
|
|
init_to_file();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/core/resource.mjs
|
|
var APIResource;
|
|
var init_resource = __esm({
|
|
"node_modules/openai/core/resource.mjs"() {
|
|
APIResource = class {
|
|
constructor(client) {
|
|
this._client = client;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/path.mjs
|
|
function encodeURIPath(str2) {
|
|
return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
|
|
}
|
|
var EMPTY, createPathTagFunction, path;
|
|
var init_path = __esm({
|
|
"node_modules/openai/internal/utils/path.mjs"() {
|
|
init_error();
|
|
EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
createPathTagFunction = (pathEncoder = encodeURIPath) => function path4(statics, ...params) {
|
|
if (statics.length === 1) {
|
|
return statics[0];
|
|
}
|
|
let postPath = false;
|
|
const invalidSegments = [];
|
|
let path5 = "";
|
|
for (let index = 0; index < statics.length; index += 1) {
|
|
if (index in statics) {
|
|
const currentValue = statics[index];
|
|
if (/[?#]/.test(currentValue)) {
|
|
postPath = true;
|
|
}
|
|
const value = params[index];
|
|
let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
|
|
if (index !== params.length && (value == null || // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Path parameters may arrive from JavaScript callers and require runtime validation before URL encoding.
|
|
typeof value === "object" && // handle values from other realms
|
|
value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY)?.toString)) {
|
|
encoded = value + "";
|
|
invalidSegments.push({
|
|
start: path5.length + currentValue.length,
|
|
length: encoded.length,
|
|
error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
|
|
});
|
|
}
|
|
path5 += currentValue + (index === params.length ? "" : encoded);
|
|
}
|
|
}
|
|
const pathOnly = path5.split(/[?#]/, 1)[0];
|
|
const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
|
|
let match;
|
|
while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
|
|
invalidSegments.push({
|
|
start: match.index,
|
|
length: match[0].length,
|
|
error: `Value "${match[0]}" can't be safely passed as a path parameter`
|
|
});
|
|
}
|
|
invalidSegments.sort((a, b) => a.start - b.start);
|
|
if (invalidSegments.length > 0) {
|
|
let lastEnd = 0;
|
|
let underline = "";
|
|
for (const segment of invalidSegments) {
|
|
const spaces = " ".repeat(segment.start - lastEnd);
|
|
const arrows = "^".repeat(segment.length);
|
|
lastEnd = segment.start + segment.length;
|
|
underline += spaces + arrows;
|
|
}
|
|
throw new OpenAIError(`Path parameters result in path with invalid segments:
|
|
${invalidSegments.map((e) => e.error).join("\n")}
|
|
${path5}
|
|
${underline}`);
|
|
}
|
|
return path5;
|
|
};
|
|
path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/chat/completions/messages.mjs
|
|
var Messages;
|
|
var init_messages = __esm({
|
|
"node_modules/openai/resources/chat/completions/messages.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Messages = class extends APIResource {
|
|
/**
|
|
* Get the messages in a stored chat completion. Only Chat Completions that have
|
|
* been created with the `store` parameter set to `true` will be returned.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const chatCompletionStoreMessage of client.chat.completions.messages.list(
|
|
* 'completion_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(completionID, query = {}, options) {
|
|
return this._client.getAPIList(path`/chat/completions/${completionID}/messages`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/error.mjs
|
|
var init_error2 = __esm({
|
|
"node_modules/openai/error.mjs"() {
|
|
init_error();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/parser.mjs
|
|
function isChatCompletionFunctionTool(tool) {
|
|
return tool !== void 0 && "function" in tool && tool.function !== void 0;
|
|
}
|
|
function isAutoParsableResponseFormat(response_format) {
|
|
return response_format?.["$brand"] === "auto-parseable-response-format";
|
|
}
|
|
function isParseableResponseFormat(format) {
|
|
return isAutoParsableResponseFormat(format) || format?.type === "json_schema";
|
|
}
|
|
function parseResponseFormatContent(format, content) {
|
|
if (!isParseableResponseFormat(format)) {
|
|
return null;
|
|
}
|
|
if (typeof format === "object" && format !== null && "$parseRaw" in format && typeof format.$parseRaw === "function") {
|
|
return format.$parseRaw(content);
|
|
}
|
|
try {
|
|
return JSON.parse(content);
|
|
} catch (error) {
|
|
if (error instanceof SyntaxError) {
|
|
throw new SyntaxError("Error reading response: invalid structured output JSON.");
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
function isAutoParsableTool(tool) {
|
|
return tool?.["$brand"] === "auto-parseable-tool";
|
|
}
|
|
function maybeParseChatCompletion(completion, params) {
|
|
if (!params || !hasAutoParseableInput(params)) {
|
|
return {
|
|
...completion,
|
|
choices: completion.choices.map((choice) => ({
|
|
...choice,
|
|
message: {
|
|
...choice.message,
|
|
parsed: null,
|
|
...choice.message.tool_calls ? {
|
|
tool_calls: choice.message.tool_calls
|
|
} : void 0
|
|
}
|
|
}))
|
|
};
|
|
}
|
|
return parseChatCompletion(completion, params);
|
|
}
|
|
function parseChatCompletion(completion, params) {
|
|
const choices = completion.choices.map((choice) => {
|
|
if (choice.finish_reason === "length") {
|
|
throw new LengthFinishReasonError();
|
|
}
|
|
if (choice.finish_reason === "content_filter") {
|
|
throw new ContentFilterFinishReasonError();
|
|
}
|
|
return {
|
|
...choice,
|
|
message: {
|
|
...choice.message,
|
|
...choice.message.tool_calls ? {
|
|
tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? void 0
|
|
} : void 0,
|
|
parsed: choice.message.content !== null && choice.message.content !== void 0 && !choice.message.refusal && (choice.message.content !== "" || !choice.message.tool_calls?.length && !choice.message.function_call) ? parseResponseFormat(params, choice.message.content) : null
|
|
}
|
|
};
|
|
});
|
|
return { ...completion, choices };
|
|
}
|
|
function parseResponseFormat(params, content) {
|
|
return parseResponseFormatContent(params.response_format, content);
|
|
}
|
|
function parseToolCall(params, toolCall) {
|
|
if (toolCall.type === "custom") {
|
|
return toolCall;
|
|
}
|
|
if (toolCall.type !== "function") {
|
|
const unsupportedType = toolCall.type;
|
|
throw new OpenAIError(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${unsupportedType}\``);
|
|
}
|
|
const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function.name);
|
|
let parsedArguments = null;
|
|
if (isAutoParsableTool(inputTool)) {
|
|
parsedArguments = inputTool.$parseRaw(toolCall.function.arguments);
|
|
} else if (inputTool?.function.strict) {
|
|
parsedArguments = parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, toolCall.function.arguments);
|
|
}
|
|
return {
|
|
...toolCall,
|
|
function: {
|
|
...toolCall.function,
|
|
parsed_arguments: parsedArguments
|
|
}
|
|
};
|
|
}
|
|
function shouldParseToolCall(params, toolCall) {
|
|
if (!params || !("tools" in params) || !params.tools || toolCall.type !== "function") {
|
|
return false;
|
|
}
|
|
const inputTool = params.tools?.find((inputTool2) => isChatCompletionFunctionTool(inputTool2) && inputTool2.function?.name === toolCall.function?.name);
|
|
return isChatCompletionFunctionTool(inputTool) && (isAutoParsableTool(inputTool) || inputTool?.function.strict || false);
|
|
}
|
|
function hasAutoParseableInput(params) {
|
|
if (isParseableResponseFormat(params.response_format)) {
|
|
return true;
|
|
}
|
|
return params.tools?.some((t) => isAutoParsableTool(t) || t.type === "function" && t.function.strict === true) ?? false;
|
|
}
|
|
function validateInputTools(tools) {
|
|
for (const tool of tools ?? []) {
|
|
if (tool.type === "custom") {
|
|
continue;
|
|
}
|
|
if (tool.type !== "function") {
|
|
const unsupportedType = tool.type;
|
|
throw new OpenAIError(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${unsupportedType}\``);
|
|
}
|
|
if (tool.function.strict !== true) {
|
|
throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`);
|
|
}
|
|
}
|
|
}
|
|
var init_parser = __esm({
|
|
"node_modules/openai/lib/parser.mjs"() {
|
|
init_error2();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/chatCompletionUtils.mjs
|
|
var isAssistantMessage, isToolMessage;
|
|
var init_chatCompletionUtils = __esm({
|
|
"node_modules/openai/lib/chatCompletionUtils.mjs"() {
|
|
isAssistantMessage = (message) => message?.role === "assistant";
|
|
isToolMessage = (message) => message?.role === "tool";
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/EventStream.mjs
|
|
function captureNativeProxyDetector() {
|
|
if (typeof process === "undefined") {
|
|
return void 0;
|
|
}
|
|
try {
|
|
const loader = Object.getOwnPropertyDescriptor(process, "getBuiltinModule");
|
|
if (!loader || !("value" in loader) || typeof loader.value !== "function") {
|
|
return void 0;
|
|
}
|
|
const util2 = Reflect.apply(loader.value, process, ["node:util"]);
|
|
if (typeof util2 !== "object" || util2 === null) {
|
|
return void 0;
|
|
}
|
|
const types = Object.getOwnPropertyDescriptor(util2, "types");
|
|
if (!types || !("value" in types) || typeof types.value !== "object" || types.value === null) {
|
|
return void 0;
|
|
}
|
|
const detector = Object.getOwnPropertyDescriptor(types.value, "isProxy");
|
|
if (!detector || !("value" in detector) || typeof detector.value !== "function") {
|
|
return void 0;
|
|
}
|
|
return detector.value;
|
|
} catch {
|
|
return void 0;
|
|
}
|
|
}
|
|
function rememberTrustedIntrinsic(constructor) {
|
|
if (typeof constructor !== "function") {
|
|
return;
|
|
}
|
|
const prototypeDescriptor = Object.getOwnPropertyDescriptor(constructor, "prototype");
|
|
if (!prototypeDescriptor || !("value" in prototypeDescriptor) || typeof prototypeDescriptor.value !== "object" && typeof prototypeDescriptor.value !== "function") {
|
|
return;
|
|
}
|
|
trustedIntrinsicPrototypes.add(prototypeDescriptor.value);
|
|
const source = functionToString.call(constructor);
|
|
if (/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(source) && prototypeDescriptor.configurable === false && prototypeDescriptor.writable === false) {
|
|
trustedNativeConstructorSources.add(source);
|
|
const descriptors = /* @__PURE__ */ new Map();
|
|
for (const key of Reflect.ownKeys(prototypeDescriptor.value)) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(prototypeDescriptor.value, key);
|
|
if (descriptor) {
|
|
descriptors.set(key, descriptor);
|
|
}
|
|
}
|
|
canonicalIntrinsicDescriptors.set(source, descriptors);
|
|
}
|
|
}
|
|
function getTrustedForeignIntrinsic(prototype) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, "constructor");
|
|
if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "function") {
|
|
return void 0;
|
|
}
|
|
const constructor = descriptor.value;
|
|
const source = functionToString.call(constructor);
|
|
const descriptors = canonicalIntrinsicDescriptors.get(source);
|
|
if (!trustedNativeConstructorSources.has(source) || !descriptors) {
|
|
return void 0;
|
|
}
|
|
const constructorPrototype = Object.getOwnPropertyDescriptor(constructor, "prototype");
|
|
if (!constructorPrototype || !("value" in constructorPrototype) || constructorPrototype.value !== prototype || constructorPrototype.configurable !== false || constructorPrototype.writable !== false) {
|
|
return void 0;
|
|
}
|
|
return { constructor, descriptors, functionPrototype: Object.getPrototypeOf(constructor) };
|
|
}
|
|
function isTrustedIntrinsicPrototype(prototype) {
|
|
return trustedIntrinsicPrototypes.has(prototype) || getTrustedForeignIntrinsic(prototype) !== void 0;
|
|
}
|
|
function isCanonicalIntrinsicFunction(value, canonical2, functionPrototype) {
|
|
if (canonical2 === void 0) {
|
|
return value === void 0;
|
|
}
|
|
if (typeof value !== "function" || typeof canonical2 !== "function") {
|
|
return false;
|
|
}
|
|
const source = functionToString.call(canonical2);
|
|
if (functionToString.call(value) !== source) {
|
|
return false;
|
|
}
|
|
const actualFunctionPrototype = Object.getPrototypeOf(value);
|
|
if (actualFunctionPrototype === functionPrototype) {
|
|
return true;
|
|
}
|
|
if (!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(source)) {
|
|
return false;
|
|
}
|
|
const intrinsic = getTrustedForeignIntrinsic(actualFunctionPrototype);
|
|
return intrinsic !== void 0 && functionToString.call(intrinsic.constructor) === nativeFunctionConstructorSource;
|
|
}
|
|
function isCanonicalIntrinsicDescriptor(descriptor, canonical2, functionPrototype) {
|
|
if (!canonical2 || descriptor.configurable !== canonical2.configurable || descriptor.enumerable !== canonical2.enumerable || "value" in descriptor !== "value" in canonical2) {
|
|
return false;
|
|
}
|
|
if ("value" in descriptor && "value" in canonical2) {
|
|
if (descriptor.writable !== canonical2.writable) {
|
|
return false;
|
|
}
|
|
if (typeof canonical2.value === "function") {
|
|
return isCanonicalIntrinsicFunction(descriptor.value, canonical2.value, functionPrototype);
|
|
}
|
|
if (canonical2.value !== null && typeof canonical2.value === "object") {
|
|
return false;
|
|
}
|
|
return Object.is(descriptor.value, canonical2.value);
|
|
}
|
|
return isCanonicalIntrinsicFunction(descriptor.get, canonical2.get, functionPrototype) && isCanonicalIntrinsicFunction(descriptor.set, canonical2.set, functionPrototype);
|
|
}
|
|
function hasNativeErrorBrand(current) {
|
|
if (nativeErrorBrand) {
|
|
return nativeErrorBrand.call(Error, current);
|
|
}
|
|
let prototype = current;
|
|
for (let depth = 0; prototype !== null && depth < MAX_BUFFERED_EVENT_DEPTH; depth += 1) {
|
|
if (Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag)) {
|
|
return false;
|
|
}
|
|
prototype = Object.getPrototypeOf(prototype);
|
|
}
|
|
return prototype === null && objectToString.call(current) === "[object Error]";
|
|
}
|
|
function getVerifiedForeignErrorConstructor(current, stackDescriptor) {
|
|
if (typeof stackDescriptor.get !== "function" || typeof stackDescriptor.set !== "function") {
|
|
return void 0;
|
|
}
|
|
let prototype = Object.getPrototypeOf(current);
|
|
for (let depth = 0; prototype !== null && depth < MAX_BUFFERED_EVENT_DEPTH; depth += 1) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, "constructor");
|
|
if (descriptor && "value" in descriptor && typeof descriptor.value === "function") {
|
|
const constructor = descriptor.value;
|
|
if (functionToString.call(constructor) === nativeErrorConstructorSource && isTrustedIntrinsicPrototype(prototype)) {
|
|
const functionPrototype = Object.getPrototypeOf(constructor);
|
|
if (Object.getPrototypeOf(stackDescriptor.get) === functionPrototype && Object.getPrototypeOf(stackDescriptor.set) === functionPrototype) {
|
|
return { constructor, prototype };
|
|
}
|
|
return void 0;
|
|
}
|
|
}
|
|
prototype = Object.getPrototypeOf(prototype);
|
|
}
|
|
return void 0;
|
|
}
|
|
function isTrustedNativeErrorStack(current, descriptor) {
|
|
if (!hasNativeErrorBrand(current)) {
|
|
return false;
|
|
}
|
|
if (errorStackDescriptor && !("value" in errorStackDescriptor) && typeof errorStackDescriptor.get === "function" && Object.prototype.isPrototypeOf.call(Error.prototype, current) && descriptor.get === errorStackDescriptor.get && descriptor.set === errorStackDescriptor.set) {
|
|
return true;
|
|
}
|
|
const verified = getVerifiedForeignErrorConstructor(current, descriptor);
|
|
if (!verified) {
|
|
return false;
|
|
}
|
|
let canonicalDescriptor = foreignErrorStackDescriptors.get(verified.prototype);
|
|
if (!canonicalDescriptor) {
|
|
const canonical2 = Reflect.construct(verified.constructor, []);
|
|
if (typeof canonical2 !== "object" || canonical2 === null || !hasNativeErrorBrand(canonical2) || Object.getPrototypeOf(canonical2) !== verified.prototype) {
|
|
return false;
|
|
}
|
|
canonicalDescriptor = Object.getOwnPropertyDescriptor(canonical2, "stack");
|
|
if (!canonicalDescriptor || "value" in canonicalDescriptor || typeof canonicalDescriptor.get !== "function" || typeof canonicalDescriptor.set !== "function") {
|
|
return false;
|
|
}
|
|
foreignErrorStackDescriptors.set(verified.prototype, canonicalDescriptor);
|
|
}
|
|
return descriptor.get === canonicalDescriptor.get && descriptor.set === canonicalDescriptor.set;
|
|
}
|
|
function createEventQueue() {
|
|
let entries = [];
|
|
let head = 0;
|
|
return {
|
|
get length() {
|
|
return entries.length - head;
|
|
},
|
|
enqueue(value) {
|
|
entries.push(value);
|
|
},
|
|
dequeue() {
|
|
if (head === entries.length) {
|
|
return void 0;
|
|
}
|
|
const value = entries[head];
|
|
entries[head] = void 0;
|
|
head += 1;
|
|
if (head === entries.length) {
|
|
entries = [];
|
|
head = 0;
|
|
} else if (head >= 1024 && head * 2 >= entries.length) {
|
|
entries = entries.slice(head);
|
|
head = 0;
|
|
}
|
|
return value;
|
|
},
|
|
clear() {
|
|
entries = [];
|
|
head = 0;
|
|
}
|
|
};
|
|
}
|
|
function getRetainedStorageBrand(current) {
|
|
let prototype = Object.getPrototypeOf(current);
|
|
for (let depth = 0; prototype !== null && depth < MAX_BUFFERED_EVENT_DEPTH; depth += 1) {
|
|
if (prototype === Date.prototype) {
|
|
return "Date";
|
|
}
|
|
if (!trustedIntrinsicPrototypes.has(prototype)) {
|
|
const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor");
|
|
if (constructor && "value" in constructor && typeof constructor.value === "function" && functionToString.call(constructor.value) === nativeDateConstructorSource && getTrustedForeignIntrinsic(prototype)) {
|
|
return "Date";
|
|
}
|
|
}
|
|
const descriptor = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag);
|
|
if (descriptor && "value" in descriptor && typeof descriptor.value === "string" && retainedStorageBrands.has(descriptor.value)) {
|
|
return descriptor.value;
|
|
}
|
|
prototype = Object.getPrototypeOf(prototype);
|
|
}
|
|
return void 0;
|
|
}
|
|
function estimateRetainedBufferBytes(current, visit3, depth) {
|
|
if (ArrayBuffer.isView(current)) {
|
|
let buffer;
|
|
let kind2 = "typed-array";
|
|
try {
|
|
buffer = typedArrayBufferGetter?.call(current);
|
|
} catch {
|
|
kind2 = "data-view";
|
|
buffer = dataViewBufferGetter?.call(current);
|
|
}
|
|
if (typeof buffer !== "object" || buffer === null) {
|
|
return { bytes: Number.POSITIVE_INFINITY, kind: kind2 };
|
|
}
|
|
visit3(buffer, depth + 1);
|
|
return { bytes: 0, kind: kind2 };
|
|
}
|
|
const brand = getRetainedStorageBrand(current);
|
|
if (!brand) {
|
|
return void 0;
|
|
}
|
|
let getter;
|
|
const kind = "buffer";
|
|
switch (brand) {
|
|
case "ArrayBuffer": {
|
|
getter = arrayBufferByteLengthGetter2;
|
|
break;
|
|
}
|
|
case "SharedArrayBuffer": {
|
|
getter = sharedArrayBufferByteLengthGetter;
|
|
break;
|
|
}
|
|
case "Blob":
|
|
case "File": {
|
|
return { bytes: Number.POSITIVE_INFINITY, kind: "blob" };
|
|
}
|
|
case "Map": {
|
|
return { bytes: 0, kind: "map" };
|
|
}
|
|
case "Date": {
|
|
Reflect.apply(dateTimestampGetter, current, []);
|
|
return { bytes: 8, kind: "date" };
|
|
}
|
|
case "Set": {
|
|
return { bytes: 0, kind: "set" };
|
|
}
|
|
case "Headers": {
|
|
return { bytes: 0, kind: "headers" };
|
|
}
|
|
default: {
|
|
return void 0;
|
|
}
|
|
}
|
|
const bytes2 = getter?.call(current);
|
|
return {
|
|
bytes: typeof bytes2 === "number" && Number.isSafeInteger(bytes2) && bytes2 >= 0 ? bytes2 : Number.POSITIVE_INFINITY,
|
|
kind
|
|
};
|
|
}
|
|
function visitHiddenEventValues(current, kind, visit3) {
|
|
if (kind === "map") {
|
|
for (const [key, entry] of mapEntries.call(current)) {
|
|
if (!visit3(key, 8) || !visit3(entry, 8)) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
if (kind === "set") {
|
|
for (const entry of setValues.call(current)) {
|
|
if (!visit3(entry, 8)) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
if (kind === "headers") {
|
|
if (!headersEntries) {
|
|
return false;
|
|
}
|
|
for (const [name, value] of headersEntries.call(current)) {
|
|
if (!visit3(name, 8) || !visit3(value, 8)) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
function getInspectableEventKeys(current, kind, availableBytes) {
|
|
if (Array.isArray(current)) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(current, "length");
|
|
const length2 = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
if (typeof length2 !== "number" || !Number.isSafeInteger(length2) || length2 < 0 || length2 > Math.floor(availableBytes / 16)) {
|
|
return void 0;
|
|
}
|
|
}
|
|
if (kind !== "typed-array") {
|
|
return Reflect.ownKeys(current);
|
|
}
|
|
const length = typedArrayLengthGetter?.call(current);
|
|
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS) {
|
|
return void 0;
|
|
}
|
|
return Reflect.ownKeys(current).filter((key) => {
|
|
if (typeof key !== "string") {
|
|
return true;
|
|
}
|
|
const index = Number(key);
|
|
return !Number.isInteger(index) || index < 0 || index >= length || String(index) !== key;
|
|
});
|
|
}
|
|
function visitInspectableEventProperties(current, kind, depth, availableBytes, charge, visit3) {
|
|
const keys = getInspectableEventKeys(current, kind, availableBytes());
|
|
if (keys === void 0) {
|
|
return false;
|
|
}
|
|
for (const key of keys) {
|
|
if (!charge(typeof key === "string" ? key.length * 2 + 8 : 8)) {
|
|
return false;
|
|
}
|
|
if (typeof key === "symbol") {
|
|
visit3(key, depth + 1);
|
|
}
|
|
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
if (!descriptor) {
|
|
return false;
|
|
}
|
|
if (!("value" in descriptor)) {
|
|
if (key === "stack" && isTrustedNativeErrorStack(current, descriptor)) {
|
|
continue;
|
|
}
|
|
return false;
|
|
}
|
|
visit3(descriptor.value, depth + 1, kind === "blob");
|
|
}
|
|
return true;
|
|
}
|
|
function visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit3, retainPrototype) {
|
|
let prototype = Object.getPrototypeOf(current);
|
|
for (let prototypeDepth = depth + 1; prototype !== null; prototypeDepth += 1) {
|
|
if (prototypeDepth >= MAX_BUFFERED_EVENT_DEPTH) {
|
|
return false;
|
|
}
|
|
if (trustedIntrinsicPrototypes.has(prototype) || isBlobInternalHandle && prototype === blobInternalHandlePrototype) {
|
|
return true;
|
|
}
|
|
if (visited.has(prototype)) {
|
|
visit3(prototype, prototypeDepth);
|
|
return availableBytes() >= 0;
|
|
}
|
|
visited.add(prototype);
|
|
const retainedPrototype = prototype;
|
|
const retained = retainPrototype(retainedPrototype, () => {
|
|
if (!charge(16)) {
|
|
return false;
|
|
}
|
|
const intrinsic = getTrustedForeignIntrinsic(retainedPrototype);
|
|
if (!intrinsic) {
|
|
return visitInspectableEventProperties(retainedPrototype, void 0, prototypeDepth, availableBytes, charge, visit3);
|
|
}
|
|
for (const key of Reflect.ownKeys(retainedPrototype)) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(retainedPrototype, key);
|
|
if (!descriptor) {
|
|
return false;
|
|
}
|
|
if (isCanonicalIntrinsicDescriptor(descriptor, intrinsic.descriptors.get(key), intrinsic.functionPrototype)) {
|
|
continue;
|
|
}
|
|
if (!charge(typeof key === "string" ? key.length * 2 + 8 : 8) || !("value" in descriptor)) {
|
|
return false;
|
|
}
|
|
if (typeof key === "symbol") {
|
|
visit3(key, prototypeDepth + 1);
|
|
}
|
|
visit3(descriptor.value, prototypeDepth + 1);
|
|
}
|
|
return availableBytes() >= 0;
|
|
});
|
|
if (!retained) {
|
|
return false;
|
|
}
|
|
prototype = Object.getPrototypeOf(retainedPrototype);
|
|
}
|
|
return true;
|
|
}
|
|
function inspectBufferedEventGraph(value, remainingBytes) {
|
|
let bytes2 = 0;
|
|
let scalarBytes = 0;
|
|
const visited = /* @__PURE__ */ new WeakSet();
|
|
const visitedSymbols = /* @__PURE__ */ new Set();
|
|
const roots = /* @__PURE__ */ new Set();
|
|
const nodes = /* @__PURE__ */ new Map();
|
|
let activeNode;
|
|
const availableBytes = () => remainingBytes - bytes2;
|
|
const charge = (amount) => {
|
|
if (!Number.isSafeInteger(amount) || amount < 0) {
|
|
bytes2 = remainingBytes + 1;
|
|
return false;
|
|
}
|
|
bytes2 += amount;
|
|
if (activeNode) {
|
|
activeNode.bytes += amount;
|
|
} else {
|
|
scalarBytes += amount;
|
|
}
|
|
return bytes2 <= remainingBytes;
|
|
};
|
|
const addIdentity = (identity) => {
|
|
if (activeNode) {
|
|
activeNode.edges.add(identity);
|
|
} else {
|
|
roots.add(identity);
|
|
}
|
|
};
|
|
const retainIdentity = (identity, inspect) => {
|
|
addIdentity(identity);
|
|
const node = { bytes: 0, edges: /* @__PURE__ */ new Set() };
|
|
nodes.set(identity, node);
|
|
const previous = activeNode;
|
|
activeNode = node;
|
|
try {
|
|
return inspect();
|
|
} finally {
|
|
activeNode = previous;
|
|
}
|
|
};
|
|
const visitSymbol = (current) => {
|
|
if (visitedSymbols.has(current)) {
|
|
addIdentity(current);
|
|
charge(8);
|
|
return;
|
|
}
|
|
visitedSymbols.add(current);
|
|
if (!retainIdentity(current, () => {
|
|
if (!symbolDescriptionGetter) {
|
|
return false;
|
|
}
|
|
const description = Reflect.apply(symbolDescriptionGetter, current, []);
|
|
return charge(8 + (description?.length ?? 0) * 2);
|
|
})) {
|
|
bytes2 = remainingBytes + 1;
|
|
}
|
|
};
|
|
const visit3 = (current, depth, isBlobInternalHandle = false) => {
|
|
if (bytes2 > remainingBytes) {
|
|
return;
|
|
}
|
|
if (typeof current === "string") {
|
|
charge(current.length * 2);
|
|
return;
|
|
}
|
|
if (typeof current === "symbol") {
|
|
visitSymbol(current);
|
|
return;
|
|
}
|
|
if (typeof current === "function") {
|
|
bytes2 = remainingBytes + 1;
|
|
return;
|
|
}
|
|
if (current === null || typeof current !== "object") {
|
|
charge(8);
|
|
return;
|
|
}
|
|
if (nativeProxyDetector?.(current)) {
|
|
bytes2 = remainingBytes + 1;
|
|
return;
|
|
}
|
|
if (depth >= MAX_BUFFERED_EVENT_DEPTH) {
|
|
bytes2 = remainingBytes + 1;
|
|
return;
|
|
}
|
|
if (visited.has(current)) {
|
|
addIdentity(current);
|
|
charge(8);
|
|
return;
|
|
}
|
|
visited.add(current);
|
|
if (!retainIdentity(current, () => {
|
|
if (!charge(16)) {
|
|
return false;
|
|
}
|
|
const retainedStorage = estimateRetainedBufferBytes(current, visit3, depth);
|
|
if (!visitRetainedEventPrototypes(current, depth, isBlobInternalHandle, visited, availableBytes, charge, visit3, retainIdentity)) {
|
|
return false;
|
|
}
|
|
if (retainedStorage !== void 0 && !charge(retainedStorage.bytes)) {
|
|
return false;
|
|
}
|
|
if (!visitHiddenEventValues(current, retainedStorage?.kind, (hiddenValue, overhead) => {
|
|
if (!charge(overhead)) {
|
|
return false;
|
|
}
|
|
visit3(hiddenValue, depth + 1);
|
|
return bytes2 <= remainingBytes;
|
|
})) {
|
|
return false;
|
|
}
|
|
return visitInspectableEventProperties(current, retainedStorage?.kind, depth, availableBytes, charge, visit3);
|
|
})) {
|
|
bytes2 = remainingBytes + 1;
|
|
}
|
|
};
|
|
try {
|
|
visit3(value, 0);
|
|
} catch {
|
|
return void 0;
|
|
}
|
|
return bytes2 <= remainingBytes ? { scalarBytes, roots, nodes } : void 0;
|
|
}
|
|
function areBufferedRetainedEdgesEqual(first, second) {
|
|
if (first.size !== second.size) {
|
|
return false;
|
|
}
|
|
for (const identity of first) {
|
|
if (!second.has(identity)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
function getBufferedLedgerNodeBytes(node, owners) {
|
|
return node.bytes + BUFFERED_LEDGER_NODE_BYTES + node.edges.size * BUFFERED_LEDGER_EDGE_BYTES + owners * BUFFERED_LEDGER_OWNER_BYTES;
|
|
}
|
|
function getBufferedLedgerEntryBytes(entry) {
|
|
return BUFFERED_LEDGER_ENTRY_BYTES + entry.scalarBytes + entry.roots.size * BUFFERED_LEDGER_EDGE_BYTES;
|
|
}
|
|
function collectBufferedLedgerIdentities(roots, candidate, records, work) {
|
|
const identities = /* @__PURE__ */ new Set();
|
|
const pending = [...roots];
|
|
while (pending.length) {
|
|
work.remaining -= 1;
|
|
if (work.remaining < 0) {
|
|
return void 0;
|
|
}
|
|
const identity = pending.pop();
|
|
if (identities.has(identity)) {
|
|
continue;
|
|
}
|
|
const node = candidate.get(identity) ?? records.get(identity);
|
|
if (!node) {
|
|
return void 0;
|
|
}
|
|
identities.add(identity);
|
|
for (const edge of node.edges) {
|
|
pending.push(edge);
|
|
}
|
|
}
|
|
return identities;
|
|
}
|
|
function getBufferedLedgerChange(identity, graph, records, changes, node) {
|
|
const existing = changes.get(identity);
|
|
if (existing) {
|
|
if (node) {
|
|
existing.node = node;
|
|
}
|
|
return existing;
|
|
}
|
|
const current = node ?? graph.nodes.get(identity) ?? records.get(identity);
|
|
if (!current) {
|
|
return void 0;
|
|
}
|
|
const update = { node: current, ownerDelta: 0 };
|
|
changes.set(identity, update);
|
|
return update;
|
|
}
|
|
function findBufferedLedgerAffectedOwners(entry, graph, records, changes, work) {
|
|
const affected = /* @__PURE__ */ new Set([entry]);
|
|
for (const [identity, node] of graph.nodes) {
|
|
work.remaining -= 1;
|
|
if (work.remaining < 0) {
|
|
return void 0;
|
|
}
|
|
const previous = records.get(identity);
|
|
if (!previous) {
|
|
continue;
|
|
}
|
|
const changedEdges = !areBufferedRetainedEdgesEqual(previous.edges, node.edges);
|
|
if (previous.bytes !== node.bytes || changedEdges) {
|
|
getBufferedLedgerChange(identity, graph, records, changes, node);
|
|
}
|
|
if (!changedEdges) {
|
|
continue;
|
|
}
|
|
for (const owner of previous.owners) {
|
|
work.remaining -= 1;
|
|
if (work.remaining < 0) {
|
|
return void 0;
|
|
}
|
|
affected.add(owner);
|
|
}
|
|
}
|
|
return affected;
|
|
}
|
|
function updateBufferedLedgerMembershipChanges(owner, next, graph, records, changes, work) {
|
|
for (const identity of owner.identities) {
|
|
work.remaining -= 1;
|
|
if (work.remaining < 0) {
|
|
return false;
|
|
}
|
|
if (!next.has(identity)) {
|
|
const update = getBufferedLedgerChange(identity, graph, records, changes);
|
|
if (!update) {
|
|
return false;
|
|
}
|
|
update.ownerDelta -= 1;
|
|
}
|
|
}
|
|
for (const identity of next) {
|
|
work.remaining -= 1;
|
|
if (work.remaining < 0) {
|
|
return false;
|
|
}
|
|
if (!owner.identities.has(identity)) {
|
|
const update = getBufferedLedgerChange(identity, graph, records, changes);
|
|
if (!update) {
|
|
return false;
|
|
}
|
|
update.ownerDelta += 1;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
function collectBufferedLedgerMemberships(entry, graph, affected, records, changes, work) {
|
|
const memberships = /* @__PURE__ */ new Map();
|
|
for (const owner of affected) {
|
|
const roots = owner === entry ? graph.roots : owner.roots;
|
|
const next = collectBufferedLedgerIdentities(roots, graph.nodes, records, work);
|
|
if (!next || !updateBufferedLedgerMembershipChanges(owner, next, graph, records, changes, work)) {
|
|
return void 0;
|
|
}
|
|
memberships.set(owner, next);
|
|
}
|
|
return memberships;
|
|
}
|
|
function projectBufferedLedgerBytes(currentBytes, entry, graph, isNew, changes, records) {
|
|
let projected = currentBytes - (isNew ? 0 : getBufferedLedgerEntryBytes(entry)) + getBufferedLedgerEntryBytes(graph);
|
|
for (const [identity, update] of changes) {
|
|
const previous = records.get(identity);
|
|
const owners = (previous?.owners.size ?? 0) + update.ownerDelta;
|
|
if (owners < 0) {
|
|
return void 0;
|
|
}
|
|
if (previous) {
|
|
projected -= getBufferedLedgerNodeBytes(previous, previous.owners.size);
|
|
}
|
|
if (owners) {
|
|
projected += getBufferedLedgerNodeBytes(update.node, owners);
|
|
}
|
|
}
|
|
return Number.isSafeInteger(projected) && projected >= 0 && projected <= MAX_BUFFERED_ITERATOR_BYTES ? projected : void 0;
|
|
}
|
|
function applyBufferedLedgerChanges(records, changes, memberships) {
|
|
for (const [identity, update] of changes) {
|
|
const previous = records.get(identity);
|
|
const owners = (previous?.owners.size ?? 0) + update.ownerDelta;
|
|
if (!owners) {
|
|
continue;
|
|
}
|
|
if (previous) {
|
|
previous.bytes = update.node.bytes;
|
|
previous.edges = update.node.edges;
|
|
} else {
|
|
records.set(identity, {
|
|
bytes: update.node.bytes,
|
|
edges: update.node.edges,
|
|
owners: /* @__PURE__ */ new Set()
|
|
});
|
|
}
|
|
}
|
|
for (const [owner, next] of memberships) {
|
|
for (const identity of owner.identities) {
|
|
if (!next.has(identity)) {
|
|
records.get(identity)?.owners.delete(owner);
|
|
}
|
|
}
|
|
for (const identity of next) {
|
|
if (!owner.identities.has(identity)) {
|
|
records.get(identity).owners.add(owner);
|
|
}
|
|
}
|
|
owner.identities = next;
|
|
}
|
|
for (const identity of changes.keys()) {
|
|
if (records.get(identity)?.owners.size === 0) {
|
|
records.delete(identity);
|
|
}
|
|
}
|
|
}
|
|
function createBufferedEventLedger() {
|
|
const records = /* @__PURE__ */ new Map();
|
|
let bytes2 = 0;
|
|
const reconcile = (entry, graph, isNew) => {
|
|
const work = { remaining: MAX_BUFFERED_LEDGER_RECONCILIATION_WORK };
|
|
const changes = /* @__PURE__ */ new Map();
|
|
const affected = findBufferedLedgerAffectedOwners(entry, graph, records, changes, work);
|
|
if (!affected) {
|
|
return false;
|
|
}
|
|
const memberships = collectBufferedLedgerMemberships(entry, graph, affected, records, changes, work);
|
|
if (!memberships) {
|
|
return false;
|
|
}
|
|
const projectedBytes = projectBufferedLedgerBytes(bytes2, entry, graph, isNew, changes, records);
|
|
if (projectedBytes === void 0) {
|
|
return false;
|
|
}
|
|
applyBufferedLedgerChanges(records, changes, memberships);
|
|
entry.scalarBytes = graph.scalarBytes;
|
|
entry.roots = graph.roots;
|
|
bytes2 = projectedBytes;
|
|
return true;
|
|
};
|
|
const release = (entry) => {
|
|
bytes2 -= getBufferedLedgerEntryBytes(entry);
|
|
for (const identity of entry.identities) {
|
|
const record = records.get(identity);
|
|
if (!record?.owners.delete(entry)) {
|
|
continue;
|
|
}
|
|
bytes2 -= BUFFERED_LEDGER_OWNER_BYTES;
|
|
if (record.owners.size === 0) {
|
|
bytes2 -= getBufferedLedgerNodeBytes(record, 0);
|
|
records.delete(identity);
|
|
}
|
|
}
|
|
entry.identities.clear();
|
|
};
|
|
return {
|
|
retain(graph) {
|
|
const entry = { scalarBytes: 0, roots: /* @__PURE__ */ new Set(), identities: /* @__PURE__ */ new Set() };
|
|
return reconcile(entry, graph, true) ? entry : void 0;
|
|
},
|
|
refresh(entry, graph) {
|
|
return reconcile(entry, graph, false);
|
|
},
|
|
release,
|
|
clear() {
|
|
records.clear();
|
|
bytes2 = 0;
|
|
}
|
|
};
|
|
}
|
|
var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_abortListeners, _EventStream_emittedListenerRegistrations, _EventStream_pendingListenerCleanup, _EventStream_pendingBufferedEventChecks, _EventStream_listenerDispatchDepth, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_terminalFailure, _EventStream_abortFromSignal, _EventStream_removeAbortListeners, _EventStream_onceForEmitted, _EventStream_removeEmittedListener, _EventStream_cleanupEmittedListeners, _EventStream_handleError, _EventStream_settleTerminalEvent, MAX_BUFFERED_ITERATOR_EVENTS, MAX_BUFFERED_ITERATOR_BYTES, MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS, MAX_BUFFERED_EVENT_DEPTH, bufferedJSONStringify, bufferedJSONParse, sdkOwnedBufferedEventArguments, typedArrayBufferGetter, typedArrayLengthGetter, dataViewBufferGetter, symbolDescriptionGetter, dateTimestampGetter, arrayBufferByteLengthGetter2, sharedArrayBufferByteLengthGetter, errorStackDescriptor, functionToString, objectToString, errorBrandDescriptor, nativeErrorBrand, nativeErrorConstructorSource, nativeDateConstructorSource, nativeFunctionConstructorSource, trustedIntrinsicPrototypes, trustedNativeConstructorSources, canonicalIntrinsicDescriptors, foreignErrorStackDescriptors, nativeProxyDetector, typedArrayConstructorDescriptor, blobInternalHandlePrototype, mapEntries, setValues, headersEntriesDescriptor, headersEntries, retainedStorageBrands, BUFFERED_LEDGER_ENTRY_BYTES, BUFFERED_LEDGER_NODE_BYTES, BUFFERED_LEDGER_EDGE_BYTES, BUFFERED_LEDGER_OWNER_BYTES, MAX_BUFFERED_LEDGER_RECONCILIATION_WORK, EventStream2;
|
|
var init_EventStream = __esm({
|
|
"node_modules/openai/lib/EventStream.mjs"() {
|
|
init_tslib();
|
|
init_error2();
|
|
MAX_BUFFERED_ITERATOR_EVENTS = 4096;
|
|
MAX_BUFFERED_ITERATOR_BYTES = 8 * 1024 * 1024;
|
|
MAX_INSPECTABLE_TYPED_ARRAY_ELEMENTS = 4096;
|
|
MAX_BUFFERED_EVENT_DEPTH = 256;
|
|
bufferedJSONStringify = JSON.stringify;
|
|
bufferedJSONParse = JSON.parse;
|
|
sdkOwnedBufferedEventArguments = /* @__PURE__ */ new WeakSet();
|
|
typedArrayBufferGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "buffer")?.get;
|
|
typedArrayLengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length")?.get;
|
|
dataViewBufferGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer")?.get;
|
|
symbolDescriptionGetter = Object.getOwnPropertyDescriptor(Symbol.prototype, "description")?.get;
|
|
dateTimestampGetter = Date.prototype.getTime;
|
|
arrayBufferByteLengthGetter2 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get;
|
|
sharedArrayBufferByteLengthGetter = typeof SharedArrayBuffer === "function" ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, "byteLength")?.get : void 0;
|
|
errorStackDescriptor = Object.getOwnPropertyDescriptor(new Error("native stack descriptor"), "stack");
|
|
functionToString = Function.prototype.toString;
|
|
objectToString = Object.prototype.toString;
|
|
errorBrandDescriptor = Object.getOwnPropertyDescriptor(Error, "isError");
|
|
nativeErrorBrand = errorBrandDescriptor && "value" in errorBrandDescriptor && typeof errorBrandDescriptor.value === "function" ? errorBrandDescriptor.value : void 0;
|
|
nativeErrorConstructorSource = functionToString.call(Error);
|
|
nativeDateConstructorSource = functionToString.call(Date);
|
|
nativeFunctionConstructorSource = functionToString.call(Function);
|
|
trustedIntrinsicPrototypes = /* @__PURE__ */ new Set([
|
|
APIConnectionError.prototype,
|
|
APIConnectionTimeoutError.prototype,
|
|
APIError.prototype,
|
|
OpenAIError.prototype,
|
|
APIUserAbortError.prototype,
|
|
AuthenticationError.prototype,
|
|
BadRequestError.prototype,
|
|
ConflictError.prototype,
|
|
ContentFilterFinishReasonError.prototype,
|
|
InternalServerError.prototype,
|
|
InvalidWebhookSignatureError.prototype,
|
|
LengthFinishReasonError.prototype,
|
|
NotFoundError.prototype,
|
|
OAuthError.prototype,
|
|
PermissionDeniedError.prototype,
|
|
RateLimitError.prototype,
|
|
SubjectTokenProviderError.prototype,
|
|
UnprocessableEntityError.prototype
|
|
]);
|
|
trustedNativeConstructorSources = /* @__PURE__ */ new Set();
|
|
canonicalIntrinsicDescriptors = /* @__PURE__ */ new Map();
|
|
foreignErrorStackDescriptors = /* @__PURE__ */ new WeakMap();
|
|
nativeProxyDetector = captureNativeProxyDetector();
|
|
for (const constructor of [
|
|
Object,
|
|
Function,
|
|
Array,
|
|
Date,
|
|
Map,
|
|
Set,
|
|
ArrayBuffer,
|
|
DataView,
|
|
Error,
|
|
EvalError,
|
|
RangeError,
|
|
ReferenceError,
|
|
SyntaxError,
|
|
TypeError,
|
|
URIError,
|
|
Uint8Array,
|
|
Uint8ClampedArray,
|
|
Uint16Array,
|
|
Uint32Array,
|
|
Int8Array,
|
|
Int16Array,
|
|
Int32Array,
|
|
Float32Array,
|
|
Float64Array
|
|
]) {
|
|
rememberTrustedIntrinsic(constructor);
|
|
}
|
|
for (const name of [
|
|
"SharedArrayBuffer",
|
|
"AggregateError",
|
|
"Float16Array",
|
|
"BigInt64Array",
|
|
"BigUint64Array",
|
|
"Blob",
|
|
"File",
|
|
"Headers"
|
|
]) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(globalThis, name);
|
|
if (descriptor && "value" in descriptor) {
|
|
rememberTrustedIntrinsic(descriptor.value);
|
|
}
|
|
}
|
|
typedArrayConstructorDescriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "constructor");
|
|
if (typedArrayConstructorDescriptor && "value" in typedArrayConstructorDescriptor) {
|
|
rememberTrustedIntrinsic(typedArrayConstructorDescriptor.value);
|
|
}
|
|
if (typeof Buffer === "function") {
|
|
rememberTrustedIntrinsic(Buffer);
|
|
}
|
|
blobInternalHandlePrototype = (() => {
|
|
if (typeof Blob !== "function") {
|
|
return void 0;
|
|
}
|
|
try {
|
|
const blob = new Blob([]);
|
|
for (const key of Object.getOwnPropertySymbols(blob)) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(blob, key);
|
|
if (descriptor && "value" in descriptor && typeof descriptor.value === "object" && descriptor.value) {
|
|
return Object.getPrototypeOf(descriptor.value);
|
|
}
|
|
}
|
|
} catch {
|
|
return void 0;
|
|
}
|
|
return void 0;
|
|
})();
|
|
mapEntries = Map.prototype.entries;
|
|
setValues = Set.prototype.values;
|
|
headersEntriesDescriptor = typeof Headers === "function" ? Object.getOwnPropertyDescriptor(Headers.prototype, "entries") : void 0;
|
|
headersEntries = headersEntriesDescriptor && "value" in headersEntriesDescriptor && typeof headersEntriesDescriptor.value === "function" ? headersEntriesDescriptor.value : void 0;
|
|
retainedStorageBrands = /* @__PURE__ */ new Set([
|
|
"ArrayBuffer",
|
|
"SharedArrayBuffer",
|
|
"Blob",
|
|
"File",
|
|
"Map",
|
|
"Date",
|
|
"Set",
|
|
"Headers"
|
|
]);
|
|
BUFFERED_LEDGER_ENTRY_BYTES = 32;
|
|
BUFFERED_LEDGER_NODE_BYTES = 32;
|
|
BUFFERED_LEDGER_EDGE_BYTES = 8;
|
|
BUFFERED_LEDGER_OWNER_BYTES = 16;
|
|
MAX_BUFFERED_LEDGER_RECONCILIATION_WORK = 128 * 1024;
|
|
EventStream2 = class {
|
|
/** Creates an unstarted stream with independent connection and completion lifecycle promises. */
|
|
constructor() {
|
|
_EventStream_instances.add(this);
|
|
this.controller = new AbortController();
|
|
_EventStream_connectedPromise.set(this, void 0);
|
|
_EventStream_resolveConnectedPromise.set(this, () => void 0);
|
|
_EventStream_rejectConnectedPromise.set(this, () => void 0);
|
|
_EventStream_endPromise.set(this, void 0);
|
|
_EventStream_resolveEndPromise.set(this, () => void 0);
|
|
_EventStream_rejectEndPromise.set(this, () => void 0);
|
|
_EventStream_listeners.set(this, /* @__PURE__ */ Object.create(null));
|
|
_EventStream_abortListeners.set(this, []);
|
|
_EventStream_emittedListenerRegistrations.set(this, /* @__PURE__ */ new WeakMap());
|
|
_EventStream_pendingListenerCleanup.set(this, /* @__PURE__ */ new Set());
|
|
_EventStream_pendingBufferedEventChecks.set(this, /* @__PURE__ */ new Set());
|
|
_EventStream_listenerDispatchDepth.set(this, 0);
|
|
_EventStream_ended.set(this, false);
|
|
_EventStream_errored.set(this, false);
|
|
_EventStream_aborted.set(this, false);
|
|
_EventStream_catchingPromiseCreated.set(this, false);
|
|
_EventStream_terminalFailure.set(this, void 0);
|
|
__classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f");
|
|
__classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f");
|
|
}), "f");
|
|
__classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f");
|
|
__classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f");
|
|
}), "f");
|
|
__classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => void 0);
|
|
__classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => void 0);
|
|
}
|
|
_run(executor) {
|
|
setTimeout(() => {
|
|
let failed = false;
|
|
Promise.resolve().then(executor).catch((error) => {
|
|
failed = true;
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
|
|
}).then(() => {
|
|
if (failed) {
|
|
return;
|
|
}
|
|
try {
|
|
this._emitFinal();
|
|
} catch (error) {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
|
|
return;
|
|
}
|
|
this._emit("end");
|
|
});
|
|
}, 0);
|
|
}
|
|
_connected() {
|
|
if (this.ended) {
|
|
return;
|
|
}
|
|
__classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this);
|
|
this._emit("connect");
|
|
}
|
|
/** Whether the stream has finished successfully, failed, or been aborted. */
|
|
get ended() {
|
|
return __classPrivateFieldGet(this, _EventStream_ended, "f");
|
|
}
|
|
/** Whether an error or user cancellation has been observed. */
|
|
get errored() {
|
|
return __classPrivateFieldGet(this, _EventStream_errored, "f");
|
|
}
|
|
/** Whether the stream ended because its request was cancelled. */
|
|
get aborted() {
|
|
return __classPrivateFieldGet(this, _EventStream_aborted, "f");
|
|
}
|
|
/**
|
|
* Cancels the underlying request; {@link done} and {@link events} observe cancellation.
|
|
* Promises returned by {@link emitted} for other events may remain pending.
|
|
*/
|
|
abort() {
|
|
this.controller.abort();
|
|
}
|
|
/** Creates a user-abort error retaining this runner's cancellation reason. */
|
|
_userAbortError() {
|
|
const error = new APIUserAbortError();
|
|
Object.defineProperty(error, "cause", {
|
|
value: this.controller.signal.reason,
|
|
writable: true,
|
|
configurable: true
|
|
});
|
|
return error;
|
|
}
|
|
_listenForAbort(signal) {
|
|
if (!signal || this.ended) {
|
|
return;
|
|
}
|
|
if (signal.aborted) {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_abortFromSignal).call(this, signal);
|
|
return;
|
|
}
|
|
if (__classPrivateFieldGet(this, _EventStream_abortListeners, "f").some((registration) => registration.signal === signal)) {
|
|
return;
|
|
}
|
|
const listener = () => __classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_abortFromSignal).call(this, signal);
|
|
signal.addEventListener("abort", listener, { once: true });
|
|
__classPrivateFieldGet(this, _EventStream_abortListeners, "f").push({ signal, listener });
|
|
}
|
|
/**
|
|
* Adds the listener function to the end of the listeners array for the event.
|
|
* No checks are made to see if the listener has already been added. Multiple calls passing
|
|
* the same combination of event and listener will result in the listener being added, and
|
|
* called, multiple times.
|
|
* @returns This stream, so that listener registration calls can be chained.
|
|
*/
|
|
on(event, listener) {
|
|
var _a6;
|
|
const listeners = (_a6 = __classPrivateFieldGet(this, _EventStream_listeners, "f"))[event] || (_a6[event] = []);
|
|
listeners.push({ listener });
|
|
return this;
|
|
}
|
|
/**
|
|
* Removes the specified listener from the listener array for the event.
|
|
* off() will remove, at most, one instance of a listener from the listener array. If any single
|
|
* listener has been added multiple times to the listener array for the specified event, then
|
|
* off() must be called multiple times to remove each instance.
|
|
* @returns This stream, so that listener registration calls can be chained.
|
|
*/
|
|
off(event, listener) {
|
|
const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
|
|
if (!listeners) {
|
|
return this;
|
|
}
|
|
const emittedRegistration = __classPrivateFieldGet(this, _EventStream_emittedListenerRegistrations, "f").get(listener);
|
|
if (emittedRegistration?.event === event && !emittedRegistration.registration.removed && !emittedRegistration.registration.detached) {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeEmittedListener).call(this, event, emittedRegistration.registration);
|
|
return this;
|
|
}
|
|
const index = listeners.findIndex((l) => !l.removed && l.listener === listener);
|
|
if (index !== -1) {
|
|
listeners.splice(index, 1);
|
|
}
|
|
return this;
|
|
}
|
|
/**
|
|
* Adds a one-time listener function for the event. The next time the event is triggered,
|
|
* this listener is removed and then invoked.
|
|
* @returns This stream, so that listener registration calls can be chained.
|
|
*/
|
|
once(event, listener) {
|
|
var _a6;
|
|
const listeners = (_a6 = __classPrivateFieldGet(this, _EventStream_listeners, "f"))[event] || (_a6[event] = []);
|
|
listeners.push({ listener, once: true });
|
|
return this;
|
|
}
|
|
/**
|
|
* This is similar to `.once()`, but returns a Promise that resolves the next time
|
|
* the event is triggered, instead of calling a listener callback.
|
|
* Events without arguments resolve to `undefined`, single-argument events resolve
|
|
* to that argument, and events with multiple arguments resolve to an argument tuple.
|
|
*
|
|
* @returns A promise for the next event, or a rejection if an error occurs first.
|
|
* Requesting the `error` event resolves with the emitted error instead.
|
|
*
|
|
* Example:
|
|
*
|
|
* const message = await stream.emitted('message') // rejects if the stream errors
|
|
*/
|
|
emitted(event) {
|
|
return new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
|
|
const onError = (error) => {
|
|
this.off(event, onEvent);
|
|
reject(error);
|
|
};
|
|
const onEvent = (...values) => {
|
|
if (event !== "error") {
|
|
this.off("error", onError);
|
|
}
|
|
resolve(values.length > 1 ? values : values[0]);
|
|
};
|
|
if (event !== "error") {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_onceForEmitted).call(this, "error", onError);
|
|
}
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_onceForEmitted).call(this, event, onEvent);
|
|
});
|
|
}
|
|
/**
|
|
* Returns an async iterator that yields every time the event is triggered.
|
|
* The iterator ends when the stream ends and rejects if the stream errors
|
|
* or is aborted. If you request the 'error' or 'abort' event, the iterator
|
|
* yields that event instead of rejecting.
|
|
*
|
|
* Example:
|
|
*
|
|
* for await (const [message] of stream.events('message')) {
|
|
* await processMessage(message);
|
|
* }
|
|
*/
|
|
events(event) {
|
|
return this._createIterator((push) => {
|
|
const onEvent = (...args) => {
|
|
sdkOwnedBufferedEventArguments.add(args);
|
|
try {
|
|
push(args);
|
|
} finally {
|
|
sdkOwnedBufferedEventArguments.delete(args);
|
|
}
|
|
};
|
|
this.on(event, onEvent);
|
|
return () => this.off(event, onEvent);
|
|
}, {
|
|
// When iterating the 'error' or 'abort' event itself, yield it as a
|
|
// value instead of rejecting the iterator.
|
|
rejectOnError: event !== "error",
|
|
rejectOnAbort: event !== "abort"
|
|
});
|
|
}
|
|
/**
|
|
* Shared buffered async-iterator adapter over this stream's events.
|
|
*
|
|
* `attach` registers the producer listener(s) with the given `push` and
|
|
* returns a cleanup function that removes them. Termination is handled
|
|
* here: the iterator ends when the stream ends, listeners are removed on
|
|
* end/return, and a terminal error is retained until buffered values have
|
|
* drained so it is surfaced even when no reader was waiting when it fired.
|
|
* Detached consumers have bounded event and byte queues; exceeding either
|
|
* limit fails the stream and aborts its underlying request. Detached queues
|
|
* also reject accessor-backed payloads because getter closures cannot be
|
|
* safely sized without executing untrusted code.
|
|
*/
|
|
_createIterator(attach, { rejectOnError = true, rejectOnAbort = true, onReturn } = {}) {
|
|
const pushQueue = createEventQueue();
|
|
const bufferedEventSizes = createEventQueue();
|
|
const readQueue = createEventQueue();
|
|
const bufferedLedger = createBufferedEventLedger();
|
|
let ended = this.ended;
|
|
let failure2;
|
|
let failureDelivered = false;
|
|
let detach = () => void 0;
|
|
const doneResult = () => ({ value: void 0, done: true });
|
|
const finishReaders = () => {
|
|
while (readQueue.length) {
|
|
readQueue.dequeue().resolve(doneResult());
|
|
}
|
|
};
|
|
const rejectReader = () => {
|
|
if (!failure2 || failureDelivered || !readQueue.length) {
|
|
return;
|
|
}
|
|
failureDelivered = true;
|
|
readQueue.dequeue().reject(failure2);
|
|
};
|
|
const cleanup = () => {
|
|
detach();
|
|
this.off("end", onEnd);
|
|
if (rejectOnError) {
|
|
this.off("error", onFailure);
|
|
}
|
|
if (rejectOnAbort) {
|
|
this.off("abort", onFailure);
|
|
}
|
|
};
|
|
const deactivateBufferedEvent = (entry) => {
|
|
entry.active = false;
|
|
if (entry.check) {
|
|
__classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f").delete(entry.check);
|
|
entry.check = void 0;
|
|
}
|
|
};
|
|
const failBufferedEvents = (discardRetained = false) => {
|
|
if (discardRetained) {
|
|
while (bufferedEventSizes.length) {
|
|
deactivateBufferedEvent(bufferedEventSizes.dequeue());
|
|
}
|
|
pushQueue.clear();
|
|
bufferedLedger.clear();
|
|
}
|
|
const error = new OpenAIError(`Event stream iterator buffer limit exceeded (${MAX_BUFFERED_ITERATOR_EVENTS} events or ${MAX_BUFFERED_ITERATOR_BYTES} bytes); consume events as they arrive.`);
|
|
try {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).call(this, error);
|
|
} finally {
|
|
this.controller.abort();
|
|
}
|
|
return error;
|
|
};
|
|
const revalidateBufferedEvent = (value, entry) => {
|
|
if (!entry.active || __classPrivateFieldGet(this, _EventStream_ended, "f")) {
|
|
return;
|
|
}
|
|
const graph = inspectBufferedEventGraph(value, MAX_BUFFERED_ITERATOR_BYTES);
|
|
if (!graph || !bufferedLedger.refresh(entry.retention, graph)) {
|
|
failBufferedEvents(true);
|
|
}
|
|
};
|
|
const push = (value) => {
|
|
if (ended) {
|
|
return;
|
|
}
|
|
const reader = readQueue.dequeue();
|
|
if (reader) {
|
|
reader.resolve({ value, done: false });
|
|
} else {
|
|
if (pushQueue.length >= MAX_BUFFERED_ITERATOR_EVENTS) {
|
|
failBufferedEvents();
|
|
return;
|
|
}
|
|
const graph = inspectBufferedEventGraph(value, MAX_BUFFERED_ITERATOR_BYTES);
|
|
const retention = graph && bufferedLedger.retain(graph);
|
|
if (!retention) {
|
|
failBufferedEvents();
|
|
return;
|
|
}
|
|
if (typeof value === "object" && value !== null && sdkOwnedBufferedEventArguments.has(value)) {
|
|
const argumentsTuple = value;
|
|
for (let index = 0; index < argumentsTuple.length; index += 1) {
|
|
const argument = argumentsTuple[index];
|
|
if (typeof argument === "string") {
|
|
argumentsTuple[index] = bufferedJSONParse(bufferedJSONStringify(argument));
|
|
}
|
|
}
|
|
}
|
|
const entry = { retention, active: true, check: void 0 };
|
|
pushQueue.enqueue(value);
|
|
bufferedEventSizes.enqueue(entry);
|
|
const check = () => {
|
|
entry.check = void 0;
|
|
revalidateBufferedEvent(value, entry);
|
|
};
|
|
entry.check = check;
|
|
__classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f").add(check);
|
|
}
|
|
};
|
|
const onFailure = (error) => {
|
|
failure2 = error;
|
|
if (!pushQueue.length) {
|
|
rejectReader();
|
|
}
|
|
};
|
|
const adoptTerminalFailure = () => {
|
|
if (failure2) {
|
|
return;
|
|
}
|
|
const terminal = __classPrivateFieldGet(this, _EventStream_terminalFailure, "f");
|
|
if (!terminal) {
|
|
return;
|
|
}
|
|
if (terminal.kind === "error" ? rejectOnError : rejectOnAbort) {
|
|
failure2 = terminal.error;
|
|
}
|
|
};
|
|
const onEnd = () => {
|
|
ended = true;
|
|
adoptTerminalFailure();
|
|
cleanup();
|
|
if (!pushQueue.length) {
|
|
rejectReader();
|
|
finishReaders();
|
|
}
|
|
};
|
|
if (!ended) {
|
|
detach = attach(push);
|
|
this.on("end", onEnd);
|
|
if (rejectOnError) {
|
|
this.on("error", onFailure);
|
|
}
|
|
if (rejectOnAbort) {
|
|
this.on("abort", onFailure);
|
|
}
|
|
}
|
|
return {
|
|
next: () => {
|
|
if (pushQueue.length) {
|
|
const value = pushQueue.dequeue();
|
|
const entry = bufferedEventSizes.dequeue();
|
|
deactivateBufferedEvent(entry);
|
|
const graph = inspectBufferedEventGraph(value, MAX_BUFFERED_ITERATOR_BYTES);
|
|
if (!graph || !bufferedLedger.refresh(entry.retention, graph)) {
|
|
const error = failBufferedEvents(true);
|
|
failureDelivered = true;
|
|
return Promise.reject(error);
|
|
}
|
|
bufferedLedger.release(entry.retention);
|
|
return Promise.resolve({ value, done: false });
|
|
}
|
|
if (ended || this.ended) {
|
|
adoptTerminalFailure();
|
|
}
|
|
if (failure2 && !failureDelivered) {
|
|
failureDelivered = true;
|
|
return Promise.reject(failure2);
|
|
}
|
|
if (ended) {
|
|
return Promise.resolve(doneResult());
|
|
}
|
|
return new Promise((resolve, reject) => {
|
|
readQueue.enqueue({ resolve, reject });
|
|
});
|
|
},
|
|
return: () => {
|
|
ended = true;
|
|
failureDelivered = true;
|
|
while (bufferedEventSizes.length) {
|
|
deactivateBufferedEvent(bufferedEventSizes.dequeue());
|
|
}
|
|
pushQueue.clear();
|
|
bufferedLedger.clear();
|
|
cleanup();
|
|
finishReaders();
|
|
if (onReturn) {
|
|
void this.done().catch(() => void 0);
|
|
onReturn();
|
|
}
|
|
return Promise.resolve(doneResult());
|
|
},
|
|
[Symbol.asyncIterator]() {
|
|
return this;
|
|
}
|
|
};
|
|
}
|
|
/** Resolves when the stream ends successfully or rejects when it fails or is aborted. */
|
|
async done() {
|
|
__classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f");
|
|
await __classPrivateFieldGet(this, _EventStream_endPromise, "f");
|
|
}
|
|
/** Returns whether an event currently has one or more registered listeners. */
|
|
_hasListeners(event) {
|
|
return Boolean(__classPrivateFieldGet(this, _EventStream_listeners, "f")[event]?.some((listener) => !listener.removed));
|
|
}
|
|
/** Dispatches a stream event and performs the associated lifecycle transitions. */
|
|
_emit(event, ...args) {
|
|
if (__classPrivateFieldGet(this, _EventStream_ended, "f")) {
|
|
return;
|
|
}
|
|
if (event === "end") {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_removeAbortListeners).call(this);
|
|
__classPrivateFieldSet(this, _EventStream_ended, true, "f");
|
|
__classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this);
|
|
}
|
|
const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
|
|
let dispatchError;
|
|
let dispatchThrew = false;
|
|
try {
|
|
if (listeners) {
|
|
__classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((listener) => {
|
|
if (listener.once) {
|
|
listener.detached = true;
|
|
}
|
|
return !listener.once && !listener.removed;
|
|
});
|
|
__classPrivateFieldSet(this, _EventStream_listenerDispatchDepth, __classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") + 1, "f");
|
|
try {
|
|
for (const registration of listeners) {
|
|
if (!registration.removed) {
|
|
const { listener } = registration;
|
|
listener(...args);
|
|
}
|
|
}
|
|
} finally {
|
|
__classPrivateFieldSet(this, _EventStream_listenerDispatchDepth, __classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") - 1, "f");
|
|
if (__classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") === 0) {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_cleanupEmittedListeners).call(this);
|
|
for (const check of __classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f")) {
|
|
__classPrivateFieldGet(this, _EventStream_pendingBufferedEventChecks, "f").delete(check);
|
|
if (!__classPrivateFieldGet(this, _EventStream_ended, "f")) {
|
|
check();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} catch (error) {
|
|
dispatchError = error;
|
|
dispatchThrew = true;
|
|
}
|
|
try {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_settleTerminalEvent).call(this, event, args, Boolean(listeners?.length));
|
|
} catch (error) {
|
|
if (!dispatchThrew) {
|
|
dispatchError = error;
|
|
dispatchThrew = true;
|
|
}
|
|
}
|
|
if (dispatchThrew) {
|
|
throw dispatchError;
|
|
}
|
|
}
|
|
// oxlint-disable-next-line class-methods-use-this -- Subclasses override this instance hook.
|
|
_emitFinal() {
|
|
}
|
|
};
|
|
_EventStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _EventStream_endPromise = /* @__PURE__ */ new WeakMap(), _EventStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _EventStream_listeners = /* @__PURE__ */ new WeakMap(), _EventStream_abortListeners = /* @__PURE__ */ new WeakMap(), _EventStream_emittedListenerRegistrations = /* @__PURE__ */ new WeakMap(), _EventStream_pendingListenerCleanup = /* @__PURE__ */ new WeakMap(), _EventStream_pendingBufferedEventChecks = /* @__PURE__ */ new WeakMap(), _EventStream_listenerDispatchDepth = /* @__PURE__ */ new WeakMap(), _EventStream_ended = /* @__PURE__ */ new WeakMap(), _EventStream_errored = /* @__PURE__ */ new WeakMap(), _EventStream_aborted = /* @__PURE__ */ new WeakMap(), _EventStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _EventStream_terminalFailure = /* @__PURE__ */ new WeakMap(), _EventStream_instances = /* @__PURE__ */ new WeakSet(), _EventStream_abortFromSignal = function _EventStream_abortFromSignal2(signal) {
|
|
try {
|
|
this.controller.abort(signal.reason);
|
|
} catch {
|
|
this.controller.abort();
|
|
}
|
|
}, _EventStream_removeAbortListeners = function _EventStream_removeAbortListeners2() {
|
|
for (const { signal, listener } of __classPrivateFieldGet(this, _EventStream_abortListeners, "f").splice(0)) {
|
|
signal.removeEventListener("abort", listener);
|
|
}
|
|
}, _EventStream_onceForEmitted = function _EventStream_onceForEmitted2(event, listener) {
|
|
const previousListeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
|
|
const previousLength = previousListeners?.length ?? 0;
|
|
this.once(event, listener);
|
|
const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[event];
|
|
const [registration] = listeners?.slice(-1) ?? [];
|
|
if ((previousListeners === void 0 || listeners === previousListeners) && listeners?.length === previousLength + 1 && registration?.listener === listener && registration.once) {
|
|
__classPrivateFieldGet(this, _EventStream_emittedListenerRegistrations, "f").set(listener, { event, registration });
|
|
}
|
|
}, _EventStream_removeEmittedListener = function _EventStream_removeEmittedListener2(event, registration) {
|
|
if (registration.removed) {
|
|
return;
|
|
}
|
|
registration.removed = true;
|
|
__classPrivateFieldGet(this, _EventStream_emittedListenerRegistrations, "f").delete(registration.listener);
|
|
__classPrivateFieldGet(this, _EventStream_pendingListenerCleanup, "f").add(event);
|
|
if (__classPrivateFieldGet(this, _EventStream_listenerDispatchDepth, "f") === 0) {
|
|
__classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_cleanupEmittedListeners).call(this);
|
|
}
|
|
}, _EventStream_cleanupEmittedListeners = function _EventStream_cleanupEmittedListeners2() {
|
|
for (const event of __classPrivateFieldGet(this, _EventStream_pendingListenerCleanup, "f")) {
|
|
const eventType = event;
|
|
const listeners = __classPrivateFieldGet(this, _EventStream_listeners, "f")[eventType];
|
|
if (listeners) {
|
|
__classPrivateFieldGet(this, _EventStream_listeners, "f")[eventType] = listeners.filter((listener) => !listener.removed);
|
|
}
|
|
}
|
|
__classPrivateFieldGet(this, _EventStream_pendingListenerCleanup, "f").clear();
|
|
}, _EventStream_handleError = function _EventStream_handleError2(error) {
|
|
__classPrivateFieldSet(this, _EventStream_errored, true, "f");
|
|
if (error instanceof Error && error.name === "AbortError") {
|
|
error = this._userAbortError();
|
|
}
|
|
if (error instanceof APIUserAbortError) {
|
|
__classPrivateFieldSet(this, _EventStream_aborted, true, "f");
|
|
return this._emit("abort", error);
|
|
}
|
|
if (error instanceof OpenAIError) {
|
|
return this._emit("error", error);
|
|
}
|
|
if (error instanceof Error) {
|
|
const openAIError = new OpenAIError(error.message);
|
|
openAIError.cause = error;
|
|
return this._emit("error", openAIError);
|
|
}
|
|
return this._emit("error", new OpenAIError(String(error)));
|
|
}, _EventStream_settleTerminalEvent = function _EventStream_settleTerminalEvent2(event, args, hasListeners) {
|
|
if (event === "abort") {
|
|
const error = args[0];
|
|
__classPrivateFieldSet(this, _EventStream_terminalFailure, __classPrivateFieldGet(this, _EventStream_terminalFailure, "f") ?? { kind: "abort", error }, "f");
|
|
if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !hasListeners) {
|
|
Promise.reject(error);
|
|
}
|
|
__classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
|
|
__classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error);
|
|
this._emit("end");
|
|
return;
|
|
}
|
|
if (event === "error") {
|
|
const error = args[0];
|
|
__classPrivateFieldSet(this, _EventStream_terminalFailure, __classPrivateFieldGet(this, _EventStream_terminalFailure, "f") ?? { kind: "error", error }, "f");
|
|
if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !hasListeners) {
|
|
Promise.reject(error);
|
|
}
|
|
__classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error);
|
|
__classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error);
|
|
this._emit("end");
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/RunnableFunction.mjs
|
|
function isRunnableFunctionWithParse(fn) {
|
|
return typeof fn.parse === "function";
|
|
}
|
|
var init_RunnableFunction = __esm({
|
|
"node_modules/openai/lib/RunnableFunction.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/AbstractChatCompletionRunner.mjs
|
|
function normalizeToolCallIds(chatCompletion) {
|
|
for (const choice of chatCompletion.choices) {
|
|
for (const toolCall of choice.message.tool_calls ?? []) {
|
|
if (!toolCall.id) {
|
|
toolCall.id = `call_${uuid4()}`;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
function toRequestMessage(message) {
|
|
if (!isAssistantMessage(message)) {
|
|
return message;
|
|
}
|
|
const requestMessage = { role: "assistant" };
|
|
if (message.audio != null) {
|
|
requestMessage.audio = { id: message.audio.id };
|
|
}
|
|
if (message.content !== void 0) {
|
|
requestMessage.content = message.content;
|
|
}
|
|
if (message.function_call != null) {
|
|
requestMessage.function_call = message.function_call;
|
|
}
|
|
if (message.name !== void 0) {
|
|
requestMessage.name = message.name;
|
|
}
|
|
if (message.refusal != null) {
|
|
requestMessage.refusal = message.refusal;
|
|
}
|
|
if (message.tool_calls !== void 0) {
|
|
requestMessage.tool_calls = message.tool_calls.map((toolCall) => {
|
|
if (toolCall.type === "custom") {
|
|
return {
|
|
id: toolCall.id,
|
|
type: toolCall.type,
|
|
custom: {
|
|
input: toolCall.custom.input,
|
|
name: toolCall.custom.name
|
|
}
|
|
};
|
|
}
|
|
return {
|
|
id: toolCall.id,
|
|
type: toolCall.type,
|
|
function: {
|
|
arguments: toolCall.function.arguments,
|
|
name: toolCall.function.name
|
|
}
|
|
};
|
|
});
|
|
}
|
|
return requestMessage;
|
|
}
|
|
var _AbstractChatCompletionRunner_instances, _a2, _AbstractChatCompletionRunner_completionArrivedBeforeAbort, _AbstractChatCompletionRunner_afterCompletionInvoked, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_throwIfAborted, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult, DEFAULT_MAX_CHAT_COMPLETIONS, AbstractChatCompletionRunner;
|
|
var init_AbstractChatCompletionRunner = __esm({
|
|
"node_modules/openai/lib/AbstractChatCompletionRunner.mjs"() {
|
|
init_tslib();
|
|
init_error2();
|
|
init_uuid();
|
|
init_parser();
|
|
init_chatCompletionUtils();
|
|
init_EventStream();
|
|
init_RunnableFunction();
|
|
DEFAULT_MAX_CHAT_COMPLETIONS = 10;
|
|
AbstractChatCompletionRunner = class extends EventStream2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
_AbstractChatCompletionRunner_instances.add(this);
|
|
this._chatCompletions = [];
|
|
_AbstractChatCompletionRunner_completionArrivedBeforeAbort.set(this, false);
|
|
_AbstractChatCompletionRunner_afterCompletionInvoked.set(this, false);
|
|
this.messages = [];
|
|
}
|
|
_addChatCompletion(chatCompletion) {
|
|
__classPrivateFieldSet(this, _AbstractChatCompletionRunner_completionArrivedBeforeAbort, !this.controller.signal.aborted, "f");
|
|
normalizeToolCallIds(chatCompletion);
|
|
this._chatCompletions.push(chatCompletion);
|
|
this._emit("chatCompletion", chatCompletion);
|
|
const message = chatCompletion.choices[0]?.message;
|
|
if (message) {
|
|
this._addMessage(message);
|
|
}
|
|
return chatCompletion;
|
|
}
|
|
_addMessage(message, emit = true, normalizeContent = true) {
|
|
if (normalizeContent && !("content" in message)) {
|
|
message.content = null;
|
|
}
|
|
this.messages.push(message);
|
|
if (emit) {
|
|
this._emit("message", message);
|
|
if (isToolMessage(message) && message.content) {
|
|
this._emit("functionToolCallResult", message.content);
|
|
} else if (isAssistantMessage(message) && message.tool_calls) {
|
|
for (const tool_call of message.tool_calls) {
|
|
if (tool_call.type === "function") {
|
|
this._emit("functionToolCall", tool_call.function);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the final ChatCompletion, or rejects
|
|
* if an error occurred or the stream ended prematurely without producing a ChatCompletion.
|
|
*/
|
|
async finalChatCompletion() {
|
|
await this.done();
|
|
const completion = this._chatCompletions[this._chatCompletions.length - 1];
|
|
if (!completion) {
|
|
throw new OpenAIError("stream ended without producing a ChatCompletion");
|
|
}
|
|
return completion;
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects
|
|
* if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
|
|
*/
|
|
async finalContent() {
|
|
await this.done();
|
|
return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the final assistant ChatCompletionMessage response,
|
|
* or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.
|
|
*/
|
|
async finalMessage() {
|
|
await this.done();
|
|
return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
|
|
}
|
|
/**
|
|
* Waits for completion and returns the last function-tool call, or `undefined`
|
|
* when no assistant message contains a function-tool call.
|
|
*/
|
|
async finalFunctionToolCall() {
|
|
await this.done();
|
|
return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
|
|
}
|
|
/** Waits for completion and returns the last matching function-tool result, if any. */
|
|
async finalFunctionToolCallResult() {
|
|
await this.done();
|
|
return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
|
|
}
|
|
/** Waits for completion and sums token usage across every chat completion in the run. */
|
|
async totalUsage() {
|
|
await this.done();
|
|
return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);
|
|
}
|
|
/** Returns a copy of the chat completions received so far, in request order. */
|
|
allChatCompletions() {
|
|
return [...this._chatCompletions];
|
|
}
|
|
_emitFinal() {
|
|
if (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_afterCompletionInvoked, "f")) {
|
|
__classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_throwIfAborted).call(this);
|
|
}
|
|
const completion = this._chatCompletions[this._chatCompletions.length - 1];
|
|
if (completion) {
|
|
this._emit("finalChatCompletion", completion);
|
|
}
|
|
const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this);
|
|
if (finalMessage) {
|
|
this._emit("finalMessage", finalMessage);
|
|
}
|
|
const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this);
|
|
if (finalContent) {
|
|
this._emit("finalContent", finalContent);
|
|
}
|
|
const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this);
|
|
if (finalFunctionCall) {
|
|
this._emit("finalFunctionToolCall", finalFunctionCall);
|
|
}
|
|
const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this);
|
|
if (finalFunctionCallResult != null) {
|
|
this._emit("finalFunctionToolCallResult", finalFunctionCallResult);
|
|
}
|
|
if (this._chatCompletions.some((c) => c.usage)) {
|
|
this._emit("totalUsage", __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));
|
|
}
|
|
}
|
|
async _createChatCompletion(client, params, options) {
|
|
this._listenForAbort(options?.signal);
|
|
__classPrivateFieldGet(_a2, _a2, "m", _AbstractChatCompletionRunner_validateParams).call(_a2, params);
|
|
const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
|
|
this._connected();
|
|
return this._addChatCompletion(parseChatCompletion(chatCompletion, params));
|
|
}
|
|
async _runChatCompletion(client, params, options) {
|
|
for (const message of params.messages) {
|
|
this._addMessage(message, false, false);
|
|
}
|
|
return await this._createChatCompletion(client, params, options);
|
|
}
|
|
async _runTools(client, params, runner, options) {
|
|
const role = "tool";
|
|
const { tool_choice = "auto", stream: stream4, toolContext: inputToolContext, ...restParams } = params;
|
|
const toolContext = inputToolContext;
|
|
const singleFunctionToCall = (
|
|
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Chat history and tool-choice inputs can contain runtime variants that select different runner behavior.
|
|
typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name
|
|
);
|
|
const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS, afterCompletion } = options || {};
|
|
const runAfterCompletion = async (completion) => {
|
|
if (afterCompletion == null) {
|
|
return;
|
|
}
|
|
__classPrivateFieldSet(this, _AbstractChatCompletionRunner_afterCompletionInvoked, true, "f");
|
|
await afterCompletion(completion, runner);
|
|
__classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_throwIfAborted).call(this);
|
|
};
|
|
const inputTools = params.tools.map((tool) => {
|
|
if (isAutoParsableTool(tool)) {
|
|
if (!tool.$callback) {
|
|
throw new OpenAIError("Tool given to `.runTools()` that does not have an associated function");
|
|
}
|
|
return {
|
|
type: "function",
|
|
function: {
|
|
function: tool.$callback,
|
|
name: tool.function.name,
|
|
description: tool.function.description || "",
|
|
parameters: tool.function.parameters,
|
|
parse: tool.$parseRaw,
|
|
strict: true
|
|
}
|
|
};
|
|
}
|
|
return tool;
|
|
});
|
|
const functionsByName = /* @__PURE__ */ Object.create(null);
|
|
for (const f of inputTools) {
|
|
if (f.type === "function") {
|
|
functionsByName[f.function.name || f.function.function.name] = f.function;
|
|
}
|
|
}
|
|
const tools = "tools" in params ? inputTools.map((t) => t.type === "function" ? {
|
|
type: "function",
|
|
function: {
|
|
name: t.function.name || t.function.function.name,
|
|
// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Tool parameter schemas use the published open JSON Schema dictionary contract, including arbitrary extensions.
|
|
parameters: t.function.parameters,
|
|
description: t.function.description,
|
|
strict: t.function.strict
|
|
}
|
|
} : (
|
|
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- Preserve the existing non-function tool pass-through; runnable and wire schema interfaces have incompatible index signatures.
|
|
t
|
|
)) : void 0;
|
|
for (const message of params.messages) {
|
|
this._addMessage(message, false, false);
|
|
}
|
|
let allowBufferedToolCall = false;
|
|
const runToolCall2 = async (toolCall) => {
|
|
const bufferedToolCall = allowBufferedToolCall;
|
|
allowBufferedToolCall = false;
|
|
if (toolCall.type !== "function") {
|
|
return { message: void 0, functionCalled: false };
|
|
}
|
|
const tool_call_id = toolCall.id;
|
|
const { name, arguments: args } = toolCall.function;
|
|
const fn = functionsByName[name];
|
|
if (!fn) {
|
|
const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
|
|
return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
|
|
}
|
|
if (singleFunctionToCall && singleFunctionToCall !== name) {
|
|
const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
|
|
return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
|
|
}
|
|
let rawContent;
|
|
if (isRunnableFunctionWithParse(fn)) {
|
|
let parsed;
|
|
try {
|
|
parsed = await fn.parse(args);
|
|
} catch (error) {
|
|
if (this.controller.signal.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
const content2 = error instanceof Error ? error.message : String(error);
|
|
return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
|
|
}
|
|
if (this.controller.signal.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
try {
|
|
rawContent = await fn.function(parsed, runner, toolContext);
|
|
} catch (error) {
|
|
if (this.controller.signal.aborted && Object.is(error, this.controller.signal.reason)) {
|
|
throw this._userAbortError();
|
|
}
|
|
throw error;
|
|
}
|
|
} else {
|
|
if (this.controller.signal.aborted && !bufferedToolCall) {
|
|
throw this._userAbortError();
|
|
}
|
|
try {
|
|
rawContent = await fn.function(args, runner, toolContext);
|
|
} catch (error) {
|
|
if (this.controller.signal.aborted && Object.is(error, this.controller.signal.reason)) {
|
|
throw this._userAbortError();
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
const content = __classPrivateFieldGet(_a2, _a2, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(_a2, rawContent);
|
|
return { message: { role, tool_call_id, content }, functionCalled: true };
|
|
};
|
|
for (let i = 0; i < maxChatCompletions; ++i) {
|
|
const chatCompletion = await this._createChatCompletion(client, {
|
|
...restParams,
|
|
tool_choice,
|
|
tools,
|
|
messages: this.messages.map(toRequestMessage)
|
|
}, options);
|
|
allowBufferedToolCall = this.controller.signal.aborted && __classPrivateFieldGet(this, _AbstractChatCompletionRunner_completionArrivedBeforeAbort, "f");
|
|
const message = chatCompletion.choices[0]?.message;
|
|
if (!message) {
|
|
throw new OpenAIError(`missing message in ChatCompletion response`);
|
|
}
|
|
if (!message.tool_calls?.length) {
|
|
await runAfterCompletion(chatCompletion);
|
|
return;
|
|
}
|
|
if (singleFunctionToCall || params.parallel_tool_calls === false) {
|
|
for (const toolCall of message.tool_calls) {
|
|
const result = await runToolCall2(toolCall);
|
|
if (result.message) {
|
|
this._addMessage(result.message);
|
|
}
|
|
if (this.controller.signal.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
if (singleFunctionToCall && result.functionCalled) {
|
|
await runAfterCompletion(chatCompletion);
|
|
return;
|
|
}
|
|
}
|
|
} else {
|
|
const results = await Promise.allSettled(message.tool_calls.map(runToolCall2));
|
|
if (!this.controller.signal.aborted) {
|
|
for (const result of results) {
|
|
if (result.status === "rejected") {
|
|
throw result.reason;
|
|
}
|
|
}
|
|
}
|
|
for (const result of results) {
|
|
if (result.status === "fulfilled" && result.value.message) {
|
|
this._addMessage(result.value.message);
|
|
}
|
|
}
|
|
if (this.controller.signal.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
}
|
|
await runAfterCompletion(chatCompletion);
|
|
}
|
|
}
|
|
};
|
|
_a2 = AbstractChatCompletionRunner, _AbstractChatCompletionRunner_completionArrivedBeforeAbort = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_afterCompletionInvoked = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() {
|
|
return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;
|
|
}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() {
|
|
let i = this.messages.length;
|
|
while (i-- > 0) {
|
|
const message = this.messages[i];
|
|
if (isAssistantMessage(message)) {
|
|
const ret = {
|
|
...message,
|
|
content: message.content ?? null,
|
|
refusal: message.refusal ?? null
|
|
};
|
|
return ret;
|
|
}
|
|
}
|
|
throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant");
|
|
}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall2() {
|
|
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
const message = this.messages[i];
|
|
if (isAssistantMessage(message) && message?.tool_calls?.length) {
|
|
for (let j = message.tool_calls.length - 1; j >= 0; j--) {
|
|
const toolCall = message.tool_calls[j];
|
|
if (toolCall?.type === "function") {
|
|
return toolCall.function;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return void 0;
|
|
}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult2() {
|
|
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
const message = this.messages[i];
|
|
if (isToolMessage(message) && message.content != null && // oxlint-disable-next-line anti-slop/no-runtime-typeof -- Chat history and tool-choice inputs can contain runtime variants that select different runner behavior.
|
|
typeof message.content === "string" && this.messages.some((x) => x.role === "assistant" && x.tool_calls?.some((y) => y.type === "function" && y.id === message.tool_call_id))) {
|
|
return message.content;
|
|
}
|
|
}
|
|
return void 0;
|
|
}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() {
|
|
const total = {
|
|
completion_tokens: 0,
|
|
prompt_tokens: 0,
|
|
total_tokens: 0
|
|
};
|
|
for (const { usage } of this._chatCompletions) {
|
|
if (usage) {
|
|
total.completion_tokens += usage.completion_tokens;
|
|
total.prompt_tokens += usage.prompt_tokens;
|
|
total.total_tokens += usage.total_tokens;
|
|
}
|
|
}
|
|
return total;
|
|
}, _AbstractChatCompletionRunner_throwIfAborted = function _AbstractChatCompletionRunner_throwIfAborted2() {
|
|
if (this.controller.signal.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) {
|
|
if (params.n != null && params.n > 1) {
|
|
throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.");
|
|
}
|
|
}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) {
|
|
if (typeof rawContent === "string") {
|
|
return rawContent;
|
|
}
|
|
if (rawContent === void 0) {
|
|
return "undefined";
|
|
}
|
|
return JSON.stringify(rawContent);
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/ChatCompletionRunner.mjs
|
|
var ChatCompletionRunner;
|
|
var init_ChatCompletionRunner = __esm({
|
|
"node_modules/openai/lib/ChatCompletionRunner.mjs"() {
|
|
init_AbstractChatCompletionRunner();
|
|
init_chatCompletionUtils();
|
|
ChatCompletionRunner = class _ChatCompletionRunner extends AbstractChatCompletionRunner {
|
|
/** Starts a non-streaming tool loop and returns its event-driven conversation runner. */
|
|
static runTools(client, params, options) {
|
|
const runner = new _ChatCompletionRunner();
|
|
const opts = {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "runTools" }
|
|
};
|
|
runner._run(() => runner._runTools(client, params, runner, opts));
|
|
return runner;
|
|
}
|
|
/**
|
|
* Appends a conversation message and emits text content for assistant replies.
|
|
* @param normalizeContent Defaults to true; initial history passes false to preserve caller-owned messages.
|
|
*/
|
|
_addMessage(message, emit = true, normalizeContent = true) {
|
|
super._addMessage(message, emit, normalizeContent);
|
|
if (emit && isAssistantMessage(message) && message.content) {
|
|
this._emit("content", message.content);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/_vendor/partial-json-parser/parser.mjs
|
|
function parseJSON(jsonString, allowPartial = Allow.ALL) {
|
|
if (typeof jsonString !== "string") {
|
|
throw new TypeError(`expecting str, got ${typeof jsonString}`);
|
|
}
|
|
if (!jsonString.trim()) {
|
|
throw new Error(`${jsonString} is empty`);
|
|
}
|
|
return _parseJSON(jsonString.trim(), allowPartial);
|
|
}
|
|
var STR, NUM, ARR, OBJ, NULL, BOOL, NAN, INFINITY, MINUS_INFINITY, INF, SPECIAL, ATOM, COLLECTION, ALL, Allow, PartialJSON, MalformedJSON, _parseJSON, partialParse;
|
|
var init_parser2 = __esm({
|
|
"node_modules/openai/_vendor/partial-json-parser/parser.mjs"() {
|
|
STR = 1;
|
|
NUM = 2;
|
|
ARR = 4;
|
|
OBJ = 8;
|
|
NULL = 16;
|
|
BOOL = 32;
|
|
NAN = 64;
|
|
INFINITY = 128;
|
|
MINUS_INFINITY = 256;
|
|
INF = INFINITY | MINUS_INFINITY;
|
|
SPECIAL = NULL | BOOL | INF | NAN;
|
|
ATOM = STR | NUM | SPECIAL;
|
|
COLLECTION = ARR | OBJ;
|
|
ALL = ATOM | COLLECTION;
|
|
Allow = {
|
|
STR,
|
|
NUM,
|
|
ARR,
|
|
OBJ,
|
|
NULL,
|
|
BOOL,
|
|
NAN,
|
|
INFINITY,
|
|
MINUS_INFINITY,
|
|
INF,
|
|
SPECIAL,
|
|
ATOM,
|
|
COLLECTION,
|
|
ALL
|
|
};
|
|
PartialJSON = class extends Error {
|
|
};
|
|
MalformedJSON = class extends Error {
|
|
};
|
|
_parseJSON = (jsonString, allow) => {
|
|
const length = jsonString.length;
|
|
let index = 0;
|
|
const markPartialJSON = (msg) => {
|
|
throw new PartialJSON(`${msg} at position ${index}`);
|
|
};
|
|
const throwMalformedError = (msg) => {
|
|
throw new MalformedJSON(`${msg} at position ${index}`);
|
|
};
|
|
const parseAny = () => {
|
|
skipBlank();
|
|
if (index >= length) {
|
|
markPartialJSON("Unexpected end of input");
|
|
}
|
|
if (jsonString[index] === '"') {
|
|
return parseStr();
|
|
}
|
|
if (jsonString[index] === "{") {
|
|
return parseObj();
|
|
}
|
|
if (jsonString[index] === "[") {
|
|
return parseArr();
|
|
}
|
|
if (jsonString.substring(index, index + 4) === "null" || Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
|
|
index += 4;
|
|
return null;
|
|
}
|
|
if (jsonString.substring(index, index + 4) === "true" || Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
|
|
index += 4;
|
|
return true;
|
|
}
|
|
if (jsonString.substring(index, index + 5) === "false" || Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
|
|
index += 5;
|
|
return false;
|
|
}
|
|
if (jsonString.substring(index, index + 8) === "Infinity" || Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
|
|
index += 8;
|
|
return Infinity;
|
|
}
|
|
if (jsonString.substring(index, index + 9) === "-Infinity" || Allow.MINUS_INFINITY & allow && length - index > 1 && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
|
|
index += 9;
|
|
return -Infinity;
|
|
}
|
|
if (jsonString.substring(index, index + 3) === "NaN" || Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
|
|
index += 3;
|
|
return Number.NaN;
|
|
}
|
|
return parseNum();
|
|
};
|
|
const parseStr = () => {
|
|
const start = index;
|
|
let escape2 = false;
|
|
index++;
|
|
while (index < length && (jsonString[index] !== '"' || escape2 && jsonString[index - 1] === "\\")) {
|
|
escape2 = jsonString[index] === "\\" ? !escape2 : false;
|
|
index++;
|
|
}
|
|
if (jsonString.charAt(index) === '"') {
|
|
try {
|
|
return JSON.parse(jsonString.substring(start, ++index - Number(escape2)));
|
|
} catch (e) {
|
|
throwMalformedError(String(e));
|
|
}
|
|
} else if (Allow.STR & allow) {
|
|
try {
|
|
return JSON.parse(jsonString.substring(start, index - Number(escape2)) + '"');
|
|
} catch {
|
|
return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
|
|
}
|
|
}
|
|
markPartialJSON("Unterminated string literal");
|
|
};
|
|
const parseObj = () => {
|
|
index++;
|
|
skipBlank();
|
|
const obj2 = {};
|
|
try {
|
|
while (jsonString[index] !== "}") {
|
|
skipBlank();
|
|
if (index >= length && Allow.OBJ & allow) {
|
|
return obj2;
|
|
}
|
|
const key = parseStr();
|
|
skipBlank();
|
|
index++;
|
|
try {
|
|
const value = parseAny();
|
|
Object.defineProperty(obj2, key, { value, writable: true, enumerable: true, configurable: true });
|
|
} catch (e) {
|
|
if (Allow.OBJ & allow) {
|
|
return obj2;
|
|
}
|
|
throw e;
|
|
}
|
|
skipBlank();
|
|
if (jsonString[index] === ",") {
|
|
index++;
|
|
}
|
|
}
|
|
} catch {
|
|
if (Allow.OBJ & allow) {
|
|
return obj2;
|
|
}
|
|
markPartialJSON("Expected '}' at end of object");
|
|
}
|
|
index++;
|
|
return obj2;
|
|
};
|
|
const parseArr = () => {
|
|
index++;
|
|
const arr2 = [];
|
|
try {
|
|
while (jsonString[index] !== "]") {
|
|
arr2.push(parseAny());
|
|
skipBlank();
|
|
if (jsonString[index] === ",") {
|
|
index++;
|
|
}
|
|
}
|
|
} catch {
|
|
if (Allow.ARR & allow) {
|
|
return arr2;
|
|
}
|
|
markPartialJSON("Expected ']' at end of array");
|
|
}
|
|
index++;
|
|
return arr2;
|
|
};
|
|
const parseNum = () => {
|
|
if (index === 0) {
|
|
if (jsonString === "-" && Allow.NUM & allow) {
|
|
markPartialJSON("Not sure what '-' is");
|
|
}
|
|
try {
|
|
return JSON.parse(jsonString);
|
|
} catch (e) {
|
|
if (Allow.NUM & allow) {
|
|
try {
|
|
if (jsonString[jsonString.length - 1] === ".") {
|
|
return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf(".")));
|
|
}
|
|
return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
|
|
} catch {
|
|
}
|
|
}
|
|
throwMalformedError(String(e));
|
|
}
|
|
}
|
|
const start = index;
|
|
if (jsonString[index] === "-") {
|
|
index++;
|
|
}
|
|
while (jsonString[index] && !",]}".includes(jsonString[index])) {
|
|
index++;
|
|
}
|
|
if (index === length && !(Allow.NUM & allow)) {
|
|
markPartialJSON("Unterminated number literal");
|
|
}
|
|
const number = jsonString.substring(start, index);
|
|
try {
|
|
return JSON.parse(number);
|
|
} catch {
|
|
if (number === "-" && Allow.NUM & allow) {
|
|
markPartialJSON("Not sure what '-' is");
|
|
}
|
|
try {
|
|
return JSON.parse(number.substring(0, number.lastIndexOf("e")));
|
|
} catch (e) {
|
|
throwMalformedError(String(e));
|
|
}
|
|
}
|
|
};
|
|
const skipBlank = () => {
|
|
while (index < length && " \n\r ".includes(jsonString[index])) {
|
|
index++;
|
|
}
|
|
};
|
|
return parseAny();
|
|
};
|
|
partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/streaming.mjs
|
|
var init_streaming2 = __esm({
|
|
"node_modules/openai/streaming.mjs"() {
|
|
init_streaming();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/ChatCompletionStream.mjs
|
|
function parseStructuredStreamingJSON(content) {
|
|
try {
|
|
return partialParse(content);
|
|
} catch (error) {
|
|
if (error instanceof MalformedJSON || error instanceof SyntaxError) {
|
|
return parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, content);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
function makeChatCompletionReadableStreamMessageChunk(chunk, message, toolCallIds) {
|
|
const payload = {
|
|
type: "message",
|
|
message,
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...toolCallIds ? { tool_call_ids: toolCallIds } : {}
|
|
};
|
|
return {
|
|
id: chunk.id,
|
|
choices: [],
|
|
created: chunk.created,
|
|
model: chunk.model,
|
|
object: `${CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX}${JSON.stringify(payload)}`
|
|
};
|
|
}
|
|
function isChatCompletionReadableStreamMessage(item) {
|
|
return "type" in item && item.type === "message" && "message" in item || "object" in item && typeof item.object === "string" && item.object.startsWith(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX);
|
|
}
|
|
function getChatCompletionReadableStreamMessage(item) {
|
|
if ("type" in item) {
|
|
return item;
|
|
}
|
|
return JSON.parse(item.object.slice(CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX.length));
|
|
}
|
|
function createPartialJSONParseState() {
|
|
return {
|
|
bytes: 0,
|
|
depth: 0,
|
|
fragments: 0,
|
|
work: 0,
|
|
escaped: false,
|
|
has_non_whitespace: false,
|
|
in_string: false,
|
|
last_parsed_bytes: 0,
|
|
pending_high_surrogate: false
|
|
};
|
|
}
|
|
function recordPartialJSONFragment(state2, budget, fragment, validationWorkBudget) {
|
|
if (budget.fragments >= MAX_PARTIAL_JSON_FRAGMENTS) {
|
|
throw new OpenAIError("Chat completion stream exceeded its structured JSON fragment limit");
|
|
}
|
|
let bytes2 = 0;
|
|
let { depth, escaped, has_non_whitespace: hasNonWhitespace, in_string: inString } = state2;
|
|
let completed = false;
|
|
let firstCharacter = true;
|
|
for (const character of fragment) {
|
|
const previousBytes = bytes2;
|
|
const codePoint = character.codePointAt(0);
|
|
if (firstCharacter && state2.pending_high_surrogate && codePoint >= 56320 && codePoint <= 57343) {
|
|
bytes2 += 1;
|
|
} else if (codePoint <= 127) {
|
|
bytes2 += 1;
|
|
} else if (codePoint <= 2047) {
|
|
bytes2 += 2;
|
|
} else if (codePoint <= 65535) {
|
|
bytes2 += 3;
|
|
} else {
|
|
bytes2 += 4;
|
|
}
|
|
firstCharacter = false;
|
|
if (budget.bytes + bytes2 > MAX_PARTIAL_JSON_BYTES) {
|
|
throw new OpenAIError("Chat completion stream exceeded its structured JSON byte limit");
|
|
}
|
|
if (validationWorkBudget && validationWorkBudget.work + bytes2 > MAX_PARTIAL_JSON_PARSE_WORK) {
|
|
validationWorkBudget.work += previousBytes;
|
|
throw new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");
|
|
}
|
|
if (character !== " " && character !== "\n" && character !== "\r" && character !== " ") {
|
|
hasNonWhitespace = true;
|
|
}
|
|
if (inString) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
} else if (character === "\\") {
|
|
escaped = true;
|
|
} else if (character === '"') {
|
|
inString = false;
|
|
completed || (completed = depth === 0);
|
|
}
|
|
continue;
|
|
}
|
|
if (character === '"') {
|
|
inString = true;
|
|
} else if (character === "{" || character === "[") {
|
|
depth += 1;
|
|
if (depth > MAX_PARTIAL_JSON_DEPTH) {
|
|
throw new OpenAIError("Chat completion stream exceeded its structured JSON nesting depth limit");
|
|
}
|
|
} else if ((character === "}" || character === "]") && depth > 0) {
|
|
depth -= 1;
|
|
completed || (completed = depth === 0);
|
|
}
|
|
}
|
|
state2.bytes += bytes2;
|
|
state2.fragments += 1;
|
|
state2.depth = depth;
|
|
state2.escaped = escaped;
|
|
state2.has_non_whitespace = hasNonWhitespace;
|
|
state2.in_string = inString;
|
|
if (fragment.length > 0) {
|
|
const finalCodeUnit = fragment.codePointAt(fragment.length - 1) ?? 0;
|
|
state2.pending_high_surrogate = finalCodeUnit >= 55296 && finalCodeUnit <= 56319;
|
|
}
|
|
budget.bytes += bytes2;
|
|
budget.fragments += 1;
|
|
if (validationWorkBudget) {
|
|
validationWorkBudget.work += bytes2;
|
|
}
|
|
if (!hasNonWhitespace || bytes2 === 0) {
|
|
return false;
|
|
}
|
|
const minimumGrowth = Math.max(EAGER_PARTIAL_JSON_BYTES, Math.floor(state2.last_parsed_bytes / 2));
|
|
if (state2.bytes > EAGER_PARTIAL_JSON_BYTES && !completed && state2.bytes - state2.last_parsed_bytes < minimumGrowth) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
function reservePartialJSONParse(state2, budget) {
|
|
if (budget.work + state2.bytes > MAX_PARTIAL_JSON_PARSE_WORK) {
|
|
return false;
|
|
}
|
|
budget.work += state2.bytes;
|
|
state2.work += state2.bytes;
|
|
state2.last_parsed_bytes = state2.bytes;
|
|
return true;
|
|
}
|
|
function captureStructuredJSONSnapshot(snapshot, property) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(snapshot, property);
|
|
if (!descriptor) {
|
|
let prototype = Object.getPrototypeOf(snapshot);
|
|
for (let depth = 0; prototype !== null; depth += 1) {
|
|
if (depth >= MAX_PARTIAL_JSON_DEPTH || Object.getOwnPropertyDescriptor(prototype, property)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
prototype = Object.getPrototypeOf(prototype);
|
|
}
|
|
return void 0;
|
|
}
|
|
if (!("value" in descriptor) || typeof descriptor.value !== "string" && descriptor.value !== null && descriptor.value !== void 0) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
return descriptor.value;
|
|
}
|
|
function captureStructuredMessageSnapshot(choice) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(choice, "message");
|
|
if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "object" || descriptor.value === null) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
return descriptor.value;
|
|
}
|
|
function captureSnapshotArray(snapshot, property, maximum, kind) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(snapshot, property);
|
|
if (!descriptor) {
|
|
let prototype = Object.getPrototypeOf(snapshot);
|
|
for (let depth = 0; prototype !== null; depth += 1) {
|
|
if (depth >= MAX_PARTIAL_JSON_DEPTH || Object.getOwnPropertyDescriptor(prototype, property)) {
|
|
throw new OpenAIError(`Chat completion stream contains an unsafe snapshot ${kind} collection`);
|
|
}
|
|
prototype = Object.getPrototypeOf(prototype);
|
|
}
|
|
return void 0;
|
|
}
|
|
if (!("value" in descriptor) || !Array.isArray(descriptor.value)) {
|
|
throw new OpenAIError(`Chat completion stream contains an unsafe snapshot ${kind} collection`);
|
|
}
|
|
const length = Object.getOwnPropertyDescriptor(descriptor.value, "length");
|
|
if (!length || !("value" in length) || !Number.isSafeInteger(length.value) || length.value > maximum) {
|
|
throw new OpenAIError(`Chat completion stream exceeded its snapshot ${kind} limit`);
|
|
}
|
|
return descriptor.value;
|
|
}
|
|
function captureSnapshotArrayItem(array, index) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(array, index);
|
|
if (!descriptor) {
|
|
return void 0;
|
|
}
|
|
if (!("value" in descriptor)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
return descriptor.value;
|
|
}
|
|
function mapCapturedSnapshotArray(array, maximum, kind, map3) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(array, "length");
|
|
const length = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maximum) {
|
|
throw new OpenAIError(`Chat completion stream exceeded its snapshot ${kind} limit`);
|
|
}
|
|
const mapped = [];
|
|
mapped.length = length;
|
|
for (let index = 0; index < length; index += 1) {
|
|
const item = Object.getOwnPropertyDescriptor(array, index);
|
|
if (!item) {
|
|
continue;
|
|
}
|
|
if (!("value" in item)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
mapped[index] = map3(item.value, index);
|
|
}
|
|
return mapped;
|
|
}
|
|
function validateStructuredJSONSnapshot(value, budget, validationWorkBudget) {
|
|
const state2 = createPartialJSONParseState();
|
|
const parseBudget = budget ?? { bytes: 0, fragments: 0, work: 0 };
|
|
recordPartialJSONFragment(state2, parseBudget, value, validationWorkBudget);
|
|
if (!reservePartialJSONParse(state2, parseBudget)) {
|
|
throw new OpenAIError("Chat completion stream exceeded its structured JSON parse-work limit");
|
|
}
|
|
return value;
|
|
}
|
|
function ownFunctionToolIdentity(toolCall) {
|
|
const type = Object.getOwnPropertyDescriptor(toolCall, "type");
|
|
const fn = Object.getOwnPropertyDescriptor(toolCall, "function");
|
|
if (!type || !("value" in type) || type.value !== "function" || !fn || !("value" in fn)) {
|
|
return void 0;
|
|
}
|
|
if (typeof fn.value !== "object" || fn.value === null) {
|
|
return void 0;
|
|
}
|
|
const name = Object.getOwnPropertyDescriptor(fn.value, "name");
|
|
if (!name || !("value" in name) || typeof name.value !== "string" || name.value.length === 0) {
|
|
return void 0;
|
|
}
|
|
return { type: "function", name: name.value };
|
|
}
|
|
function assertBoundToolCallIdentity(toolCall, identity) {
|
|
const current = ownFunctionToolIdentity(toolCall);
|
|
if (!current || current.name !== identity.name || current.type !== identity.type) {
|
|
throw new OpenAIError("Chat completion stream contains a changed tool call identity");
|
|
}
|
|
}
|
|
function assignOwnProperties(target, source) {
|
|
if (Object.prototype.propertyIsEnumerable.call(source, "__proto__") && !hasOwn(target, "__proto__")) {
|
|
Object.defineProperty(target, "__proto__", {
|
|
value: void 0,
|
|
writable: true,
|
|
enumerable: true,
|
|
configurable: true
|
|
});
|
|
}
|
|
return Object.assign(target, source);
|
|
}
|
|
function cloneParserConfigObject(value, stableFields = []) {
|
|
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
for (const field of stableFields) {
|
|
const descriptor = descriptors[field];
|
|
if (!descriptor && !(field in value)) {
|
|
continue;
|
|
}
|
|
descriptors[field] = {
|
|
// oxlint-disable-next-line anti-slop/no-reflect-get -- Generic config cloning must resolve inherited/accessor keys outside the declared config shape.
|
|
value: descriptor && "value" in descriptor ? descriptor.value : Reflect.get(value, field, value),
|
|
enumerable: descriptor?.enumerable ?? false,
|
|
configurable: descriptor?.configurable ?? true,
|
|
writable: descriptor && "writable" in descriptor ? descriptor.writable : false
|
|
};
|
|
}
|
|
return Object.create(Object.getPrototypeOf(value), descriptors);
|
|
}
|
|
function snapshotChatCompletionParserParams(params) {
|
|
const snapshot = cloneParserConfigObject(params);
|
|
if (params.tools) {
|
|
const stableTools = [];
|
|
const lengthDescriptor = Object.getOwnPropertyDescriptor(params.tools, "length");
|
|
const length = lengthDescriptor && "value" in lengthDescriptor ? lengthDescriptor.value : void 0;
|
|
const toolCount = typeof length === "number" && Number.isSafeInteger(length) && length >= 0 ? Math.min(length, MAX_STREAM_TOOL_CALLS) : 0;
|
|
for (let index = 0; index < toolCount; index += 1) {
|
|
const item = Object.getOwnPropertyDescriptor(params.tools, String(index));
|
|
if (!item || !("value" in item)) {
|
|
stableTools.length = index + 1;
|
|
continue;
|
|
}
|
|
const tool = item.value;
|
|
const stableTool = cloneParserConfigObject(tool, [
|
|
"type",
|
|
"$brand",
|
|
"$parseRaw",
|
|
"$callback",
|
|
"function"
|
|
]);
|
|
const descriptors = Object.getOwnPropertyDescriptors(stableTool);
|
|
if (isChatCompletionFunctionTool(stableTool)) {
|
|
const descriptor = descriptors.function;
|
|
descriptors.function = {
|
|
...descriptor && "value" in descriptor ? descriptor : { configurable: true, enumerable: true, writable: true },
|
|
value: cloneParserConfigObject(stableTool.function, ["name", "strict"])
|
|
};
|
|
}
|
|
stableTools[index] = Object.create(Object.getPrototypeOf(tool), descriptors);
|
|
}
|
|
snapshot.tools = stableTools;
|
|
}
|
|
if (params.response_format) {
|
|
snapshot.response_format = cloneParserConfigObject(params.response_format, [
|
|
"type",
|
|
"$brand",
|
|
"$parseRaw"
|
|
]);
|
|
}
|
|
return snapshot;
|
|
}
|
|
function canonicalSerializedParserSchema(value, budget) {
|
|
const ancestors = /* @__PURE__ */ new WeakSet();
|
|
const charge = (bytes2) => {
|
|
if (!Number.isSafeInteger(bytes2) || bytes2 < 0 || budget.bytes + bytes2 > MAX_SERIALIZED_PARSER_SCHEMA_BYTES) {
|
|
return false;
|
|
}
|
|
budget.bytes += bytes2;
|
|
return true;
|
|
};
|
|
const visit3 = (current, depth) => {
|
|
if (depth > MAX_SERIALIZED_PARSER_SCHEMA_DEPTH || budget.nodes >= MAX_SERIALIZED_PARSER_SCHEMA_NODES) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
budget.nodes += 1;
|
|
if (current === void 0 || typeof current === "function" || typeof current === "symbol") {
|
|
return OMITTED_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
if (typeof current === "bigint") {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
if (current === null || typeof current === "boolean" || typeof current === "number") {
|
|
const serialized = stringifyParserSchemaValue(current);
|
|
return typeof serialized === "string" && charge(serialized.length) ? serialized : UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
if (typeof current === "string") {
|
|
if (!charge(current.length * 6 + 2)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
return stringifyParserSchemaValue(current);
|
|
}
|
|
if (typeof current !== "object" || ancestors.has(current)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
const array = Array.isArray(current);
|
|
const prototype = Object.getPrototypeOf(current);
|
|
if (array && prototype !== Array.prototype || !array && prototype !== null && prototype !== Object.prototype) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
for (let owner = current; owner !== null; owner = Object.getPrototypeOf(owner)) {
|
|
const serializer = Object.getOwnPropertyDescriptor(owner, "toJSON");
|
|
if (!serializer) {
|
|
continue;
|
|
}
|
|
if (!("value" in serializer) || typeof serializer.value === "function") {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
break;
|
|
}
|
|
ancestors.add(current);
|
|
try {
|
|
if (!charge(2)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
if (array) {
|
|
const lengthDescriptor = Object.getOwnPropertyDescriptor(current, "length");
|
|
const length = lengthDescriptor && "value" in lengthDescriptor ? lengthDescriptor.value : void 0;
|
|
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > MAX_SERIALIZED_PARSER_SCHEMA_NODES - budget.nodes) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
const items = [];
|
|
for (let index = 0; index < length; index += 1) {
|
|
const key = String(index);
|
|
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
if (!descriptor) {
|
|
if (Object.getOwnPropertyDescriptor(Array.prototype, key) || Object.getOwnPropertyDescriptor(Object.prototype, key)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
budget.nodes += 1;
|
|
if (!charge(4)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
items.push("null");
|
|
continue;
|
|
}
|
|
if (!("value" in descriptor)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
const item = visit3(descriptor.value, depth + 1);
|
|
if (item === UNSAFE_SERIALIZED_PARSER_VALUE) {
|
|
return item;
|
|
}
|
|
items.push(item === OMITTED_SERIALIZED_PARSER_VALUE ? "null" : item);
|
|
}
|
|
return `[${items.join(",")}]`;
|
|
}
|
|
const keys = Reflect.ownKeys(current);
|
|
if (keys.length > MAX_SERIALIZED_PARSER_SCHEMA_NODES - budget.nodes) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
const entries = [];
|
|
for (const key of keys) {
|
|
if (typeof key !== "string") {
|
|
continue;
|
|
}
|
|
const descriptor = Object.getOwnPropertyDescriptor(current, key);
|
|
if (!descriptor) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
if (!descriptor.enumerable) {
|
|
continue;
|
|
}
|
|
if (!("value" in descriptor)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
entries.push([key, descriptor.value]);
|
|
}
|
|
entries.sort(([left], [right]) => {
|
|
if (left === right) {
|
|
return 0;
|
|
}
|
|
return left < right ? -1 : 1;
|
|
});
|
|
const fields = [];
|
|
for (const [key, entry] of entries) {
|
|
const normalized = visit3(entry, depth + 1);
|
|
if (normalized === UNSAFE_SERIALIZED_PARSER_VALUE) {
|
|
return normalized;
|
|
}
|
|
if (normalized === OMITTED_SERIALIZED_PARSER_VALUE) {
|
|
continue;
|
|
}
|
|
if (!charge(key.length * 6 + 3)) {
|
|
return UNSAFE_SERIALIZED_PARSER_VALUE;
|
|
}
|
|
fields.push(`${stringifyParserSchemaValue(key)}:${normalized}`);
|
|
}
|
|
return `{${fields.join(",")}}`;
|
|
} finally {
|
|
ancestors.delete(current);
|
|
}
|
|
};
|
|
try {
|
|
const normalized = visit3(value, 0);
|
|
return typeof normalized === "string" ? normalized : void 0;
|
|
} catch {
|
|
return void 0;
|
|
}
|
|
}
|
|
function rememberSerializedParserSchema(signatures, source, holder, key) {
|
|
const parser = Object.getOwnPropertyDescriptor(source, "$parseRaw");
|
|
const schema4 = Object.getOwnPropertyDescriptor(holder, key);
|
|
if (!parser || !("value" in parser) || typeof parser.value !== "function" || !schema4 || !("value" in schema4)) {
|
|
return;
|
|
}
|
|
const normalized = canonicalSerializedParserSchema(schema4.value, { nodes: 0, bytes: 0 });
|
|
if (normalized !== void 0) {
|
|
signatures.set(source, normalized);
|
|
}
|
|
}
|
|
function hasMatchingSerializedParserSchema(signatures, source, holder, key, value) {
|
|
const expected = source && signatures.get(source);
|
|
const descriptor = Object.getOwnPropertyDescriptor(holder, key);
|
|
return expected !== void 0 && descriptor !== void 0 && "value" in descriptor && canonicalSerializedParserSchema(value, { nodes: 0, bytes: 0 }) === expected;
|
|
}
|
|
function serializedParserDescriptor(descriptor, value) {
|
|
return descriptor && "value" in descriptor ? { ...descriptor, value } : { configurable: true, enumerable: true, writable: true, value };
|
|
}
|
|
function shadowSerializedParserMetadata(descriptors, source, fields) {
|
|
for (const field of fields) {
|
|
const descriptor = descriptors[field];
|
|
if (!descriptor && !(field in source)) {
|
|
continue;
|
|
}
|
|
descriptors[field] = descriptor && "value" in descriptor ? { ...descriptor, value: void 0 } : {
|
|
configurable: descriptor?.configurable ?? true,
|
|
enumerable: descriptor?.enumerable ?? false,
|
|
writable: false,
|
|
value: void 0
|
|
};
|
|
}
|
|
}
|
|
function snapshotSerializedParserTool(serialized) {
|
|
const source = serialized.source ?? {
|
|
type: serialized.type,
|
|
...serialized.type === "function" ? { function: {} } : {}
|
|
};
|
|
const descriptors = Object.getOwnPropertyDescriptors(source);
|
|
descriptors.type = serializedParserDescriptor(descriptors.type, serialized.type);
|
|
if (serialized.type !== "function" || !serialized.function) {
|
|
if (descriptors.function) {
|
|
descriptors.function = serializedParserDescriptor(descriptors.function, void 0);
|
|
}
|
|
shadowSerializedParserMetadata(descriptors, source, ["$brand", "$parseRaw", "$callback"]);
|
|
return Object.create(Object.getPrototypeOf(source), descriptors);
|
|
}
|
|
const descriptor = descriptors.function;
|
|
const original = descriptor && "value" in descriptor && typeof descriptor.value === "object" && descriptor.value !== null ? descriptor.value : {};
|
|
const functionDescriptors = Object.getOwnPropertyDescriptors(original);
|
|
functionDescriptors["name"] = serializedParserDescriptor(functionDescriptors["name"], serialized.function.name);
|
|
functionDescriptors["strict"] = serializedParserDescriptor(functionDescriptors["strict"], serialized.function.strict);
|
|
descriptors.function = serializedParserDescriptor(descriptor, Object.create(Object.getPrototypeOf(original), functionDescriptors));
|
|
if (!serialized.function.schemaMatches) {
|
|
shadowSerializedParserMetadata(descriptors, source, ["$brand", "$parseRaw", "$callback"]);
|
|
}
|
|
return Object.create(Object.getPrototypeOf(source), descriptors);
|
|
}
|
|
function snapshotSerializedResponseFormat(serialized) {
|
|
const source = serialized.source ?? { type: serialized.type };
|
|
const descriptors = Object.getOwnPropertyDescriptors(source);
|
|
descriptors.type = serializedParserDescriptor(descriptors.type, serialized.type);
|
|
if (serialized.type !== "json_schema" || !serialized.source || !serialized.schemaMatches) {
|
|
shadowSerializedParserMetadata(descriptors, source, ["$brand", "$parseRaw"]);
|
|
}
|
|
return Object.create(Object.getPrototypeOf(source), descriptors);
|
|
}
|
|
function ownSerializedParserObject(holder, key) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(holder, key);
|
|
if (!descriptor || !("value" in descriptor)) {
|
|
return void 0;
|
|
}
|
|
const { value } = descriptor;
|
|
return typeof value === "object" && value !== null ? value : void 0;
|
|
}
|
|
function observeSerializedChatCompletionParserParams(body, initial, update) {
|
|
const originalToolOwners = /* @__PURE__ */ new WeakMap();
|
|
const originalSchemaSignatures = /* @__PURE__ */ new WeakMap();
|
|
if (body.tools) {
|
|
for (let index = 0; index < body.tools.length && index < MAX_STREAM_TOOL_CALLS; index += 1) {
|
|
const owner = ownSerializedParserObject(body.tools, String(index));
|
|
const source = initial.tools?.[index];
|
|
if (owner && source) {
|
|
originalToolOwners.set(owner, source);
|
|
const originalFunction = ownSerializedParserObject(source, "function");
|
|
if (originalFunction) {
|
|
rememberSerializedParserSchema(originalSchemaSignatures, source, originalFunction, "parameters");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (initial.response_format) {
|
|
rememberSerializedParserSchema(originalSchemaSignatures, initial.response_format, initial.response_format, "json_schema");
|
|
}
|
|
let root;
|
|
let tools;
|
|
let responseFormat;
|
|
let responseFrame;
|
|
let frames = [];
|
|
let toolFrames = /* @__PURE__ */ new WeakMap();
|
|
let actualToolOwners = /* @__PURE__ */ new Map();
|
|
let functionFrames = /* @__PURE__ */ new WeakMap();
|
|
return observeJSONRequestBody(body, {
|
|
value(holder, key, value) {
|
|
if (!root && key === "" && typeof value === "object" && value !== null) {
|
|
root = value;
|
|
tools = void 0;
|
|
responseFormat = void 0;
|
|
responseFrame = void 0;
|
|
frames = [];
|
|
toolFrames = /* @__PURE__ */ new WeakMap();
|
|
actualToolOwners = /* @__PURE__ */ new Map();
|
|
functionFrames = /* @__PURE__ */ new WeakMap();
|
|
return;
|
|
}
|
|
if (holder === root && key === "response_format") {
|
|
if (typeof value === "object" && value !== null) {
|
|
responseFormat = value;
|
|
const owner = ownSerializedParserObject(holder, key);
|
|
responseFrame = {
|
|
source: owner === body.response_format ? initial.response_format : void 0,
|
|
schemaMatches: false
|
|
};
|
|
}
|
|
return;
|
|
}
|
|
if (holder === root && key === "tools") {
|
|
if (Array.isArray(value)) {
|
|
tools = new Proxy(value, {
|
|
get(target, property) {
|
|
const actual = Reflect.get(target, property, target);
|
|
if (typeof property === "string") {
|
|
const index = Number(property);
|
|
if (Number.isSafeInteger(index) && index >= 0 && index < MAX_STREAM_TOOL_CALLS && String(index) === property) {
|
|
actualToolOwners.set(index, typeof actual === "object" && actual !== null ? actual : void 0);
|
|
}
|
|
}
|
|
return actual;
|
|
}
|
|
});
|
|
return tools;
|
|
}
|
|
return;
|
|
}
|
|
if (holder === tools) {
|
|
const index = Number(key);
|
|
if (!Number.isSafeInteger(index) || index < 0 || index >= MAX_STREAM_TOOL_CALLS || typeof value !== "object" || value === null) {
|
|
return;
|
|
}
|
|
const owner = actualToolOwners.get(index);
|
|
const source = owner ? originalToolOwners.get(owner) : void 0;
|
|
const frame = { source };
|
|
frames[index] = frame;
|
|
toolFrames.set(value, frame);
|
|
return;
|
|
}
|
|
const tool = toolFrames.get(holder);
|
|
if (tool) {
|
|
if (key === "type" && typeof value === "string") {
|
|
tool.type = value;
|
|
} else if (key === "function" && typeof value === "object" && value !== null) {
|
|
const fn2 = { source: tool.source, schemaMatches: false };
|
|
tool.function = fn2;
|
|
functionFrames.set(value, fn2);
|
|
}
|
|
return;
|
|
}
|
|
if (holder === responseFormat && responseFrame) {
|
|
if (key === "type" && typeof value === "string") {
|
|
responseFrame.type = value;
|
|
} else if (key === "json_schema") {
|
|
responseFrame.schemaMatches = hasMatchingSerializedParserSchema(originalSchemaSignatures, responseFrame.source, holder, key, value);
|
|
}
|
|
return;
|
|
}
|
|
const fn = functionFrames.get(holder);
|
|
if (fn) {
|
|
if (key === "name" && typeof value === "string") {
|
|
fn.name = value;
|
|
} else if (key === "strict" && typeof value === "boolean") {
|
|
fn.strict = value;
|
|
} else if (key === "parameters") {
|
|
fn.schemaMatches = hasMatchingSerializedParserSchema(originalSchemaSignatures, fn.source, holder, key, value);
|
|
}
|
|
}
|
|
return void 0;
|
|
},
|
|
complete() {
|
|
if (!root) {
|
|
return;
|
|
}
|
|
const snapshot = cloneParserConfigObject(initial);
|
|
if (tools) {
|
|
const serializedTools = [];
|
|
for (let index = 0; index < frames.length; index += 1) {
|
|
const frame = frames[index];
|
|
if (frame) {
|
|
serializedTools[index] = snapshotSerializedParserTool(frame);
|
|
}
|
|
}
|
|
snapshot.tools = serializedTools;
|
|
} else {
|
|
delete snapshot.tools;
|
|
}
|
|
if (responseFrame) {
|
|
snapshot.response_format = snapshotSerializedResponseFormat(responseFrame);
|
|
} else {
|
|
delete snapshot.response_format;
|
|
}
|
|
update(snapshot);
|
|
root = void 0;
|
|
tools = void 0;
|
|
responseFormat = void 0;
|
|
responseFrame = void 0;
|
|
frames = [];
|
|
toolFrames = /* @__PURE__ */ new WeakMap();
|
|
actualToolOwners = /* @__PURE__ */ new Map();
|
|
functionFrames = /* @__PURE__ */ new WeakMap();
|
|
}
|
|
});
|
|
}
|
|
function finalizeChatCompletion(snapshot, params, audioDoneChoiceIndexes, validatedMessages) {
|
|
const { id, choices, created, model: model2, system_fingerprint, ...rest } = snapshot;
|
|
const completion = {
|
|
...rest,
|
|
id,
|
|
choices: mapCapturedSnapshotArray(choices, MAX_STREAM_CHOICES, "choice", (choice) => {
|
|
const validated = validatedMessages.get(choice);
|
|
if (!validated) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
const stableChoice = new Proxy(choice, {
|
|
get(target, property, receiver) {
|
|
return property === "message" ? validated.message : Reflect.get(target, property, receiver);
|
|
}
|
|
});
|
|
const { message: sourceMessage, finish_reason, index, logprobs, ...choiceRest } = stableChoice;
|
|
const message = new Proxy(sourceMessage, {
|
|
get(target, property, receiver) {
|
|
if (property === "content") {
|
|
return validated.content;
|
|
}
|
|
if (property === "refusal") {
|
|
return validated.refusal;
|
|
}
|
|
if (property === "tool_calls") {
|
|
return validated.toolCallCollection;
|
|
}
|
|
return Reflect.get(target, property, receiver);
|
|
}
|
|
});
|
|
const { content = null, function_call, tool_calls, audio, ...messageRest } = message;
|
|
const finishReason = finish_reason ?? (audioDoneChoiceIndexes.has(index) && isCompleteAudio(audio) ? "stop" : null);
|
|
if (!finishReason) {
|
|
throw new OpenAIError(`missing finish_reason for choice ${index}`);
|
|
}
|
|
const audioResponse = audio ? { audio } : {};
|
|
const role = message.role;
|
|
if (!role) {
|
|
throw new OpenAIError(`missing role for choice ${index}`);
|
|
}
|
|
if (function_call) {
|
|
const { arguments: args, name } = function_call;
|
|
if (args == null) {
|
|
throw new OpenAIError(`missing function_call.arguments for choice ${index}`);
|
|
}
|
|
if (!name) {
|
|
throw new OpenAIError(`missing function_call.name for choice ${index}`);
|
|
}
|
|
return {
|
|
...choiceRest,
|
|
message: {
|
|
...audioResponse,
|
|
content,
|
|
function_call: { arguments: args, name },
|
|
role,
|
|
refusal: message.refusal ?? null
|
|
},
|
|
finish_reason: finishReason,
|
|
index,
|
|
logprobs
|
|
};
|
|
}
|
|
if (tool_calls) {
|
|
return {
|
|
...choiceRest,
|
|
index,
|
|
finish_reason: finishReason,
|
|
logprobs,
|
|
message: {
|
|
...messageRest,
|
|
...audioResponse,
|
|
role,
|
|
content,
|
|
refusal: message.refusal ?? null,
|
|
tool_calls: mapCapturedSnapshotArray(tool_calls, MAX_STREAM_TOOL_CALLS, "tool-call", (tool_call, i) => {
|
|
const captured = validated.toolCalls.get(i);
|
|
if (!captured) {
|
|
const identity = ownFunctionToolIdentity(tool_call);
|
|
if (identity && shouldParseToolCall(params, {
|
|
type: identity.type,
|
|
function: { name: identity.name }
|
|
})) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
}
|
|
if (captured && captured.tool !== tool_call) {
|
|
throw new OpenAIError("Chat completion stream contains a changed tool call identity");
|
|
}
|
|
const stableFunction = captured && new Proxy(captured.function, {
|
|
get(target, property, receiver) {
|
|
if (property === "arguments") {
|
|
return captured.arguments;
|
|
}
|
|
if (property === "name") {
|
|
return captured.name;
|
|
}
|
|
return Reflect.get(target, property, receiver);
|
|
}
|
|
});
|
|
const stableTool = captured && stableFunction ? new Proxy(tool_call, {
|
|
get(target, property, receiver) {
|
|
if (property === "type") {
|
|
return captured.type;
|
|
}
|
|
if (property === "function") {
|
|
return stableFunction;
|
|
}
|
|
return Reflect.get(target, property, receiver);
|
|
}
|
|
}) : tool_call;
|
|
if (stableTool.type == null) {
|
|
throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type`);
|
|
}
|
|
if (stableTool.type === "custom") {
|
|
const { custom, type: type2, id: id3, ...toolRest2 } = stableTool;
|
|
const { input = "", name: name2, ...customRest } = custom || {};
|
|
if (name2 == null) {
|
|
throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].custom.name`);
|
|
}
|
|
return {
|
|
...toolRest2,
|
|
id: id3 || `call_${uuid4()}`,
|
|
type: type2,
|
|
custom: { ...customRest, name: name2, input }
|
|
};
|
|
}
|
|
const { function: fn, type, id: id2, ...toolRest } = stableTool;
|
|
const { arguments: args, name, ...fnRest } = fn || {};
|
|
if (name == null) {
|
|
throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name`);
|
|
}
|
|
if (args == null) {
|
|
throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments`);
|
|
}
|
|
return {
|
|
...toolRest,
|
|
id: id2 || `call_${uuid4()}`,
|
|
type,
|
|
function: { ...fnRest, name, arguments: args }
|
|
};
|
|
})
|
|
}
|
|
};
|
|
}
|
|
return {
|
|
...choiceRest,
|
|
message: { ...messageRest, ...audioResponse, content, role, refusal: message.refusal ?? null },
|
|
finish_reason: finishReason,
|
|
index,
|
|
logprobs
|
|
};
|
|
}),
|
|
created,
|
|
model: model2,
|
|
object: "chat.completion",
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...system_fingerprint ? { system_fingerprint } : {}
|
|
};
|
|
return maybeParseChatCompletion(completion, params);
|
|
}
|
|
function isCompleteAudio(audio) {
|
|
return audio?.id != null && audio.data != null && audio.transcript != null && audio.expires_at != null;
|
|
}
|
|
function assertIsEmpty(obj2) {
|
|
void obj2;
|
|
}
|
|
function assertNever(_x) {
|
|
return _x;
|
|
}
|
|
var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_rejectsUnfinishedTurns, _ChatCompletionStream_audioDoneChoiceIndexes, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_hasAutoParseableTool, _ChatCompletionStream_partialJSONParseBudget, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_validateStructuredSnapshots, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion, CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX, MAX_STREAM_CHOICES, MAX_STREAM_TOOL_CALLS, MAX_PARTIAL_JSON_BYTES, MAX_PARTIAL_JSON_FRAGMENTS, MAX_PARTIAL_JSON_DEPTH, MAX_PARTIAL_JSON_PARSE_WORK, EAGER_PARTIAL_JSON_BYTES, MAX_SERIALIZED_PARSER_SCHEMA_NODES, stringifyParserSchemaValue, MAX_SERIALIZED_PARSER_SCHEMA_BYTES, MAX_SERIALIZED_PARSER_SCHEMA_DEPTH, OMITTED_SERIALIZED_PARSER_VALUE, UNSAFE_SERIALIZED_PARSER_VALUE, ChatCompletionStream;
|
|
var init_ChatCompletionStream = __esm({
|
|
"node_modules/openai/lib/ChatCompletionStream.mjs"() {
|
|
init_tslib();
|
|
init_parser2();
|
|
init_error2();
|
|
init_request_options();
|
|
init_uuid();
|
|
init_values();
|
|
init_parser();
|
|
init_streaming2();
|
|
init_AbstractChatCompletionRunner();
|
|
CHAT_COMPLETION_READABLE_STREAM_MESSAGE_PREFIX = "chat.completion.chunk.message:";
|
|
MAX_STREAM_CHOICES = 128;
|
|
MAX_STREAM_TOOL_CALLS = 128;
|
|
MAX_PARTIAL_JSON_BYTES = 16 * 1024 * 1024;
|
|
MAX_PARTIAL_JSON_FRAGMENTS = 65536;
|
|
MAX_PARTIAL_JSON_DEPTH = 128;
|
|
MAX_PARTIAL_JSON_PARSE_WORK = 64 * 1024 * 1024;
|
|
EAGER_PARTIAL_JSON_BYTES = 1024;
|
|
MAX_SERIALIZED_PARSER_SCHEMA_NODES = 4096;
|
|
stringifyParserSchemaValue = JSON.stringify;
|
|
MAX_SERIALIZED_PARSER_SCHEMA_BYTES = 1024 * 1024;
|
|
MAX_SERIALIZED_PARSER_SCHEMA_DEPTH = 64;
|
|
OMITTED_SERIALIZED_PARSER_VALUE = /* @__PURE__ */ Symbol("omitted serialized parser value");
|
|
UNSAFE_SERIALIZED_PARSER_VALUE = /* @__PURE__ */ Symbol("unsafe serialized parser value");
|
|
ChatCompletionStream = class _ChatCompletionStream extends AbstractChatCompletionRunner {
|
|
/** Creates an unstarted stream, retaining request parameters for structured-output parsing. */
|
|
constructor(params) {
|
|
super();
|
|
_ChatCompletionStream_instances.add(this);
|
|
_ChatCompletionStream_params.set(this, void 0);
|
|
_ChatCompletionStream_rejectsUnfinishedTurns.set(this, false);
|
|
_ChatCompletionStream_audioDoneChoiceIndexes.set(this, void 0);
|
|
_ChatCompletionStream_choiceEventStates.set(this, void 0);
|
|
_ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);
|
|
_ChatCompletionStream_hasAutoParseableTool.set(this, void 0);
|
|
_ChatCompletionStream_partialJSONParseBudget.set(this, void 0);
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, false, "f");
|
|
const tools = params?.tools;
|
|
const lengthDescriptor = tools && Object.getOwnPropertyDescriptor(tools, "length");
|
|
const length = lengthDescriptor && "value" in lengthDescriptor ? lengthDescriptor.value : void 0;
|
|
if (tools && typeof length === "number" && Number.isSafeInteger(length) && length >= 0) {
|
|
for (let index = 0; index < Math.min(length, MAX_STREAM_TOOL_CALLS); index += 1) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(tools, String(index));
|
|
if (!descriptor || !("value" in descriptor)) {
|
|
continue;
|
|
}
|
|
const tool = descriptor.value;
|
|
if (isChatCompletionFunctionTool(tool) && (isAutoParsableTool(tool) || tool.function.strict === true)) {
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, true, "f");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_partialJSONParseBudget, { bytes: 0, fragments: 0, work: 0 }, "f");
|
|
}
|
|
/** The latest accumulated completion, or `undefined` before a chunk arrives or after finalization. */
|
|
get currentChatCompletionSnapshot() {
|
|
return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
|
|
}
|
|
/**
|
|
* Intended for use on the frontend, consuming a stream produced with
|
|
* `.toReadableStream()` on the backend.
|
|
*
|
|
* Original input messages are not included in the serialized stream. Tool-result
|
|
* messages explicitly serialized by a streaming tool runner are replayed.
|
|
*/
|
|
static fromReadableStream(stream4) {
|
|
const runner = new _ChatCompletionStream(null);
|
|
runner._run(() => runner._fromReadableStream(stream4));
|
|
return runner;
|
|
}
|
|
/** Starts a streaming chat completion request and returns its event-driven helper. */
|
|
static createChatCompletion(client, params, options) {
|
|
const runner = new _ChatCompletionStream(params);
|
|
runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, __metadata: { ...options?.__metadata, helperMethod: "stream" } }));
|
|
return runner;
|
|
}
|
|
/** Rejects unfinished turns before tool callbacks while preserving ordinary stream and replay behavior. */
|
|
_runTools(client, params, runner, options) {
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_rejectsUnfinishedTurns, true, "f");
|
|
return super._runTools(client, params, runner, options);
|
|
}
|
|
async _createChatCompletion(client, params, options) {
|
|
this._listenForAbort(options?.signal);
|
|
const requestParams = { ...params, stream: true };
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_params, requestParams, "f");
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
|
|
const parserParams = snapshotChatCompletionParserParams(requestParams);
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_params, parserParams, "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, parserParams.tools?.some((tool) => isChatCompletionFunctionTool(tool) && (isAutoParsableTool(tool) || tool.function.strict === true)) ?? false, "f");
|
|
const stopObserving = requestParams.tools || requestParams.response_format ? observeSerializedChatCompletionParserParams(requestParams, parserParams, (serialized) => {
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_params, serialized, "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_hasAutoParseableTool, serialized.tools?.some((tool) => isChatCompletionFunctionTool(tool) && (isAutoParsableTool(tool) || tool.function.strict === true)) ?? false, "f");
|
|
}) : void 0;
|
|
const stream4 = await client.chat.completions.create(requestParams, {
|
|
...options,
|
|
signal: this.controller.signal
|
|
}).finally(stopObserving);
|
|
this._connected();
|
|
for await (const chunk of stream4) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
|
|
}
|
|
async _fromReadableStream(readableStream, options) {
|
|
this._listenForAbort(options?.signal);
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
|
|
this._connected();
|
|
const stream4 = Stream.fromReadableStream(readableStream, this.controller);
|
|
let chatId;
|
|
for await (const item of stream4) {
|
|
if ("error" in item && hasOwn(item, "error") && typeof item.error === "object" && item.error !== null) {
|
|
throw new APIError(void 0, item.error, void 0, void 0);
|
|
}
|
|
if (isChatCompletionReadableStreamMessage(item)) {
|
|
const message = getChatCompletionReadableStreamMessage(item);
|
|
if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
|
|
const toolCalls = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f").choices[0]?.message.tool_calls;
|
|
for (const [index, id] of message.tool_call_ids?.entries() ?? []) {
|
|
const toolCall = toolCalls?.[index];
|
|
if (toolCall && id) {
|
|
toolCall.id = id;
|
|
}
|
|
}
|
|
this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
|
|
chatId = void 0;
|
|
}
|
|
this._addMessage(message.message);
|
|
continue;
|
|
}
|
|
const chunk = item;
|
|
if (chatId && chunk.id && chatId !== chunk.id) {
|
|
this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
|
|
}
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk);
|
|
if (chunk.id) {
|
|
chatId = chunk.id;
|
|
}
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
|
|
return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
|
|
}
|
|
const lastChatCompletion = this._chatCompletions[this._chatCompletions.length - 1];
|
|
if (lastChatCompletion) {
|
|
return lastChatCompletion;
|
|
}
|
|
throw new OpenAIError(`request ended without sending any chunks`);
|
|
}
|
|
/** Iterates over raw API chunks; stopping iteration early aborts the underlying request. */
|
|
[(_ChatCompletionStream_params = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_rejectsUnfinishedTurns = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_audioDoneChoiceIndexes = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_choiceEventStates = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_hasAutoParseableTool = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_partialJSONParseBudget = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() {
|
|
if (this.ended) {
|
|
return;
|
|
}
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_partialJSONParseBudget, { bytes: 0, fragments: 0, work: 0 }, "f");
|
|
}, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState2(choice) {
|
|
let state2 = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
|
|
if (state2) {
|
|
return state2;
|
|
}
|
|
state2 = {
|
|
content_done: false,
|
|
content_parse_state: void 0,
|
|
refusal_done: false,
|
|
logprobs_content_done: false,
|
|
logprobs_refusal_done: false,
|
|
done_tool_calls: /* @__PURE__ */ new Set(),
|
|
current_tool_call_index: null,
|
|
tool_call_parse_states: /* @__PURE__ */ new Map(),
|
|
tool_call_identities: /* @__PURE__ */ new Map()
|
|
};
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state2;
|
|
return state2;
|
|
}, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) {
|
|
if (this.ended) {
|
|
return;
|
|
}
|
|
const capturedChoiceFrames = /* @__PURE__ */ new WeakMap();
|
|
const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk, capturedChoiceFrames);
|
|
this._emit("chunk", chunk, completion);
|
|
for (const choice of chunk.choices) {
|
|
const capturedChoice = capturedChoiceFrames.get(choice);
|
|
const choiceSnapshot = completion.choices[capturedChoice?.index ?? choice.index];
|
|
const capturedToolCalls = capturedChoice?.tool_calls ?? [];
|
|
const { delta } = choice;
|
|
const structuredResponse = isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format);
|
|
const boundedSnapshot = structuredResponse || __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f");
|
|
const messageSnapshot = boundedSnapshot ? captureStructuredMessageSnapshot(choiceSnapshot) : choiceSnapshot.message;
|
|
const refusal = boundedSnapshot ? captureStructuredJSONSnapshot(messageSnapshot, "refusal") : messageSnapshot.refusal;
|
|
const parseableContent = !refusal && structuredResponse;
|
|
const messageContent = parseableContent ? captureStructuredJSONSnapshot(messageSnapshot, "content") : messageSnapshot.content;
|
|
if (delta?.content != null && messageSnapshot.role === "assistant" && messageContent) {
|
|
this._emit("content", delta.content, messageContent);
|
|
this._emit("content.delta", {
|
|
delta: delta.content,
|
|
snapshot: messageContent,
|
|
parsed: messageSnapshot.parsed
|
|
});
|
|
}
|
|
if (delta?.refusal != null && messageSnapshot.role === "assistant" && refusal) {
|
|
this._emit("refusal.delta", {
|
|
delta: delta.refusal,
|
|
snapshot: refusal
|
|
});
|
|
}
|
|
if (choice.logprobs?.content != null && messageSnapshot.role === "assistant") {
|
|
this._emit("logprobs.content.delta", {
|
|
content: choice.logprobs?.content,
|
|
snapshot: choiceSnapshot.logprobs?.content ?? []
|
|
});
|
|
}
|
|
if (choice.logprobs?.refusal != null && messageSnapshot.role === "assistant") {
|
|
this._emit("logprobs.refusal.delta", {
|
|
refusal: choice.logprobs?.refusal,
|
|
snapshot: choiceSnapshot.logprobs?.refusal ?? []
|
|
});
|
|
}
|
|
const state2 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
|
|
if (choiceSnapshot.finish_reason) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
|
|
if (state2.current_tool_call_index != null) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state2.current_tool_call_index);
|
|
}
|
|
}
|
|
for (const toolCall of capturedToolCalls) {
|
|
if (state2.current_tool_call_index !== toolCall.index) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);
|
|
if (state2.current_tool_call_index != null) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state2.current_tool_call_index);
|
|
}
|
|
}
|
|
state2.current_tool_call_index = toolCall.index;
|
|
}
|
|
for (const toolCallDelta of capturedToolCalls) {
|
|
const toolCallSnapshot = messageSnapshot.tool_calls?.[toolCallDelta.index];
|
|
if (!toolCallSnapshot?.type) {
|
|
continue;
|
|
}
|
|
if (toolCallSnapshot.type === "function") {
|
|
const boundIdentity = state2.tool_call_identities.get(toolCallDelta.index);
|
|
let argumentsSnapshot;
|
|
if (boundIdentity?.parseable) {
|
|
const capturedArguments = captureStructuredJSONSnapshot(toolCallSnapshot.function, "arguments");
|
|
if (typeof capturedArguments !== "string") {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
argumentsSnapshot = capturedArguments;
|
|
} else {
|
|
argumentsSnapshot = toolCallSnapshot.function.arguments;
|
|
}
|
|
this._emit("tool_calls.function.arguments.delta", {
|
|
name: toolCallSnapshot.function.name,
|
|
index: toolCallDelta.index,
|
|
arguments: argumentsSnapshot,
|
|
parsed_arguments: toolCallSnapshot.function.parsed_arguments,
|
|
arguments_delta: toolCallDelta.arguments_delta
|
|
});
|
|
} else if (toolCallSnapshot.type !== "custom") {
|
|
assertNever(toolCallSnapshot);
|
|
}
|
|
}
|
|
}
|
|
}, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent2(choiceSnapshot, toolCallIndex) {
|
|
const state2 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
|
|
if (state2.done_tool_calls.has(toolCallIndex)) {
|
|
return;
|
|
}
|
|
const messageSnapshot = __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f") ? captureStructuredMessageSnapshot(choiceSnapshot) : choiceSnapshot.message;
|
|
const toolCallSnapshot = messageSnapshot.tool_calls?.[toolCallIndex];
|
|
if (!toolCallSnapshot) {
|
|
throw new Error("no tool call snapshot");
|
|
}
|
|
const boundIdentity = state2.tool_call_identities.get(toolCallIndex);
|
|
if (boundIdentity) {
|
|
assertBoundToolCallIdentity(toolCallSnapshot, boundIdentity);
|
|
}
|
|
if (!toolCallSnapshot.type) {
|
|
throw new Error("tool call snapshot missing `type`");
|
|
}
|
|
if (toolCallSnapshot.type === "function") {
|
|
const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name);
|
|
let parsedArguments = null;
|
|
const parseable = isAutoParsableTool(inputTool) || inputTool?.function.strict === true;
|
|
let argumentsSnapshot;
|
|
if (parseable) {
|
|
if (__classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"));
|
|
}
|
|
const capturedArguments = captureStructuredJSONSnapshot(toolCallSnapshot.function, "arguments");
|
|
if (typeof capturedArguments !== "string") {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
argumentsSnapshot = capturedArguments;
|
|
} else {
|
|
argumentsSnapshot = toolCallSnapshot.function.arguments;
|
|
}
|
|
if (isAutoParsableTool(inputTool)) {
|
|
parsedArguments = inputTool.$parseRaw(validateStructuredJSONSnapshot(argumentsSnapshot));
|
|
} else if (inputTool?.function.strict) {
|
|
parsedArguments = parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, validateStructuredJSONSnapshot(argumentsSnapshot));
|
|
}
|
|
if (choiceSnapshot.finish_reason) {
|
|
state2.done_tool_calls.add(toolCallIndex);
|
|
}
|
|
this._emit("tool_calls.function.arguments.done", {
|
|
name: toolCallSnapshot.function.name,
|
|
index: toolCallIndex,
|
|
arguments: argumentsSnapshot,
|
|
parsed_arguments: parsedArguments
|
|
});
|
|
} else if (toolCallSnapshot.type !== "custom") {
|
|
assertNever(toolCallSnapshot);
|
|
}
|
|
}, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents2(choiceSnapshot) {
|
|
const state2 = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);
|
|
const structuredResponse = isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format);
|
|
const boundedSnapshot = structuredResponse || __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f");
|
|
const messageSnapshot = boundedSnapshot ? captureStructuredMessageSnapshot(choiceSnapshot) : choiceSnapshot.message;
|
|
const refusal = boundedSnapshot ? captureStructuredJSONSnapshot(messageSnapshot, "refusal") : messageSnapshot.refusal;
|
|
const parseableContent = !refusal && structuredResponse;
|
|
const content = parseableContent ? captureStructuredJSONSnapshot(messageSnapshot, "content") : messageSnapshot.content;
|
|
if (content != null && (content !== "" || !refusal && !messageSnapshot.tool_calls?.length && !messageSnapshot.function_call) && !state2.content_done) {
|
|
if (parseableContent && __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f")) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"));
|
|
}
|
|
state2.content_done = true;
|
|
this._emit("content.done", {
|
|
content,
|
|
parsed: refusal ? null : parseResponseFormatContent(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format, parseableContent ? validateStructuredJSONSnapshot(content) : content)
|
|
});
|
|
}
|
|
if (refusal && !state2.refusal_done) {
|
|
state2.refusal_done = true;
|
|
this._emit("refusal.done", { refusal });
|
|
}
|
|
if (choiceSnapshot.logprobs?.content && !state2.logprobs_content_done) {
|
|
state2.logprobs_content_done = true;
|
|
this._emit("logprobs.content.done", { content: choiceSnapshot.logprobs.content });
|
|
}
|
|
if (choiceSnapshot.logprobs?.refusal && !state2.logprobs_refusal_done) {
|
|
state2.logprobs_refusal_done = true;
|
|
this._emit("logprobs.refusal.done", { refusal: choiceSnapshot.logprobs.refusal });
|
|
}
|
|
}, _ChatCompletionStream_validateStructuredSnapshots = function _ChatCompletionStream_validateStructuredSnapshots2(snapshot) {
|
|
const finalJSONBudget = { bytes: 0, fragments: 0, work: 0 };
|
|
const parseableContent = isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format);
|
|
const validatedMessages = /* @__PURE__ */ new WeakMap();
|
|
const choices = captureSnapshotArray(snapshot, "choices", MAX_STREAM_CHOICES, "choice");
|
|
if (!choices) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe snapshot choice collection");
|
|
}
|
|
for (let choiceIndex = 0; choiceIndex < choices.length; choiceIndex += 1) {
|
|
const choice = captureSnapshotArrayItem(choices, choiceIndex);
|
|
if (!choice) {
|
|
continue;
|
|
}
|
|
const message = captureStructuredMessageSnapshot(choice);
|
|
const refusal = captureStructuredJSONSnapshot(message, "refusal");
|
|
const content = captureStructuredJSONSnapshot(message, "content");
|
|
const validatedTools = /* @__PURE__ */ new Map();
|
|
const toolCalls = captureSnapshotArray(message, "tool_calls", MAX_STREAM_TOOL_CALLS, "tool-call");
|
|
validatedMessages.set(choice, Object.freeze({
|
|
message,
|
|
content,
|
|
refusal,
|
|
toolCallCollection: toolCalls,
|
|
toolCalls: validatedTools
|
|
}));
|
|
const state2 = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index];
|
|
if (parseableContent && !refusal && typeof content === "string") {
|
|
validateStructuredJSONSnapshot(content, finalJSONBudget, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"));
|
|
}
|
|
for (const [index, identity] of state2?.tool_call_identities ?? []) {
|
|
const toolCall = toolCalls && captureSnapshotArrayItem(toolCalls, index);
|
|
if (!toolCall) {
|
|
throw new OpenAIError("Chat completion stream contains a changed tool call identity");
|
|
}
|
|
assertBoundToolCallIdentity(toolCall, identity);
|
|
}
|
|
if (!__classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f")) {
|
|
continue;
|
|
}
|
|
for (let toolCallIndex = 0; toolCallIndex < (toolCalls?.length ?? 0); toolCallIndex += 1) {
|
|
const toolCall = captureSnapshotArrayItem(toolCalls, toolCallIndex);
|
|
if (!toolCall) {
|
|
continue;
|
|
}
|
|
const identity = ownFunctionToolIdentity(toolCall);
|
|
if (!identity) {
|
|
const type = Object.getOwnPropertyDescriptor(toolCall, "type");
|
|
if (type && !("value" in type)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
if (type?.value !== "function") {
|
|
continue;
|
|
}
|
|
const fn2 = Object.getOwnPropertyDescriptor(toolCall, "function");
|
|
if (fn2 && !("value" in fn2)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
if (fn2 && typeof fn2.value === "object" && fn2.value !== null) {
|
|
const name = Object.getOwnPropertyDescriptor(fn2.value, "name");
|
|
if (name && !("value" in name)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
if (!shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), {
|
|
type: identity.type,
|
|
function: { name: identity.name }
|
|
})) {
|
|
continue;
|
|
}
|
|
const descriptor = Object.getOwnPropertyDescriptor(toolCall, "function");
|
|
if (!descriptor || !("value" in descriptor)) {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
const fn = descriptor.value;
|
|
const argumentsSnapshot = captureStructuredJSONSnapshot(fn, "arguments");
|
|
if (typeof argumentsSnapshot !== "string") {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
validateStructuredJSONSnapshot(argumentsSnapshot, finalJSONBudget, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"));
|
|
validatedTools.set(toolCallIndex, Object.freeze({
|
|
tool: toolCall,
|
|
function: fn,
|
|
type: identity.type,
|
|
name: identity.name,
|
|
arguments: argumentsSnapshot
|
|
}));
|
|
}
|
|
}
|
|
return validatedMessages;
|
|
}, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() {
|
|
if (this.ended) {
|
|
throw new OpenAIError(`stream has ended, this shouldn't happen`);
|
|
}
|
|
const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
|
|
if (!snapshot) {
|
|
throw new OpenAIError(`request ended without sending any chunks`);
|
|
}
|
|
const validatedMessages = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, snapshot);
|
|
const audioDoneChoiceIndexes = __classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_audioDoneChoiceIndexes, /* @__PURE__ */ new Set(), "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f");
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f");
|
|
return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), audioDoneChoiceIndexes, validatedMessages);
|
|
}, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk, capturedChoiceFrames) {
|
|
var _a6, _b, _c, _d, _e;
|
|
let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f");
|
|
const { choices, obfuscation: _obfuscation, ...rest } = chunk;
|
|
if (!snapshot) {
|
|
const newSnapshot = {
|
|
...rest,
|
|
choices: []
|
|
};
|
|
__classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, newSnapshot, "f");
|
|
snapshot = newSnapshot;
|
|
} else if (chunk.id) {
|
|
assignOwnProperties(snapshot, rest);
|
|
}
|
|
const requestedChoiceCount = __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.n;
|
|
const maxChoices = typeof requestedChoiceCount === "number" && Number.isSafeInteger(requestedChoiceCount) && requestedChoiceCount > 0 ? Math.min(requestedChoiceCount, MAX_STREAM_CHOICES) : MAX_STREAM_CHOICES;
|
|
for (const chunkChoice of chunk.choices) {
|
|
const { delta, finish_reason, index, logprobs = null, ...other } = chunkChoice;
|
|
const capturedToolCalls = [];
|
|
capturedChoiceFrames.set(chunkChoice, Object.freeze({ index, tool_calls: capturedToolCalls }));
|
|
if (!Number.isSafeInteger(index) || index < 0 || index >= maxChoices) {
|
|
throw new OpenAIError(`Chat completion stream contains an invalid choice index: ${index}`);
|
|
}
|
|
let choice = snapshot.choices[index];
|
|
if (!choice) {
|
|
const newChoice = { finish_reason, index, message: {}, logprobs: null, ...other };
|
|
snapshot.choices[index] = newChoice;
|
|
choice = newChoice;
|
|
}
|
|
if (isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format) || __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f")) {
|
|
captureStructuredJSONSnapshot(captureStructuredMessageSnapshot(choice), "refusal");
|
|
}
|
|
if (logprobs) {
|
|
if (choice.logprobs) {
|
|
const { content: content2, refusal: refusal2, ...rest3 } = logprobs;
|
|
assertIsEmpty(rest3);
|
|
assignOwnProperties(choice.logprobs, rest3);
|
|
if (content2) {
|
|
(_a6 = choice.logprobs).content ?? (_a6.content = []);
|
|
choice.logprobs.content.push(...content2);
|
|
}
|
|
if (refusal2) {
|
|
(_b = choice.logprobs).refusal ?? (_b.refusal = []);
|
|
choice.logprobs.refusal.push(...refusal2);
|
|
}
|
|
} else {
|
|
choice.logprobs = { ...logprobs };
|
|
if (logprobs.content) {
|
|
choice.logprobs.content = [...logprobs.content];
|
|
}
|
|
if (logprobs.refusal) {
|
|
choice.logprobs.refusal = [...logprobs.refusal];
|
|
}
|
|
}
|
|
}
|
|
if (finish_reason) {
|
|
choice.finish_reason = finish_reason;
|
|
if (__classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && (__classPrivateFieldGet(this, _ChatCompletionStream_rejectsUnfinishedTurns, "f") || hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")))) {
|
|
if (finish_reason === "length") {
|
|
throw new LengthFinishReasonError();
|
|
}
|
|
if (finish_reason === "content_filter") {
|
|
throw new ContentFilterFinishReasonError();
|
|
}
|
|
}
|
|
}
|
|
assignOwnProperties(choice, other);
|
|
if (!delta) {
|
|
Object.freeze(capturedToolCalls);
|
|
continue;
|
|
}
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").delete(index);
|
|
const { audio, content, refusal, function_call, role, ...capturedDeltaFields } = delta;
|
|
const { tool_calls: capturedToolCallDelta, ...rest2 } = capturedDeltaFields;
|
|
const tool_calls = hasOwn(capturedDeltaFields, "tool_calls") ? capturedToolCallDelta : delta.tool_calls;
|
|
assertIsEmpty(rest2);
|
|
assignOwnProperties(choice.message, rest2);
|
|
if (audio?.expires_at != null && audio.id == null && audio.data == null && audio.transcript == null && content == null && refusal == null && function_call == null && role == null && tool_calls == null && Object.keys(rest2).length === 0) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_audioDoneChoiceIndexes, "f").add(index);
|
|
}
|
|
if (refusal) {
|
|
choice.message.refusal = (choice.message.refusal || "") + refusal;
|
|
}
|
|
if (role) {
|
|
choice.message.role = role;
|
|
}
|
|
if (audio) {
|
|
const audioSnapshot = (_c = choice.message).audio ?? (_c.audio = {});
|
|
if (audio.id != null) {
|
|
audioSnapshot.id = audio.id;
|
|
}
|
|
if (audio.data != null) {
|
|
audioSnapshot.data = (audioSnapshot.data ?? "") + audio.data;
|
|
}
|
|
if (audio.transcript != null) {
|
|
audioSnapshot.transcript = (audioSnapshot.transcript ?? "") + audio.transcript;
|
|
}
|
|
if (audio.expires_at != null) {
|
|
audioSnapshot.expires_at = audio.expires_at;
|
|
}
|
|
}
|
|
if (function_call) {
|
|
if (choice.message.function_call) {
|
|
if (function_call.name) {
|
|
choice.message.function_call.name = function_call.name;
|
|
}
|
|
if (function_call.arguments) {
|
|
(_d = choice.message.function_call).arguments ?? (_d.arguments = "");
|
|
choice.message.function_call.arguments += function_call.arguments;
|
|
}
|
|
} else {
|
|
choice.message.function_call = function_call;
|
|
}
|
|
}
|
|
if (content != null) {
|
|
if (!choice.message.refusal && isParseableResponseFormat(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format)) {
|
|
const eventState = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choice);
|
|
const parseState = eventState.content_parse_state ?? (eventState.content_parse_state = createPartialJSONParseState());
|
|
const shouldParse = recordPartialJSONFragment(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"), content);
|
|
choice.message.content = (captureStructuredJSONSnapshot(choice.message, "content") || "") + content;
|
|
if (!parseState.has_non_whitespace) {
|
|
choice.message.parsed = null;
|
|
} else if (shouldParse && reservePartialJSONParse(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"))) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, snapshot);
|
|
choice.message.parsed = parseStructuredStreamingJSON(validateStructuredJSONSnapshot(choice.message.content));
|
|
} else if (content.length > 0) {
|
|
choice.message.parsed = null;
|
|
}
|
|
} else {
|
|
choice.message.content = (choice.message.content || "") + content;
|
|
}
|
|
}
|
|
if (tool_calls) {
|
|
const toolCallSnapshots = (_e = choice.message).tool_calls ?? (_e.tool_calls = []);
|
|
for (const toolCallDelta of tool_calls) {
|
|
const { index: index2, id, type, function: fn, custom, ...rest3 } = toolCallDelta;
|
|
if (!Number.isSafeInteger(index2) || index2 < 0 || index2 >= MAX_STREAM_TOOL_CALLS) {
|
|
throw new OpenAIError(`Chat completion stream contains an invalid tool call index: ${index2}`);
|
|
}
|
|
let argumentsDelta = "";
|
|
const tool_call = toolCallSnapshots[index2] ?? (toolCallSnapshots[index2] = {});
|
|
const functionName = fn?.name;
|
|
const eventState = __classPrivateFieldGet(this, _ChatCompletionStream_hasAutoParseableTool, "f") ? __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choice) : void 0;
|
|
let boundIdentity = eventState?.tool_call_identities.get(index2);
|
|
if (boundIdentity) {
|
|
assertBoundToolCallIdentity(tool_call, boundIdentity);
|
|
if (type !== void 0 && type !== boundIdentity.type || functionName !== void 0 && functionName !== boundIdentity.name) {
|
|
throw new OpenAIError("Chat completion stream contains a changed tool call identity");
|
|
}
|
|
}
|
|
assignOwnProperties(tool_call, rest3);
|
|
if (id) {
|
|
tool_call.id = id;
|
|
}
|
|
if (type) {
|
|
tool_call.type = type;
|
|
}
|
|
if (custom) {
|
|
const customSnapshot = tool_call.custom ?? (tool_call.custom = { name: custom.name ?? "", input: "" });
|
|
if (custom.name) {
|
|
customSnapshot.name = custom.name;
|
|
}
|
|
if (custom.input) {
|
|
customSnapshot.input += custom.input;
|
|
}
|
|
}
|
|
if (fn) {
|
|
const functionSnapshot = tool_call.function ?? (tool_call.function = { name: functionName ?? "", arguments: "" });
|
|
if (functionName) {
|
|
functionSnapshot.name = functionName;
|
|
}
|
|
if (eventState && !boundIdentity) {
|
|
const identity = ownFunctionToolIdentity(tool_call);
|
|
const configuredTool = identity && __classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === identity.name);
|
|
if (identity) {
|
|
boundIdentity = {
|
|
...identity,
|
|
parseable: configuredTool !== void 0 && shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), {
|
|
type: identity.type,
|
|
function: { name: identity.name }
|
|
})
|
|
};
|
|
eventState.tool_call_identities.set(index2, boundIdentity);
|
|
if (!boundIdentity.parseable) {
|
|
const provisionalState = eventState.tool_call_parse_states.get(index2);
|
|
if (provisionalState) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f").bytes -= provisionalState.bytes;
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f").fragments -= provisionalState.fragments;
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f").work -= provisionalState.work;
|
|
eventState.tool_call_parse_states.delete(index2);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const argumentFragment = fn.arguments;
|
|
if (argumentFragment != null) {
|
|
argumentsDelta = argumentFragment;
|
|
if (eventState && boundIdentity?.parseable !== false) {
|
|
let parseState = eventState.tool_call_parse_states.get(index2);
|
|
if (!parseState) {
|
|
parseState = createPartialJSONParseState();
|
|
eventState.tool_call_parse_states.set(index2, parseState);
|
|
}
|
|
const shouldParse = recordPartialJSONFragment(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"), argumentFragment);
|
|
const previousArguments = captureStructuredJSONSnapshot(functionSnapshot, "arguments");
|
|
if (typeof previousArguments !== "string") {
|
|
throw new OpenAIError("Chat completion stream contains an unsafe structured JSON snapshot");
|
|
}
|
|
functionSnapshot.arguments = previousArguments + argumentFragment;
|
|
if (shouldParse && boundIdentity?.parseable === true && reservePartialJSONParse(parseState, __classPrivateFieldGet(this, _ChatCompletionStream_partialJSONParseBudget, "f"))) {
|
|
__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_validateStructuredSnapshots).call(this, snapshot);
|
|
functionSnapshot.parsed_arguments = parseStructuredStreamingJSON(validateStructuredJSONSnapshot(functionSnapshot.arguments));
|
|
} else if (argumentFragment.length > 0 && hasOwn(functionSnapshot, "parsed_arguments")) {
|
|
functionSnapshot.parsed_arguments = void 0;
|
|
}
|
|
} else {
|
|
functionSnapshot.arguments += argumentFragment;
|
|
}
|
|
}
|
|
}
|
|
capturedToolCalls.push(Object.freeze({ index: index2, arguments_delta: argumentsDelta }));
|
|
}
|
|
}
|
|
Object.freeze(capturedToolCalls);
|
|
}
|
|
return snapshot;
|
|
}, Symbol.asyncIterator)]() {
|
|
return this._createIterator((push) => {
|
|
const onChunk = (chunk) => push(chunk);
|
|
this.on("chunk", onChunk);
|
|
return () => this.off("chunk", onChunk);
|
|
}, { onReturn: () => this.abort() });
|
|
}
|
|
/** Serializes raw completion chunks into a readable stream for transfer to another runtime. */
|
|
toReadableStream() {
|
|
const stream4 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
|
|
return stream4.toReadableStream();
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/ChatCompletionStreamingRunner.mjs
|
|
var ChatCompletionStreamingRunner;
|
|
var init_ChatCompletionStreamingRunner = __esm({
|
|
"node_modules/openai/lib/ChatCompletionStreamingRunner.mjs"() {
|
|
init_ChatCompletionStream();
|
|
init_error2();
|
|
init_streaming2();
|
|
init_chatCompletionUtils();
|
|
ChatCompletionStreamingRunner = class _ChatCompletionStreamingRunner extends ChatCompletionStream {
|
|
/** Restores a serialized tool run, including intermediate completions and tool-result messages. */
|
|
static fromReadableStream(stream4) {
|
|
const runner = new _ChatCompletionStreamingRunner(null);
|
|
runner._run(() => runner._fromReadableStream(stream4));
|
|
return runner;
|
|
}
|
|
/** Serializes completion chunks and tool-result messages for replay in another runtime. */
|
|
toReadableStream() {
|
|
let lastChunk;
|
|
let toolCallIds;
|
|
const iterator = this._createIterator((push) => {
|
|
const onChunk = (chunk) => {
|
|
lastChunk = chunk;
|
|
push(chunk);
|
|
};
|
|
const onMessage = (message) => {
|
|
if (isAssistantMessage(message)) {
|
|
toolCallIds = message.tool_calls?.map((toolCall) => toolCall.id);
|
|
return;
|
|
}
|
|
if (isToolMessage(message)) {
|
|
if (!lastChunk) {
|
|
throw new OpenAIError("cannot serialize a tool message before receiving any chunks");
|
|
}
|
|
push(makeChatCompletionReadableStreamMessageChunk(lastChunk, message, toolCallIds));
|
|
toolCallIds = void 0;
|
|
}
|
|
};
|
|
this.on("chunk", onChunk);
|
|
this.on("message", onMessage);
|
|
return () => {
|
|
this.off("chunk", onChunk);
|
|
this.off("message", onMessage);
|
|
};
|
|
}, { onReturn: () => this.abort() });
|
|
const stream4 = new Stream(() => iterator, this.controller);
|
|
return stream4.toReadableStream();
|
|
}
|
|
/** Starts a streaming tool loop and returns its event-driven conversation runner. */
|
|
static runTools(client, params, options) {
|
|
const runner = new _ChatCompletionStreamingRunner(
|
|
// @ts-expect-error TODO these types are incompatible
|
|
params
|
|
);
|
|
const opts = {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "runTools" }
|
|
};
|
|
runner._run(() => runner._runTools(client, params, runner, opts));
|
|
return runner;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/chat/completions/completions.mjs
|
|
var Completions;
|
|
var init_completions = __esm({
|
|
"node_modules/openai/resources/chat/completions/completions.mjs"() {
|
|
init_resource();
|
|
init_messages();
|
|
init_messages();
|
|
init_pagination();
|
|
init_path();
|
|
init_ChatCompletionRunner();
|
|
init_ChatCompletionStreamingRunner();
|
|
init_ChatCompletionStream();
|
|
init_parser();
|
|
init_ChatCompletionStreamingRunner();
|
|
init_RunnableFunction();
|
|
init_ChatCompletionStream();
|
|
init_ChatCompletionRunner();
|
|
Completions = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.messages = new Messages(this._client);
|
|
}
|
|
create(body, options) {
|
|
return this._client.post("/chat/completions", {
|
|
body,
|
|
...options,
|
|
stream: body.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get a stored chat completion. Only Chat Completions that have been created with
|
|
* the `store` parameter set to `true` will be returned.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const chatCompletion =
|
|
* await client.chat.completions.retrieve('completion_id');
|
|
* ```
|
|
*/
|
|
retrieve(completionID, options) {
|
|
return this._client.get(path`/chat/completions/${completionID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modify a stored chat completion. Only Chat Completions that have been created
|
|
* with the `store` parameter set to `true` can be modified. Currently, the only
|
|
* supported modification is to update the `metadata` field.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const chatCompletion = await client.chat.completions.update(
|
|
* 'completion_id',
|
|
* { metadata: { foo: 'string' } },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(completionID, body, options) {
|
|
return this._client.post(path`/chat/completions/${completionID}`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List stored Chat Completions. Only Chat Completions that have been stored with
|
|
* the `store` parameter set to `true` will be returned.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const chatCompletion of client.chat.completions.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/chat/completions", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a stored chat completion. Only Chat Completions that have been created
|
|
* with the `store` parameter set to `true` can be deleted.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const chatCompletionDeleted =
|
|
* await client.chat.completions.delete('completion_id');
|
|
* ```
|
|
*/
|
|
delete(completionID, options) {
|
|
return this._client.delete(path`/chat/completions/${completionID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
parse(body, options) {
|
|
validateInputTools(body.tools);
|
|
return this._client.chat.completions.create(body, {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "chat.completions.parse" }
|
|
})._thenUnwrap((completion) => parseChatCompletion(completion, body));
|
|
}
|
|
runTools(body, options) {
|
|
if (body.stream) {
|
|
return ChatCompletionStreamingRunner.runTools(this._client, body, options);
|
|
}
|
|
return ChatCompletionRunner.runTools(this._client, body, options);
|
|
}
|
|
/**
|
|
* Creates a chat completion stream
|
|
*/
|
|
stream(body, options) {
|
|
return ChatCompletionStream.createChatCompletion(this._client, body, options);
|
|
}
|
|
};
|
|
Completions.Messages = Messages;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/chat/chat.mjs
|
|
var Chat;
|
|
var init_chat = __esm({
|
|
"node_modules/openai/resources/chat/chat.mjs"() {
|
|
init_resource();
|
|
init_completions();
|
|
init_completions();
|
|
Chat = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.completions = new Completions(this._client);
|
|
}
|
|
};
|
|
Chat.Completions = Completions;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/chat/completions/index.mjs
|
|
var init_completions2 = __esm({
|
|
"node_modules/openai/resources/chat/completions/index.mjs"() {
|
|
init_completions();
|
|
init_completions();
|
|
init_messages();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/chat/index.mjs
|
|
var init_chat2 = __esm({
|
|
"node_modules/openai/resources/chat/index.mjs"() {
|
|
init_chat();
|
|
init_completions2();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/shared.mjs
|
|
var init_shared = __esm({
|
|
"node_modules/openai/resources/shared.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/admin-api-keys.mjs
|
|
var AdminAPIKeys;
|
|
var init_admin_api_keys = __esm({
|
|
"node_modules/openai/resources/admin/organization/admin-api-keys.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
AdminAPIKeys = class extends APIResource {
|
|
/**
|
|
* Create an organization admin API key
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const adminAPIKey =
|
|
* await client.admin.organization.adminAPIKeys.create({
|
|
* name: 'New Admin Key',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/admin_api_keys", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieve a single organization API key
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const adminAPIKey =
|
|
* await client.admin.organization.adminAPIKeys.retrieve(
|
|
* 'key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(keyID, options) {
|
|
return this._client.get(path`/organization/admin_api_keys/${keyID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List organization API keys
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const adminAPIKey of client.admin.organization.adminAPIKeys.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/admin_api_keys", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete an organization admin API key
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const adminAPIKey =
|
|
* await client.admin.organization.adminAPIKeys.delete(
|
|
* 'key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(keyID, options) {
|
|
return this._client.delete(path`/organization/admin_api_keys/${keyID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/audit-logs.mjs
|
|
var AuditLogs;
|
|
var init_audit_logs = __esm({
|
|
"node_modules/openai/resources/admin/organization/audit-logs.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
AuditLogs = class extends APIResource {
|
|
/**
|
|
* List user actions and configuration changes within this organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const auditLogListResponse of client.admin.organization.auditLogs.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/audit_logs", ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/certificates.mjs
|
|
var Certificates;
|
|
var init_certificates = __esm({
|
|
"node_modules/openai/resources/admin/organization/certificates.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Certificates = class extends APIResource {
|
|
/**
|
|
* Upload a certificate to the organization. This does **not** automatically
|
|
* activate the certificate.
|
|
*
|
|
* Organizations can upload up to 50 certificates.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const certificate =
|
|
* await client.admin.organization.certificates.create({
|
|
* certificate: 'certificate',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/certificates", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get a certificate that has been uploaded to the organization.
|
|
*
|
|
* You can get a certificate regardless of whether it is active or not.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const certificate =
|
|
* await client.admin.organization.certificates.retrieve(
|
|
* 'certificate_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(certificateID, query = {}, options) {
|
|
return this._client.get(path`/organization/certificates/${certificateID}`, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modify a certificate. Note that only the name can be modified.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const certificate =
|
|
* await client.admin.organization.certificates.update(
|
|
* 'certificate_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(certificateID, body, options) {
|
|
return this._client.post(path`/organization/certificates/${certificateID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List uploaded certificates for this organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const certificateListResponse of client.admin.organization.certificates.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/certificates", ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Delete a certificate from the organization.
|
|
*
|
|
* The certificate must be inactive for the organization and all projects.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const certificate =
|
|
* await client.admin.organization.certificates.delete(
|
|
* 'certificate_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(certificateID, options) {
|
|
return this._client.delete(path`/organization/certificates/${certificateID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Activate certificates at the organization level.
|
|
*
|
|
* You can atomically and idempotently activate up to 10 certificates at a time.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const certificateActivateResponse of client.admin.organization.certificates.activate(
|
|
* { certificate_ids: ['cert_abc'] },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
activate(body, options) {
|
|
return this._client.getAPIList("/organization/certificates/activate", Page, {
|
|
body,
|
|
method: "post",
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deactivate certificates at the organization level.
|
|
*
|
|
* You can atomically and idempotently deactivate up to 10 certificates at a time.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const certificateDeactivateResponse of client.admin.organization.certificates.deactivate(
|
|
* { certificate_ids: ['cert_abc'] },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
deactivate(body, options) {
|
|
return this._client.getAPIList("/organization/certificates/deactivate", Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/data-retention.mjs
|
|
var DataRetention;
|
|
var init_data_retention = __esm({
|
|
"node_modules/openai/resources/admin/organization/data-retention.mjs"() {
|
|
init_resource();
|
|
DataRetention = class extends APIResource {
|
|
/**
|
|
* Retrieves organization data retention controls.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationDataRetention =
|
|
* await client.admin.organization.dataRetention.retrieve();
|
|
* ```
|
|
*/
|
|
retrieve(options) {
|
|
return this._client.get("/organization/data_retention", {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates organization data retention controls.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationDataRetention =
|
|
* await client.admin.organization.dataRetention.update({
|
|
* retention_type: 'zero_data_retention',
|
|
* });
|
|
* ```
|
|
*/
|
|
update(body, options) {
|
|
return this._client.post("/organization/data_retention", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/invites.mjs
|
|
var Invites;
|
|
var init_invites = __esm({
|
|
"node_modules/openai/resources/admin/organization/invites.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Invites = class extends APIResource {
|
|
/**
|
|
* Create an invite for a user to the organization. The invite must be accepted by
|
|
* the user before they have access to the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const invite =
|
|
* await client.admin.organization.invites.create({
|
|
* email: 'email',
|
|
* role: 'reader',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/invites", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves an invite.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const invite =
|
|
* await client.admin.organization.invites.retrieve(
|
|
* 'invite_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(inviteID, options) {
|
|
return this._client.get(path`/organization/invites/${inviteID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of invites in the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const invite of client.admin.organization.invites.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/invites", ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete an invite. If the invite has already been accepted, it cannot be deleted.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const invite =
|
|
* await client.admin.organization.invites.delete(
|
|
* 'invite_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(inviteID, options) {
|
|
return this._client.delete(path`/organization/invites/${inviteID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/roles.mjs
|
|
var Roles;
|
|
var init_roles = __esm({
|
|
"node_modules/openai/resources/admin/organization/roles.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Roles = class extends APIResource {
|
|
/**
|
|
* Creates a custom role for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role = await client.admin.organization.roles.create({
|
|
* permissions: ['string'],
|
|
* role_name: 'role_name',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/roles", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves an organization role.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role = await client.admin.organization.roles.retrieve(
|
|
* 'role_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(roleID, options) {
|
|
return this._client.get(path`/organization/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates an existing organization role.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role = await client.admin.organization.roles.update(
|
|
* 'role_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(roleID, body, options) {
|
|
return this._client.post(path`/organization/roles/${roleID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the roles configured for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const role of client.admin.organization.roles.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/roles", NextCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a custom role from the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role = await client.admin.organization.roles.delete(
|
|
* 'role_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(roleID, options) {
|
|
return this._client.delete(path`/organization/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/spend-alerts.mjs
|
|
var SpendAlerts;
|
|
var init_spend_alerts = __esm({
|
|
"node_modules/openai/resources/admin/organization/spend-alerts.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
SpendAlerts = class extends APIResource {
|
|
/**
|
|
* Creates an organization spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendAlert =
|
|
* await client.admin.organization.spendAlerts.create({
|
|
* currency: 'USD',
|
|
* interval: 'month',
|
|
* notification_channel: {
|
|
* recipients: ['string'],
|
|
* type: 'email',
|
|
* },
|
|
* threshold_amount: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/spend_alerts", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves an organization spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendAlert =
|
|
* await client.admin.organization.spendAlerts.retrieve(
|
|
* 'alert_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(alertID, options) {
|
|
return this._client.get(path`/organization/spend_alerts/${alertID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates an organization spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendAlert =
|
|
* await client.admin.organization.spendAlerts.update(
|
|
* 'alert_id',
|
|
* {
|
|
* currency: 'USD',
|
|
* interval: 'month',
|
|
* notification_channel: {
|
|
* recipients: ['string'],
|
|
* type: 'email',
|
|
* },
|
|
* threshold_amount: 0,
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(alertID, body, options) {
|
|
return this._client.post(path`/organization/spend_alerts/${alertID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists organization spend alerts.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const organizationSpendAlert of client.admin.organization.spendAlerts.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/spend_alerts", ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Deletes an organization spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendAlertDeleted =
|
|
* await client.admin.organization.spendAlerts.delete(
|
|
* 'alert_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(alertID, options) {
|
|
return this._client.delete(path`/organization/spend_alerts/${alertID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/spend-limit.mjs
|
|
var SpendLimit;
|
|
var init_spend_limit = __esm({
|
|
"node_modules/openai/resources/admin/organization/spend-limit.mjs"() {
|
|
init_resource();
|
|
SpendLimit = class extends APIResource {
|
|
/**
|
|
* Get the organization's hard spend limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendLimit =
|
|
* await client.admin.organization.spendLimit.retrieve();
|
|
* ```
|
|
*/
|
|
retrieve(options) {
|
|
return this._client.get("/organization/spend_limit", {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Create or replace the organization's hard spend limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendLimit =
|
|
* await client.admin.organization.spendLimit.update({
|
|
* currency: 'USD',
|
|
* interval: 'month',
|
|
* threshold_amount: 1,
|
|
* });
|
|
* ```
|
|
*/
|
|
update(body, options) {
|
|
return this._client.post("/organization/spend_limit", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete the organization's hard spend limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationSpendLimitDeleted =
|
|
* await client.admin.organization.spendLimit.delete();
|
|
* ```
|
|
*/
|
|
delete(options) {
|
|
return this._client.delete("/organization/spend_limit", {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/usage.mjs
|
|
var Usage;
|
|
var init_usage = __esm({
|
|
"node_modules/openai/resources/admin/organization/usage.mjs"() {
|
|
init_resource();
|
|
Usage = class extends APIResource {
|
|
/**
|
|
* Get audio speeches usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.audioSpeeches({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
audioSpeeches(query, options) {
|
|
return this._client.get("/organization/usage/audio_speeches", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get audio transcriptions usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.audioTranscriptions(
|
|
* { start_time: 0 },
|
|
* );
|
|
* ```
|
|
*/
|
|
audioTranscriptions(query, options) {
|
|
return this._client.get("/organization/usage/audio_transcriptions", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get code interpreter sessions usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.codeInterpreterSessions(
|
|
* { start_time: 0 },
|
|
* );
|
|
* ```
|
|
*/
|
|
codeInterpreterSessions(query, options) {
|
|
return this._client.get("/organization/usage/code_interpreter_sessions", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get completions usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.completions({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
completions(query, options) {
|
|
return this._client.get("/organization/usage/completions", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get costs details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.costs({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
costs(query, options) {
|
|
return this._client.get("/organization/costs", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get embeddings usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.embeddings({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
embeddings(query, options) {
|
|
return this._client.get("/organization/usage/embeddings", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get file search calls usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.fileSearchCalls({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
fileSearchCalls(query, options) {
|
|
return this._client.get("/organization/usage/file_search_calls", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get images usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.images({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
images(query, options) {
|
|
return this._client.get("/organization/usage/images", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get moderations usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.moderations({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
moderations(query, options) {
|
|
return this._client.get("/organization/usage/moderations", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get vector stores usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.vectorStores({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
vectorStores(query, options) {
|
|
return this._client.get("/organization/usage/vector_stores", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get web search calls usage details for the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.admin.organization.usage.webSearchCalls({
|
|
* start_time: 0,
|
|
* });
|
|
* ```
|
|
*/
|
|
webSearchCalls(query, options) {
|
|
return this._client.get("/organization/usage/web_search_calls", {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/groups/roles.mjs
|
|
var Roles2;
|
|
var init_roles2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/groups/roles.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Roles2 = class extends APIResource {
|
|
/**
|
|
* Assigns an organization role to a group within the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.groups.roles.create(
|
|
* 'group_id',
|
|
* { role_id: 'role_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(groupID, body, options) {
|
|
return this._client.post(path`/organization/groups/${groupID}/roles`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves an organization role assigned to a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.groups.roles.retrieve(
|
|
* 'role_id',
|
|
* { group_id: 'group_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(roleID, params, options) {
|
|
const { group_id } = params;
|
|
return this._client.get(path`/organization/groups/${group_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the organization roles assigned to a group within the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const roleListResponse of client.admin.organization.groups.roles.list(
|
|
* 'group_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(groupID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/groups/${groupID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Unassigns an organization role from a group within the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.groups.roles.delete(
|
|
* 'role_id',
|
|
* { group_id: 'group_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(roleID, params, options) {
|
|
const { group_id } = params;
|
|
return this._client.delete(path`/organization/groups/${group_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/groups/users.mjs
|
|
var Users;
|
|
var init_users = __esm({
|
|
"node_modules/openai/resources/admin/organization/groups/users.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Users = class extends APIResource {
|
|
/**
|
|
* Adds a user to a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const user =
|
|
* await client.admin.organization.groups.users.create(
|
|
* 'group_id',
|
|
* { user_id: 'user_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(groupID, body, options) {
|
|
return this._client.post(path`/organization/groups/${groupID}/users`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a user in a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const user =
|
|
* await client.admin.organization.groups.users.retrieve(
|
|
* 'user_id',
|
|
* { group_id: 'group_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(userID, params, options) {
|
|
const { group_id } = params;
|
|
return this._client.get(path`/organization/groups/${group_id}/users/${userID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the users assigned to a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const organizationGroupUser of client.admin.organization.groups.users.list(
|
|
* 'group_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(groupID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/groups/${groupID}/users`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Removes a user from a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const user =
|
|
* await client.admin.organization.groups.users.delete(
|
|
* 'user_id',
|
|
* { group_id: 'group_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(userID, params, options) {
|
|
const { group_id } = params;
|
|
return this._client.delete(path`/organization/groups/${group_id}/users/${userID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/groups/groups.mjs
|
|
var Groups;
|
|
var init_groups = __esm({
|
|
"node_modules/openai/resources/admin/organization/groups/groups.mjs"() {
|
|
init_resource();
|
|
init_roles2();
|
|
init_roles2();
|
|
init_users();
|
|
init_users();
|
|
init_pagination();
|
|
init_path();
|
|
Groups = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.users = new Users(this._client);
|
|
this.roles = new Roles2(this._client);
|
|
}
|
|
/**
|
|
* Creates a new group in the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const group = await client.admin.organization.groups.create(
|
|
* { name: 'x' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/groups", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const group =
|
|
* await client.admin.organization.groups.retrieve(
|
|
* 'group_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(groupID, options) {
|
|
return this._client.get(path`/organization/groups/${groupID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates a group's information.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const group = await client.admin.organization.groups.update(
|
|
* 'group_id',
|
|
* { name: 'x' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(groupID, body, options) {
|
|
return this._client.post(path`/organization/groups/${groupID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists all groups in the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const group of client.admin.organization.groups.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/groups", NextCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a group from the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const group = await client.admin.organization.groups.delete(
|
|
* 'group_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(groupID, options) {
|
|
return this._client.delete(path`/organization/groups/${groupID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Groups.Users = Users;
|
|
Groups.Roles = Roles2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/api-keys.mjs
|
|
var APIKeys;
|
|
var init_api_keys = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/api-keys.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
APIKeys = class extends APIResource {
|
|
/**
|
|
* Retrieves an API key in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectAPIKey =
|
|
* await client.admin.organization.projects.apiKeys.retrieve(
|
|
* 'api_key_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(apiKeyID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.get(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of API keys in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const projectAPIKey of client.admin.organization.projects.apiKeys.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/api_keys`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Deletes an API key from the project.
|
|
*
|
|
* Returns confirmation of the key deletion, or an error if the key belonged to a
|
|
* service account.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const apiKey =
|
|
* await client.admin.organization.projects.apiKeys.delete(
|
|
* 'api_key_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(apiKeyID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.delete(path`/organization/projects/${project_id}/api_keys/${apiKeyID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/certificates.mjs
|
|
var Certificates2;
|
|
var init_certificates2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/certificates.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Certificates2 = class extends APIResource {
|
|
/**
|
|
* List certificates for this project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const certificateListResponse of client.admin.organization.projects.certificates.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/certificates`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Activate certificates at the project level.
|
|
*
|
|
* You can atomically and idempotently activate up to 10 certificates at a time.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const certificateActivateResponse of client.admin.organization.projects.certificates.activate(
|
|
* 'project_id',
|
|
* { certificate_ids: ['cert_abc'] },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
activate(projectID, body, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/activate`, Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Deactivate certificates at the project level. You can atomically and
|
|
* idempotently deactivate up to 10 certificates at a time.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const certificateDeactivateResponse of client.admin.organization.projects.certificates.deactivate(
|
|
* 'project_id',
|
|
* { certificate_ids: ['cert_abc'] },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
deactivate(projectID, body, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/certificates/deactivate`, Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/data-retention.mjs
|
|
var DataRetention2;
|
|
var init_data_retention2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/data-retention.mjs"() {
|
|
init_resource();
|
|
init_path();
|
|
DataRetention2 = class extends APIResource {
|
|
/**
|
|
* Retrieves project data retention controls.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectDataRetention =
|
|
* await client.admin.organization.projects.dataRetention.retrieve(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(projectID, options) {
|
|
return this._client.get(path`/organization/projects/${projectID}/data_retention`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates project data retention controls.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectDataRetention =
|
|
* await client.admin.organization.projects.dataRetention.update(
|
|
* 'project_id',
|
|
* { retention_type: 'organization_default' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/data_retention`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs
|
|
var HostedToolPermissions;
|
|
var init_hosted_tool_permissions = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs"() {
|
|
init_resource();
|
|
init_path();
|
|
HostedToolPermissions = class extends APIResource {
|
|
/**
|
|
* Returns hosted tool permissions for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectHostedToolPermissions =
|
|
* await client.admin.organization.projects.hostedToolPermissions.retrieve(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(projectID, options) {
|
|
return this._client.get(path`/organization/projects/${projectID}/hosted_tool_permissions`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates hosted tool permissions for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectHostedToolPermissions =
|
|
* await client.admin.organization.projects.hostedToolPermissions.update(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/hosted_tool_permissions`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/model-permissions.mjs
|
|
var ModelPermissions;
|
|
var init_model_permissions = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/model-permissions.mjs"() {
|
|
init_resource();
|
|
init_path();
|
|
ModelPermissions = class extends APIResource {
|
|
/**
|
|
* Returns model permissions for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectModelPermissions =
|
|
* await client.admin.organization.projects.modelPermissions.retrieve(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(projectID, options) {
|
|
return this._client.get(path`/organization/projects/${projectID}/model_permissions`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates model permissions for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectModelPermissions =
|
|
* await client.admin.organization.projects.modelPermissions.update(
|
|
* 'project_id',
|
|
* { mode: 'allow_list', model_ids: ['string'] },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/model_permissions`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes model permissions for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectModelPermissionsDeleted =
|
|
* await client.admin.organization.projects.modelPermissions.delete(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(projectID, options) {
|
|
return this._client.delete(path`/organization/projects/${projectID}/model_permissions`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/rate-limits.mjs
|
|
var RateLimits;
|
|
var init_rate_limits = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/rate-limits.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
RateLimits = class extends APIResource {
|
|
/**
|
|
* Returns the rate limits per model for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const projectRateLimit of client.admin.organization.projects.rateLimits.listRateLimits(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
listRateLimits(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/rate_limits`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Updates a project rate limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectRateLimit =
|
|
* await client.admin.organization.projects.rateLimits.updateRateLimit(
|
|
* 'rate_limit_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
updateRateLimit(rateLimitID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/organization/projects/${project_id}/rate_limits/${rateLimitID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/roles.mjs
|
|
var Roles3;
|
|
var init_roles3 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/roles.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Roles3 = class extends APIResource {
|
|
/**
|
|
* Creates a custom role for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.roles.create(
|
|
* 'project_id',
|
|
* { permissions: ['string'], role_name: 'role_name' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(projectID, body, options) {
|
|
return this._client.post(path`/projects/${projectID}/roles`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a project role.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.roles.retrieve(
|
|
* 'role_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(roleID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.get(path`/projects/${project_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates an existing project role.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.roles.update(
|
|
* 'role_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(roleID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/projects/${project_id}/roles/${roleID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the roles configured for a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const role of client.admin.organization.projects.roles.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/projects/${projectID}/roles`, NextCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a custom role from a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.roles.delete(
|
|
* 'role_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(roleID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.delete(path`/projects/${project_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs
|
|
var SpendAlerts2;
|
|
var init_spend_alerts2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
SpendAlerts2 = class extends APIResource {
|
|
/**
|
|
* Creates a project spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendAlert =
|
|
* await client.admin.organization.projects.spendAlerts.create(
|
|
* 'project_id',
|
|
* {
|
|
* currency: 'USD',
|
|
* interval: 'month',
|
|
* notification_channel: {
|
|
* recipients: ['string'],
|
|
* type: 'email',
|
|
* },
|
|
* threshold_amount: 0,
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/spend_alerts`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a project spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendAlert =
|
|
* await client.admin.organization.projects.spendAlerts.retrieve(
|
|
* 'alert_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(alertID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.get(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates a project spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendAlert =
|
|
* await client.admin.organization.projects.spendAlerts.update(
|
|
* 'alert_id',
|
|
* {
|
|
* project_id: 'project_id',
|
|
* currency: 'USD',
|
|
* interval: 'month',
|
|
* notification_channel: {
|
|
* recipients: ['string'],
|
|
* type: 'email',
|
|
* },
|
|
* threshold_amount: 0,
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(alertID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists project spend alerts.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const projectSpendAlert of client.admin.organization.projects.spendAlerts.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/spend_alerts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Deletes a project spend alert.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendAlertDeleted =
|
|
* await client.admin.organization.projects.spendAlerts.delete(
|
|
* 'alert_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(alertID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.delete(path`/organization/projects/${project_id}/spend_alerts/${alertID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/spend-limit.mjs
|
|
var SpendLimit2;
|
|
var init_spend_limit2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/spend-limit.mjs"() {
|
|
init_resource();
|
|
init_path();
|
|
SpendLimit2 = class extends APIResource {
|
|
/**
|
|
* Get a project's hard spend limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendLimit =
|
|
* await client.admin.organization.projects.spendLimit.retrieve(
|
|
* 'proj_123',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(projectID, options) {
|
|
return this._client.get(path`/organization/projects/${projectID}/spend_limit`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Create or replace a project's hard spend limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendLimit =
|
|
* await client.admin.organization.projects.spendLimit.update(
|
|
* 'proj_123',
|
|
* {
|
|
* currency: 'USD',
|
|
* interval: 'month',
|
|
* threshold_amount: 1,
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/spend_limit`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a project's hard spend limit.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectSpendLimitDeleted =
|
|
* await client.admin.organization.projects.spendLimit.delete(
|
|
* 'proj_123',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(projectID, options) {
|
|
return this._client.delete(path`/organization/projects/${projectID}/spend_limit`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/groups/roles.mjs
|
|
var Roles4;
|
|
var init_roles4 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/groups/roles.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Roles4 = class extends APIResource {
|
|
/**
|
|
* Assigns a project role to a group within a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.groups.roles.create(
|
|
* 'group_id',
|
|
* { project_id: 'project_id', role_id: 'role_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(groupID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/projects/${project_id}/groups/${groupID}/roles`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a project role assigned to a group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.groups.roles.retrieve(
|
|
* 'role_id',
|
|
* { project_id: 'project_id', group_id: 'group_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(roleID, params, options) {
|
|
const { project_id, group_id } = params;
|
|
return this._client.get(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the project roles assigned to a group within a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const roleListResponse of client.admin.organization.projects.groups.roles.list(
|
|
* 'group_id',
|
|
* { project_id: 'project_id' },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(groupID, params, options) {
|
|
const { project_id, ...query } = params;
|
|
return this._client.getAPIList(path`/projects/${project_id}/groups/${groupID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Unassigns a project role from a group within a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.groups.roles.delete(
|
|
* 'role_id',
|
|
* { project_id: 'project_id', group_id: 'group_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(roleID, params, options) {
|
|
const { project_id, group_id } = params;
|
|
return this._client.delete(path`/projects/${project_id}/groups/${group_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/groups/groups.mjs
|
|
var Groups2;
|
|
var init_groups2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/groups/groups.mjs"() {
|
|
init_resource();
|
|
init_roles4();
|
|
init_roles4();
|
|
init_pagination();
|
|
init_path();
|
|
Groups2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.roles = new Roles4(this._client);
|
|
}
|
|
/**
|
|
* Grants a group access to a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectGroup =
|
|
* await client.admin.organization.projects.groups.create(
|
|
* 'project_id',
|
|
* { group_id: 'group_id', role: 'role' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/groups`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a project's group.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectGroup =
|
|
* await client.admin.organization.projects.groups.retrieve(
|
|
* 'group_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(groupID, params, options) {
|
|
const { project_id, ...query } = params;
|
|
return this._client.get(path`/organization/projects/${project_id}/groups/${groupID}`, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the groups that have access to a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const projectGroup of client.admin.organization.projects.groups.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/groups`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Revokes a group's access to a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const group =
|
|
* await client.admin.organization.projects.groups.delete(
|
|
* 'group_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(groupID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.delete(path`/organization/projects/${project_id}/groups/${groupID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Groups2.Roles = Roles4;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs
|
|
var APIKeys2;
|
|
var init_api_keys2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/service-accounts/api-keys.mjs"() {
|
|
init_resource();
|
|
init_path();
|
|
APIKeys2 = class extends APIResource {
|
|
/**
|
|
* Creates an API key for a service account in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const apiKey =
|
|
* await client.admin.organization.projects.serviceAccounts.apiKeys.create(
|
|
* 'service_account_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(serviceAccountID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}/api_keys`, { body, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs
|
|
var ServiceAccounts;
|
|
var init_service_accounts = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/service-accounts/service-accounts.mjs"() {
|
|
init_resource();
|
|
init_api_keys2();
|
|
init_api_keys2();
|
|
init_pagination();
|
|
init_path();
|
|
ServiceAccounts = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.apiKeys = new APIKeys2(this._client);
|
|
}
|
|
/**
|
|
* Creates a new service account in the project. By default, this also returns an
|
|
* unredacted API key for the service account.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const serviceAccount =
|
|
* await client.admin.organization.projects.serviceAccounts.create(
|
|
* 'project_id',
|
|
* { name: 'name' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/service_accounts`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a service account in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectServiceAccount =
|
|
* await client.admin.organization.projects.serviceAccounts.retrieve(
|
|
* 'service_account_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(serviceAccountID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.get(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates a service account in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectServiceAccount =
|
|
* await client.admin.organization.projects.serviceAccounts.update(
|
|
* 'service_account_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(serviceAccountID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { body, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Returns a list of service accounts in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const projectServiceAccount of client.admin.organization.projects.serviceAccounts.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/service_accounts`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Deletes a service account from the project.
|
|
*
|
|
* Returns confirmation of service account deletion, or an error if the project is
|
|
* archived (archived projects have no service accounts).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const serviceAccount =
|
|
* await client.admin.organization.projects.serviceAccounts.delete(
|
|
* 'service_account_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(serviceAccountID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.delete(path`/organization/projects/${project_id}/service_accounts/${serviceAccountID}`, { ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
};
|
|
ServiceAccounts.APIKeys = APIKeys2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/users/roles.mjs
|
|
var Roles5;
|
|
var init_roles5 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/users/roles.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Roles5 = class extends APIResource {
|
|
/**
|
|
* Assigns a project role to a user within a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.users.roles.create(
|
|
* 'user_id',
|
|
* { project_id: 'project_id', role_id: 'role_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(userID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/projects/${project_id}/users/${userID}/roles`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a project role assigned to a user.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.users.roles.retrieve(
|
|
* 'role_id',
|
|
* { project_id: 'project_id', user_id: 'user_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(roleID, params, options) {
|
|
const { project_id, user_id } = params;
|
|
return this._client.get(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the project roles assigned to a user within a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const roleListResponse of client.admin.organization.projects.users.roles.list(
|
|
* 'user_id',
|
|
* { project_id: 'project_id' },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(userID, params, options) {
|
|
const { project_id, ...query } = params;
|
|
return this._client.getAPIList(path`/projects/${project_id}/users/${userID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Unassigns a project role from a user within a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.projects.users.roles.delete(
|
|
* 'role_id',
|
|
* { project_id: 'project_id', user_id: 'user_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(roleID, params, options) {
|
|
const { project_id, user_id } = params;
|
|
return this._client.delete(path`/projects/${project_id}/users/${user_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/users/users.mjs
|
|
var Users2;
|
|
var init_users2 = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/users/users.mjs"() {
|
|
init_resource();
|
|
init_roles5();
|
|
init_roles5();
|
|
init_pagination();
|
|
init_path();
|
|
Users2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.roles = new Roles5(this._client);
|
|
}
|
|
/**
|
|
* Adds a user to the project. Users must already be members of the organization to
|
|
* be added to a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectUser =
|
|
* await client.admin.organization.projects.users.create(
|
|
* 'project_id',
|
|
* { role: 'role' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/users`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a user in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectUser =
|
|
* await client.admin.organization.projects.users.retrieve(
|
|
* 'user_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(userID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.get(path`/organization/projects/${project_id}/users/${userID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a user's role in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const projectUser =
|
|
* await client.admin.organization.projects.users.update(
|
|
* 'user_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(userID, params, options) {
|
|
const { project_id, ...body } = params;
|
|
return this._client.post(path`/organization/projects/${project_id}/users/${userID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of users in the project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const projectUser of client.admin.organization.projects.users.list(
|
|
* 'project_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(projectID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/projects/${projectID}/users`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Deletes a user from the project.
|
|
*
|
|
* Returns confirmation of project user deletion, or an error if the project is
|
|
* archived (archived projects have no users).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const user =
|
|
* await client.admin.organization.projects.users.delete(
|
|
* 'user_id',
|
|
* { project_id: 'project_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(userID, params, options) {
|
|
const { project_id } = params;
|
|
return this._client.delete(path`/organization/projects/${project_id}/users/${userID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Users2.Roles = Roles5;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/projects/projects.mjs
|
|
var Projects;
|
|
var init_projects = __esm({
|
|
"node_modules/openai/resources/admin/organization/projects/projects.mjs"() {
|
|
init_resource();
|
|
init_api_keys();
|
|
init_api_keys();
|
|
init_certificates2();
|
|
init_certificates2();
|
|
init_data_retention2();
|
|
init_data_retention2();
|
|
init_hosted_tool_permissions();
|
|
init_hosted_tool_permissions();
|
|
init_model_permissions();
|
|
init_model_permissions();
|
|
init_rate_limits();
|
|
init_rate_limits();
|
|
init_roles3();
|
|
init_roles3();
|
|
init_spend_alerts2();
|
|
init_spend_alerts2();
|
|
init_spend_limit2();
|
|
init_spend_limit2();
|
|
init_groups2();
|
|
init_groups2();
|
|
init_service_accounts();
|
|
init_service_accounts();
|
|
init_users2();
|
|
init_users2();
|
|
init_pagination();
|
|
init_path();
|
|
Projects = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.users = new Users2(this._client);
|
|
this.serviceAccounts = new ServiceAccounts(this._client);
|
|
this.apiKeys = new APIKeys(this._client);
|
|
this.rateLimits = new RateLimits(this._client);
|
|
this.modelPermissions = new ModelPermissions(this._client);
|
|
this.hostedToolPermissions = new HostedToolPermissions(this._client);
|
|
this.groups = new Groups2(this._client);
|
|
this.roles = new Roles3(this._client);
|
|
this.dataRetention = new DataRetention2(this._client);
|
|
this.spendLimit = new SpendLimit2(this._client);
|
|
this.spendAlerts = new SpendAlerts2(this._client);
|
|
this.certificates = new Certificates2(this._client);
|
|
}
|
|
/**
|
|
* Create a new project in the organization. Projects can be created and archived,
|
|
* but cannot be deleted.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const project =
|
|
* await client.admin.organization.projects.create({
|
|
* name: 'name',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/organization/projects", {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const project =
|
|
* await client.admin.organization.projects.retrieve(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(projectID, options) {
|
|
return this._client.get(path`/organization/projects/${projectID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a project in the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const project =
|
|
* await client.admin.organization.projects.update(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(projectID, body, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of projects.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const project of client.admin.organization.projects.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/projects", ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Archives a project in the organization. Archived projects cannot be used or
|
|
* updated.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const project =
|
|
* await client.admin.organization.projects.archive(
|
|
* 'project_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(projectID, options) {
|
|
return this._client.post(path`/organization/projects/${projectID}/archive`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Projects.Users = Users2;
|
|
Projects.ServiceAccounts = ServiceAccounts;
|
|
Projects.APIKeys = APIKeys;
|
|
Projects.RateLimits = RateLimits;
|
|
Projects.ModelPermissions = ModelPermissions;
|
|
Projects.HostedToolPermissions = HostedToolPermissions;
|
|
Projects.Groups = Groups2;
|
|
Projects.Roles = Roles3;
|
|
Projects.DataRetention = DataRetention2;
|
|
Projects.SpendLimit = SpendLimit2;
|
|
Projects.SpendAlerts = SpendAlerts2;
|
|
Projects.Certificates = Certificates2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/users/roles.mjs
|
|
var Roles6;
|
|
var init_roles6 = __esm({
|
|
"node_modules/openai/resources/admin/organization/users/roles.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Roles6 = class extends APIResource {
|
|
/**
|
|
* Assigns an organization role to a user within the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.users.roles.create(
|
|
* 'user_id',
|
|
* { role_id: 'role_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(userID, body, options) {
|
|
return this._client.post(path`/organization/users/${userID}/roles`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves an organization role assigned to a user.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.users.roles.retrieve(
|
|
* 'role_id',
|
|
* { user_id: 'user_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(roleID, params, options) {
|
|
const { user_id } = params;
|
|
return this._client.get(path`/organization/users/${user_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists the organization roles assigned to a user within the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const roleListResponse of client.admin.organization.users.roles.list(
|
|
* 'user_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(userID, query = {}, options) {
|
|
return this._client.getAPIList(path`/organization/users/${userID}/roles`, NextCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* Unassigns an organization role from a user within the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const role =
|
|
* await client.admin.organization.users.roles.delete(
|
|
* 'role_id',
|
|
* { user_id: 'user_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(roleID, params, options) {
|
|
const { user_id } = params;
|
|
return this._client.delete(path`/organization/users/${user_id}/roles/${roleID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/users/users.mjs
|
|
var Users3;
|
|
var init_users3 = __esm({
|
|
"node_modules/openai/resources/admin/organization/users/users.mjs"() {
|
|
init_resource();
|
|
init_roles6();
|
|
init_roles6();
|
|
init_pagination();
|
|
init_path();
|
|
Users3 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.roles = new Roles6(this._client);
|
|
}
|
|
/**
|
|
* Retrieves a user by their identifier.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationUser =
|
|
* await client.admin.organization.users.retrieve('user_id');
|
|
* ```
|
|
*/
|
|
retrieve(userID, options) {
|
|
return this._client.get(path`/organization/users/${userID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a user's role in the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const organizationUser =
|
|
* await client.admin.organization.users.update('user_id');
|
|
* ```
|
|
*/
|
|
update(userID, body, options) {
|
|
return this._client.post(path`/organization/users/${userID}`, {
|
|
body,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists all of the users in the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const organizationUser of client.admin.organization.users.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/organization/users", ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a user from the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const user = await client.admin.organization.users.delete(
|
|
* 'user_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(userID, options) {
|
|
return this._client.delete(path`/organization/users/${userID}`, {
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Users3.Roles = Roles6;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/organization/organization.mjs
|
|
var Organization;
|
|
var init_organization = __esm({
|
|
"node_modules/openai/resources/admin/organization/organization.mjs"() {
|
|
init_resource();
|
|
init_admin_api_keys();
|
|
init_admin_api_keys();
|
|
init_audit_logs();
|
|
init_audit_logs();
|
|
init_certificates();
|
|
init_certificates();
|
|
init_data_retention();
|
|
init_data_retention();
|
|
init_invites();
|
|
init_invites();
|
|
init_roles();
|
|
init_roles();
|
|
init_spend_alerts();
|
|
init_spend_alerts();
|
|
init_spend_limit();
|
|
init_spend_limit();
|
|
init_usage();
|
|
init_usage();
|
|
init_groups();
|
|
init_groups();
|
|
init_projects();
|
|
init_projects();
|
|
init_users3();
|
|
init_users3();
|
|
Organization = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.auditLogs = new AuditLogs(this._client);
|
|
this.adminAPIKeys = new AdminAPIKeys(this._client);
|
|
this.usage = new Usage(this._client);
|
|
this.invites = new Invites(this._client);
|
|
this.users = new Users3(this._client);
|
|
this.groups = new Groups(this._client);
|
|
this.roles = new Roles(this._client);
|
|
this.dataRetention = new DataRetention(this._client);
|
|
this.spendLimit = new SpendLimit(this._client);
|
|
this.spendAlerts = new SpendAlerts(this._client);
|
|
this.certificates = new Certificates(this._client);
|
|
this.projects = new Projects(this._client);
|
|
}
|
|
};
|
|
Organization.AuditLogs = AuditLogs;
|
|
Organization.AdminAPIKeys = AdminAPIKeys;
|
|
Organization.Usage = Usage;
|
|
Organization.Invites = Invites;
|
|
Organization.Users = Users3;
|
|
Organization.Groups = Groups;
|
|
Organization.Roles = Roles;
|
|
Organization.DataRetention = DataRetention;
|
|
Organization.SpendLimit = SpendLimit;
|
|
Organization.SpendAlerts = SpendAlerts;
|
|
Organization.Certificates = Certificates;
|
|
Organization.Projects = Projects;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/admin/admin.mjs
|
|
var Admin;
|
|
var init_admin = __esm({
|
|
"node_modules/openai/resources/admin/admin.mjs"() {
|
|
init_resource();
|
|
init_organization();
|
|
init_organization();
|
|
Admin = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.organization = new Organization(this._client);
|
|
}
|
|
};
|
|
Admin.Organization = Organization;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/audio/speech.mjs
|
|
var Speech;
|
|
var init_speech = __esm({
|
|
"node_modules/openai/resources/audio/speech.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
Speech = class extends APIResource {
|
|
/**
|
|
* Generates audio from the input text.
|
|
*
|
|
* Returns the audio file content, or a stream of audio events.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const speech = await client.audio.speech.create({
|
|
* input: 'input',
|
|
* model: 'tts-1',
|
|
* voice: 'alloy',
|
|
* });
|
|
*
|
|
* const content = await speech.blob();
|
|
* console.log(content);
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/audio/speech", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/octet-stream" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/audio/transcriptions.mjs
|
|
var Transcriptions;
|
|
var init_transcriptions = __esm({
|
|
"node_modules/openai/resources/audio/transcriptions.mjs"() {
|
|
init_resource();
|
|
init_uploads();
|
|
Transcriptions = class extends APIResource {
|
|
create(body, options) {
|
|
return this._client.post("/audio/transcriptions", multipartFormRequestOptions({
|
|
body,
|
|
...options,
|
|
stream: body.stream ?? false,
|
|
__metadata: { model: body.model },
|
|
__security: { bearerAuth: true }
|
|
}, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/audio/translations.mjs
|
|
var Translations;
|
|
var init_translations = __esm({
|
|
"node_modules/openai/resources/audio/translations.mjs"() {
|
|
init_resource();
|
|
init_uploads();
|
|
Translations = class extends APIResource {
|
|
create(body, options) {
|
|
return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model }, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/audio/audio.mjs
|
|
var Audio;
|
|
var init_audio = __esm({
|
|
"node_modules/openai/resources/audio/audio.mjs"() {
|
|
init_resource();
|
|
init_speech();
|
|
init_speech();
|
|
init_transcriptions();
|
|
init_transcriptions();
|
|
init_translations();
|
|
init_translations();
|
|
Audio = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.transcriptions = new Transcriptions(this._client);
|
|
this.translations = new Translations(this._client);
|
|
this.speech = new Speech(this._client);
|
|
}
|
|
};
|
|
Audio.Transcriptions = Transcriptions;
|
|
Audio.Translations = Translations;
|
|
Audio.Speech = Speech;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/batches.mjs
|
|
var Batches;
|
|
var init_batches = __esm({
|
|
"node_modules/openai/resources/batches.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Batches = class extends APIResource {
|
|
/**
|
|
* Creates and executes a batch from an uploaded file of requests
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/batches", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Retrieves a batch.
|
|
*/
|
|
retrieve(batchID, options) {
|
|
return this._client.get(path`/batches/${batchID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* List your organization's batches.
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/batches", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Cancels an in-progress batch. The batch will be in status `cancelling` for up to
|
|
* 10 minutes, before changing to `cancelled`, where it will have partial results
|
|
* (if any) available in the output file.
|
|
*/
|
|
cancel(batchID, options) {
|
|
return this._client.post(path`/batches/${batchID}/cancel`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/assistants.mjs
|
|
var Assistants;
|
|
var init_assistants = __esm({
|
|
"node_modules/openai/resources/beta/assistants.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Assistants = class extends APIResource {
|
|
/**
|
|
* Create an assistant with a model and instructions.
|
|
*
|
|
* @deprecated
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/assistants", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves an assistant.
|
|
*
|
|
* @deprecated
|
|
*/
|
|
retrieve(assistantID, options) {
|
|
return this._client.get(path`/assistants/${assistantID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies an assistant.
|
|
*
|
|
* @deprecated
|
|
*/
|
|
update(assistantID, body, options) {
|
|
return this._client.post(path`/assistants/${assistantID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of assistants.
|
|
*
|
|
* @deprecated
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/assistants", CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete an assistant.
|
|
*
|
|
* @deprecated
|
|
*/
|
|
delete(assistantID, options) {
|
|
return this._client.delete(path`/assistants/${assistantID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/realtime/sessions.mjs
|
|
var Sessions;
|
|
var init_sessions = __esm({
|
|
"node_modules/openai/resources/beta/realtime/sessions.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
Sessions = class extends APIResource {
|
|
/**
|
|
* Create an ephemeral API token for use in client-side applications with the
|
|
* Realtime API. Can be configured with the same session parameters as the
|
|
* `session.update` client event.
|
|
*
|
|
* It responds with a session object, plus a `client_secret` key which contains a
|
|
* usable ephemeral API token that can be used to authenticate browser clients for
|
|
* the Realtime API.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const session =
|
|
* await client.beta.realtime.sessions.create();
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/realtime/sessions", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/realtime/transcription-sessions.mjs
|
|
var TranscriptionSessions;
|
|
var init_transcription_sessions = __esm({
|
|
"node_modules/openai/resources/beta/realtime/transcription-sessions.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
TranscriptionSessions = class extends APIResource {
|
|
/**
|
|
* Create an ephemeral API token for use in client-side applications with the
|
|
* Realtime API specifically for realtime transcriptions. Can be configured with
|
|
* the same session parameters as the `transcription_session.update` client event.
|
|
*
|
|
* It responds with a session object, plus a `client_secret` key which contains a
|
|
* usable ephemeral API token that can be used to authenticate browser clients for
|
|
* the Realtime API.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const transcriptionSession =
|
|
* await client.beta.realtime.transcriptionSessions.create();
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/realtime/transcription_sessions", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/realtime/realtime.mjs
|
|
var Realtime;
|
|
var init_realtime = __esm({
|
|
"node_modules/openai/resources/beta/realtime/realtime.mjs"() {
|
|
init_resource();
|
|
init_sessions();
|
|
init_sessions();
|
|
init_transcription_sessions();
|
|
init_transcription_sessions();
|
|
Realtime = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.sessions = new Sessions(this._client);
|
|
this.transcriptionSessions = new TranscriptionSessions(this._client);
|
|
}
|
|
};
|
|
Realtime.Sessions = Sessions;
|
|
Realtime.TranscriptionSessions = TranscriptionSessions;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/environments/files.mjs
|
|
var Files;
|
|
var init_files = __esm({
|
|
"node_modules/openai/resources/beta/agents/environments/files.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Files = class extends APIResource {
|
|
/**
|
|
* Copies inline bytes or a Files API file into a connected execution environment.
|
|
* See
|
|
* [environment files](https://developers.openai.com/api/docs/guides/agents-api/environments/files).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const environmentFile =
|
|
* await client.beta.agents.environments.files.create(
|
|
* 'environment_id',
|
|
* {
|
|
* type: 'inline',
|
|
* path: '/workspace/example.txt',
|
|
* data: 'SGVsbG8K',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(environmentID, body, options) {
|
|
return this._client.post(path`/agents/environments/${environmentID}/files`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists live files on a connected execution environment with optional directory
|
|
* filtering and opaque cursor pagination. See
|
|
* [environment files](https://developers.openai.com/api/docs/guides/agents-api/environments/files).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const environmentFile of client.beta.agents.environments.files.list(
|
|
* 'environment_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(environmentID, query = {}, options) {
|
|
return this._client.getAPIList(path`/agents/environments/${environmentID}/files`, TokenPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/environments/templates.mjs
|
|
var Templates;
|
|
var init_templates = __esm({
|
|
"node_modules/openai/resources/beta/agents/environments/templates.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Templates = class extends APIResource {
|
|
/**
|
|
* Creates reusable environment configuration without returning confidential setup
|
|
* commands or environment values. See
|
|
* [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const environmentTemplate =
|
|
* await client.beta.agents.environments.templates.create();
|
|
* ```
|
|
*/
|
|
create(body = {}, options) {
|
|
return this._client.post("/agents/environments/templates", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves reusable environment configuration without returning confidential
|
|
* values. See
|
|
* [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const environmentTemplate =
|
|
* await client.beta.agents.environments.templates.retrieve(
|
|
* 'environment_template_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(environmentTemplateID, options) {
|
|
return this._client.get(path`/agents/environments/templates/${environmentTemplateID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates reusable environment configuration without returning confidential
|
|
* values. See
|
|
* [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const environmentTemplate =
|
|
* await client.beta.agents.environments.templates.update(
|
|
* 'environment_template_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(environmentTemplateID, body = {}, options) {
|
|
return this._client.post(path`/agents/environments/templates/${environmentTemplateID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists reusable environment templates without returning confidential values. See
|
|
* [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const environmentTemplate of client.beta.agents.environments.templates.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/agents/environments/templates", CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes reusable environment configuration and all confidential template inputs.
|
|
* See
|
|
* [reusing a hosted setup](https://developers.openai.com/api/docs/guides/agents-api/tools#reuse-a-hosted-plugin-setup).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const environmentTemplateDeleted =
|
|
* await client.beta.agents.environments.templates.delete(
|
|
* 'environment_template_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(environmentTemplateID, options) {
|
|
return this._client.delete(path`/agents/environments/templates/${environmentTemplateID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/environments/environments.mjs
|
|
var Environments;
|
|
var init_environments = __esm({
|
|
"node_modules/openai/resources/beta/agents/environments/environments.mjs"() {
|
|
init_resource();
|
|
init_files();
|
|
init_files();
|
|
init_templates();
|
|
init_templates();
|
|
init_headers2();
|
|
init_path();
|
|
Environments = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.files = new Files(this._client);
|
|
this.templates = new Templates(this._client);
|
|
}
|
|
/**
|
|
* Retrieves an execution environment's connection status and safe installed
|
|
* metadata. See
|
|
* [environment lifecycle](https://developers.openai.com/api/docs/guides/agents-api/environments/lifecycle).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const environmentInfo =
|
|
* await client.beta.agents.environments.retrieve(
|
|
* 'environment_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(environmentID, options) {
|
|
return this._client.get(path`/agents/environments/${environmentID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Environments.Files = Files;
|
|
Environments.Templates = Templates;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/agents/turn-state.mjs
|
|
var _TurnState_turnID, _TurnState_turnEnded, _TurnState_eventIDs, _TurnState_calls, TurnState;
|
|
var init_turn_state = __esm({
|
|
"node_modules/openai/lib/agents/turn-state.mjs"() {
|
|
init_tslib();
|
|
TurnState = class {
|
|
constructor() {
|
|
_TurnState_turnID.set(this, void 0);
|
|
_TurnState_turnEnded.set(this, false);
|
|
_TurnState_eventIDs.set(this, /* @__PURE__ */ new Set());
|
|
_TurnState_calls.set(this, /* @__PURE__ */ new Set());
|
|
}
|
|
/** Records a delivery unless its event ID is in the bounded recent window. */
|
|
accept(event) {
|
|
if (__classPrivateFieldGet(this, _TurnState_eventIDs, "f").has(event.event_id)) {
|
|
return false;
|
|
}
|
|
if (__classPrivateFieldGet(this, _TurnState_eventIDs, "f").size === 1024) {
|
|
const oldest = __classPrivateFieldGet(this, _TurnState_eventIDs, "f").values().next();
|
|
if (!oldest.done) {
|
|
__classPrivateFieldGet(this, _TurnState_eventIDs, "f").delete(oldest.value);
|
|
}
|
|
}
|
|
__classPrivateFieldGet(this, _TurnState_eventIDs, "f").add(event.event_id);
|
|
if (event.type === "agent.session.turn.created" && event.turn.subagent_id === null && __classPrivateFieldGet(this, _TurnState_turnID, "f") === void 0) {
|
|
__classPrivateFieldSet(this, _TurnState_turnID, event.turn_id, "f");
|
|
}
|
|
if ((event.type === "agent.session.turn.completed" || event.type === "agent.session.turn.failed" || event.type === "agent.session.turn.cancelled") && __classPrivateFieldGet(this, _TurnState_turnID, "f") !== void 0 && event.turn_id === __classPrivateFieldGet(this, _TurnState_turnID, "f")) {
|
|
__classPrivateFieldSet(this, _TurnState_turnEnded, true, "f");
|
|
}
|
|
return true;
|
|
}
|
|
/** Checks session termination after updating the selected turn state. */
|
|
terminal(event) {
|
|
return event.type === "agent.session.failed" || event.type === "agent.session.idle" && __classPrivateFieldGet(this, _TurnState_turnEnded, "f");
|
|
}
|
|
/** Returns each tool call once for the full invocation, including subagent turns. */
|
|
call(event) {
|
|
if (event.type !== "agent.session.turn.item.added" || event.item.type !== "function_call") {
|
|
return;
|
|
}
|
|
const call = event.item;
|
|
const key = JSON.stringify([call.turn_id, call.call_id]);
|
|
if (__classPrivateFieldGet(this, _TurnState_calls, "f").has(key)) {
|
|
return;
|
|
}
|
|
__classPrivateFieldGet(this, _TurnState_calls, "f").add(key);
|
|
return call;
|
|
}
|
|
};
|
|
_TurnState_turnID = /* @__PURE__ */ new WeakMap(), _TurnState_turnEnded = /* @__PURE__ */ new WeakMap(), _TurnState_eventIDs = /* @__PURE__ */ new WeakMap(), _TurnState_calls = /* @__PURE__ */ new WeakMap();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/agents/agent-session-stream.mjs
|
|
function isInputContent(value) {
|
|
if (!isObj(value)) {
|
|
return false;
|
|
}
|
|
const content = value;
|
|
let field;
|
|
if (content["type"] === "input_text") {
|
|
field = "text";
|
|
} else if (content["type"] === "input_image") {
|
|
field = "image_url";
|
|
} else {
|
|
return false;
|
|
}
|
|
return hasOwn(content, "type") && hasOwn(content, field) && typeof content[field] === "string";
|
|
}
|
|
function normalizedOutput(value) {
|
|
if (value === null) {
|
|
return null;
|
|
}
|
|
if (typeof value === "string" || Array.isArray(value) && value.every(isInputContent)) {
|
|
return value;
|
|
}
|
|
throw new OpenAIError("Tool output must be text, content, a JSON object, or null");
|
|
}
|
|
function toolResult(call, value) {
|
|
const output = isObj(value) ? JSON.stringify(value) : value;
|
|
const serialized = JSON.stringify(output);
|
|
if (serialized === void 0) {
|
|
throw new OpenAIError("Tool output must be JSON serializable");
|
|
}
|
|
return {
|
|
type: "agent.session.input.tool_result",
|
|
turn_id: call.turn_id,
|
|
call_id: call.call_id,
|
|
success: true,
|
|
output: normalizedOutput(typeof output === "string" ? output : JSON.parse(serialized))
|
|
};
|
|
}
|
|
async function cancelBody(response) {
|
|
try {
|
|
await response?.body?.cancel();
|
|
} catch {
|
|
}
|
|
}
|
|
var _AgentSessionStream_instances, _AgentSessionStream_consumed, _AgentSessionStream_stream, _AgentSessionStream_response, _AgentSessionStream_reading, _AgentSessionStream_sessions, _AgentSessionStream_sessionID, _AgentSessionStream_input, _AgentSessionStream_handlers, _AgentSessionStream_inputKey, _AgentSessionStream_options, _AgentSessionStream_iterate, _AgentSessionStream_result, _AgentSessionStream_checkAbort, _AgentSessionStream_abortError, _AgentSessionStream_wait, _AgentSessionStream_submit, AgentSessionStream;
|
|
var init_agent_session_stream = __esm({
|
|
"node_modules/openai/lib/agents/agent-session-stream.mjs"() {
|
|
init_tslib();
|
|
init_turn_state();
|
|
init_error();
|
|
init_headers2();
|
|
init_uuid();
|
|
init_values();
|
|
AgentSessionStream = class {
|
|
/** Creates an unstarted helper. Prefer client.beta.agents.sessions.stream(). */
|
|
constructor(sessions, sessionID, params, options) {
|
|
_AgentSessionStream_instances.add(this);
|
|
this.controller = new AbortController();
|
|
_AgentSessionStream_consumed.set(this, false);
|
|
_AgentSessionStream_stream.set(this, void 0);
|
|
_AgentSessionStream_response.set(this, void 0);
|
|
_AgentSessionStream_reading.set(this, false);
|
|
_AgentSessionStream_sessions.set(this, void 0);
|
|
_AgentSessionStream_sessionID.set(this, void 0);
|
|
_AgentSessionStream_input.set(this, void 0);
|
|
_AgentSessionStream_handlers.set(this, void 0);
|
|
_AgentSessionStream_inputKey.set(this, void 0);
|
|
_AgentSessionStream_options.set(this, void 0);
|
|
const input = typeof params.input === "string" ? [{ role: "user", content: [{ type: "input_text", text: params.input }] }] : params.input;
|
|
if (params.input.length === 0) {
|
|
throw new OpenAIError("input must not be empty");
|
|
}
|
|
__classPrivateFieldSet(this, _AgentSessionStream_sessions, sessions, "f");
|
|
__classPrivateFieldSet(this, _AgentSessionStream_sessionID, sessionID, "f");
|
|
__classPrivateFieldSet(this, _AgentSessionStream_input, { type: "agent.session.input.message", input }, "f");
|
|
__classPrivateFieldSet(this, _AgentSessionStream_handlers, new Map(Object.entries(params.toolHandlers ?? {})), "f");
|
|
const headers = buildHeaders([options?.headers]);
|
|
__classPrivateFieldSet(this, _AgentSessionStream_inputKey, headers.nulls.has("idempotency-key") ? void 0 : headers.values.get("idempotency-key") ?? params.idempotencyKey ?? options?.idempotencyKey ?? uuid4(), "f");
|
|
headers.values.delete("idempotency-key");
|
|
headers.nulls.delete("idempotency-key");
|
|
const { idempotencyKey: _key, ...rest } = options ?? {};
|
|
__classPrivateFieldSet(this, _AgentSessionStream_options, { ...rest, headers }, "f");
|
|
}
|
|
/** Closes local requests without cancelling the turn; an optional reason becomes the abort error's cause. */
|
|
abort(reason) {
|
|
this.controller.abort(reason);
|
|
__classPrivateFieldGet(this, _AgentSessionStream_stream, "f")?.controller.abort(this.controller.signal.reason);
|
|
if (!__classPrivateFieldGet(this, _AgentSessionStream_reading, "f")) {
|
|
void cancelBody(__classPrivateFieldGet(this, _AgentSessionStream_response, "f"));
|
|
}
|
|
}
|
|
/** Starts iteration once; use for await to ensure early exits close the connection. */
|
|
[(_AgentSessionStream_consumed = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_stream = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_response = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_reading = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_sessions = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_sessionID = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_input = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_handlers = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_inputKey = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_options = /* @__PURE__ */ new WeakMap(), _AgentSessionStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
if (__classPrivateFieldGet(this, _AgentSessionStream_consumed, "f")) {
|
|
throw new OpenAIError("An AgentSessionStream can only be consumed once");
|
|
}
|
|
__classPrivateFieldSet(this, _AgentSessionStream_consumed, true, "f");
|
|
return __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_iterate).call(this);
|
|
}
|
|
};
|
|
_AgentSessionStream_iterate = async function* _AgentSessionStream_iterate2() {
|
|
const externalSignal = __classPrivateFieldGet(this, _AgentSessionStream_options, "f").signal;
|
|
const abort = () => this.abort(externalSignal?.aborted ? externalSignal.reason : this.controller.signal.reason);
|
|
externalSignal?.addEventListener("abort", abort, { once: true });
|
|
this.controller.signal.addEventListener("abort", abort, { once: true });
|
|
const options = { ...__classPrivateFieldGet(this, _AgentSessionStream_options, "f"), signal: this.controller.signal };
|
|
const state2 = new TurnState();
|
|
try {
|
|
if (externalSignal?.aborted) {
|
|
this.abort(externalSignal.reason);
|
|
}
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
const session = await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").retrieve(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), options);
|
|
if (session.status !== "idle") {
|
|
throw new OpenAIError("sessions.stream requires an idle session; use sessions.events.stream for active sessions");
|
|
}
|
|
const subscription = await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").events.stream(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), options).withResponse();
|
|
__classPrivateFieldSet(this, _AgentSessionStream_stream, subscription.data, "f");
|
|
__classPrivateFieldSet(this, _AgentSessionStream_response, subscription.response, "f");
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").events.create(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), {
|
|
events: [__classPrivateFieldGet(this, _AgentSessionStream_input, "f")],
|
|
// Spread creates an own data property without invoking inherited setters or changing the object prototype.
|
|
...__classPrivateFieldGet(this, _AgentSessionStream_inputKey, "f") === void 0 ? {} : { "Idempotency-Key": __classPrivateFieldGet(this, _AgentSessionStream_inputKey, "f") }
|
|
}, {
|
|
...options,
|
|
headers: buildHeaders([options.headers, { "Idempotency-Key": __classPrivateFieldGet(this, _AgentSessionStream_inputKey, "f") ?? null }])
|
|
});
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
__classPrivateFieldSet(this, _AgentSessionStream_reading, true, "f");
|
|
for await (const event of __classPrivateFieldGet(this, _AgentSessionStream_stream, "f")) {
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
if (!state2.accept(event)) {
|
|
continue;
|
|
}
|
|
const terminal = state2.terminal(event);
|
|
const pendingCall = state2.call(event);
|
|
const handler = pendingCall && __classPrivateFieldGet(this, _AgentSessionStream_handlers, "f").get(pendingCall.name);
|
|
const call = pendingCall && handler ? structuredClone(pendingCall) : void 0;
|
|
if (terminal) {
|
|
__classPrivateFieldGet(this, _AgentSessionStream_stream, "f").controller.abort();
|
|
}
|
|
yield event;
|
|
if (terminal) {
|
|
return;
|
|
}
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
if (!call || !handler) {
|
|
continue;
|
|
}
|
|
const result = await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_result).call(this, call, handler);
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_submit).call(this, result, options);
|
|
}
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
throw new OpenAIError("Session event stream ended before the turn reached idle or failed");
|
|
} finally {
|
|
externalSignal?.removeEventListener("abort", abort);
|
|
this.controller.signal.removeEventListener("abort", abort);
|
|
this.abort();
|
|
}
|
|
}, _AgentSessionStream_result = async function _AgentSessionStream_result2(call, handler) {
|
|
try {
|
|
const args = typeof call.arguments === "string" ? JSON.parse(call.arguments) : call.arguments;
|
|
if (!isObj(args)) {
|
|
throw new OpenAIError("Function arguments must be a JSON object");
|
|
}
|
|
return toolResult(call, await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_wait).call(this, () => handler(args)));
|
|
} catch {
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
return {
|
|
type: "agent.session.input.tool_result",
|
|
turn_id: call.turn_id,
|
|
call_id: call.call_id,
|
|
success: false,
|
|
error: "Tool handler failed."
|
|
};
|
|
}
|
|
}, _AgentSessionStream_checkAbort = function _AgentSessionStream_checkAbort2() {
|
|
if (this.controller.signal.aborted) {
|
|
throw __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_abortError).call(this);
|
|
}
|
|
}, _AgentSessionStream_abortError = function _AgentSessionStream_abortError2() {
|
|
const error = new APIUserAbortError();
|
|
Object.defineProperty(error, "cause", {
|
|
value: this.controller.signal.reason,
|
|
writable: true,
|
|
configurable: true
|
|
});
|
|
return error;
|
|
}, _AgentSessionStream_wait = async function _AgentSessionStream_wait2(action) {
|
|
let onAbort;
|
|
const aborted = new Promise((_resolve, reject) => {
|
|
onAbort = () => reject(__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_abortError).call(this));
|
|
this.controller.signal.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
try {
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
const invoke = async () => await action();
|
|
return await Promise.race([invoke(), aborted]);
|
|
} finally {
|
|
if (onAbort) {
|
|
this.controller.signal.removeEventListener("abort", onAbort);
|
|
}
|
|
}
|
|
}, _AgentSessionStream_submit = async function _AgentSessionStream_submit2(result, options, key = uuid4(), attempt = 0) {
|
|
__classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_checkAbort).call(this);
|
|
try {
|
|
await __classPrivateFieldGet(this, _AgentSessionStream_sessions, "f").events.create(__classPrivateFieldGet(this, _AgentSessionStream_sessionID, "f"), { events: [result], "Idempotency-Key": key }, options);
|
|
} catch (error) {
|
|
const delay = [100, 300, 600][attempt];
|
|
if (delay === void 0 || !(error instanceof BadRequestError) || error.code !== "invalid_request_error" || !error.error || !("message" in error.error) || error.error.message !== `Unknown pending tool call: ${result.call_id}`) {
|
|
throw error;
|
|
}
|
|
let timer;
|
|
try {
|
|
await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_wait).call(this, () => (
|
|
// oxlint-disable-next-line promise/avoid-new -- Own the registration timer so cancellation clears it promptly.
|
|
new Promise((resolve) => {
|
|
timer = setTimeout(resolve, delay);
|
|
})
|
|
));
|
|
} finally {
|
|
if (timer !== void 0) {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
await __classPrivateFieldGet(this, _AgentSessionStream_instances, "m", _AgentSessionStream_submit2).call(this, result, options, key, attempt + 1);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/artifacts.mjs
|
|
var Artifacts;
|
|
var init_artifacts = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/artifacts.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Artifacts = class extends APIResource {
|
|
/**
|
|
* Retrieves immutable metadata for one durable session artifact. See
|
|
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const sessionArtifact =
|
|
* await client.beta.agents.sessions.artifacts.retrieve(
|
|
* 'artifact_id',
|
|
* { session_id: 'session_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(artifactID, params, options) {
|
|
const { session_id } = params;
|
|
return this._client.get(path`/agents/sessions/${session_id}/artifacts/${artifactID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists immutable artifacts published by completed hosted session turns. See
|
|
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const sessionArtifact of client.beta.agents.sessions.artifacts.list(
|
|
* 'session_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, query = {}, options) {
|
|
return this._client.getAPIList(path`/agents/sessions/${sessionID}/artifacts`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes an immutable session artifact without deleting its live environment file
|
|
* or original Files API object. See
|
|
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const sessionArtifactDeleted =
|
|
* await client.beta.agents.sessions.artifacts.delete(
|
|
* 'artifact_id',
|
|
* { session_id: 'session_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(artifactID, params, options) {
|
|
const { session_id } = params;
|
|
return this._client.delete(path`/agents/sessions/${session_id}/artifacts/${artifactID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Downloads immutable session artifact bytes after the execution environment
|
|
* expires. See
|
|
* [session artifacts](https://developers.openai.com/api/docs/guides/agents-api/environments/files#openai-hosted-artifacts).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.beta.agents.sessions.artifacts.content(
|
|
* 'artifact_id',
|
|
* { session_id: 'session_id' },
|
|
* );
|
|
*
|
|
* const content = await response.blob();
|
|
* console.log(content);
|
|
* ```
|
|
*/
|
|
content(artifactID, params, options) {
|
|
const { session_id } = params;
|
|
return this._client.get(path`/agents/sessions/${session_id}/artifacts/${artifactID}/content`, {
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ "OpenAI-Beta": "agents=v1", Accept: "application/octet-stream" },
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/events.mjs
|
|
var Events;
|
|
var init_events = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/events.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
Events = class extends APIResource {
|
|
/**
|
|
* Submits message, cancellation, or tool-result events to a managed agent session.
|
|
* Cancellation can recover a still-open turn whose backend execution has ended by
|
|
* marking it cancelled and abandoning unpublished outputs. Saved results,
|
|
* published files, and existing terminal outcomes are preserved. HTTP 202 confirms
|
|
* acceptance, not durable completion. See
|
|
* [session events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.beta.agents.sessions.events.create(
|
|
* 'session_id',
|
|
* {
|
|
* events: [
|
|
* {
|
|
* input: [
|
|
* {
|
|
* content: [{ text: 'text', type: 'input_text' }],
|
|
* role: 'user',
|
|
* },
|
|
* ],
|
|
* type: 'agent.session.input.message',
|
|
* },
|
|
* ],
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(sessionID, params, options) {
|
|
const { "Idempotency-Key": idempotencyKey, ...body } = params;
|
|
return this._client.post(path`/agents/sessions/${sessionID}/events`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([
|
|
{
|
|
"OpenAI-Beta": "agents=v1",
|
|
Accept: "*/*",
|
|
...idempotencyKey != null ? { "Idempotency-Key": idempotencyKey } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Streams live events for an agent session. See
|
|
* [session events](https://developers.openai.com/api/docs/guides/agents-api/sessions/events).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agentSessionEvent =
|
|
* await client.beta.agents.sessions.events.stream(
|
|
* 'session_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
stream(sessionID, options) {
|
|
return this._client.get(path`/agents/sessions/${sessionID}/events`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1", Accept: "text/event-stream" }, options?.headers]),
|
|
stream: true,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/items.mjs
|
|
var Items;
|
|
var init_items = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Items = class extends APIResource {
|
|
/**
|
|
* Lists items produced by the session's root agent, including its interactions
|
|
* with subagents. Each subagent has its own item history. See
|
|
* [inspecting agent output](https://developers.openai.com/api/docs/guides/agents-api/observability).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const agentSessionItem of client.beta.agents.sessions.items.list(
|
|
* 'session_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, query = {}, options) {
|
|
return this._client.getAPIList(path`/agents/sessions/${sessionID}/items`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/turns.mjs
|
|
var Turns;
|
|
var init_turns = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/turns.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Turns = class extends APIResource {
|
|
/**
|
|
* Retrieves a turn's current status, timestamps, usage, and error. Returns 404 if
|
|
* the turn does not belong to the session. See
|
|
* [session turns](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage#inspect-session-turns).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const turn =
|
|
* await client.beta.agents.sessions.turns.retrieve(
|
|
* 'turn_id',
|
|
* { session_id: 'session_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(turnID, params, options) {
|
|
const { session_id } = params;
|
|
return this._client.get(path`/agents/sessions/${session_id}/turns/${turnID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists turns by creation time and turn ID. The after cursor is exclusive in the
|
|
* selected order. See
|
|
* [session turns](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage#inspect-session-turns).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const turn of client.beta.agents.sessions.turns.list(
|
|
* 'session_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, query = {}, options) {
|
|
return this._client.getAPIList(path`/agents/sessions/${sessionID}/turns`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/subagents/items.mjs
|
|
var Items2;
|
|
var init_items2 = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/subagents/items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Items2 = class extends APIResource {
|
|
/**
|
|
* Lists this subagent's own items across all of its turns. See
|
|
* [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const agentSessionItem of client.beta.agents.sessions.subagents.items.list(
|
|
* 'subagent_id',
|
|
* { session_id: 'session_id' },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(subagentID, params, options) {
|
|
const { session_id, ...query } = params;
|
|
return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagentID}/items`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/subagents/turns/items.mjs
|
|
var Items3;
|
|
var init_items3 = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/subagents/turns/items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Items3 = class extends APIResource {
|
|
/**
|
|
* Lists items belonging to one turn of this subagent. See
|
|
* [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const agentSessionItem of client.beta.agents.sessions.subagents.turns.items.list(
|
|
* 'turn_id',
|
|
* { session_id: 'session_id', subagent_id: 'subagent_id' },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(turnID, params, options) {
|
|
const { session_id, subagent_id, ...query } = params;
|
|
return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagent_id}/turns/${turnID}/items`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/subagents/turns/turns.mjs
|
|
var Turns2;
|
|
var init_turns2 = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/subagents/turns/turns.mjs"() {
|
|
init_resource();
|
|
init_items3();
|
|
init_items3();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Turns2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.items = new Items3(this._client);
|
|
}
|
|
/**
|
|
* Retrieves a turn belonging to this subagent. See
|
|
* [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const turn =
|
|
* await client.beta.agents.sessions.subagents.turns.retrieve(
|
|
* 'turn_id',
|
|
* {
|
|
* session_id: 'session_id',
|
|
* subagent_id: 'subagent_id',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(turnID, params, options) {
|
|
const { session_id, subagent_id } = params;
|
|
return this._client.get(path`/agents/sessions/${session_id}/subagents/${subagent_id}/turns/${turnID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists all turns of this subagent, including turns after a resume. See
|
|
* [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const turn of client.beta.agents.sessions.subagents.turns.list(
|
|
* 'subagent_id',
|
|
* { session_id: 'session_id' },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(subagentID, params, options) {
|
|
const { session_id, ...query } = params;
|
|
return this._client.getAPIList(path`/agents/sessions/${session_id}/subagents/${subagentID}/turns`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Turns2.Items = Items3;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/subagents/subagents.mjs
|
|
var Subagents;
|
|
var init_subagents = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/subagents/subagents.mjs"() {
|
|
init_resource();
|
|
init_items2();
|
|
init_items2();
|
|
init_turns2();
|
|
init_turns2();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Subagents = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.items = new Items2(this._client);
|
|
this.turns = new Turns2(this._client);
|
|
}
|
|
/**
|
|
* Retrieves a subagent belonging to this session. See
|
|
* [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const subagent =
|
|
* await client.beta.agents.sessions.subagents.retrieve(
|
|
* 'subagent_id',
|
|
* { session_id: 'session_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(subagentID, params, options) {
|
|
const { session_id } = params;
|
|
return this._client.get(path`/agents/sessions/${session_id}/subagents/${subagentID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists subagents in a session, including nested and closed subagents. See
|
|
* [subagent workflows](https://developers.openai.com/api/docs/guides/agents-api/multi-agent).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const subagent of client.beta.agents.sessions.subagents.list(
|
|
* 'session_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, query = {}, options) {
|
|
return this._client.getAPIList(path`/agents/sessions/${sessionID}/subagents`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Subagents.Items = Items2;
|
|
Subagents.Turns = Turns2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/sessions/sessions.mjs
|
|
var Sessions2;
|
|
var init_sessions2 = __esm({
|
|
"node_modules/openai/resources/beta/agents/sessions/sessions.mjs"() {
|
|
init_agent_session_stream();
|
|
init_resource();
|
|
init_artifacts();
|
|
init_artifacts();
|
|
init_events();
|
|
init_events();
|
|
init_items();
|
|
init_items();
|
|
init_turns();
|
|
init_turns();
|
|
init_subagents();
|
|
init_subagents();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Sessions2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.subagents = new Subagents(this._client);
|
|
this.artifacts = new Artifacts(this._client);
|
|
this.items = new Items(this._client);
|
|
this.events = new Events(this._client);
|
|
this.turns = new Turns(this._client);
|
|
}
|
|
/** Stream one turn on an idle session with a single input writer. See AgentSessionStream for lifecycle and tool handling. */
|
|
stream(sessionID, params, options) {
|
|
return new AgentSessionStream(this, sessionID, params, options);
|
|
}
|
|
create(body, options) {
|
|
return this._client.post("/agents/sessions", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
stream: body.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves the current state of a managed agent session. See
|
|
* [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agentSession =
|
|
* await client.beta.agents.sessions.retrieve('session_id');
|
|
* ```
|
|
*/
|
|
retrieve(sessionID, options) {
|
|
return this._client.get(path`/agents/sessions/${sessionID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates session metadata, model, reasoning effort, or service tier. Model
|
|
* settings apply to subsequent turns. Omitted fields are unchanged. See
|
|
* [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agentSession =
|
|
* await client.beta.agents.sessions.update('session_id');
|
|
* ```
|
|
*/
|
|
update(sessionID, body = {}, options) {
|
|
return this._client.post(path`/agents/sessions/${sessionID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists managed agent sessions using ID-based pagination and the requested sort
|
|
* order. See
|
|
* [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const agentSession of client.beta.agents.sessions.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/agents/sessions", CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Removes a managed agent session from the public API and returns a deletion
|
|
* confirmation. If backend execution has ended, deletion can cancel a still-open
|
|
* public turn and abandon unpublished outputs. Running execution must be cancelled
|
|
* first. Physical cleanup may continue asynchronously. See
|
|
* [managing sessions](https://developers.openai.com/api/docs/guides/agents-api/sessions/manage).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agentSessionDeleted =
|
|
* await client.beta.agents.sessions.delete('session_id');
|
|
* ```
|
|
*/
|
|
delete(sessionID, options) {
|
|
return this._client.delete(path`/agents/sessions/${sessionID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Sessions2.Subagents = Subagents;
|
|
Sessions2.Artifacts = Artifacts;
|
|
Sessions2.Items = Items;
|
|
Sessions2.Events = Events;
|
|
Sessions2.Turns = Turns;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/vaults/credentials.mjs
|
|
var Credentials;
|
|
var init_credentials = __esm({
|
|
"node_modules/openai/resources/beta/agents/vaults/credentials.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Credentials = class extends APIResource {
|
|
/**
|
|
* Creates a vault credential. Secret values are write-only and are never returned.
|
|
* See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const credential =
|
|
* await client.beta.agents.vaults.credentials.create(
|
|
* 'vault_id',
|
|
* {
|
|
* auth: {
|
|
* access_token: 'access_token',
|
|
* mcp_server_url: 'mcp_server_url',
|
|
* type: 'mcp_oauth',
|
|
* },
|
|
* name: 'x',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(vaultID, body, options) {
|
|
return this._client.post(path`/vaults/${vaultID}/credentials`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves vault credential metadata without returning secret values. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const credential =
|
|
* await client.beta.agents.vaults.credentials.retrieve(
|
|
* 'credential_id',
|
|
* { vault_id: 'vault_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(credentialID, params, options) {
|
|
const { vault_id } = params;
|
|
return this._client.get(path`/vaults/${vault_id}/credentials/${credentialID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Rotates a vault credential's write-only secret and returns only credential
|
|
* metadata. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const credential =
|
|
* await client.beta.agents.vaults.credentials.update(
|
|
* 'credential_id',
|
|
* {
|
|
* vault_id: 'vault_id',
|
|
* auth: { type: 'mcp_oauth' },
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(credentialID, params, options) {
|
|
const { vault_id, ...body } = params;
|
|
return this._client.post(path`/vaults/${vault_id}/credentials/${credentialID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists a vault's credentials using ID-based pagination without returning secret
|
|
* values. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const credential of client.beta.agents.vaults.credentials.list(
|
|
* 'vault_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(vaultID, query = {}, options) {
|
|
return this._client.getAPIList(path`/vaults/${vaultID}/credentials`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a vault credential. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const credentialDeleted =
|
|
* await client.beta.agents.vaults.credentials.delete(
|
|
* 'credential_id',
|
|
* { vault_id: 'vault_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(credentialID, params, options) {
|
|
const { vault_id } = params;
|
|
return this._client.delete(path`/vaults/${vault_id}/credentials/${credentialID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/vaults/vaults.mjs
|
|
var Vaults;
|
|
var init_vaults = __esm({
|
|
"node_modules/openai/resources/beta/agents/vaults/vaults.mjs"() {
|
|
init_resource();
|
|
init_credentials();
|
|
init_credentials();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Vaults = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.credentials = new Credentials(this._client);
|
|
}
|
|
/**
|
|
* Creates a vault for the current project. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const vault = await client.beta.agents.vaults.create();
|
|
* ```
|
|
*/
|
|
create(body = {}, options) {
|
|
return this._client.post("/vaults", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a vault by its ID. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const vault = await client.beta.agents.vaults.retrieve(
|
|
* 'vault_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(vaultID, options) {
|
|
return this._client.get(path`/vaults/${vaultID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists vaults using ID-based pagination. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const vault of client.beta.agents.vaults.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/vaults", CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a vault and all its credentials. See
|
|
* [vaults](https://developers.openai.com/api/docs/guides/agents-api/tools/vaults).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const vaultDeleted = await client.beta.agents.vaults.delete(
|
|
* 'vault_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(vaultID, options) {
|
|
return this._client.delete(path`/vaults/${vaultID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Vaults.Credentials = Credentials;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/agents/agents.mjs
|
|
var Agents;
|
|
var init_agents = __esm({
|
|
"node_modules/openai/resources/beta/agents/agents.mjs"() {
|
|
init_resource();
|
|
init_environments();
|
|
init_environments();
|
|
init_sessions2();
|
|
init_sessions2();
|
|
init_vaults();
|
|
init_vaults();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Agents = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.environments = new Environments(this._client);
|
|
this.vaults = new Vaults(this._client);
|
|
this.sessions = new Sessions2(this._client);
|
|
}
|
|
/**
|
|
* Creates a reusable agent without storing credentials. See
|
|
* [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agent = await client.beta.agents.create({
|
|
* model: 'model',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/agents", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a reusable agent by ID. See
|
|
* [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agent = await client.beta.agents.retrieve('agent_id');
|
|
* ```
|
|
*/
|
|
retrieve(agentID, options) {
|
|
return this._client.get(path`/agents/${agentID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates a reusable agent. See
|
|
* [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agent = await client.beta.agents.update('agent_id');
|
|
* ```
|
|
*/
|
|
update(agentID, body = {}, options) {
|
|
return this._client.post(path`/agents/${agentID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Lists reusable agents in the current project. See
|
|
* [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const agent of client.beta.agents.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/agents", CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a reusable agent. See
|
|
* [agent configuration](https://developers.openai.com/api/docs/guides/agents-api/configuration).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const agentDeleted = await client.beta.agents.delete(
|
|
* 'agent_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(agentID, options) {
|
|
return this._client.delete(path`/agents/${agentID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "agents=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Agents.Environments = Environments;
|
|
Agents.Vaults = Vaults;
|
|
Agents.Sessions = Sessions2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/chatkit/sessions.mjs
|
|
var Sessions3;
|
|
var init_sessions3 = __esm({
|
|
"node_modules/openai/resources/beta/chatkit/sessions.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
Sessions3 = class extends APIResource {
|
|
/**
|
|
* Create a ChatKit session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const chatSession =
|
|
* await client.beta.chatkit.sessions.create({
|
|
* user: 'x',
|
|
* workflow: { id: 'id' },
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/chatkit/sessions", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Cancel an active ChatKit session and return its most recent metadata.
|
|
*
|
|
* Cancelling prevents new requests from using the issued client secret.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const chatSession =
|
|
* await client.beta.chatkit.sessions.cancel('cksess_123');
|
|
* ```
|
|
*/
|
|
cancel(sessionID, options) {
|
|
return this._client.post(path`/chatkit/sessions/${sessionID}/cancel`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/chatkit/threads.mjs
|
|
var Threads;
|
|
var init_threads = __esm({
|
|
"node_modules/openai/resources/beta/chatkit/threads.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Threads = class extends APIResource {
|
|
/**
|
|
* Retrieve a ChatKit thread by its identifier.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const chatkitThread =
|
|
* await client.beta.chatkit.threads.retrieve('cthr_123');
|
|
* ```
|
|
*/
|
|
retrieve(threadID, options) {
|
|
return this._client.get(path`/chatkit/threads/${threadID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List ChatKit threads with optional pagination and user filters.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const chatkitThread of client.beta.chatkit.threads.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/chatkit/threads", ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a ChatKit thread along with its items and stored attachments.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const thread = await client.beta.chatkit.threads.delete(
|
|
* 'cthr_123',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(threadID, options) {
|
|
return this._client.delete(path`/chatkit/threads/${threadID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List items that belong to a ChatKit thread.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const thread of client.beta.chatkit.threads.listItems(
|
|
* 'cthr_123',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
listItems(threadID, query = {}, options) {
|
|
return this._client.getAPIList(path`/chatkit/threads/${threadID}/items`, ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "chatkit_beta=v1" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/chatkit/chatkit.mjs
|
|
var ChatKit;
|
|
var init_chatkit = __esm({
|
|
"node_modules/openai/resources/beta/chatkit/chatkit.mjs"() {
|
|
init_resource();
|
|
init_sessions3();
|
|
init_sessions3();
|
|
init_threads();
|
|
init_threads();
|
|
ChatKit = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.sessions = new Sessions3(this._client);
|
|
this.threads = new Threads(this._client);
|
|
}
|
|
};
|
|
ChatKit.Sessions = Sessions3;
|
|
ChatKit.Threads = Threads;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/responses/input-items.mjs
|
|
var InputItems;
|
|
var init_input_items = __esm({
|
|
"node_modules/openai/resources/beta/responses/input-items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
InputItems = class extends APIResource {
|
|
/**
|
|
* Returns a list of input items for a given response.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaResponseItem of client.beta.responses.inputItems.list(
|
|
* 'response_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(responseID, params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList(path`/responses/${responseID}/input_items?beta=true`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/responses/input-tokens.mjs
|
|
var InputTokens;
|
|
var init_input_tokens = __esm({
|
|
"node_modules/openai/resources/beta/responses/input-tokens.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
InputTokens = class extends APIResource {
|
|
/**
|
|
* Returns input token counts of the request.
|
|
*
|
|
* Returns an object with `object` set to `response.input_tokens` and an
|
|
* `input_tokens` count.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.beta.responses.inputTokens.count();
|
|
* ```
|
|
*/
|
|
count(params = {}, options) {
|
|
const { betas, ...body } = params ?? {};
|
|
return this._client.post("/responses/input_tokens?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/responses/responses.mjs
|
|
var Responses;
|
|
var init_responses = __esm({
|
|
"node_modules/openai/resources/beta/responses/responses.mjs"() {
|
|
init_resource();
|
|
init_input_items();
|
|
init_input_items();
|
|
init_input_tokens();
|
|
init_input_tokens();
|
|
init_headers2();
|
|
init_path();
|
|
Responses = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.inputItems = new InputItems(this._client);
|
|
this.inputTokens = new InputTokens(this._client);
|
|
}
|
|
create(params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post("/responses?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
stream: params.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
retrieve(responseID, params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.get(path`/responses/${responseID}?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
stream: params?.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a model response with the given ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.beta.responses.delete(
|
|
* 'resp_677efb5139a88190b512bc3fef8e535d',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(responseID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.delete(path`/responses/${responseID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ Accept: "*/*", ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Cancels a model response with the given ID. Only responses created with the
|
|
* `background` parameter set to `true` can be cancelled.
|
|
* [Learn more](https://developers.openai.com/api/docs/guides/background).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaResponse = await client.beta.responses.cancel(
|
|
* 'resp_677efb5139a88190b512bc3fef8e535d',
|
|
* );
|
|
* ```
|
|
*/
|
|
cancel(responseID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.post(path`/responses/${responseID}/cancel?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Compact a conversation. Returns a compacted response object.
|
|
*
|
|
* Learn when and how to compact long-running conversations in the
|
|
* [conversation state guide](https://developers.openai.com/api/docs/guides/conversation-state#managing-the-context-window).
|
|
* For ZDR-compatible compaction details, see
|
|
* [Compaction (advanced)](https://developers.openai.com/api/docs/guides/conversation-state#compaction-advanced).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaCompactedResponse =
|
|
* await client.beta.responses.compact({
|
|
* model: 'gpt-6-astra',
|
|
* });
|
|
* ```
|
|
*/
|
|
compact(params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post("/responses/compact?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([
|
|
{ ...betas?.toString() != null ? { "openai-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Responses.InputItems = InputItems;
|
|
Responses.InputTokens = InputTokens;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/threads/messages.mjs
|
|
var Messages2;
|
|
var init_messages2 = __esm({
|
|
"node_modules/openai/resources/beta/threads/messages.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Messages2 = class extends APIResource {
|
|
/**
|
|
* Create a message.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
create(threadID, body, options) {
|
|
return this._client.post(path`/threads/${threadID}/messages`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieve a message.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
retrieve(messageID, params, options) {
|
|
const { thread_id } = params;
|
|
return this._client.get(path`/threads/${thread_id}/messages/${messageID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a message.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
update(messageID, params, options) {
|
|
const { thread_id, ...body } = params;
|
|
return this._client.post(path`/threads/${thread_id}/messages/${messageID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of messages for a given thread.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
list(threadID, query = {}, options) {
|
|
return this._client.getAPIList(path`/threads/${threadID}/messages`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a message.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
delete(messageID, params, options) {
|
|
const { thread_id } = params;
|
|
return this._client.delete(path`/threads/${thread_id}/messages/${messageID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/threads/runs/steps.mjs
|
|
var Steps;
|
|
var init_steps = __esm({
|
|
"node_modules/openai/resources/beta/threads/runs/steps.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Steps = class extends APIResource {
|
|
/**
|
|
* Retrieves a run step.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
retrieve(stepID, params, options) {
|
|
const { thread_id, run_id, ...query } = params;
|
|
return this._client.get(path`/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of run steps belonging to a run.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
list(runID, params, options) {
|
|
const { thread_id, ...query } = params;
|
|
return this._client.getAPIList(path`/threads/${thread_id}/runs/${runID}/steps`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/base64.mjs
|
|
var fromBase64, toFloat32Array;
|
|
var init_base64 = __esm({
|
|
"node_modules/openai/internal/utils/base64.mjs"() {
|
|
init_error();
|
|
init_bytes();
|
|
fromBase64 = (str2) => {
|
|
if (typeof globalThis.Buffer !== "undefined") {
|
|
const buf = globalThis.Buffer.from(str2, "base64");
|
|
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
}
|
|
if (typeof atob !== "undefined") {
|
|
const bstr = atob(str2);
|
|
const buf = new Uint8Array(bstr.length);
|
|
for (let i = 0; i < bstr.length; i++) {
|
|
buf[i] = bstr.charCodeAt(i);
|
|
}
|
|
return buf;
|
|
}
|
|
throw new OpenAIError("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined");
|
|
};
|
|
toFloat32Array = (base64Str) => {
|
|
if (typeof Buffer !== "undefined") {
|
|
const buf = Buffer.from(base64Str, "base64");
|
|
if (buf.length % Float32Array.BYTES_PER_ELEMENT !== 0) {
|
|
throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");
|
|
}
|
|
return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT));
|
|
} else {
|
|
const binaryStr = atob(base64Str);
|
|
const len = binaryStr.length;
|
|
const bytes2 = new Uint8Array(len);
|
|
for (let i = 0; i < len; i++) {
|
|
bytes2[i] = binaryStr.charCodeAt(i);
|
|
}
|
|
return Array.from(new Float32Array(bytes2.buffer));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils/env.mjs
|
|
var readEnv;
|
|
var init_env = __esm({
|
|
"node_modules/openai/internal/utils/env.mjs"() {
|
|
readEnv = (env) => {
|
|
try {
|
|
if (typeof globalThis.process !== "undefined") {
|
|
return globalThis.process.env?.[env]?.trim() || void 0;
|
|
}
|
|
if (typeof globalThis.Deno !== "undefined") {
|
|
return globalThis.Deno.env?.get?.(env)?.trim() || void 0;
|
|
}
|
|
} catch {
|
|
return void 0;
|
|
}
|
|
return void 0;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/utils.mjs
|
|
var init_utils2 = __esm({
|
|
"node_modules/openai/internal/utils.mjs"() {
|
|
init_values();
|
|
init_base64();
|
|
init_env();
|
|
init_log();
|
|
init_uuid();
|
|
init_sleep();
|
|
init_query();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/assistant-stream-delta.mjs
|
|
function getAssistantStreamDiagnosticProperty(property) {
|
|
switch (property) {
|
|
case "value":
|
|
case "arguments":
|
|
case "input":
|
|
case "text":
|
|
case "content":
|
|
case "annotations":
|
|
case "metadata":
|
|
case "name":
|
|
case "role":
|
|
case "status":
|
|
case "tool_calls":
|
|
case "step_details": {
|
|
return property;
|
|
}
|
|
default: {
|
|
return "unknown";
|
|
}
|
|
}
|
|
}
|
|
function createAssistantStreamDeltaProjection(cacheArrays) {
|
|
return { arrays: /* @__PURE__ */ new Map(), cacheArrays, records: /* @__PURE__ */ new WeakMap() };
|
|
}
|
|
function commitAssistantStreamArrayProjection(projection) {
|
|
for (const [array, projected] of projection.arrays) {
|
|
if (projected.cacheable && !externallyMutableAssistantStreamValues.has(array)) {
|
|
assistantStreamArrayStates.set(array, {
|
|
length: projected.length,
|
|
ownEntryCount: projected.ownEntryCount
|
|
});
|
|
} else {
|
|
assistantStreamArrayStates.delete(array);
|
|
}
|
|
}
|
|
}
|
|
function isPrimitiveAssistantStreamValue(value) {
|
|
return typeof value === "string" || typeof value === "number";
|
|
}
|
|
function isPrimitiveAssistantStreamArrayDelta(accumulator, delta) {
|
|
return delta.every(isPrimitiveAssistantStreamValue) && accumulator.every(isPrimitiveAssistantStreamValue);
|
|
}
|
|
function countOwnAssistantStreamArrayEntries(accumulator) {
|
|
let count = 0;
|
|
for (const key of Object.keys(accumulator)) {
|
|
const index = Number(key);
|
|
if (Number.isSafeInteger(index) && index >= 0 && index < accumulator.length && String(index) === key) {
|
|
count += 1;
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
function getAssistantStreamArrayOwnEntryCount(accumulator, enforceSparseHoleBudget, cachedState) {
|
|
if (!enforceSparseHoleBudget) {
|
|
return 0;
|
|
}
|
|
if (cachedState?.length === accumulator.length) {
|
|
return cachedState.ownEntryCount;
|
|
}
|
|
return countOwnAssistantStreamArrayEntries(accumulator);
|
|
}
|
|
function getAssistantStreamDeltaIndex(deltaEntry, kind, baselineLength) {
|
|
const { index } = deltaEntry;
|
|
if (kind === "array" && (index === null || index === void 0)) {
|
|
throw new Error("Expected array delta entry to have an `index` property");
|
|
}
|
|
if (kind === "array" && typeof index !== "number") {
|
|
throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");
|
|
}
|
|
if (!Number.isSafeInteger(index) || index < 0 || index >= baselineLength + MAX_ASSISTANT_STREAM_ARRAY_GROWTH || index >= MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH) {
|
|
const safeIndex = typeof index === "number" ? index : "unknown";
|
|
throw new OpenAIError(`Assistant stream delta contains an invalid ${kind} index: ${safeIndex}`);
|
|
}
|
|
return index;
|
|
}
|
|
function assertValidAssistantStreamArrayDelta(accumulator, delta, kind, projection, validateRecord) {
|
|
let projectedArray = projection.arrays.get(accumulator);
|
|
if (!projectedArray) {
|
|
const enforceSparseHoleBudget = projection.cacheArrays && !externallyMutableAssistantStreamValues.has(accumulator);
|
|
const cachedState = enforceSparseHoleBudget ? assistantStreamArrayStates.get(accumulator) : void 0;
|
|
projectedArray = {
|
|
baselineLength: accumulator.length,
|
|
cacheable: enforceSparseHoleBudget,
|
|
enforceSparseHoleBudget,
|
|
entries: /* @__PURE__ */ new Map(),
|
|
length: accumulator.length,
|
|
ownEntryCount: getAssistantStreamArrayOwnEntryCount(accumulator, enforceSparseHoleBudget, cachedState)
|
|
};
|
|
projection.arrays.set(accumulator, projectedArray);
|
|
}
|
|
for (const deltaEntry of delta) {
|
|
if (!isObj(deltaEntry)) {
|
|
throw new Error("Expected array delta entry to be an object but got an invalid value");
|
|
}
|
|
const validatedIndex = getAssistantStreamDeltaIndex(deltaEntry, kind, projectedArray.baselineLength);
|
|
let accumulatedEntry;
|
|
if (projectedArray.entries.has(validatedIndex)) {
|
|
accumulatedEntry = projectedArray.entries.get(validatedIndex);
|
|
} else if (hasOwn(accumulator, validatedIndex)) {
|
|
accumulatedEntry = accumulator[validatedIndex];
|
|
if (accumulatedEntry === null || accumulatedEntry === void 0) {
|
|
projectedArray.entries.set(validatedIndex, deltaEntry);
|
|
}
|
|
} else {
|
|
projectedArray.entries.set(validatedIndex, deltaEntry);
|
|
projectedArray.ownEntryCount += 1;
|
|
}
|
|
const projectedLength = Math.max(projectedArray.length, validatedIndex + 1);
|
|
if (projectedArray.enforceSparseHoleBudget && projectedLength - projectedArray.ownEntryCount > MAX_ASSISTANT_STREAM_ARRAY_GROWTH) {
|
|
throw new OpenAIError(`Assistant stream delta contains an invalid ${kind} index: ${validatedIndex}`);
|
|
}
|
|
if (isObj(accumulatedEntry)) {
|
|
validateRecord(accumulatedEntry, deltaEntry, projection);
|
|
}
|
|
projectedArray.length = projectedLength;
|
|
}
|
|
}
|
|
function assertValidAssistantStreamDeltaIndices(accumulator, delta, projection) {
|
|
let projectedValues = projection.records.get(accumulator);
|
|
for (const [key, deltaValue] of Object.entries(delta)) {
|
|
if (key === "index" || key === "type") {
|
|
continue;
|
|
}
|
|
let accumulatedValue;
|
|
if (projectedValues?.has(key)) {
|
|
accumulatedValue = projectedValues.get(key);
|
|
} else if (hasOwn(accumulator, key)) {
|
|
accumulatedValue = accumulator[key];
|
|
}
|
|
if (accumulatedValue === null || accumulatedValue === void 0) {
|
|
if (!projectedValues) {
|
|
projectedValues = /* @__PURE__ */ new Map();
|
|
projection.records.set(accumulator, projectedValues);
|
|
}
|
|
projectedValues.set(key, deltaValue);
|
|
continue;
|
|
}
|
|
if (isObj(accumulatedValue) && isObj(deltaValue)) {
|
|
assertValidAssistantStreamDeltaIndices(accumulatedValue, deltaValue, projection);
|
|
} else if (Array.isArray(accumulatedValue) && Array.isArray(deltaValue) && !isPrimitiveAssistantStreamArrayDelta(accumulatedValue, deltaValue)) {
|
|
assertValidAssistantStreamArrayDelta(accumulatedValue, deltaValue, "array", projection, assertValidAssistantStreamDeltaIndices);
|
|
}
|
|
}
|
|
}
|
|
function isAssistantStreamValueExternallyMutable(value) {
|
|
return (isObj(value) || Array.isArray(value)) && externallyMutableAssistantStreamValues.has(value);
|
|
}
|
|
function markAssistantStreamValueExternallyMutable(value) {
|
|
if (!isObj(value) && !Array.isArray(value) || externallyMutableAssistantStreamValues.has(value)) {
|
|
return;
|
|
}
|
|
externallyMutableAssistantStreamValues.add(value);
|
|
if (Array.isArray(value)) {
|
|
assistantStreamArrayStates.delete(value);
|
|
}
|
|
for (const key of Reflect.ownKeys(value)) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
if (descriptor && "value" in descriptor) {
|
|
markAssistantStreamValueExternallyMutable(descriptor.value);
|
|
}
|
|
}
|
|
}
|
|
function defineAssistantStreamArrayEntry(accumulator, index, value) {
|
|
if (externallyMutableAssistantStreamValues.has(accumulator)) {
|
|
markAssistantStreamValueExternallyMutable(value);
|
|
}
|
|
Object.defineProperty(accumulator, index, {
|
|
configurable: true,
|
|
enumerable: true,
|
|
value,
|
|
writable: true
|
|
});
|
|
}
|
|
function getRequiredAssistantStreamArrayIndex(deltaEntry) {
|
|
const { index } = deltaEntry;
|
|
if (index === null || index === void 0) {
|
|
throw new Error("Expected array delta entry to have an `index` property");
|
|
}
|
|
if (typeof index !== "number") {
|
|
throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");
|
|
}
|
|
return index;
|
|
}
|
|
function applyAssistantStreamArrayDelta(accumulator, delta, applyRecord) {
|
|
if (isPrimitiveAssistantStreamArrayDelta(accumulator, delta)) {
|
|
accumulator.push(...delta);
|
|
assistantStreamArrayStates.delete(accumulator);
|
|
return;
|
|
}
|
|
for (const deltaEntry of delta) {
|
|
if (!isObj(deltaEntry)) {
|
|
throw new Error("Expected array delta entry to be an object but got an invalid value");
|
|
}
|
|
const index = getRequiredAssistantStreamArrayIndex(deltaEntry);
|
|
if (hasOwn(accumulator, index)) {
|
|
const accumulatedEntry = accumulator[index];
|
|
if (accumulatedEntry === null || accumulatedEntry === void 0) {
|
|
if (externallyMutableAssistantStreamValues.has(accumulator)) {
|
|
markAssistantStreamValueExternallyMutable(deltaEntry);
|
|
}
|
|
accumulator[index] = deltaEntry;
|
|
} else {
|
|
accumulator[index] = applyRecord(accumulatedEntry, deltaEntry);
|
|
}
|
|
} else {
|
|
defineAssistantStreamArrayEntry(accumulator, index, deltaEntry);
|
|
}
|
|
}
|
|
}
|
|
function applyAssistantStreamDelta(accumulator, delta) {
|
|
const externallyMutable = externallyMutableAssistantStreamValues.has(accumulator);
|
|
for (const [key, deltaValue] of Object.entries(delta)) {
|
|
if (key === "__proto__" || key === "constructor" || key === "prototype") {
|
|
throw new OpenAIError(`Assistant stream delta contains an unsafe property: ${key}`);
|
|
}
|
|
if (!hasOwn(accumulator, key)) {
|
|
if (externallyMutable) {
|
|
markAssistantStreamValueExternallyMutable(deltaValue);
|
|
}
|
|
accumulator[key] = deltaValue;
|
|
continue;
|
|
}
|
|
let accumulatedValue = accumulator[key];
|
|
if (accumulatedValue === null || accumulatedValue === void 0) {
|
|
if (externallyMutable) {
|
|
markAssistantStreamValueExternallyMutable(deltaValue);
|
|
}
|
|
accumulator[key] = deltaValue;
|
|
continue;
|
|
}
|
|
if (key === "index" || key === "type") {
|
|
accumulator[key] = deltaValue;
|
|
continue;
|
|
}
|
|
if (typeof accumulatedValue === "string" && typeof deltaValue === "string") {
|
|
accumulatedValue += deltaValue;
|
|
} else if (typeof accumulatedValue === "number" && typeof deltaValue === "number") {
|
|
accumulatedValue += deltaValue;
|
|
} else if (isObj(accumulatedValue) && isObj(deltaValue)) {
|
|
accumulatedValue = applyAssistantStreamDelta(accumulatedValue, deltaValue);
|
|
} else if (Array.isArray(accumulatedValue) && Array.isArray(deltaValue)) {
|
|
applyAssistantStreamArrayDelta(accumulatedValue, deltaValue, applyAssistantStreamDelta);
|
|
continue;
|
|
} else {
|
|
throw new TypeError(`Unhandled record type: ${getAssistantStreamDiagnosticProperty(key)}`);
|
|
}
|
|
accumulator[key] = accumulatedValue;
|
|
}
|
|
return accumulator;
|
|
}
|
|
function assertSafeAssistantStreamDelta(value) {
|
|
if (!isObj(value) && !Array.isArray(value)) {
|
|
return;
|
|
}
|
|
for (const [key, nestedValue] of Object.entries(value)) {
|
|
if (key === "__proto__" || key === "constructor" || key === "prototype") {
|
|
throw new OpenAIError(`Assistant stream delta contains an unsafe property: ${key}`);
|
|
}
|
|
assertSafeAssistantStreamDelta(nestedValue);
|
|
}
|
|
}
|
|
function accumulateAssistantStreamDelta(accumulator, delta, cacheArrays = false) {
|
|
assertSafeAssistantStreamDelta(delta);
|
|
const accumulatorRecord = accumulator;
|
|
const deltaRecord = delta;
|
|
const projection = createAssistantStreamDeltaProjection(cacheArrays && !isAssistantStreamValueExternallyMutable(accumulator));
|
|
assertValidAssistantStreamDeltaIndices(accumulatorRecord, deltaRecord, projection);
|
|
applyAssistantStreamDelta(accumulatorRecord, deltaRecord);
|
|
commitAssistantStreamArrayProjection(projection);
|
|
return accumulator;
|
|
}
|
|
function createAssistantStreamArrayDeltaCommit(accumulator, delta, kind, cacheArrays = true) {
|
|
assertSafeAssistantStreamDelta(delta);
|
|
const projection = createAssistantStreamDeltaProjection(cacheArrays && !isAssistantStreamValueExternallyMutable(accumulator));
|
|
assertValidAssistantStreamArrayDelta(accumulator, delta, kind, projection, assertValidAssistantStreamDeltaIndices);
|
|
return () => commitAssistantStreamArrayProjection(projection);
|
|
}
|
|
var MAX_ASSISTANT_STREAM_ARRAY_GROWTH, MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH, assistantStreamArrayStates, externallyMutableAssistantStreamValues;
|
|
var init_assistant_stream_delta = __esm({
|
|
"node_modules/openai/internal/assistant-stream-delta.mjs"() {
|
|
init_error2();
|
|
init_utils2();
|
|
MAX_ASSISTANT_STREAM_ARRAY_GROWTH = 1024;
|
|
MAX_EXTERNALLY_MUTABLE_ASSISTANT_STREAM_ARRAY_LENGTH = 65536;
|
|
assistantStreamArrayStates = /* @__PURE__ */ new WeakMap();
|
|
externallyMutableAssistantStreamValues = /* @__PURE__ */ new WeakSet();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/AssistantStream.mjs
|
|
function stabilizeAssistantStreamEvent(event) {
|
|
const eventDescriptor = Object.getOwnPropertyDescriptor(event, "event");
|
|
const dataDescriptor = Object.getOwnPropertyDescriptor(event, "data");
|
|
const eventType = Reflect.get(event, "event", event);
|
|
const data = Reflect.get(event, "data", event);
|
|
let stableData = data;
|
|
if (eventType === "thread.message.created" || eventType === "thread.message.in_progress" || eventType === "thread.message.delta" || eventType === "thread.message.completed" || eventType === "thread.message.incomplete" || eventType === "thread.run.step.created" || eventType === "thread.run.step.in_progress" || eventType === "thread.run.step.delta" || eventType === "thread.run.step.completed" || eventType === "thread.run.step.failed" || eventType === "thread.run.step.cancelled" || eventType === "thread.run.step.expired") {
|
|
const messageID = Object.getOwnPropertyDescriptor(data, "id");
|
|
if (messageID && "value" in messageID && // SAFETY: The own id descriptor was found above; keep its live read unknown while comparing it with the captured descriptor value.
|
|
data.id !== messageID.value) {
|
|
const canonicalID = messageID.value;
|
|
stableData = new Proxy(data, {
|
|
get(target, property) {
|
|
return property === "id" ? canonicalID : Reflect.get(target, property, target);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
const stableEvent = Object.freeze({ event: eventType, data: stableData });
|
|
const ordinaryEvent = eventDescriptor !== void 0 && "value" in eventDescriptor && eventDescriptor.value === eventType && dataDescriptor !== void 0 && "value" in dataDescriptor && dataDescriptor.value === data && stableData === data;
|
|
return {
|
|
event: stableEvent,
|
|
exposedEvent: ordinaryEvent ? event : { event: eventType, data: stableData }
|
|
};
|
|
}
|
|
function assertNever2(_x) {
|
|
return _x;
|
|
}
|
|
var _AssistantStream_instances, _AssistantStream_runStepSnapshots, _AssistantStream_runStepIDOwners, _AssistantStream_activeRunStepID, _AssistantStream_messageSnapshots, _AssistantStream_messageIDOwners, _AssistantStream_messageSnapshot, _AssistantStream_activeMessageID, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_validateRunStepEvent, _AssistantStream_reserveRunStepAlias, _AssistantStream_validateMessageEvent, _AssistantStream_reserveMessageAlias, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_emitExposed, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun, AssistantStream;
|
|
var init_AssistantStream = __esm({
|
|
"node_modules/openai/lib/AssistantStream.mjs"() {
|
|
init_tslib();
|
|
init_streaming2();
|
|
init_error2();
|
|
init_EventStream();
|
|
init_utils2();
|
|
init_assistant_stream_delta();
|
|
AssistantStream = class _AssistantStream extends EventStream2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
_AssistantStream_instances.add(this);
|
|
_AssistantStream_runStepSnapshots.set(this, /* @__PURE__ */ Object.create(null));
|
|
_AssistantStream_runStepIDOwners.set(this, /* @__PURE__ */ new Map());
|
|
_AssistantStream_activeRunStepID.set(this, void 0);
|
|
_AssistantStream_messageSnapshots.set(this, /* @__PURE__ */ Object.create(null));
|
|
_AssistantStream_messageIDOwners.set(this, /* @__PURE__ */ new Map());
|
|
_AssistantStream_messageSnapshot.set(this, void 0);
|
|
_AssistantStream_activeMessageID.set(this, void 0);
|
|
_AssistantStream_finalRun.set(this, void 0);
|
|
_AssistantStream_currentContentIndex.set(this, void 0);
|
|
_AssistantStream_currentContent.set(this, void 0);
|
|
_AssistantStream_currentToolCallIndex.set(this, void 0);
|
|
_AssistantStream_currentToolCall.set(this, void 0);
|
|
_AssistantStream_currentEvent.set(this, void 0);
|
|
_AssistantStream_currentRunSnapshot.set(this, void 0);
|
|
_AssistantStream_currentRunStepSnapshot.set(this, void 0);
|
|
}
|
|
/** Iterates over cloned raw assistant events; stopping early aborts the underlying request. */
|
|
[(_AssistantStream_runStepSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_runStepIDOwners = /* @__PURE__ */ new WeakMap(), _AssistantStream_activeRunStepID = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshots = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageIDOwners = /* @__PURE__ */ new WeakMap(), _AssistantStream_messageSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_activeMessageID = /* @__PURE__ */ new WeakMap(), _AssistantStream_finalRun = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContentIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentContent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCallIndex = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentToolCall = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentEvent = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_currentRunStepSnapshot = /* @__PURE__ */ new WeakMap(), _AssistantStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
return this._createIterator((push) => {
|
|
const onEvent = (event) => push(structuredClone(event));
|
|
this.on("event", onEvent);
|
|
return () => this.off("event", onEvent);
|
|
}, { onReturn: () => this.abort() });
|
|
}
|
|
/** Restores an assistant stream from events serialized by `toReadableStream()`. */
|
|
static fromReadableStream(stream4) {
|
|
const runner = new _AssistantStream();
|
|
runner._run(() => runner._fromReadableStream(stream4));
|
|
return runner;
|
|
}
|
|
async _fromReadableStream(readableStream, options) {
|
|
this._listenForAbort(options?.signal);
|
|
this._connected();
|
|
const stream4 = Stream.fromReadableStream(readableStream, this.controller);
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
|
|
}
|
|
/** Serializes assistant events into a readable stream for transfer to another runtime. */
|
|
toReadableStream() {
|
|
const stream4 = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);
|
|
return stream4.toReadableStream();
|
|
}
|
|
/** Submits tool outputs and starts streaming the continuation of an existing assistant run. */
|
|
static createToolAssistantStream(runId, runs, params, options) {
|
|
const runner = new _AssistantStream();
|
|
runner._run(() => runner._runToolAssistantStream(runId, runs, params, {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "stream" }
|
|
}));
|
|
return runner;
|
|
}
|
|
async _createToolAssistantStream(run, runId, params, options) {
|
|
this._listenForAbort(options?.signal);
|
|
const body = { ...params, stream: true };
|
|
const stream4 = await run.submitToolOutputs(runId, body, {
|
|
...options,
|
|
signal: this.controller.signal
|
|
});
|
|
this._connected();
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
|
|
}
|
|
/** Creates an assistant thread and starts streaming its newly created run. */
|
|
static createThreadAssistantStream(params, thread, options) {
|
|
const runner = new _AssistantStream();
|
|
runner._run(() => runner._threadAssistantStream(params, thread, {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "stream" }
|
|
}));
|
|
return runner;
|
|
}
|
|
/** Creates a run on an existing assistant thread and starts streaming its events. */
|
|
static createAssistantStream(threadId, runs, params, options) {
|
|
const runner = new _AssistantStream();
|
|
runner._run(() => runner._runAssistantStream(threadId, runs, params, {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "stream" }
|
|
}));
|
|
return runner;
|
|
}
|
|
/** Returns the most recent raw event, or `undefined` before any event arrives. */
|
|
currentEvent() {
|
|
markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"));
|
|
return __classPrivateFieldGet(this, _AssistantStream_currentEvent, "f");
|
|
}
|
|
/** Returns the latest run snapshot, or `undefined` before a run event arrives. */
|
|
currentRun() {
|
|
markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"));
|
|
return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f");
|
|
}
|
|
/** Returns the message currently being accumulated, or `undefined` before message creation. */
|
|
currentMessageSnapshot() {
|
|
markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
|
|
return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f");
|
|
}
|
|
/** Returns the run step currently being accumulated, or `undefined` before a step begins. */
|
|
currentRunStepSnapshot() {
|
|
markAssistantStreamValueExternallyMutable(__classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"));
|
|
return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f");
|
|
}
|
|
/** Waits for successful completion and returns the final snapshot of every observed run step. */
|
|
async finalRunSteps() {
|
|
await this.done();
|
|
return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"));
|
|
}
|
|
/**
|
|
* Waits for successful completion and returns the final snapshot of every observed message.
|
|
* Terminal message events replace accumulated snapshots without mutating earlier snapshots.
|
|
*/
|
|
async finalMessages() {
|
|
await this.done();
|
|
return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"));
|
|
}
|
|
/** Waits for completion and returns the final run, or rejects if no terminal run was received. */
|
|
async finalRun() {
|
|
await this.done();
|
|
if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) {
|
|
throw new Error("Final run was not received.");
|
|
}
|
|
return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
|
|
}
|
|
async _createThreadAssistantStream(thread, params, options) {
|
|
this._listenForAbort(options?.signal);
|
|
const body = { ...params, stream: true };
|
|
const stream4 = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
|
|
this._connected();
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
|
|
}
|
|
async _createAssistantStream(run, threadId, params, options) {
|
|
this._listenForAbort(options?.signal);
|
|
const body = { ...params, stream: true };
|
|
const stream4 = await run.create(threadId, body, { ...options, signal: this.controller.signal });
|
|
this._connected();
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
|
|
}
|
|
/**
|
|
* Applies an assistant delta to its mutable snapshot, concatenating text and
|
|
* merging nested objects and indexed array entries.
|
|
*/
|
|
static accumulateDelta(acc, delta) {
|
|
return accumulateAssistantStreamDelta(acc, delta);
|
|
}
|
|
_addRun(run) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "run", run);
|
|
return run;
|
|
}
|
|
async _threadAssistantStream(params, thread, options) {
|
|
return await this._createThreadAssistantStream(thread, params, options);
|
|
}
|
|
async _runAssistantStream(threadId, runs, params, options) {
|
|
return await this._createAssistantStream(runs, threadId, params, options);
|
|
}
|
|
async _runToolAssistantStream(runId, runs, params, options) {
|
|
return await this._createToolAssistantStream(runs, runId, params, options);
|
|
}
|
|
};
|
|
_AssistantStream_addEvent = function _AssistantStream_addEvent2(event) {
|
|
if (this.ended) {
|
|
return;
|
|
}
|
|
const { event: stableEvent, exposedEvent } = stabilizeAssistantStreamEvent(event);
|
|
let messageID;
|
|
let messageData;
|
|
let runStepID;
|
|
let runStepData;
|
|
switch (stableEvent.event) {
|
|
case "thread.message.created":
|
|
case "thread.message.in_progress":
|
|
case "thread.message.delta":
|
|
case "thread.message.completed":
|
|
case "thread.message.incomplete": {
|
|
messageID = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_validateMessageEvent).call(this, stableEvent);
|
|
messageData = stableEvent.data;
|
|
break;
|
|
}
|
|
case "thread.run.step.created":
|
|
case "thread.run.step.in_progress":
|
|
case "thread.run.step.delta":
|
|
case "thread.run.step.completed":
|
|
case "thread.run.step.failed":
|
|
case "thread.run.step.cancelled":
|
|
case "thread.run.step.expired": {
|
|
runStepID = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_validateRunStepEvent).call(this, stableEvent);
|
|
runStepData = stableEvent.data;
|
|
break;
|
|
}
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_currentEvent, exposedEvent, "f");
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, exposedEvent);
|
|
if (messageID !== void 0 && messageData !== void 0) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, messageData, messageID);
|
|
}
|
|
if (runStepID !== void 0 && runStepData !== void 0) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, runStepData, runStepID);
|
|
}
|
|
if (runStepID === void 0 && __classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f") !== void 0 && __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"), __classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f"));
|
|
}
|
|
switch (stableEvent.event) {
|
|
case "thread.created": {
|
|
break;
|
|
}
|
|
case "thread.run.created":
|
|
case "thread.run.queued":
|
|
case "thread.run.in_progress":
|
|
case "thread.run.requires_action":
|
|
case "thread.run.completed":
|
|
case "thread.run.incomplete":
|
|
case "thread.run.failed":
|
|
case "thread.run.cancelling":
|
|
case "thread.run.cancelled":
|
|
case "thread.run.expired": {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, stableEvent);
|
|
break;
|
|
}
|
|
case "thread.run.step.created":
|
|
case "thread.run.step.in_progress":
|
|
case "thread.run.step.delta":
|
|
case "thread.run.step.completed":
|
|
case "thread.run.step.failed":
|
|
case "thread.run.step.cancelled":
|
|
case "thread.run.step.expired": {
|
|
if (runStepID === void 0) {
|
|
throw new OpenAIError("Received assistant run-step event without a canonical run-step ID");
|
|
}
|
|
const activeRunStep = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
|
|
if (activeRunStep) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, activeRunStep, runStepID);
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, stableEvent, runStepID);
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, stableEvent.data, runStepID);
|
|
const retainedRunStep = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
|
|
if (retainedRunStep) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveRunStepAlias).call(this, retainedRunStep, runStepID);
|
|
}
|
|
break;
|
|
}
|
|
case "thread.message.created":
|
|
case "thread.message.in_progress":
|
|
case "thread.message.delta":
|
|
case "thread.message.completed":
|
|
case "thread.message.incomplete": {
|
|
if (messageID !== void 0 && __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"), messageID);
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, stableEvent);
|
|
if (messageID !== void 0) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, stableEvent.data, messageID);
|
|
const retainedMessage = __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[messageID];
|
|
if (retainedMessage) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_reserveMessageAlias).call(this, retainedMessage, messageID);
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "error": {
|
|
throw new APIError(void 0, stableEvent.data, void 0, void 0);
|
|
}
|
|
default: {
|
|
assertNever2(stableEvent);
|
|
}
|
|
}
|
|
}, _AssistantStream_endRequest = function _AssistantStream_endRequest2() {
|
|
if (this.ended) {
|
|
throw new OpenAIError(`stream has ended, this shouldn't happen`);
|
|
}
|
|
if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) {
|
|
throw new Error("Final run has not been received");
|
|
}
|
|
return __classPrivateFieldGet(this, _AssistantStream_finalRun, "f");
|
|
}, _AssistantStream_validateRunStepEvent = function _AssistantStream_validateRunStepEvent2(event) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(event.data, "id");
|
|
const runStepID = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
if (typeof runStepID !== "string" || runStepID.length === 0) {
|
|
throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");
|
|
}
|
|
if (event.event === "thread.run.step.delta") {
|
|
const delta = event.data.delta;
|
|
if (delta && hasOwn(delta, "id")) {
|
|
throw new OpenAIError("Run-step deltas must not contain an id field");
|
|
}
|
|
}
|
|
if (event.event === "thread.run.step.created") {
|
|
if (__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f") !== void 0) {
|
|
throw new OpenAIError(`Received run-step creation for "${runStepID}" before the active run step "${__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f")}" reached a terminal state`);
|
|
}
|
|
if (hasOwn(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"), runStepID) || __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").has(runStepID)) {
|
|
throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_activeRunStepID, runStepID, "f");
|
|
__classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, runStepID);
|
|
return runStepID;
|
|
}
|
|
if (__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f") !== void 0) {
|
|
if (runStepID !== __classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f")) {
|
|
throw new OpenAIError(`Received ${event.event} for run step "${runStepID}", which does not match the active run step "${__classPrivateFieldGet(this, _AssistantStream_activeRunStepID, "f")}"`);
|
|
}
|
|
return runStepID;
|
|
}
|
|
if (event.event === "thread.run.step.delta") {
|
|
if (!hasOwn(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"), runStepID)) {
|
|
throw new OpenAIError("Received a RunStepDelta before creation of a snapshot");
|
|
}
|
|
throw new OpenAIError(`Received run-step delta for "${runStepID}" with no active run step`);
|
|
}
|
|
if (hasOwn(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f"), runStepID) || __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").has(runStepID)) {
|
|
throw new OpenAIError(`Received run-step event for run step "${runStepID}", which has already been created`);
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, runStepID);
|
|
if (event.event === "thread.run.step.in_progress") {
|
|
__classPrivateFieldSet(this, _AssistantStream_activeRunStepID, runStepID, "f");
|
|
}
|
|
return runStepID;
|
|
}, _AssistantStream_reserveRunStepAlias = function _AssistantStream_reserveRunStepAlias2(data, canonicalID) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(data, "id");
|
|
const runStepID = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
if (typeof runStepID !== "string" || runStepID.length === 0) {
|
|
throw new OpenAIError("Received assistant run-step event with an invalid run-step ID");
|
|
}
|
|
const owner = __classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").get(runStepID);
|
|
if (owner !== void 0 && owner !== canonicalID) {
|
|
throw new OpenAIError(`Received run-step creation for run step "${runStepID}", which has already been created`);
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_runStepIDOwners, "f").set(runStepID, canonicalID);
|
|
}, _AssistantStream_validateMessageEvent = function _AssistantStream_validateMessageEvent2(event) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(event.data, "id");
|
|
const messageID = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
if (typeof messageID !== "string" || messageID.length === 0) {
|
|
throw new OpenAIError("Received assistant message event with an invalid message ID");
|
|
}
|
|
if (event.event === "thread.message.created") {
|
|
if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
|
|
throw new OpenAIError(`Received message creation for "${messageID}" before the active message "${__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")}" reached a terminal state`);
|
|
}
|
|
if (hasOwn(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f"), messageID) || __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").has(messageID)) {
|
|
throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_activeMessageID, messageID, "f");
|
|
__classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").set(messageID, messageID);
|
|
return messageID;
|
|
}
|
|
if (!__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
|
|
if (event.event === "thread.message.delta") {
|
|
throw new OpenAIError("Received a delta with no existing snapshot (there should be one from message creation)");
|
|
}
|
|
throw new OpenAIError("Received thread message event with no existing snapshot");
|
|
}
|
|
if (messageID !== __classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")) {
|
|
throw new OpenAIError(`Received ${event.event} for message "${messageID}", which does not match the active message "${__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")}"`);
|
|
}
|
|
return messageID;
|
|
}, _AssistantStream_reserveMessageAlias = function _AssistantStream_reserveMessageAlias2(data, canonicalID) {
|
|
const descriptor = Object.getOwnPropertyDescriptor(data, "id");
|
|
const messageID = descriptor && "value" in descriptor ? descriptor.value : void 0;
|
|
if (typeof messageID !== "string" || messageID.length === 0) {
|
|
throw new OpenAIError("Received assistant message event with an invalid message ID");
|
|
}
|
|
const owner = __classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").get(messageID);
|
|
if (owner !== void 0 && owner !== canonicalID) {
|
|
throw new OpenAIError(`Received message creation for message "${messageID}", which has already been created`);
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_messageIDOwners, "f").set(messageID, canonicalID);
|
|
}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage2(event) {
|
|
const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
|
|
__classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f");
|
|
if (!__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")) {
|
|
throw new OpenAIError("Received thread message event with no active message ID");
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[__classPrivateFieldGet(this, _AssistantStream_activeMessageID, "f")] = accumulatedMessage;
|
|
for (const content of newContent) {
|
|
const snapshotContent = accumulatedMessage.content[content.index];
|
|
if (snapshotContent?.type === "text") {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textCreated", snapshotContent.text);
|
|
}
|
|
}
|
|
switch (event.event) {
|
|
case "thread.message.created": {
|
|
__classPrivateFieldSet(this, _AssistantStream_currentContentIndex, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_currentContent, void 0, "f");
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "messageCreated", event.data);
|
|
break;
|
|
}
|
|
case "thread.message.in_progress": {
|
|
break;
|
|
}
|
|
case "thread.message.delta": {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "messageDelta", event.data.delta, accumulatedMessage);
|
|
if (event.data.delta.content) {
|
|
for (const content of event.data.delta.content) {
|
|
if (content.type === "text" && content.text) {
|
|
const textDelta = content.text;
|
|
const snapshot = accumulatedMessage.content[content.index];
|
|
if (snapshot && snapshot.type === "text") {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textDelta", textDelta, snapshot.text);
|
|
} else {
|
|
throw new Error("The snapshot associated with this text delta is not text or missing");
|
|
}
|
|
}
|
|
if (content.index !== __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) {
|
|
if (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) {
|
|
switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) {
|
|
case "text": {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
|
|
break;
|
|
}
|
|
case "image_file": {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "imageFileDone", __classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f");
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f");
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case "thread.message.completed":
|
|
case "thread.message.incomplete": {
|
|
if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== void 0) {
|
|
const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")];
|
|
if (currentContent) {
|
|
switch (currentContent.type) {
|
|
case "image_file": {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "imageFileDone", currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
|
|
break;
|
|
}
|
|
case "text": {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "textDone", currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"));
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "messageDone", event.data);
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_currentContentIndex, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_currentContent, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_messageSnapshot, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_activeMessageID, void 0, "f");
|
|
}
|
|
}
|
|
}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep2(event, runStepID) {
|
|
const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event, runStepID);
|
|
__classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f");
|
|
switch (event.event) {
|
|
case "thread.run.step.created": {
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "runStepCreated", event.data);
|
|
break;
|
|
}
|
|
case "thread.run.step.delta": {
|
|
const delta = event.data.delta;
|
|
if (delta.step_details && delta.step_details.type === "tool_calls" && delta.step_details.tool_calls && accumulatedRunStep.step_details.type === "tool_calls") {
|
|
for (const toolCall of delta.step_details.tool_calls) {
|
|
if (toolCall.index === __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDelta", toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);
|
|
} else {
|
|
if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f");
|
|
if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallCreated", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "runStepDelta", event.data.delta, accumulatedRunStep);
|
|
break;
|
|
}
|
|
case "thread.run.step.completed":
|
|
case "thread.run.step.failed":
|
|
case "thread.run.step.cancelled":
|
|
case "thread.run.step.expired": {
|
|
__classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_activeRunStepID, void 0, "f");
|
|
const details = event.data.step_details;
|
|
if (details.type === "tool_calls" && __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
|
|
}
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "runStepDone", event.data, accumulatedRunStep);
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
|
|
break;
|
|
}
|
|
case "thread.run.step.in_progress": {
|
|
break;
|
|
}
|
|
}
|
|
}, _AssistantStream_emitExposed = function _AssistantStream_emitExposed2(event, ...args) {
|
|
if (this._hasListeners(event)) {
|
|
for (const value of args) {
|
|
markAssistantStreamValueExternallyMutable(value);
|
|
}
|
|
}
|
|
this._emit(event, ...args);
|
|
}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent2(event) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "event", event);
|
|
}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep2(event, runStepID) {
|
|
switch (event.event) {
|
|
case "thread.run.step.created": {
|
|
__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID] = event.data;
|
|
return event.data;
|
|
}
|
|
case "thread.run.step.delta": {
|
|
const snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
|
|
if (!snapshot) {
|
|
throw new Error("Received a RunStepDelta before creation of a snapshot");
|
|
}
|
|
const delta = event.data.delta;
|
|
if (delta) {
|
|
if (hasOwn(delta, "id")) {
|
|
throw new OpenAIError("Run-step deltas must not contain an id field");
|
|
}
|
|
const accumulated = accumulateAssistantStreamDelta(snapshot, delta, true);
|
|
__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID] = accumulated;
|
|
}
|
|
return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
|
|
}
|
|
case "thread.run.step.completed":
|
|
case "thread.run.step.failed":
|
|
case "thread.run.step.cancelled":
|
|
case "thread.run.step.expired":
|
|
case "thread.run.step.in_progress": {
|
|
__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID] = event.data;
|
|
break;
|
|
}
|
|
}
|
|
if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID]) {
|
|
return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[runStepID];
|
|
}
|
|
throw new Error("No snapshot available");
|
|
}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage2(event, snapshot) {
|
|
const newContent = [];
|
|
switch (event.event) {
|
|
case "thread.message.created": {
|
|
return [event.data, newContent];
|
|
}
|
|
case "thread.message.delta": {
|
|
if (!snapshot) {
|
|
throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");
|
|
}
|
|
const data = event.data;
|
|
if (data.delta.content) {
|
|
assertSafeAssistantStreamDelta(data.delta);
|
|
const cacheArrays = !isAssistantStreamValueExternallyMutable(snapshot);
|
|
const commitProjection = createAssistantStreamArrayDeltaCommit(snapshot.content, data.delta.content, "content", cacheArrays);
|
|
for (const contentElement of data.delta.content) {
|
|
if (hasOwn(snapshot.content, contentElement.index)) {
|
|
const currentContent = snapshot.content[contentElement.index];
|
|
snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent, cacheArrays);
|
|
} else {
|
|
defineAssistantStreamArrayEntry(snapshot.content, contentElement.index, contentElement);
|
|
newContent.push(contentElement);
|
|
}
|
|
}
|
|
commitProjection();
|
|
}
|
|
return [snapshot, newContent];
|
|
}
|
|
case "thread.message.in_progress":
|
|
case "thread.message.completed":
|
|
case "thread.message.incomplete": {
|
|
if (snapshot) {
|
|
return [event.event === "thread.message.in_progress" ? snapshot : event.data, newContent];
|
|
}
|
|
throw new Error("Received thread message event with no existing snapshot");
|
|
}
|
|
}
|
|
throw new Error("Tried to accumulate a non-message event");
|
|
}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent2(contentElement, currentContent, cacheArrays) {
|
|
return accumulateAssistantStreamDelta(currentContent, contentElement, cacheArrays);
|
|
}, _AssistantStream_handleRun = function _AssistantStream_handleRun2(event) {
|
|
__classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f");
|
|
switch (event.event) {
|
|
case "thread.run.created": {
|
|
break;
|
|
}
|
|
case "thread.run.queued": {
|
|
break;
|
|
}
|
|
case "thread.run.in_progress": {
|
|
break;
|
|
}
|
|
case "thread.run.requires_action":
|
|
case "thread.run.cancelled":
|
|
case "thread.run.failed":
|
|
case "thread.run.completed":
|
|
case "thread.run.expired":
|
|
case "thread.run.incomplete": {
|
|
__classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f");
|
|
if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) {
|
|
__classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_emitExposed).call(this, "toolCallDone", __classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f"));
|
|
}
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, void 0, "f");
|
|
__classPrivateFieldSet(this, _AssistantStream_currentToolCall, void 0, "f");
|
|
break;
|
|
}
|
|
case "thread.run.cancelling": {
|
|
break;
|
|
}
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/polling.mjs
|
|
function sleepUntilAborted(milliseconds, signal) {
|
|
return new Promise((resolve, reject) => {
|
|
let timer;
|
|
let registered;
|
|
let settled = false;
|
|
const removeAbortListener = (listener) => {
|
|
try {
|
|
signal.removeEventListener("abort", listener);
|
|
} catch {
|
|
}
|
|
};
|
|
const cleanup = () => {
|
|
if (timer !== void 0) {
|
|
clearTimeout(timer);
|
|
timer = void 0;
|
|
}
|
|
if (registered) {
|
|
const listener = registered;
|
|
registered = void 0;
|
|
removeAbortListener(listener);
|
|
}
|
|
};
|
|
const abort = () => {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
cleanup();
|
|
try {
|
|
const error = new APIUserAbortError();
|
|
Object.defineProperty(error, "cause", {
|
|
value: signal.reason,
|
|
writable: true,
|
|
configurable: true
|
|
});
|
|
reject(error);
|
|
} catch (error) {
|
|
reject(error);
|
|
}
|
|
};
|
|
if (signal.aborted) {
|
|
abort();
|
|
return;
|
|
}
|
|
timer = setTimeout(() => {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
cleanup();
|
|
resolve();
|
|
}, milliseconds);
|
|
registered = abort;
|
|
try {
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
if (settled) {
|
|
removeAbortListener(abort);
|
|
} else if (signal.aborted) {
|
|
abort();
|
|
}
|
|
} catch (error) {
|
|
if (settled) {
|
|
removeAbortListener(abort);
|
|
} else {
|
|
settled = true;
|
|
cleanup();
|
|
reject(error);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
async function pollWithResponse(retrieve, intermediateStatuses, terminalStatuses, options) {
|
|
const headers = buildHeaders([
|
|
options?.headers,
|
|
{
|
|
"X-Stainless-Poll-Helper": "true",
|
|
"X-Stainless-Custom-Poll-Interval": options?.pollIntervalMs?.toString() ?? void 0
|
|
}
|
|
]);
|
|
while (true) {
|
|
const { data, response } = await retrieve(headers).withResponse();
|
|
const { status } = data;
|
|
if (intermediateStatuses.includes(status)) {
|
|
let sleepInterval = 5e3;
|
|
const pollIntervalMs = options?.pollIntervalMs;
|
|
if (pollIntervalMs || pollIntervalMs === 0) {
|
|
sleepInterval = pollIntervalMs;
|
|
} else {
|
|
const headerInterval = response.headers.get("openai-poll-after-ms");
|
|
if (headerInterval) {
|
|
const headerIntervalMs = Number.parseInt(headerInterval);
|
|
if (!Number.isNaN(headerIntervalMs)) {
|
|
sleepInterval = headerIntervalMs;
|
|
}
|
|
}
|
|
}
|
|
const signal = options && Object.prototype.propertyIsEnumerable.call(options, "signal") ? options.signal : void 0;
|
|
await (signal ? sleepUntilAborted(sleepInterval, signal) : sleep(sleepInterval));
|
|
} else if (terminalStatuses.includes(status)) {
|
|
return data;
|
|
}
|
|
}
|
|
}
|
|
var init_polling = __esm({
|
|
"node_modules/openai/lib/polling.mjs"() {
|
|
init_error();
|
|
init_headers2();
|
|
init_sleep();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/assistant-run-polling.mjs
|
|
function pollAssistantRun(resource, runID, params, options) {
|
|
return pollWithResponse((headers) => resource.retrieve(runID, params, {
|
|
...options,
|
|
headers: { ...options?.headers, ...headers }
|
|
}), ["queued", "in_progress", "cancelling"], ["requires_action", "incomplete", "cancelled", "completed", "failed", "expired"], options);
|
|
}
|
|
var init_assistant_run_polling = __esm({
|
|
"node_modules/openai/lib/assistant-run-polling.mjs"() {
|
|
init_polling();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/threads/runs/runs.mjs
|
|
var Runs;
|
|
var init_runs = __esm({
|
|
"node_modules/openai/resources/beta/threads/runs/runs.mjs"() {
|
|
init_resource();
|
|
init_steps();
|
|
init_steps();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_AssistantStream();
|
|
init_assistant_run_polling();
|
|
init_path();
|
|
Runs = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.steps = new Steps(this._client);
|
|
}
|
|
create(threadID, params, options) {
|
|
const { include, ...body } = params;
|
|
return this._client.post(path`/threads/${threadID}/runs`, {
|
|
query: { include },
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
stream: params.stream ?? false,
|
|
__synthesizeEventData: true,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a run.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
retrieve(runID, params, options) {
|
|
const { thread_id } = params;
|
|
return this._client.get(path`/threads/${thread_id}/runs/${runID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a run.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
update(runID, params, options) {
|
|
const { thread_id, ...body } = params;
|
|
return this._client.post(path`/threads/${thread_id}/runs/${runID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of runs belonging to a thread.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
list(threadID, query = {}, options) {
|
|
return this._client.getAPIList(path`/threads/${threadID}/runs`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Cancels a run that is `in_progress`.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
cancel(runID, params, options) {
|
|
const { thread_id } = params;
|
|
return this._client.post(path`/threads/${thread_id}/runs/${runID}/cancel`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* A helper to create a run an poll for a terminal state. More information on Run
|
|
* lifecycles can be found here:
|
|
* https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
|
|
*/
|
|
async createAndPoll(threadId, body, options) {
|
|
const run = await this.create(threadId, body, options);
|
|
return await this.poll(run.id, { thread_id: threadId }, options);
|
|
}
|
|
/**
|
|
* Create a Run stream
|
|
*
|
|
* @deprecated use `stream` instead
|
|
*/
|
|
createAndStream(threadId, body, options) {
|
|
return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
|
|
}
|
|
/**
|
|
* A helper to poll a run status until it reaches a terminal state. More
|
|
* information on Run lifecycles can be found here:
|
|
* https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
|
|
*/
|
|
async poll(runId, params, options) {
|
|
return await pollAssistantRun(this, runId, params, options);
|
|
}
|
|
/**
|
|
* Create a Run stream
|
|
*/
|
|
stream(threadId, body, options) {
|
|
return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);
|
|
}
|
|
submitToolOutputs(runID, params, options) {
|
|
const { thread_id, ...body } = params;
|
|
return this._client.post(path`/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
stream: params.stream ?? false,
|
|
__synthesizeEventData: true,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* A helper to submit a tool output to a run and poll for a terminal run state.
|
|
* More information on Run lifecycles can be found here:
|
|
* https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
|
|
*/
|
|
async submitToolOutputsAndPoll(runId, params, options) {
|
|
const run = await this.submitToolOutputs(runId, params, options);
|
|
return await this.poll(run.id, params, options);
|
|
}
|
|
/**
|
|
* Submit the tool outputs from a previous run and stream the run to a terminal
|
|
* state. More information on Run lifecycles can be found here:
|
|
* https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
|
|
*/
|
|
submitToolOutputsStream(runId, params, options) {
|
|
return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options);
|
|
}
|
|
};
|
|
Runs.Steps = Steps;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/threads/threads.mjs
|
|
var Threads2;
|
|
var init_threads2 = __esm({
|
|
"node_modules/openai/resources/beta/threads/threads.mjs"() {
|
|
init_resource();
|
|
init_messages2();
|
|
init_messages2();
|
|
init_runs();
|
|
init_runs();
|
|
init_headers2();
|
|
init_AssistantStream();
|
|
init_path();
|
|
Threads2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.runs = new Runs(this._client);
|
|
this.messages = new Messages2(this._client);
|
|
}
|
|
/**
|
|
* Create a thread.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
create(body = {}, options) {
|
|
return this._client.post("/threads", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a thread.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
retrieve(threadID, options) {
|
|
return this._client.get(path`/threads/${threadID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a thread.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
update(threadID, body, options) {
|
|
return this._client.post(path`/threads/${threadID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a thread.
|
|
*
|
|
* @deprecated The Assistants API is deprecated in favor of the Responses API
|
|
*/
|
|
delete(threadID, options) {
|
|
return this._client.delete(path`/threads/${threadID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
createAndRun(body, options) {
|
|
return this._client.post("/threads/runs", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
stream: body.stream ?? false,
|
|
__synthesizeEventData: true,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* A helper to create a thread, start a run and then poll for a terminal state.
|
|
* More information on Run lifecycles can be found here:
|
|
* https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps
|
|
*/
|
|
async createAndRunPoll(body, options) {
|
|
const run = await this.createAndRun(body, options);
|
|
return await this.runs.poll(run.id, { thread_id: run.thread_id }, options);
|
|
}
|
|
/**
|
|
* Create a thread and stream the run back
|
|
*/
|
|
createAndRunStream(body, options) {
|
|
return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);
|
|
}
|
|
};
|
|
Threads2.Runs = Runs;
|
|
Threads2.Messages = Messages2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/beta/beta.mjs
|
|
var Beta;
|
|
var init_beta = __esm({
|
|
"node_modules/openai/resources/beta/beta.mjs"() {
|
|
init_resource();
|
|
init_assistants();
|
|
init_assistants();
|
|
init_realtime();
|
|
init_realtime();
|
|
init_agents();
|
|
init_agents();
|
|
init_chatkit();
|
|
init_chatkit();
|
|
init_responses();
|
|
init_responses();
|
|
init_threads2();
|
|
init_threads2();
|
|
Beta = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.realtime = new Realtime(this._client);
|
|
this.agents = new Agents(this._client);
|
|
this.responses = new Responses(this._client);
|
|
this.chatkit = new ChatKit(this._client);
|
|
this.assistants = new Assistants(this._client);
|
|
this.threads = new Threads2(this._client);
|
|
}
|
|
};
|
|
Beta.Realtime = Realtime;
|
|
Beta.Agents = Agents;
|
|
Beta.Responses = Responses;
|
|
Beta.ChatKit = ChatKit;
|
|
Beta.Assistants = Assistants;
|
|
Beta.Threads = Threads2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/completions.mjs
|
|
var Completions2;
|
|
var init_completions3 = __esm({
|
|
"node_modules/openai/resources/completions.mjs"() {
|
|
init_resource();
|
|
Completions2 = class extends APIResource {
|
|
create(body, options) {
|
|
return this._client.post("/completions", {
|
|
body,
|
|
...options,
|
|
stream: body.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/containers/files/content.mjs
|
|
var Content;
|
|
var init_content = __esm({
|
|
"node_modules/openai/resources/containers/files/content.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
Content = class extends APIResource {
|
|
/**
|
|
* Retrieve Container File Content
|
|
*/
|
|
retrieve(fileID, params, options) {
|
|
const { container_id } = params;
|
|
return this._client.get(path`/containers/${container_id}/files/${fileID}/content`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/containers/files/files.mjs
|
|
var Files2;
|
|
var init_files2 = __esm({
|
|
"node_modules/openai/resources/containers/files/files.mjs"() {
|
|
init_resource();
|
|
init_content();
|
|
init_content();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_uploads();
|
|
init_path();
|
|
Files2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.content = new Content(this._client);
|
|
}
|
|
/**
|
|
* Create a Container File
|
|
*
|
|
* You can send either a multipart/form-data request with the raw file content, or
|
|
* a JSON request with a file ID.
|
|
*/
|
|
create(containerID, body, options) {
|
|
return this._client.post(path`/containers/${containerID}/files`, maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
/**
|
|
* Retrieve Container File
|
|
*/
|
|
retrieve(fileID, params, options) {
|
|
const { container_id } = params;
|
|
return this._client.get(path`/containers/${container_id}/files/${fileID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List Container files
|
|
*/
|
|
list(containerID, query = {}, options) {
|
|
return this._client.getAPIList(path`/containers/${containerID}/files`, CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete Container File
|
|
*/
|
|
delete(fileID, params, options) {
|
|
const { container_id } = params;
|
|
return this._client.delete(path`/containers/${container_id}/files/${fileID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Files2.Content = Content;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/containers/containers.mjs
|
|
var Containers;
|
|
var init_containers = __esm({
|
|
"node_modules/openai/resources/containers/containers.mjs"() {
|
|
init_resource();
|
|
init_files2();
|
|
init_files2();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
Containers = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.files = new Files2(this._client);
|
|
}
|
|
/**
|
|
* Create Container
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/containers", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Retrieve Container
|
|
*/
|
|
retrieve(containerID, options) {
|
|
return this._client.get(path`/containers/${containerID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List Containers
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/containers", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete Container
|
|
*/
|
|
delete(containerID, options) {
|
|
return this._client.delete(path`/containers/${containerID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Containers.Files = Files2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/content-provenance-checks.mjs
|
|
var ContentProvenanceChecks;
|
|
var init_content_provenance_checks = __esm({
|
|
"node_modules/openai/resources/content-provenance-checks.mjs"() {
|
|
init_resource();
|
|
init_uploads();
|
|
ContentProvenanceChecks = class extends APIResource {
|
|
/**
|
|
* Check whether an image or audio file contains known OpenAI provenance signals.
|
|
* [Learn more about content provenance](https://developers.openai.com/api/docs/guides/content-provenance).
|
|
*
|
|
* If `not_detected`, it means the tool did not find supported signals in the
|
|
* uploaded file. The content could still have been generated by OpenAI if the
|
|
* metadata was stripped or has evidence of tampering, the watermark was degraded,
|
|
* it comes from a legacy generation model, or it was created before provenance
|
|
* signals were available. Content could also still be AI-generated by another
|
|
* company's model, which the tool currently does not detect.
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/content_provenance_checks", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/conversations/items.mjs
|
|
var Items4;
|
|
var init_items4 = __esm({
|
|
"node_modules/openai/resources/conversations/items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Items4 = class extends APIResource {
|
|
/**
|
|
* Create items in a conversation with the given ID.
|
|
*/
|
|
create(conversationID, params, options) {
|
|
const { include, ...body } = params;
|
|
return this._client.post(path`/conversations/${conversationID}/items`, {
|
|
query: { include },
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get a single item from a conversation with the given IDs.
|
|
*/
|
|
retrieve(itemID, params, options) {
|
|
const { conversation_id, ...query } = params;
|
|
return this._client.get(path`/conversations/${conversation_id}/items/${itemID}`, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List all items for a conversation with the given ID.
|
|
*/
|
|
list(conversationID, query = {}, options) {
|
|
return this._client.getAPIList(path`/conversations/${conversationID}/items`, ConversationCursorPage, { query, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Delete an item from a conversation with the given IDs.
|
|
*/
|
|
delete(itemID, params, options) {
|
|
const { conversation_id } = params;
|
|
return this._client.delete(path`/conversations/${conversation_id}/items/${itemID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/conversations/conversations.mjs
|
|
var Conversations;
|
|
var init_conversations = __esm({
|
|
"node_modules/openai/resources/conversations/conversations.mjs"() {
|
|
init_resource();
|
|
init_items4();
|
|
init_items4();
|
|
init_path();
|
|
Conversations = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.items = new Items4(this._client);
|
|
}
|
|
/**
|
|
* Create a conversation.
|
|
*/
|
|
create(body = {}, options) {
|
|
return this._client.post("/conversations", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Get a conversation
|
|
*/
|
|
retrieve(conversationID, options) {
|
|
return this._client.get(path`/conversations/${conversationID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Update a conversation
|
|
*/
|
|
update(conversationID, body, options) {
|
|
return this._client.post(path`/conversations/${conversationID}`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a conversation. Items in the conversation will not be deleted.
|
|
*/
|
|
delete(conversationID, options) {
|
|
return this._client.delete(path`/conversations/${conversationID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Conversations.Items = Items4;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/embeddings.mjs
|
|
function createEmbedding(client, body, options) {
|
|
const hasUserProvidedEncodingFormat = !!body.encoding_format;
|
|
const encodingFormat = hasUserProvidedEncodingFormat ? body.encoding_format : "base64";
|
|
if (hasUserProvidedEncodingFormat) {
|
|
loggerFor(client).debug("embeddings/user defined encoding_format:", body.encoding_format);
|
|
}
|
|
const optimizedBody = { ...body, encoding_format: encodingFormat };
|
|
const requestOptions = {
|
|
body: optimizedBody,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
};
|
|
const response = client.post("/embeddings", requestOptions);
|
|
if (hasUserProvidedEncodingFormat) {
|
|
return response;
|
|
}
|
|
loggerFor(client).debug("embeddings/decoding base64 embeddings from base64");
|
|
return response._thenUnwrap((data) => {
|
|
const embeddings = data?.data;
|
|
if (embeddings !== void 0) {
|
|
if (!Array.isArray(embeddings)) {
|
|
throw new TypeError("Expected embeddings response data to be an array");
|
|
}
|
|
const { length } = embeddings;
|
|
for (let index = 0; index < length; index += 1) {
|
|
if (index in embeddings) {
|
|
const embeddingBase64Obj = embeddings[index];
|
|
const { embedding } = embeddingBase64Obj;
|
|
if (Array.isArray(embedding)) {
|
|
continue;
|
|
}
|
|
embeddingBase64Obj.embedding = toFloat32Array(embedding);
|
|
}
|
|
}
|
|
}
|
|
return data;
|
|
});
|
|
}
|
|
var init_embeddings = __esm({
|
|
"node_modules/openai/lib/embeddings.mjs"() {
|
|
init_utils2();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/embeddings.mjs
|
|
var Embeddings;
|
|
var init_embeddings2 = __esm({
|
|
"node_modules/openai/resources/embeddings.mjs"() {
|
|
init_resource();
|
|
init_embeddings();
|
|
Embeddings = class extends APIResource {
|
|
create(body, options) {
|
|
return createEmbedding(this._client, body, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/evals/runs/output-items.mjs
|
|
var OutputItems;
|
|
var init_output_items = __esm({
|
|
"node_modules/openai/resources/evals/runs/output-items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
OutputItems = class extends APIResource {
|
|
/**
|
|
* Get an evaluation run output item by ID.
|
|
*/
|
|
retrieve(outputItemID, params, options) {
|
|
const { eval_id, run_id } = params;
|
|
return this._client.get(path`/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get a list of output items for an evaluation run.
|
|
*/
|
|
list(runID, params, options) {
|
|
const { eval_id, ...query } = params;
|
|
return this._client.getAPIList(path`/evals/${eval_id}/runs/${runID}/output_items`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/evals/runs/runs.mjs
|
|
var Runs2;
|
|
var init_runs2 = __esm({
|
|
"node_modules/openai/resources/evals/runs/runs.mjs"() {
|
|
init_resource();
|
|
init_output_items();
|
|
init_output_items();
|
|
init_pagination();
|
|
init_path();
|
|
Runs2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.outputItems = new OutputItems(this._client);
|
|
}
|
|
/**
|
|
* Kicks off a new run for a given evaluation, specifying the data source, and what
|
|
* model configuration to use to test. The datasource will be validated against the
|
|
* schema specified in the config of the evaluation.
|
|
*/
|
|
create(evalID, body, options) {
|
|
return this._client.post(path`/evals/${evalID}/runs`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get an evaluation run by ID.
|
|
*/
|
|
retrieve(runID, params, options) {
|
|
const { eval_id } = params;
|
|
return this._client.get(path`/evals/${eval_id}/runs/${runID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get a list of runs for an evaluation.
|
|
*/
|
|
list(evalID, query = {}, options) {
|
|
return this._client.getAPIList(path`/evals/${evalID}/runs`, CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete an eval run.
|
|
*/
|
|
delete(runID, params, options) {
|
|
const { eval_id } = params;
|
|
return this._client.delete(path`/evals/${eval_id}/runs/${runID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Cancel an ongoing evaluation run.
|
|
*/
|
|
cancel(runID, params, options) {
|
|
const { eval_id } = params;
|
|
return this._client.post(path`/evals/${eval_id}/runs/${runID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Runs2.OutputItems = OutputItems;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/evals/evals.mjs
|
|
var Evals;
|
|
var init_evals = __esm({
|
|
"node_modules/openai/resources/evals/evals.mjs"() {
|
|
init_resource();
|
|
init_runs2();
|
|
init_runs2();
|
|
init_pagination();
|
|
init_path();
|
|
Evals = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.runs = new Runs2(this._client);
|
|
}
|
|
/**
|
|
* Create the structure of an evaluation that can be used to test a model's
|
|
* performance. An evaluation is a set of testing criteria and the config for a
|
|
* data source, which dictates the schema of the data used in the evaluation. After
|
|
* creating an evaluation, you can run it on different models and model parameters.
|
|
* We support several types of graders and datasources. For more information, see
|
|
* the [Evals guide](https://developers.openai.com/api/docs/guides/evals).
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/evals", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Get an evaluation by ID.
|
|
*/
|
|
retrieve(evalID, options) {
|
|
return this._client.get(path`/evals/${evalID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Update certain properties of an evaluation.
|
|
*/
|
|
update(evalID, body, options) {
|
|
return this._client.post(path`/evals/${evalID}`, { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* List evaluations for a project.
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/evals", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete an evaluation.
|
|
*/
|
|
delete(evalID, options) {
|
|
return this._client.delete(path`/evals/${evalID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
Evals.Runs = Runs2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/file-processing.mjs
|
|
async function waitForFileProcessing(resource, id, pollInterval, maxWait) {
|
|
const terminalStates = /* @__PURE__ */ new Set(["processed", "error", "deleted"]);
|
|
const start = performance.now();
|
|
let file2 = await resource.retrieve(id);
|
|
while (!file2.status || !terminalStates.has(file2.status)) {
|
|
await sleep(pollInterval);
|
|
file2 = await resource.retrieve(id);
|
|
if (performance.now() - start > maxWait) {
|
|
throw new APIConnectionTimeoutError({
|
|
message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`
|
|
});
|
|
}
|
|
}
|
|
return file2;
|
|
}
|
|
var init_file_processing = __esm({
|
|
"node_modules/openai/lib/file-processing.mjs"() {
|
|
init_error2();
|
|
init_sleep();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/files.mjs
|
|
var Files3;
|
|
var init_files3 = __esm({
|
|
"node_modules/openai/resources/files.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_uploads();
|
|
init_file_processing();
|
|
init_path();
|
|
Files3 = class extends APIResource {
|
|
/**
|
|
* Upload a file that can be used across various endpoints. Individual files can be
|
|
* up to 512 MB, and each project can store up to 2.5 TB of files in total. There
|
|
* is no organization-wide storage limit. Uploads to this endpoint are rate-limited
|
|
* to 1,000 requests per minute per authenticated user.
|
|
*
|
|
* - The Assistants API supports files up to 2 million tokens and of specific file
|
|
* types. See the
|
|
* [Assistants Tools guide](https://developers.openai.com/api/docs/guides/tools)
|
|
* for details.
|
|
* - The Fine-tuning API only supports `.jsonl` files. The input also has certain
|
|
* required formats for fine-tuning
|
|
* [chat](https://developers.openai.com/api/docs/guides/supervised-fine-tuning#formatting-your-data)
|
|
* or
|
|
* [completions](https://developers.openai.com/api/docs/guides/supervised-fine-tuning#formatting-your-data)
|
|
* models.
|
|
* - The Batch API only supports `.jsonl` files up to 200 MB in size. The input
|
|
* also has a specific required
|
|
* [format](https://developers.openai.com/api/docs/guides/batch#1-prepare-your-batch-file).
|
|
* - For Retrieval or `file_search` ingestion, upload files here first. If you need
|
|
* to attach multiple uploaded files to the same vector store, use
|
|
* [`/vector_stores/{vector_store_id}/file_batches`](https://developers.openai.com/api/reference/resources/vector_stores/subresources/file_batches/methods/create)
|
|
* instead of attaching them one by one. Vector store attachment has separate
|
|
* limits from file upload, including 2,000 attached files per minute per
|
|
* organization.
|
|
*
|
|
* Please [contact us](https://help.openai.com/) if you need to increase these
|
|
* storage limits.
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/files", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
/**
|
|
* Returns information about a specific file.
|
|
*/
|
|
retrieve(fileID, options) {
|
|
return this._client.get(path`/files/${fileID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Returns a list of files.
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/files", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a file and remove it from all vector stores.
|
|
*/
|
|
delete(fileID, options) {
|
|
return this._client.delete(path`/files/${fileID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Returns a response containing the contents of the specified file.
|
|
*/
|
|
content(fileID, options) {
|
|
return this._client.get(path`/files/${fileID}/content`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
/**
|
|
* Waits for the given file to be processed, default timeout is 30 mins.
|
|
*/
|
|
async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) {
|
|
return await waitForFileProcessing(this, id, pollInterval, maxWait);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/methods.mjs
|
|
var Methods;
|
|
var init_methods = __esm({
|
|
"node_modules/openai/resources/fine-tuning/methods.mjs"() {
|
|
init_resource();
|
|
Methods = class extends APIResource {
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/alpha/graders.mjs
|
|
var Graders;
|
|
var init_graders = __esm({
|
|
"node_modules/openai/resources/fine-tuning/alpha/graders.mjs"() {
|
|
init_resource();
|
|
Graders = class extends APIResource {
|
|
/**
|
|
* Run a grader.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.fineTuning.alpha.graders.run({
|
|
* grader: {
|
|
* input: 'input',
|
|
* name: 'name',
|
|
* operation: 'eq',
|
|
* reference: 'reference',
|
|
* type: 'string_check',
|
|
* },
|
|
* model_sample: 'model_sample',
|
|
* });
|
|
* ```
|
|
*/
|
|
run(body, options) {
|
|
return this._client.post("/fine_tuning/alpha/graders/run", {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Validate a grader.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.fineTuning.alpha.graders.validate({
|
|
* grader: {
|
|
* input: 'input',
|
|
* name: 'name',
|
|
* operation: 'eq',
|
|
* reference: 'reference',
|
|
* type: 'string_check',
|
|
* },
|
|
* });
|
|
* ```
|
|
*/
|
|
validate(body, options) {
|
|
return this._client.post("/fine_tuning/alpha/graders/validate", {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/alpha/alpha.mjs
|
|
var Alpha;
|
|
var init_alpha = __esm({
|
|
"node_modules/openai/resources/fine-tuning/alpha/alpha.mjs"() {
|
|
init_resource();
|
|
init_graders();
|
|
init_graders();
|
|
Alpha = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.graders = new Graders(this._client);
|
|
}
|
|
};
|
|
Alpha.Graders = Graders;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs
|
|
var Permissions;
|
|
var init_permissions = __esm({
|
|
"node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Permissions = class extends APIResource {
|
|
/**
|
|
* **NOTE:** Calling this endpoint requires an
|
|
* [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
|
|
*
|
|
* This enables organization owners to share fine-tuned models with other projects
|
|
* in their organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create(
|
|
* 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
|
|
* { project_ids: ['string'] },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
create(fineTunedModelCheckpoint, body, options) {
|
|
return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, Page, { body, method: "post", ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* **NOTE:** This endpoint requires an
|
|
* [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
|
|
*
|
|
* Organization owners can use this endpoint to view all permissions for a
|
|
* fine-tuned model checkpoint.
|
|
*
|
|
* @deprecated Retrieve is deprecated. Please swap to the paginated list method instead.
|
|
*/
|
|
retrieve(fineTunedModelCheckpoint, query = {}, options) {
|
|
return this._client.get(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, {
|
|
query,
|
|
...options,
|
|
__security: { adminAPIKeyAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* **NOTE:** This endpoint requires an
|
|
* [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
|
|
*
|
|
* Organization owners can use this endpoint to view all permissions for a
|
|
* fine-tuned model checkpoint.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const permissionListResponse of client.fineTuning.checkpoints.permissions.list(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(fineTunedModelCheckpoint, query = {}, options) {
|
|
return this._client.getAPIList(path`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, ConversationCursorPage, { query, ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
/**
|
|
* **NOTE:** This endpoint requires an
|
|
* [admin API key](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/admin_api_keys).
|
|
*
|
|
* Organization owners can use this endpoint to delete a permission for a
|
|
* fine-tuned model checkpoint.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const permission =
|
|
* await client.fineTuning.checkpoints.permissions.delete(
|
|
* 'cp_zc4Q7MP6XxulcVzj4MZdwsAB',
|
|
* {
|
|
* fine_tuned_model_checkpoint:
|
|
* 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(permissionID, params, options) {
|
|
const { fine_tuned_model_checkpoint } = params;
|
|
return this._client.delete(path`/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, { ...options, __security: { adminAPIKeyAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs
|
|
var Checkpoints;
|
|
var init_checkpoints = __esm({
|
|
"node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs"() {
|
|
init_resource();
|
|
init_permissions();
|
|
init_permissions();
|
|
Checkpoints = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.permissions = new Permissions(this._client);
|
|
}
|
|
};
|
|
Checkpoints.Permissions = Permissions;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs
|
|
var Checkpoints2;
|
|
var init_checkpoints2 = __esm({
|
|
"node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Checkpoints2 = class extends APIResource {
|
|
/**
|
|
* List checkpoints for a fine-tuning job.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(fineTuningJobID, query = {}, options) {
|
|
return this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/jobs/jobs.mjs
|
|
var Jobs;
|
|
var init_jobs = __esm({
|
|
"node_modules/openai/resources/fine-tuning/jobs/jobs.mjs"() {
|
|
init_resource();
|
|
init_checkpoints2();
|
|
init_checkpoints2();
|
|
init_pagination();
|
|
init_path();
|
|
Jobs = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.checkpoints = new Checkpoints2(this._client);
|
|
}
|
|
/**
|
|
* Creates a fine-tuning job which begins the process of creating a new model from
|
|
* a given dataset.
|
|
*
|
|
* Response includes details of the enqueued job including job status and the name
|
|
* of the fine-tuned models once complete.
|
|
*
|
|
* [Learn more about fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fineTuningJob = await client.fineTuning.jobs.create({
|
|
* model: 'gpt-4o-mini',
|
|
* training_file: 'file-abc123',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/fine_tuning/jobs", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Get info about a fine-tuning job.
|
|
*
|
|
* [Learn more about fine-tuning](https://developers.openai.com/api/docs/guides/model-optimization)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fineTuningJob = await client.fineTuning.jobs.retrieve(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(fineTuningJobID, options) {
|
|
return this._client.get(path`/fine_tuning/jobs/${fineTuningJobID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List your organization's fine-tuning jobs
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const fineTuningJob of client.fineTuning.jobs.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/fine_tuning/jobs", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Immediately cancel a fine-tune job.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fineTuningJob = await client.fineTuning.jobs.cancel(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* );
|
|
* ```
|
|
*/
|
|
cancel(fineTuningJobID, options) {
|
|
return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/cancel`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get status updates for a fine-tuning job.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
listEvents(fineTuningJobID, query = {}, options) {
|
|
return this._client.getAPIList(path`/fine_tuning/jobs/${fineTuningJobID}/events`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Pause a fine-tune job.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fineTuningJob = await client.fineTuning.jobs.pause(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* );
|
|
* ```
|
|
*/
|
|
pause(fineTuningJobID, options) {
|
|
return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/pause`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Resume a fine-tune job.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fineTuningJob = await client.fineTuning.jobs.resume(
|
|
* 'ft-AF1WoRqd3aJAHsqc9NY7iL8F',
|
|
* );
|
|
* ```
|
|
*/
|
|
resume(fineTuningJobID, options) {
|
|
return this._client.post(path`/fine_tuning/jobs/${fineTuningJobID}/resume`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Jobs.Checkpoints = Checkpoints2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/fine-tuning/fine-tuning.mjs
|
|
var FineTuning;
|
|
var init_fine_tuning = __esm({
|
|
"node_modules/openai/resources/fine-tuning/fine-tuning.mjs"() {
|
|
init_resource();
|
|
init_methods();
|
|
init_methods();
|
|
init_alpha();
|
|
init_alpha();
|
|
init_checkpoints();
|
|
init_checkpoints();
|
|
init_jobs();
|
|
init_jobs();
|
|
FineTuning = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.methods = new Methods(this._client);
|
|
this.jobs = new Jobs(this._client);
|
|
this.checkpoints = new Checkpoints(this._client);
|
|
this.alpha = new Alpha(this._client);
|
|
}
|
|
};
|
|
FineTuning.Methods = Methods;
|
|
FineTuning.Jobs = Jobs;
|
|
FineTuning.Checkpoints = Checkpoints;
|
|
FineTuning.Alpha = Alpha;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/graders/grader-models.mjs
|
|
var GraderModels;
|
|
var init_grader_models = __esm({
|
|
"node_modules/openai/resources/graders/grader-models.mjs"() {
|
|
init_resource();
|
|
GraderModels = class extends APIResource {
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/graders/graders.mjs
|
|
var Graders2;
|
|
var init_graders2 = __esm({
|
|
"node_modules/openai/resources/graders/graders.mjs"() {
|
|
init_resource();
|
|
init_grader_models();
|
|
init_grader_models();
|
|
Graders2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.graderModels = new GraderModels(this._client);
|
|
}
|
|
};
|
|
Graders2.GraderModels = GraderModels;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/images.mjs
|
|
var Images;
|
|
var init_images = __esm({
|
|
"node_modules/openai/resources/images.mjs"() {
|
|
init_resource();
|
|
init_uploads();
|
|
Images = class extends APIResource {
|
|
/**
|
|
* Creates a variation of a given image. This endpoint only supports `dall-e-2`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const imagesResponse = await client.images.createVariation({
|
|
* image: fs.createReadStream('otter.png'),
|
|
* });
|
|
* ```
|
|
*/
|
|
createVariation(body, options) {
|
|
return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
edit(body, options) {
|
|
return this._client.post("/images/edits", multipartFormRequestOptions({
|
|
body,
|
|
...options,
|
|
stream: body.stream ?? false,
|
|
__metadata: { ...options?.__metadata, ...body.model == null ? {} : { model: body.model } },
|
|
__security: { bearerAuth: true }
|
|
}, this._client));
|
|
}
|
|
generate(body, options) {
|
|
return this._client.post("/images/generations", {
|
|
body,
|
|
...options,
|
|
stream: body.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/live/sessions.mjs
|
|
var Sessions4;
|
|
var init_sessions4 = __esm({
|
|
"node_modules/openai/resources/live/sessions.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
Sessions4 = class extends APIResource {
|
|
/**
|
|
* Accept an incoming SIP call. Supply session with type live, the model, and
|
|
* startup configuration. Before accepting calls, follow the
|
|
* [Live prompting guide](https://developers.openai.com/api/docs/guides/live-prompting)
|
|
* to write frontend conversation instructions and a separate backend prompt. SIP
|
|
* media format is negotiated; omit audio.format.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.live.sessions.accept('session_id', {
|
|
* session: { model: 'gpt-live-1', type: 'live' },
|
|
* });
|
|
* ```
|
|
*/
|
|
accept(sessionID, body, options) {
|
|
return this._client.post(path`/live/sessions/${sessionID}/accept`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Get Live session content
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.live.sessions.downloadRecording('live_SQ');
|
|
*
|
|
* const content = await response.blob();
|
|
* console.log(content);
|
|
* ```
|
|
*/
|
|
downloadRecording(sessionID, options) {
|
|
return this._client.get(path`/live/sessions/${sessionID}/content`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
/**
|
|
* Fork a stored Live session onto a new WebRTC connection.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.live.sessions.fork(
|
|
* 'session_id',
|
|
* { transport: { sdp: 'x', type: 'webrtc' } },
|
|
* );
|
|
* ```
|
|
*/
|
|
fork(sessionID, body, options) {
|
|
return this._client.post(path`/live/sessions/${sessionID}/fork`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* End a SIP call identified by session_id.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.live.sessions.hangup('session_id');
|
|
* ```
|
|
*/
|
|
hangup(sessionID, options) {
|
|
return this._client.post(path`/live/sessions/${sessionID}/hangup`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Transfer a SIP call to another destination. Supply a nonblank target_uri for the
|
|
* SIP Refer-To header.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.live.sessions.refer('session_id', {
|
|
* target_uri: 'tel:+14155550123',
|
|
* });
|
|
* ```
|
|
*/
|
|
refer(sessionID, body, options) {
|
|
return this._client.post(path`/live/sessions/${sessionID}/refer`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Reject an incoming SIP call. Send a required SIP rejection status_code between
|
|
* 300 and 699.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.live.sessions.reject('session_id', {
|
|
* status_code: 486,
|
|
* });
|
|
* ```
|
|
*/
|
|
reject(sessionID, body, options) {
|
|
return this._client.post(path`/live/sessions/${sessionID}/reject`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/live/forks/forks.mjs
|
|
var Forks;
|
|
var init_forks = __esm({
|
|
"node_modules/openai/resources/live/forks/forks.mjs"() {
|
|
init_resource();
|
|
Forks = class extends APIResource {
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/live/sideband/sideband.mjs
|
|
var Sideband;
|
|
var init_sideband = __esm({
|
|
"node_modules/openai/resources/live/sideband/sideband.mjs"() {
|
|
init_resource();
|
|
Sideband = class extends APIResource {
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/live/live.mjs
|
|
var Live;
|
|
var init_live = __esm({
|
|
"node_modules/openai/resources/live/live.mjs"() {
|
|
init_resource();
|
|
init_sessions4();
|
|
init_sessions4();
|
|
init_forks();
|
|
init_forks();
|
|
init_sideband();
|
|
init_sideband();
|
|
Live = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.sideband = new Sideband(this._client);
|
|
this.forks = new Forks(this._client);
|
|
this.sessions = new Sessions4(this._client);
|
|
}
|
|
/**
|
|
* Create a Live WebRTC session. Start with the
|
|
* [Live prompting guide](https://developers.openai.com/api/docs/guides/live-prompting).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const live = await client.live.create({
|
|
* session: { model: 'gpt-live-1' },
|
|
* transport: { sdp: 'x', type: 'webrtc' },
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/live/sessions", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
Live.Sideband = Sideband;
|
|
Live.Forks = Forks;
|
|
Live.Sessions = Sessions4;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/models.mjs
|
|
var Models;
|
|
var init_models2 = __esm({
|
|
"node_modules/openai/resources/models.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
Models = class extends APIResource {
|
|
/**
|
|
* Retrieves a model instance, providing basic information about the model such as
|
|
* the owner and permissioning.
|
|
*/
|
|
retrieve(model2, options) {
|
|
return this._client.get(path`/models/${model2}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Lists the currently available models, and provides basic information about each
|
|
* one such as the owner and availability.
|
|
*/
|
|
list(options) {
|
|
return this._client.getAPIList("/models", Page, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Delete a fine-tuned model. You must have the Owner role in your organization to
|
|
* delete a model.
|
|
*/
|
|
delete(model2, options) {
|
|
return this._client.delete(path`/models/${model2}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/moderations.mjs
|
|
var Moderations;
|
|
var init_moderations = __esm({
|
|
"node_modules/openai/resources/moderations.mjs"() {
|
|
init_resource();
|
|
Moderations = class extends APIResource {
|
|
/**
|
|
* Classifies if text and/or image inputs are potentially harmful. Learn more in
|
|
* the
|
|
* [moderation guide](https://developers.openai.com/api/docs/guides/moderation).
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/moderations", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/multipart-encoding.mjs
|
|
async function encodedMultipartFormRequestOptions(options, client, encodings, rawBodyField = null) {
|
|
if (options.body === null || typeof options.body !== "object" || Array.isArray(options.body)) {
|
|
throw new TypeError("Multipart request body must be an object");
|
|
}
|
|
const body = Object.fromEntries(Object.entries(options.body).filter(([, value]) => value !== void 0));
|
|
if (rawBodyField !== null && Object.keys(body).length === 1 && Object.prototype.hasOwnProperty.call(body, rawBodyField)) {
|
|
const value = body[rawBodyField];
|
|
if (typeof value !== "string")
|
|
throw new TypeError("Raw multipart alternative must be a string");
|
|
return {
|
|
...options,
|
|
body: value,
|
|
headers: buildHeaders([options.headers, { "content-type": encodings[rawBodyField].content_type }])
|
|
};
|
|
}
|
|
const encoded = [];
|
|
for (const [name, encoding] of Object.entries(encodings)) {
|
|
if (!Object.prototype.hasOwnProperty.call(body, name))
|
|
continue;
|
|
const value = body[name];
|
|
const data = encoding.json ? JSON.stringify(value) : value;
|
|
if (typeof data !== "string")
|
|
throw new TypeError(`Multipart field ${name} must encode as a string`);
|
|
encoded.push([name, makeFile([data], "", { type: encoding.content_type })]);
|
|
delete body[name];
|
|
}
|
|
const multipart = await multipartFormRequestOptions({ ...options, body }, client);
|
|
const form = multipart.body;
|
|
if (!(form instanceof FormData)) {
|
|
await form.cancel();
|
|
throw new TypeError("Unexpected streaming upload in typed multipart request body");
|
|
}
|
|
for (const [name, part] of encoded)
|
|
form.append(name, part, "");
|
|
return {
|
|
...options,
|
|
body: form,
|
|
headers: buildHeaders([options.headers, { "content-type": null }])
|
|
};
|
|
}
|
|
var init_multipart_encoding = __esm({
|
|
"node_modules/openai/internal/multipart-encoding.mjs"() {
|
|
init_uploads();
|
|
init_headers2();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/realtime/calls.mjs
|
|
var Calls;
|
|
var init_calls = __esm({
|
|
"node_modules/openai/resources/realtime/calls.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
init_multipart_encoding();
|
|
Calls = class extends APIResource {
|
|
/**
|
|
* Create a new Realtime API call over WebRTC and receive the SDP answer needed to
|
|
* complete the peer connection.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.realtime.calls.create({
|
|
* sdp: 'sdp',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/realtime/calls", encodedMultipartFormRequestOptions({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/sdp" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
}, this._client, {
|
|
sdp: { content_type: "application/sdp", json: false },
|
|
session: { content_type: "application/json", json: true }
|
|
}, "sdp"));
|
|
}
|
|
/**
|
|
* Accept an incoming SIP call and configure the realtime session that will handle
|
|
* it.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.realtime.calls.accept('call_id', {
|
|
* type: 'realtime',
|
|
* });
|
|
* ```
|
|
*/
|
|
accept(callID, body, options) {
|
|
return this._client.post(path`/realtime/calls/${callID}/accept`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* End an active Realtime API call, whether it was initiated over SIP or WebRTC.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.realtime.calls.hangup('call_id');
|
|
* ```
|
|
*/
|
|
hangup(callID, options) {
|
|
return this._client.post(path`/realtime/calls/${callID}/hangup`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Transfer an active SIP call to a new destination using the SIP REFER verb.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.realtime.calls.refer('call_id', {
|
|
* target_uri: 'tel:+14155550123',
|
|
* });
|
|
* ```
|
|
*/
|
|
refer(callID, body, options) {
|
|
return this._client.post(path`/realtime/calls/${callID}/refer`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Decline an incoming SIP call by returning a SIP status code to the caller.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.realtime.calls.reject('call_id');
|
|
* ```
|
|
*/
|
|
reject(callID, body = {}, options) {
|
|
return this._client.post(path`/realtime/calls/${callID}/reject`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/realtime/client-secrets.mjs
|
|
var ClientSecrets;
|
|
var init_client_secrets = __esm({
|
|
"node_modules/openai/resources/realtime/client-secrets.mjs"() {
|
|
init_resource();
|
|
ClientSecrets = class extends APIResource {
|
|
/**
|
|
* Create a Realtime client secret with an associated session configuration.
|
|
*
|
|
* Client secrets are short-lived tokens that can be passed to a client app, such
|
|
* as a web frontend or mobile client, which grants access to the Realtime API
|
|
* without leaking your main API key. You can configure a custom TTL for each
|
|
* client secret.
|
|
*
|
|
* You can also attach session configuration options to the client secret, which
|
|
* will be applied to any sessions created using that client secret, but these can
|
|
* also be overridden by the client connection.
|
|
*
|
|
* [Learn more about authentication with client secrets over WebRTC](https://developers.openai.com/api/docs/guides/realtime-webrtc).
|
|
*
|
|
* Returns the created client secret and the effective session object. The client
|
|
* secret is a string that looks like `ek_1234`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const clientSecret =
|
|
* await client.realtime.clientSecrets.create();
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/realtime/client_secrets", {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/realtime/realtime.mjs
|
|
var Realtime2;
|
|
var init_realtime2 = __esm({
|
|
"node_modules/openai/resources/realtime/realtime.mjs"() {
|
|
init_resource();
|
|
init_calls();
|
|
init_calls();
|
|
init_client_secrets();
|
|
init_client_secrets();
|
|
Realtime2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.clientSecrets = new ClientSecrets(this._client);
|
|
this.calls = new Calls(this._client);
|
|
}
|
|
};
|
|
Realtime2.ClientSecrets = ClientSecrets;
|
|
Realtime2.Calls = Calls;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/ResponsesParser.mjs
|
|
function maybeParseResponse(response, params) {
|
|
if (!params || !hasAutoParseableInput2(params)) {
|
|
const parsed = {
|
|
...response,
|
|
output_parsed: null,
|
|
output: response.output.map((item) => {
|
|
if (item.type === "function_call") {
|
|
return {
|
|
...item,
|
|
parsed_arguments: null
|
|
};
|
|
}
|
|
if (item.type === "message") {
|
|
return {
|
|
...item,
|
|
content: item.content.map((content) => ({
|
|
...content,
|
|
parsed: null
|
|
}))
|
|
};
|
|
}
|
|
return item;
|
|
})
|
|
};
|
|
if (needsOutputText(response, parsed)) {
|
|
addOutputText(parsed);
|
|
}
|
|
return parsed;
|
|
}
|
|
return parseResponse(response, params);
|
|
}
|
|
function parseResponse(response, params) {
|
|
const shouldParse = !response.status || response.status === "completed";
|
|
const output = response.output.map((item) => {
|
|
if (item.type === "function_call") {
|
|
return shouldParse ? parseToolCall2(params, item) : { ...item, parsed_arguments: null };
|
|
}
|
|
if (item.type === "message") {
|
|
const content = item.content.map((content2) => {
|
|
if (content2.type === "output_text") {
|
|
return {
|
|
...content2,
|
|
parsed: shouldParse ? parseTextFormat(params, content2.text) : null
|
|
};
|
|
}
|
|
return content2;
|
|
});
|
|
return {
|
|
...item,
|
|
content
|
|
};
|
|
}
|
|
return item;
|
|
});
|
|
const parsed = { ...response, output };
|
|
if (needsOutputText(response, parsed)) {
|
|
addOutputText(parsed);
|
|
}
|
|
Object.defineProperty(parsed, "output_parsed", {
|
|
enumerable: true,
|
|
get() {
|
|
for (const output2 of parsed.output) {
|
|
if (output2.type !== "message") {
|
|
continue;
|
|
}
|
|
for (const content of output2.content) {
|
|
if (content.type === "output_text" && content.parsed !== null) {
|
|
return content.parsed;
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
});
|
|
return parsed;
|
|
}
|
|
function parseTextFormat(params, content) {
|
|
return parseResponseFormatContent(params.text?.format, content);
|
|
}
|
|
function hasAutoParseableInput2(params) {
|
|
if (isParseableResponseFormat(params.text?.format)) {
|
|
return true;
|
|
}
|
|
return Array.isArray(params.tools) && params.tools.some((tool) => isAutoParsableTool2(tool) || tool.type === "function" && tool.strict === true || tool.type === "namespace" && tool.tools.some((nested) => nested.type === "function" && (isAutoParsableTool2(nested) || nested.strict === true)));
|
|
}
|
|
function isAutoParsableTool2(tool) {
|
|
return tool?.["$brand"] === "auto-parseable-tool";
|
|
}
|
|
function getInputToolByName(input_tools, name, namespace) {
|
|
for (const tool of input_tools) {
|
|
if (namespace == null) {
|
|
if (tool.type === "function" && tool.name === name) {
|
|
return tool;
|
|
}
|
|
} else if (tool.type === "namespace" && tool.name === namespace) {
|
|
return tool.tools.find((nested) => nested.type === "function" && nested.name === name);
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
function parseToolCall2(params, toolCall) {
|
|
const inputTool = getInputToolByName(params.tools ?? [], toolCall.name, toolCall.namespace);
|
|
let parsedArguments = null;
|
|
if (isAutoParsableTool2(inputTool)) {
|
|
parsedArguments = inputTool.$parseRaw(toolCall.arguments);
|
|
} else if (inputTool?.strict) {
|
|
parsedArguments = parseResponseFormatContent({ type: "json_schema", $parseRaw: void 0 }, toolCall.arguments);
|
|
}
|
|
return {
|
|
...toolCall,
|
|
parsed_arguments: parsedArguments
|
|
};
|
|
}
|
|
function needsOutputText(response, target) {
|
|
return !Object.getOwnPropertyDescriptor(response, "output_text") || target.output_text == null;
|
|
}
|
|
function addOutputText(rsp) {
|
|
const texts = [];
|
|
for (const output of rsp.output) {
|
|
if (output.type !== "message") {
|
|
continue;
|
|
}
|
|
for (const content of output.content) {
|
|
if (content.type === "output_text") {
|
|
texts.push(content.text);
|
|
}
|
|
}
|
|
}
|
|
rsp.output_text = texts.join("");
|
|
}
|
|
var init_ResponsesParser = __esm({
|
|
"node_modules/openai/lib/ResponsesParser.mjs"() {
|
|
init_error2();
|
|
init_parser();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/responses/output-text-index.mjs
|
|
var OutputTextIndex;
|
|
var init_output_text_index = __esm({
|
|
"node_modules/openai/internal/responses/output-text-index.mjs"() {
|
|
OutputTextIndex = class {
|
|
constructor() {
|
|
this.capacity = 1;
|
|
this.values = [0, 0];
|
|
this.size = 0;
|
|
}
|
|
get length() {
|
|
return this.size;
|
|
}
|
|
append(value) {
|
|
if (this.size === this.capacity) {
|
|
this.grow();
|
|
}
|
|
const index = this.size;
|
|
this.size += 1;
|
|
this.update(index, value);
|
|
}
|
|
update(index, value) {
|
|
if (!Number.isSafeInteger(index) || index < 0 || index >= this.size) {
|
|
throw new RangeError(`missing output at index ${index}`);
|
|
}
|
|
let node = this.capacity + index;
|
|
const difference = value - (this.values[node] ?? 0);
|
|
if (difference === 0) {
|
|
return;
|
|
}
|
|
while (node >= 1) {
|
|
this.values[node] = (this.values[node] ?? 0) + difference;
|
|
node = Math.floor(node / 2);
|
|
}
|
|
}
|
|
prefixSum(end) {
|
|
if (!Number.isSafeInteger(end) || end < 0 || end > this.size) {
|
|
throw new RangeError(`missing output at index ${end}`);
|
|
}
|
|
let start = this.capacity;
|
|
let stop2 = this.capacity + end;
|
|
let sum = 0;
|
|
while (start < stop2) {
|
|
if (start % 2 === 1) {
|
|
sum += this.values[start] ?? 0;
|
|
start += 1;
|
|
}
|
|
if (stop2 % 2 === 1) {
|
|
stop2 -= 1;
|
|
sum += this.values[stop2] ?? 0;
|
|
}
|
|
start = Math.floor(start / 2);
|
|
stop2 = Math.floor(stop2 / 2);
|
|
}
|
|
return sum;
|
|
}
|
|
grow() {
|
|
const previousCapacity = this.capacity;
|
|
this.capacity *= 2;
|
|
const values = Array.from({ length: this.capacity * 2 }, () => 0);
|
|
for (let index = 0; index < this.size; index += 1) {
|
|
values[this.capacity + index] = this.values[previousCapacity + index] ?? 0;
|
|
}
|
|
for (let index = this.capacity - 1; index > 0; index -= 1) {
|
|
values[index] = (values[index * 2] ?? 0) + (values[index * 2 + 1] ?? 0);
|
|
}
|
|
this.values = values;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/responses/canonical-output-text.mjs
|
|
function createCanonicalResponseContext() {
|
|
return {
|
|
canonicalSnapshot: void 0,
|
|
outputTextLengths: /* @__PURE__ */ new WeakMap(),
|
|
outputTextIndex: new OutputTextIndex()
|
|
};
|
|
}
|
|
function getOutputText(context, output) {
|
|
if (output.type !== "message") {
|
|
return "";
|
|
}
|
|
let text = "";
|
|
for (const content of output.content) {
|
|
if (content.type === "output_text") {
|
|
text += content.text;
|
|
}
|
|
}
|
|
context.outputTextLengths.set(output, text.length);
|
|
return text;
|
|
}
|
|
function ensureCanonicalOutputText(context, snapshot) {
|
|
if (context.canonicalSnapshot === snapshot) {
|
|
return;
|
|
}
|
|
const outputTextIndex = new OutputTextIndex();
|
|
let text = "";
|
|
for (const output of snapshot.output) {
|
|
const outputText = getOutputText(context, output);
|
|
text += outputText;
|
|
outputTextIndex.append(outputText.length);
|
|
}
|
|
snapshot.output_text = text;
|
|
context.outputTextIndex = outputTextIndex;
|
|
context.canonicalSnapshot = snapshot;
|
|
}
|
|
function cloneResponse(context, response) {
|
|
context.canonicalSnapshot = void 0;
|
|
context.outputTextLengths = /* @__PURE__ */ new WeakMap();
|
|
context.outputTextIndex = new OutputTextIndex();
|
|
const snapshot = structuredClone(response);
|
|
if (!Object.getOwnPropertyDescriptor(snapshot, "output_text") || snapshot.output_text === null || snapshot.output_text === void 0) {
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
} else if (snapshot.output.length === 0 && snapshot.output_text === "") {
|
|
context.canonicalSnapshot = snapshot;
|
|
}
|
|
return snapshot;
|
|
}
|
|
function updateCachedOutputTextLength(context, output, outputIndex, previousText, nextText) {
|
|
const length = context.outputTextLengths.get(output);
|
|
if (length !== void 0) {
|
|
const nextLength = length - previousText.length + nextText.length;
|
|
context.outputTextLengths.set(output, nextLength);
|
|
context.outputTextIndex.update(outputIndex, nextLength);
|
|
}
|
|
}
|
|
function replaceOutputTextSuffix(snapshot, previousText, nextText) {
|
|
if (previousText.length === 0) {
|
|
snapshot.output_text += nextText;
|
|
return;
|
|
}
|
|
snapshot.output_text = snapshot.output_text.slice(0, snapshot.output_text.length - previousText.length) + nextText;
|
|
}
|
|
function getPrecedingContentTextLength(context, output, contentIndex, nextText) {
|
|
if (contentIndex === void 0 || output?.type !== "message") {
|
|
return 0;
|
|
}
|
|
if (contentIndex < output.content.length - contentIndex - 1) {
|
|
let precedingContentLength = 0;
|
|
for (let index = 0; index < contentIndex; index += 1) {
|
|
const precedingContent = output.content[index];
|
|
if (precedingContent?.type === "output_text") {
|
|
precedingContentLength += precedingContent.text.length;
|
|
}
|
|
}
|
|
return precedingContentLength;
|
|
}
|
|
let followingContentLength = 0;
|
|
for (let index = contentIndex + 1; index < output.content.length; index += 1) {
|
|
const followingContent = output.content[index];
|
|
if (followingContent?.type === "output_text") {
|
|
followingContentLength += followingContent.text.length;
|
|
}
|
|
}
|
|
const outputTextLength = context.outputTextLengths.get(output) ?? getOutputText(context, output).length;
|
|
return outputTextLength - followingContentLength - nextText.length;
|
|
}
|
|
function updateOutputText(context, snapshot, outputIndex, previousText, nextText, contentIndex) {
|
|
if (previousText === nextText) {
|
|
return;
|
|
}
|
|
const output = snapshot.output[outputIndex];
|
|
if (outputIndex === snapshot.output.length - 1 && (contentIndex === void 0 || output?.type === "message" && contentIndex === output.content.length - 1)) {
|
|
replaceOutputTextSuffix(snapshot, previousText, nextText);
|
|
return;
|
|
}
|
|
const precedingContentLength = getPrecedingContentTextLength(context, output, contentIndex, nextText);
|
|
const offset = context.outputTextIndex.prefixSum(outputIndex) + precedingContentLength;
|
|
if (offset + previousText.length === snapshot.output_text.length) {
|
|
replaceOutputTextSuffix(snapshot, previousText, nextText);
|
|
return;
|
|
}
|
|
snapshot.output_text = snapshot.output_text.slice(0, offset) + nextText + snapshot.output_text.slice(offset + previousText.length);
|
|
}
|
|
var init_canonical_output_text = __esm({
|
|
"node_modules/openai/internal/responses/canonical-output-text.mjs"() {
|
|
init_output_text_index();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/responses/response-accumulator.mjs
|
|
function validateArrayIndex(collection, index, kind, allowAppend = false) {
|
|
if (!Array.isArray(collection) || !Number.isSafeInteger(index) || index < 0 || index > collection.length || (index === collection.length ? !allowAppend || index in collection : !hasOwn(collection, index))) {
|
|
throw new OpenAIError(`missing ${kind} at index ${index}`);
|
|
}
|
|
}
|
|
function validateArrayAppend(collection, index, kind) {
|
|
if (index !== collection.length) {
|
|
throw new OpenAIError(`missing ${kind} at index ${index}`);
|
|
}
|
|
validateArrayIndex(collection, index, kind, true);
|
|
}
|
|
function getOutput(snapshot, outputIndex) {
|
|
validateArrayIndex(snapshot.output, outputIndex, "output");
|
|
const output = snapshot.output[outputIndex];
|
|
if (!output) {
|
|
throw new OpenAIError(`missing output at index ${outputIndex}`);
|
|
}
|
|
return output;
|
|
}
|
|
function hasRoutedOutputCallIdentity(output) {
|
|
return output.type === "function_call" || output.type === "custom_tool_call" || output.type === "shell_call" || output.type === "shell_call_output";
|
|
}
|
|
function getOutputItemIdentityKeys(output, eventType) {
|
|
if (!hasOwn(output, "type") || typeof output.type !== "string") {
|
|
throw new OpenAIError(`expected an own output item type for ${eventType}`);
|
|
}
|
|
const optionalPlatformID = output.type === "function_call" || output.type === "custom_tool_call";
|
|
const identities = [];
|
|
if (hasOwn(output, "id")) {
|
|
if (typeof output.id !== "string" || output.id.length === 0) {
|
|
throw new OpenAIError(`expected a non-empty output item id for ${eventType}`);
|
|
}
|
|
identities.push(`id:${output.id}`);
|
|
} else if (!optionalPlatformID) {
|
|
throw new OpenAIError(`expected a non-empty output item id for ${eventType}`);
|
|
}
|
|
if (hasRoutedOutputCallIdentity(output)) {
|
|
if (!hasOwn(output, "call_id") || typeof output.call_id !== "string" || output.call_id.length === 0) {
|
|
throw new OpenAIError(`expected a non-empty output item call_id for ${eventType}`);
|
|
}
|
|
identities.push(`call:${output.type}:${output.call_id}`);
|
|
}
|
|
return identities;
|
|
}
|
|
function assertOutputItemIdentitiesAvailable(identities, keys) {
|
|
for (const key of keys) {
|
|
if (identities.has(key)) {
|
|
throw new OpenAIError(`duplicate output item identity '${key}'`);
|
|
}
|
|
}
|
|
}
|
|
function addOutputItemIdentities(identities, keys) {
|
|
assertOutputItemIdentitiesAvailable(identities, keys);
|
|
for (const key of keys) {
|
|
identities.add(key);
|
|
}
|
|
}
|
|
function createResponseOutputIdentityIndex(snapshot) {
|
|
const identityIndex = {
|
|
snapshot,
|
|
output: snapshot.output,
|
|
length: snapshot.output.length,
|
|
identities: /* @__PURE__ */ new Set()
|
|
};
|
|
for (let index = 0; index < snapshot.output.length; index += 1) {
|
|
const output = getOutput(snapshot, index);
|
|
addOutputItemIdentities(identityIndex.identities, getOutputItemIdentityKeys(output, "response snapshot"));
|
|
}
|
|
return identityIndex;
|
|
}
|
|
function getResponseOutputIdentityIndex(context, snapshot) {
|
|
const cached = responseOutputIdentityIndexes.get(context);
|
|
if (cached && cached.snapshot === snapshot && cached.output === snapshot.output && cached.length === snapshot.output.length) {
|
|
return cached;
|
|
}
|
|
const identityIndex = createResponseOutputIdentityIndex(snapshot);
|
|
responseOutputIdentityIndexes.set(context, identityIndex);
|
|
return identityIndex;
|
|
}
|
|
function cloneValidatedResponse(context, response) {
|
|
const nextContext = createCanonicalResponseContext();
|
|
const snapshot = cloneResponse(nextContext, response);
|
|
const identityIndex = createResponseOutputIdentityIndex(snapshot);
|
|
context.canonicalSnapshot = nextContext.canonicalSnapshot;
|
|
context.outputTextLengths = nextContext.outputTextLengths;
|
|
context.outputTextIndex = nextContext.outputTextIndex;
|
|
responseOutputIdentityIndexes.set(context, identityIndex);
|
|
return snapshot;
|
|
}
|
|
function getExpectedOutputItemType(event) {
|
|
if (event.type === "response.content_part.added" || event.type === "response.content_part.done") {
|
|
return event.part.type === "reasoning_text" ? "reasoning" : "message";
|
|
}
|
|
return expectedOutputItemTypes[event.type];
|
|
}
|
|
function validateCompletedOutputItemIdentity(event, snapshot) {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
const replacement = event.item;
|
|
getOutputItemIdentityKeys(output, event.type);
|
|
getOutputItemIdentityKeys(replacement, event.type);
|
|
if (!hasOwn(replacement, "type") || output.type !== replacement.type) {
|
|
throw new OpenAIError(`expected output item type '${output.type}', got '${replacement.type}'`);
|
|
}
|
|
const outputID = hasOwn(output, "id") ? output.id : void 0;
|
|
const replacementID = hasOwn(replacement, "id") ? replacement.id : void 0;
|
|
if (outputID !== replacementID) {
|
|
throw new OpenAIError(`expected output item id '${outputID}', got '${replacementID}'`);
|
|
}
|
|
if (hasRoutedOutputCallIdentity(output) && hasRoutedOutputCallIdentity(replacement) && output.call_id !== replacement.call_id) {
|
|
throw new OpenAIError(`expected output item call_id '${output.call_id}', got '${replacement.call_id}'`);
|
|
}
|
|
}
|
|
function validateOutputItemIdentity(event, snapshot, rejectInvalidShellTargets) {
|
|
if (event.type === "response.output_item.done") {
|
|
validateCompletedOutputItemIdentity(event, snapshot);
|
|
return;
|
|
}
|
|
if (rejectInvalidShellTargets && (event.type === "response.shell_call_command.added" || event.type === "response.shell_call_command.delta" || event.type === "response.shell_call_command.done")) {
|
|
const output2 = getOutput(snapshot, event.output_index);
|
|
if (!hasOwn(output2, "type") || output2.type !== "shell_call") {
|
|
throw new OpenAIError(`expected output item type 'shell_call', got '${output2.type}'`);
|
|
}
|
|
return;
|
|
}
|
|
if (event.type !== "response.content_part.added" && event.type !== "response.content_part.done" && !hasOwn(expectedOutputItemTypes, event.type)) {
|
|
return;
|
|
}
|
|
const itemEvent = event;
|
|
if (!hasOwn(event, "item_id") || typeof itemEvent.item_id !== "string" || itemEvent.item_id.length === 0) {
|
|
throw new OpenAIError(`expected a non-empty item_id for ${event.type}`);
|
|
}
|
|
const output = getOutput(snapshot, itemEvent.output_index);
|
|
const outputID = hasOwn(output, "id") ? output.id : void 0;
|
|
if (outputID !== itemEvent.item_id) {
|
|
throw new OpenAIError(`expected item_id '${outputID}', got '${itemEvent.item_id}'`);
|
|
}
|
|
const expectedType = getExpectedOutputItemType(itemEvent);
|
|
if (output.type !== expectedType) {
|
|
throw new OpenAIError(`expected output item type '${expectedType}', got '${output.type}'`);
|
|
}
|
|
}
|
|
function getContent(content, contentIndex) {
|
|
validateArrayIndex(content, contentIndex, "content");
|
|
const part = content[contentIndex];
|
|
if (!part) {
|
|
throw new OpenAIError(`missing content at index ${contentIndex}`);
|
|
}
|
|
return part;
|
|
}
|
|
function getShellOutputContent(snapshot, output, commandIndex) {
|
|
const shellCall = snapshot.output.find((item) => item.type === "shell_call" && item.call_id === output.call_id);
|
|
if (shellCall) {
|
|
validateArrayIndex(shellCall.action.commands, commandIndex, "command");
|
|
} else {
|
|
validateArrayIndex(output.output, commandIndex, "content", true);
|
|
}
|
|
while (output.output.length <= commandIndex) {
|
|
output.output.push({
|
|
stdout: "",
|
|
stderr: "",
|
|
outcome: { type: "exit", exit_code: 0 }
|
|
});
|
|
}
|
|
return getContent(output.output, commandIndex);
|
|
}
|
|
function createSupportedResponseEventTypes(eventTypes) {
|
|
return new Set(eventTypes);
|
|
}
|
|
function assertNever3(_value) {
|
|
throw new OpenAIError("Unhandled response stream event: unknown");
|
|
}
|
|
function sanitizeResponseEvent(event) {
|
|
let descriptor;
|
|
try {
|
|
descriptor = Object.getOwnPropertyDescriptor(event, "type");
|
|
} catch {
|
|
return assertNever3(event);
|
|
}
|
|
const type = descriptor?.value;
|
|
if (
|
|
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate untrusted streamed item identifiers and discriminators before mutating the response snapshot.
|
|
typeof type !== "string" || !supportedResponseEventTypes.has(type)
|
|
) {
|
|
return assertNever3(event);
|
|
}
|
|
const stableValues = /* @__PURE__ */ new Map([["type", type]]);
|
|
const itemScoped = type === "response.output_item.added" || type === "response.output_item.done" || type === "response.content_part.added" || type === "response.content_part.done" || type === "response.shell_call_command.added" || type === "response.shell_call_command.delta" || type === "response.shell_call_command.done" || hasOwn(expectedOutputItemTypes, type);
|
|
if (itemScoped) {
|
|
try {
|
|
for (const field of responseEventRoutingFields) {
|
|
const routingDescriptor = Object.getOwnPropertyDescriptor(event, field);
|
|
stableValues.set(field, routingDescriptor ? event[field] : void 0);
|
|
}
|
|
if (type === "response.output_item.done") {
|
|
stableValues.set("item", structuredClone(event.item));
|
|
} else if (type === "response.content_part.added" || type === "response.content_part.done") {
|
|
stableValues.set("part", structuredClone(event.part));
|
|
}
|
|
} catch {
|
|
return assertNever3(event);
|
|
}
|
|
}
|
|
return new Proxy(event, {
|
|
get(target, property) {
|
|
return stableValues.has(property) ? stableValues.get(property) : Reflect.get(target, property, target);
|
|
}
|
|
});
|
|
}
|
|
function accumulateOutputItemEvent(event, snapshot, context) {
|
|
switch (event.type) {
|
|
case "response.output_item.added": {
|
|
validateArrayAppend(snapshot.output, event.output_index, "output");
|
|
const identityIndex = getResponseOutputIdentityIndex(context, snapshot);
|
|
const output = structuredClone(event.item);
|
|
const identities = getOutputItemIdentityKeys(output, event.type);
|
|
assertOutputItemIdentitiesAvailable(identityIndex.identities, identities);
|
|
if (output.type === "message") {
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
}
|
|
snapshot.output.push(output);
|
|
addOutputItemIdentities(identityIndex.identities, identities);
|
|
identityIndex.length = snapshot.output.length;
|
|
const text = getOutputText(context, output);
|
|
if (context.canonicalSnapshot === snapshot) {
|
|
context.outputTextIndex.append(text.length);
|
|
}
|
|
if (text) {
|
|
snapshot.output_text += text;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.output_item.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
const previousText = getOutputText(context, output);
|
|
const replacement = event.item;
|
|
if (output.type === "message" || replacement.type === "message") {
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
}
|
|
snapshot.output[event.output_index] = replacement;
|
|
const nextText = getOutputText(context, replacement);
|
|
if (context.canonicalSnapshot === snapshot) {
|
|
context.outputTextIndex.update(event.output_index, nextText.length);
|
|
}
|
|
updateOutputText(context, snapshot, event.output_index, previousText, nextText);
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateContentPartAddedEvent(event, snapshot, context) {
|
|
switch (event.type) {
|
|
case "response.content_part.added": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
const { type } = output;
|
|
const { part } = event;
|
|
if (type === "message" && part.type !== "reasoning_text") {
|
|
validateArrayAppend(output.content, event.content_index, "content");
|
|
const content = part;
|
|
if (content.type === "output_text") {
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
}
|
|
output.content.push(content);
|
|
if (content.type === "output_text") {
|
|
updateCachedOutputTextLength(context, output, event.output_index, "", content.text);
|
|
updateOutputText(context, snapshot, event.output_index, "", content.text, event.content_index);
|
|
}
|
|
} else if (type === "reasoning" && part.type === "reasoning_text") {
|
|
const content = output.content ?? [];
|
|
validateArrayAppend(content, event.content_index, "content");
|
|
if (!output.content) {
|
|
output.content = content;
|
|
}
|
|
content.push(part);
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateContentPartDoneEvent(event, snapshot, context) {
|
|
switch (event.type) {
|
|
case "response.content_part.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
const { part } = event;
|
|
if (output.type === "message" && part.type !== "reasoning_text") {
|
|
const content = getContent(output.content, event.content_index);
|
|
const previousText = content.type === "output_text" ? content.text : "";
|
|
const replacement = part;
|
|
if (content.type === "output_text" || replacement.type === "output_text") {
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
}
|
|
output.content[event.content_index] = replacement;
|
|
const nextText = replacement.type === "output_text" ? replacement.text : "";
|
|
updateCachedOutputTextLength(context, output, event.output_index, previousText, nextText);
|
|
updateOutputText(context, snapshot, event.output_index, previousText, nextText, event.content_index);
|
|
} else if (output.type === "reasoning" && part.type === "reasoning_text") {
|
|
const { content } = output;
|
|
if (!content) {
|
|
throw new OpenAIError(`missing content at index ${event.content_index}`);
|
|
}
|
|
getContent(content, event.content_index);
|
|
content[event.content_index] = part;
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateOutputTextEvent(event, snapshot, context) {
|
|
switch (event.type) {
|
|
case "response.output_text.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "message") {
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "output_text") {
|
|
throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
|
|
}
|
|
const previousText = content.text;
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
content.text = previousText + event.delta;
|
|
updateCachedOutputTextLength(context, output, event.output_index, previousText, content.text);
|
|
if (event.output_index === snapshot.output.length - 1 && event.content_index === output.content.length - 1) {
|
|
snapshot.output_text += event.delta;
|
|
} else {
|
|
updateOutputText(context, snapshot, event.output_index, previousText, content.text, event.content_index);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
case "response.output_text.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "message") {
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "output_text") {
|
|
throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
|
|
}
|
|
const previousText = content.text;
|
|
ensureCanonicalOutputText(context, snapshot);
|
|
content.text = event.text;
|
|
updateCachedOutputTextLength(context, output, event.output_index, previousText, event.text);
|
|
updateOutputText(context, snapshot, event.output_index, previousText, event.text, event.content_index);
|
|
}
|
|
return true;
|
|
}
|
|
case "response.output_text.annotation.added": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "message") {
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "output_text") {
|
|
throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
|
|
}
|
|
validateArrayIndex(content.annotations, event.annotation_index, "annotation", true);
|
|
content.annotations[event.annotation_index] = structuredClone(event.annotation);
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateRefusalAndArgumentsEvent(event, snapshot) {
|
|
switch (event.type) {
|
|
case "response.refusal.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "message") {
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "refusal") {
|
|
throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
|
|
}
|
|
content.refusal += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.refusal.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "message") {
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "refusal") {
|
|
throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
|
|
}
|
|
content.refusal = event.refusal;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.function_call_arguments.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "function_call") {
|
|
output.arguments += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.function_call_arguments.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "function_call") {
|
|
output.arguments = event.arguments;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.custom_tool_call_input.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "custom_tool_call") {
|
|
output.input += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.custom_tool_call_input.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "custom_tool_call") {
|
|
output.input = event.input;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.mcp_call_arguments.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "mcp_call") {
|
|
output.arguments += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.mcp_call_arguments.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "mcp_call") {
|
|
output.arguments = event.arguments;
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateShellEvent(event, snapshot) {
|
|
switch (event.type) {
|
|
case "response.shell_call_command.added":
|
|
case "response.shell_call_command.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "shell_call") {
|
|
const allowAppend = event.type === "response.shell_call_command.added";
|
|
validateArrayIndex(output.action.commands, event.command_index, "command", allowAppend);
|
|
output.action.commands[event.command_index] = event.command;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.shell_call_command.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "shell_call") {
|
|
validateArrayIndex(output.action.commands, event.command_index, "command");
|
|
output.action.commands[event.command_index] += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.shell_call_output_content.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "shell_call_output") {
|
|
const content = getShellOutputContent(snapshot, output, event.command_index);
|
|
content.stdout += event.delta.stdout ?? "";
|
|
content.stderr += event.delta.stderr ?? "";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.shell_call_output_content.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "shell_call_output") {
|
|
const content = getContent(event.output, 0);
|
|
getShellOutputContent(snapshot, output, event.command_index);
|
|
output.output[event.command_index] = structuredClone(content);
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateReasoningEvent(event, snapshot) {
|
|
switch (event.type) {
|
|
case "response.reasoning_text.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "reasoning") {
|
|
if (!output.content) {
|
|
throw new OpenAIError(`missing content at index ${event.content_index}`);
|
|
}
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "reasoning_text") {
|
|
throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
|
|
}
|
|
content.text += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.reasoning_text.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "reasoning") {
|
|
if (!output.content) {
|
|
throw new OpenAIError(`missing content at index ${event.content_index}`);
|
|
}
|
|
const content = getContent(output.content, event.content_index);
|
|
if (content.type !== "reasoning_text") {
|
|
throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
|
|
}
|
|
content.text = event.text;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.reasoning_summary_part.added": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "reasoning") {
|
|
validateArrayAppend(output.summary, event.summary_index, "content");
|
|
output.summary.push(structuredClone(event.part));
|
|
}
|
|
return true;
|
|
}
|
|
case "response.reasoning_summary_part.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "reasoning") {
|
|
getContent(output.summary, event.summary_index);
|
|
output.summary[event.summary_index] = structuredClone(event.part);
|
|
}
|
|
return true;
|
|
}
|
|
case "response.reasoning_summary_text.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "reasoning") {
|
|
const part = getContent(output.summary, event.summary_index);
|
|
part.text += event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.reasoning_summary_text.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "reasoning") {
|
|
const part = getContent(output.summary, event.summary_index);
|
|
part.text = event.text;
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateCodeInterpreterEvent(event, snapshot) {
|
|
switch (event.type) {
|
|
case "response.code_interpreter_call_code.delta": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "code_interpreter_call") {
|
|
output.code = (output.code ?? "") + event.delta;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.code_interpreter_call_code.done": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "code_interpreter_call") {
|
|
output.code = event.code;
|
|
}
|
|
return true;
|
|
}
|
|
case "response.code_interpreter_call.in_progress": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "code_interpreter_call") {
|
|
output.status = "in_progress";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.code_interpreter_call.interpreting": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "code_interpreter_call") {
|
|
output.status = "interpreting";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.code_interpreter_call.completed": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "code_interpreter_call") {
|
|
output.status = "completed";
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateSearchStatusEvent(event, snapshot) {
|
|
switch (event.type) {
|
|
case "response.file_search_call.in_progress": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "file_search_call") {
|
|
output.status = "in_progress";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.file_search_call.searching": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "file_search_call") {
|
|
output.status = "searching";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.file_search_call.completed": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "file_search_call") {
|
|
output.status = "completed";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.web_search_call.in_progress": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "web_search_call") {
|
|
output.status = "in_progress";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.web_search_call.searching": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "web_search_call") {
|
|
output.status = "searching";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.web_search_call.completed": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "web_search_call") {
|
|
output.status = "completed";
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function accumulateImageAndMcpStatusEvent(event, snapshot) {
|
|
switch (event.type) {
|
|
case "response.image_generation_call.in_progress": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "image_generation_call") {
|
|
output.status = "in_progress";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.image_generation_call.generating": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "image_generation_call") {
|
|
output.status = "generating";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.image_generation_call.completed": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "image_generation_call") {
|
|
output.status = "completed";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.mcp_call.in_progress": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "mcp_call") {
|
|
output.status = "in_progress";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.mcp_call.completed": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "mcp_call") {
|
|
output.status = "completed";
|
|
}
|
|
return true;
|
|
}
|
|
case "response.mcp_call.failed": {
|
|
const output = getOutput(snapshot, event.output_index);
|
|
if (output.type === "mcp_call") {
|
|
output.status = "failed";
|
|
}
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function isResponseLifecycleEvent(event) {
|
|
switch (event.type) {
|
|
case "response.created":
|
|
case "response.queued":
|
|
case "response.in_progress":
|
|
case "response.completed":
|
|
case "response.failed":
|
|
case "response.incomplete": {
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function isIgnoredResponseEvent(event) {
|
|
switch (event.type) {
|
|
case "response.audio.delta":
|
|
case "response.audio.done":
|
|
case "response.audio.transcript.delta":
|
|
case "response.audio.transcript.done":
|
|
case "response.compaction.compacting":
|
|
case "response.image_generation_call.partial_image":
|
|
case "response.mcp_list_tools.in_progress":
|
|
case "response.mcp_list_tools.completed":
|
|
case "response.mcp_list_tools.failed":
|
|
case "keepalive":
|
|
case "error": {
|
|
return true;
|
|
}
|
|
default: {
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
function createResponseContext() {
|
|
return createCanonicalResponseContext();
|
|
}
|
|
function accumulateResponseWithContext(event, snapshot, context, rejectInvalidShellTargets = false, onSanitizedEvent) {
|
|
const dispatchEvent = sanitizeResponseEvent(event);
|
|
if (onSanitizedEvent && dispatchEvent.type !== "keepalive") {
|
|
onSanitizedEvent(dispatchEvent);
|
|
}
|
|
if (!snapshot) {
|
|
if (dispatchEvent.type !== "response.created") {
|
|
throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${dispatchEvent.type}`);
|
|
}
|
|
return cloneValidatedResponse(context, dispatchEvent.response);
|
|
}
|
|
validateOutputItemIdentity(dispatchEvent, snapshot, rejectInvalidShellTargets);
|
|
if (accumulateOutputItemEvent(dispatchEvent, snapshot, context)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateContentPartAddedEvent(dispatchEvent, snapshot, context)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateContentPartDoneEvent(dispatchEvent, snapshot, context)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateOutputTextEvent(dispatchEvent, snapshot, context)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateRefusalAndArgumentsEvent(dispatchEvent, snapshot)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateShellEvent(dispatchEvent, snapshot)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateReasoningEvent(dispatchEvent, snapshot)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateCodeInterpreterEvent(dispatchEvent, snapshot)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateSearchStatusEvent(dispatchEvent, snapshot)) {
|
|
return snapshot;
|
|
}
|
|
if (accumulateImageAndMcpStatusEvent(dispatchEvent, snapshot)) {
|
|
return snapshot;
|
|
}
|
|
if (isResponseLifecycleEvent(dispatchEvent)) {
|
|
return cloneValidatedResponse(context, dispatchEvent.response);
|
|
}
|
|
if (isIgnoredResponseEvent(dispatchEvent)) {
|
|
return snapshot;
|
|
}
|
|
return assertNever3(dispatchEvent);
|
|
}
|
|
var responseOutputIdentityIndexes, expectedOutputItemTypes, supportedResponseEventTypes, responseEventRoutingFields;
|
|
var init_response_accumulator = __esm({
|
|
"node_modules/openai/internal/responses/response-accumulator.mjs"() {
|
|
init_error2();
|
|
init_utils2();
|
|
init_canonical_output_text();
|
|
responseOutputIdentityIndexes = /* @__PURE__ */ new WeakMap();
|
|
expectedOutputItemTypes = {
|
|
"response.output_text.delta": "message",
|
|
"response.output_text.done": "message",
|
|
"response.output_text.annotation.added": "message",
|
|
"response.refusal.delta": "message",
|
|
"response.refusal.done": "message",
|
|
"response.function_call_arguments.delta": "function_call",
|
|
"response.function_call_arguments.done": "function_call",
|
|
"response.custom_tool_call_input.delta": "custom_tool_call",
|
|
"response.custom_tool_call_input.done": "custom_tool_call",
|
|
"response.mcp_call_arguments.delta": "mcp_call",
|
|
"response.mcp_call_arguments.done": "mcp_call",
|
|
"response.mcp_call.in_progress": "mcp_call",
|
|
"response.mcp_call.completed": "mcp_call",
|
|
"response.mcp_call.failed": "mcp_call",
|
|
"response.shell_call_output_content.delta": "shell_call_output",
|
|
"response.shell_call_output_content.done": "shell_call_output",
|
|
"response.reasoning_text.delta": "reasoning",
|
|
"response.reasoning_text.done": "reasoning",
|
|
"response.reasoning_summary_part.added": "reasoning",
|
|
"response.reasoning_summary_part.done": "reasoning",
|
|
"response.reasoning_summary_text.delta": "reasoning",
|
|
"response.reasoning_summary_text.done": "reasoning",
|
|
"response.code_interpreter_call_code.delta": "code_interpreter_call",
|
|
"response.code_interpreter_call_code.done": "code_interpreter_call",
|
|
"response.code_interpreter_call.in_progress": "code_interpreter_call",
|
|
"response.code_interpreter_call.interpreting": "code_interpreter_call",
|
|
"response.code_interpreter_call.completed": "code_interpreter_call",
|
|
"response.file_search_call.in_progress": "file_search_call",
|
|
"response.file_search_call.searching": "file_search_call",
|
|
"response.file_search_call.completed": "file_search_call",
|
|
"response.web_search_call.in_progress": "web_search_call",
|
|
"response.web_search_call.searching": "web_search_call",
|
|
"response.web_search_call.completed": "web_search_call",
|
|
"response.image_generation_call.in_progress": "image_generation_call",
|
|
"response.image_generation_call.generating": "image_generation_call",
|
|
"response.image_generation_call.completed": "image_generation_call",
|
|
"response.image_generation_call.partial_image": "image_generation_call",
|
|
"response.mcp_list_tools.in_progress": "mcp_list_tools",
|
|
"response.mcp_list_tools.completed": "mcp_list_tools",
|
|
"response.mcp_list_tools.failed": "mcp_list_tools",
|
|
"response.compaction.compacting": "compaction"
|
|
};
|
|
supportedResponseEventTypes = createSupportedResponseEventTypes([
|
|
"response.output_item.added",
|
|
"response.output_item.done",
|
|
"response.content_part.added",
|
|
"response.content_part.done",
|
|
"response.output_text.delta",
|
|
"response.output_text.done",
|
|
"response.output_text.annotation.added",
|
|
"response.refusal.delta",
|
|
"response.refusal.done",
|
|
"response.function_call_arguments.delta",
|
|
"response.function_call_arguments.done",
|
|
"response.custom_tool_call_input.delta",
|
|
"response.custom_tool_call_input.done",
|
|
"response.mcp_call_arguments.delta",
|
|
"response.mcp_call_arguments.done",
|
|
"response.shell_call_command.added",
|
|
"response.shell_call_command.done",
|
|
"response.shell_call_command.delta",
|
|
"response.shell_call_output_content.delta",
|
|
"response.shell_call_output_content.done",
|
|
"response.reasoning_text.delta",
|
|
"response.reasoning_text.done",
|
|
"response.reasoning_summary_part.added",
|
|
"response.reasoning_summary_part.done",
|
|
"response.reasoning_summary_text.delta",
|
|
"response.reasoning_summary_text.done",
|
|
"response.code_interpreter_call_code.delta",
|
|
"response.code_interpreter_call_code.done",
|
|
"response.code_interpreter_call.in_progress",
|
|
"response.code_interpreter_call.interpreting",
|
|
"response.code_interpreter_call.completed",
|
|
"response.file_search_call.in_progress",
|
|
"response.file_search_call.searching",
|
|
"response.file_search_call.completed",
|
|
"response.web_search_call.in_progress",
|
|
"response.web_search_call.searching",
|
|
"response.web_search_call.completed",
|
|
"response.image_generation_call.in_progress",
|
|
"response.image_generation_call.generating",
|
|
"response.image_generation_call.completed",
|
|
"response.mcp_call.in_progress",
|
|
"response.mcp_call.completed",
|
|
"response.mcp_call.failed",
|
|
"response.created",
|
|
"response.queued",
|
|
"response.in_progress",
|
|
"response.completed",
|
|
"response.failed",
|
|
"response.incomplete",
|
|
"response.audio.delta",
|
|
"response.audio.done",
|
|
"response.audio.transcript.delta",
|
|
"response.audio.transcript.done",
|
|
"response.compaction.compacting",
|
|
"response.image_generation_call.partial_image",
|
|
"response.mcp_list_tools.in_progress",
|
|
"response.mcp_list_tools.completed",
|
|
"response.mcp_list_tools.failed",
|
|
"keepalive",
|
|
"error"
|
|
]);
|
|
responseEventRoutingFields = [
|
|
"item_id",
|
|
"output_index",
|
|
"content_index",
|
|
"annotation_index",
|
|
"command_index",
|
|
"summary_index"
|
|
];
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/responses/ResponseStream.mjs
|
|
function finalizeResponse(snapshot, params) {
|
|
return maybeParseResponse(snapshot, params);
|
|
}
|
|
var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_accumulatorContext, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, ResponseStream;
|
|
var init_ResponseStream = __esm({
|
|
"node_modules/openai/lib/responses/ResponseStream.mjs"() {
|
|
init_tslib();
|
|
init_error2();
|
|
init_EventStream();
|
|
init_response_accumulator();
|
|
init_ResponsesParser();
|
|
init_streaming2();
|
|
ResponseStream = class _ResponseStream extends EventStream2 {
|
|
/** Creates an unstarted stream, retaining request parameters for structured-output parsing. */
|
|
constructor(params) {
|
|
super();
|
|
_ResponseStream_instances.add(this);
|
|
_ResponseStream_params.set(this, void 0);
|
|
_ResponseStream_currentResponseSnapshot.set(this, void 0);
|
|
_ResponseStream_finalResponse.set(this, void 0);
|
|
_ResponseStream_accumulatorContext.set(this, createResponseContext());
|
|
__classPrivateFieldSet(this, _ResponseStream_params, params, "f");
|
|
}
|
|
/** Starts a new response stream or replays an existing response by its identifier. */
|
|
static createResponse(client, params, options) {
|
|
const runner = new _ResponseStream(params);
|
|
runner._run(() => runner._createOrRetrieveResponse(client, params, {
|
|
...options,
|
|
__metadata: { ...options?.__metadata, helperMethod: "stream" }
|
|
}));
|
|
return runner;
|
|
}
|
|
/** Consumes serialized response events from a readable stream in another runtime. */
|
|
static fromReadableStream(stream4) {
|
|
const runner = new _ResponseStream(null);
|
|
runner._run(() => runner._fromReadableStream(stream4));
|
|
return runner;
|
|
}
|
|
async _createOrRetrieveResponse(client, params, options) {
|
|
this._listenForAbort(options?.signal);
|
|
__classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
|
|
let stream4;
|
|
let starting_after = null;
|
|
if ("response_id" in params) {
|
|
stream4 = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true });
|
|
starting_after = params.starting_after ?? null;
|
|
} else {
|
|
stream4 = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
|
|
}
|
|
this._connected();
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
|
|
}
|
|
async _fromReadableStream(readableStream, options) {
|
|
this._listenForAbort(options?.signal);
|
|
__classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
|
|
this._connected();
|
|
const stream4 = Stream.fromReadableStream(readableStream, this.controller);
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, null);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw this._userAbortError();
|
|
}
|
|
return __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this);
|
|
}
|
|
/** Iterates over response events; stopping iteration early aborts the underlying request. */
|
|
[(_ResponseStream_params = /* @__PURE__ */ new WeakMap(), _ResponseStream_currentResponseSnapshot = /* @__PURE__ */ new WeakMap(), _ResponseStream_finalResponse = /* @__PURE__ */ new WeakMap(), _ResponseStream_accumulatorContext = /* @__PURE__ */ new WeakMap(), _ResponseStream_instances = /* @__PURE__ */ new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest2() {
|
|
if (this.ended) {
|
|
return;
|
|
}
|
|
__classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
|
|
__classPrivateFieldSet(this, _ResponseStream_accumulatorContext, createResponseContext(), "f");
|
|
}, _ResponseStream_addEvent = function _ResponseStream_addEvent2(event, starting_after) {
|
|
if (this.ended) {
|
|
return;
|
|
}
|
|
const maybeEmit = (name, event2) => {
|
|
if (starting_after == null || event2.sequence_number > starting_after) {
|
|
this._emit(name, event2);
|
|
}
|
|
};
|
|
if (event.type === "error") {
|
|
const error = (
|
|
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- An error event can contain malformed server data; validate its container before extracting error details.
|
|
"error" in event && typeof event.error === "object" && event.error !== null ? event.error : event
|
|
);
|
|
throw new APIError(void 0, error, event.message, void 0);
|
|
}
|
|
let dispatchEvent = event;
|
|
const response = accumulateResponseWithContext(event, __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"), __classPrivateFieldGet(this, _ResponseStream_accumulatorContext, "f"), true, (sanitizedEvent) => {
|
|
dispatchEvent = sanitizedEvent;
|
|
});
|
|
__classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, response, "f");
|
|
maybeEmit("event", event);
|
|
switch (dispatchEvent.type) {
|
|
case "response.output_text.delta": {
|
|
const output = response.output[dispatchEvent.output_index];
|
|
if (!output) {
|
|
throw new OpenAIError(`missing output at index ${dispatchEvent.output_index}`);
|
|
}
|
|
if (output.type === "message") {
|
|
const content = output.content[dispatchEvent.content_index];
|
|
if (!content) {
|
|
throw new OpenAIError(`missing content at index ${dispatchEvent.content_index}`);
|
|
}
|
|
if (content.type !== "output_text") {
|
|
throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
|
|
}
|
|
maybeEmit("response.output_text.delta", {
|
|
...dispatchEvent,
|
|
type: dispatchEvent.type,
|
|
item_id: dispatchEvent.item_id,
|
|
output_index: dispatchEvent.output_index,
|
|
content_index: dispatchEvent.content_index,
|
|
snapshot: content.text
|
|
});
|
|
}
|
|
break;
|
|
}
|
|
case "response.function_call_arguments.delta": {
|
|
const output = response.output[dispatchEvent.output_index];
|
|
if (!output) {
|
|
throw new OpenAIError(`missing output at index ${dispatchEvent.output_index}`);
|
|
}
|
|
if (output.type === "function_call") {
|
|
maybeEmit("response.function_call_arguments.delta", {
|
|
...dispatchEvent,
|
|
type: dispatchEvent.type,
|
|
item_id: dispatchEvent.item_id,
|
|
output_index: dispatchEvent.output_index,
|
|
snapshot: output.arguments
|
|
});
|
|
}
|
|
break;
|
|
}
|
|
default: {
|
|
maybeEmit(dispatchEvent.type, event);
|
|
break;
|
|
}
|
|
}
|
|
}, _ResponseStream_endRequest = function _ResponseStream_endRequest2() {
|
|
if (this.ended) {
|
|
throw new OpenAIError(`stream has ended, this shouldn't happen`);
|
|
}
|
|
const snapshot = __classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f");
|
|
if (!snapshot) {
|
|
throw new OpenAIError(`request ended without sending any events`);
|
|
}
|
|
__classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, void 0, "f");
|
|
__classPrivateFieldSet(this, _ResponseStream_accumulatorContext, createResponseContext(), "f");
|
|
const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet(this, _ResponseStream_params, "f"));
|
|
__classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f");
|
|
return parsedResponse;
|
|
}, Symbol.asyncIterator)]() {
|
|
return this._createIterator((push) => {
|
|
const onEvent = (event) => push(event);
|
|
this.on("event", onEvent);
|
|
return () => this.off("event", onEvent);
|
|
}, { onReturn: () => this.abort() });
|
|
}
|
|
/**
|
|
* Waits for the stream to end and returns its latest accumulated response.
|
|
*
|
|
* A clean end after at least one response event resolves even when the response is
|
|
* incomplete. Network errors, cancellation, and streams without a response reject.
|
|
*/
|
|
async finalResponse() {
|
|
await this.done();
|
|
const response = __classPrivateFieldGet(this, _ResponseStream_finalResponse, "f");
|
|
if (!response) {
|
|
throw new OpenAIError("stream ended without producing a Response");
|
|
}
|
|
return response;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/responses/input-items.mjs
|
|
var InputItems2;
|
|
var init_input_items2 = __esm({
|
|
"node_modules/openai/resources/responses/input-items.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_path();
|
|
InputItems2 = class extends APIResource {
|
|
/**
|
|
* Returns a list of input items for a given response.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const responseItem of client.responses.inputItems.list(
|
|
* 'response_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(responseID, query = {}, options) {
|
|
return this._client.getAPIList(path`/responses/${responseID}/input_items`, CursorPage, { query, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/responses/input-tokens.mjs
|
|
var InputTokens2;
|
|
var init_input_tokens2 = __esm({
|
|
"node_modules/openai/resources/responses/input-tokens.mjs"() {
|
|
init_resource();
|
|
InputTokens2 = class extends APIResource {
|
|
/**
|
|
* Returns input token counts of the request.
|
|
*
|
|
* Returns an object with `object` set to `response.input_tokens` and an
|
|
* `input_tokens` count.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.responses.inputTokens.count();
|
|
* ```
|
|
*/
|
|
count(body = {}, options) {
|
|
return this._client.post("/responses/input_tokens", {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/responses/responses.mjs
|
|
var Responses2;
|
|
var init_responses2 = __esm({
|
|
"node_modules/openai/resources/responses/responses.mjs"() {
|
|
init_ResponsesParser();
|
|
init_ResponseStream();
|
|
init_resource();
|
|
init_input_items2();
|
|
init_input_items2();
|
|
init_input_tokens2();
|
|
init_input_tokens2();
|
|
init_headers2();
|
|
init_path();
|
|
Responses2 = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.inputItems = new InputItems2(this._client);
|
|
this.inputTokens = new InputTokens2(this._client);
|
|
}
|
|
create(body, options) {
|
|
return this._client.post("/responses", {
|
|
body,
|
|
...options,
|
|
stream: body.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
})._thenUnwrap((rsp) => {
|
|
if ("object" in rsp && rsp.object === "response") {
|
|
addOutputText(rsp);
|
|
}
|
|
return rsp;
|
|
});
|
|
}
|
|
retrieve(responseID, query = {}, options) {
|
|
return this._client.get(path`/responses/${responseID}`, {
|
|
query,
|
|
...options,
|
|
stream: query?.stream ?? false,
|
|
__security: { bearerAuth: true }
|
|
})._thenUnwrap((rsp) => {
|
|
if ("object" in rsp && rsp.object === "response") {
|
|
addOutputText(rsp);
|
|
}
|
|
return rsp;
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a model response with the given ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* await client.responses.delete(
|
|
* 'resp_677efb5139a88190b512bc3fef8e535d',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(responseID, options) {
|
|
return this._client.delete(path`/responses/${responseID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "*/*" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
parse(body, options) {
|
|
return this._client.responses.create(body, options)._thenUnwrap((response) => parseResponse(response, body));
|
|
}
|
|
/**
|
|
* Creates a model response stream
|
|
*/
|
|
stream(body, options) {
|
|
return ResponseStream.createResponse(this._client, body, options);
|
|
}
|
|
/**
|
|
* Cancels a model response with the given ID. Only responses created with the
|
|
* `background` parameter set to `true` can be cancelled.
|
|
* [Learn more](https://developers.openai.com/api/docs/guides/background).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.responses.cancel(
|
|
* 'resp_677efb5139a88190b512bc3fef8e535d',
|
|
* );
|
|
* ```
|
|
*/
|
|
cancel(responseID, options) {
|
|
return this._client.post(path`/responses/${responseID}/cancel`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Compact a conversation. Returns a compacted response object.
|
|
*
|
|
* Learn when and how to compact long-running conversations in the
|
|
* [conversation state guide](https://developers.openai.com/api/docs/guides/conversation-state#managing-the-context-window).
|
|
* For ZDR-compatible compaction details, see
|
|
* [Compaction (advanced)](https://developers.openai.com/api/docs/guides/conversation-state#compaction-advanced).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const compactedResponse = await client.responses.compact({
|
|
* model: 'gpt-6-astra',
|
|
* });
|
|
* ```
|
|
*/
|
|
compact(body, options) {
|
|
return this._client.post("/responses/compact", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
Responses2.InputItems = InputItems2;
|
|
Responses2.InputTokens = InputTokens2;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/safety/alerts.mjs
|
|
var Alerts;
|
|
var init_alerts = __esm({
|
|
"node_modules/openai/resources/safety/alerts.mjs"() {
|
|
init_resource();
|
|
init_path();
|
|
Alerts = class extends APIResource {
|
|
/**
|
|
* Get a safety alert belonging to the authenticated API project.
|
|
*/
|
|
retrieve(id, options) {
|
|
return this._client.get(path`/safety/alerts/${id}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/safety/safety.mjs
|
|
var Safety;
|
|
var init_safety = __esm({
|
|
"node_modules/openai/resources/safety/safety.mjs"() {
|
|
init_resource();
|
|
init_alerts();
|
|
init_alerts();
|
|
Safety = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.alerts = new Alerts(this._client);
|
|
}
|
|
};
|
|
Safety.Alerts = Alerts;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/skills/content.mjs
|
|
var Content2;
|
|
var init_content2 = __esm({
|
|
"node_modules/openai/resources/skills/content.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
Content2 = class extends APIResource {
|
|
/**
|
|
* Download a skill zip bundle by its ID.
|
|
*/
|
|
retrieve(skillID, options) {
|
|
return this._client.get(path`/skills/${skillID}/content`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/skills/versions/content.mjs
|
|
var Content3;
|
|
var init_content3 = __esm({
|
|
"node_modules/openai/resources/skills/versions/content.mjs"() {
|
|
init_resource();
|
|
init_headers2();
|
|
init_path();
|
|
Content3 = class extends APIResource {
|
|
/**
|
|
* Download a skill version zip bundle.
|
|
*/
|
|
retrieve(version, params, options) {
|
|
const { skill_id } = params;
|
|
return this._client.get(path`/skills/${skill_id}/versions/${version}/content`, {
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/skills/versions/versions.mjs
|
|
var Versions;
|
|
var init_versions = __esm({
|
|
"node_modules/openai/resources/skills/versions/versions.mjs"() {
|
|
init_resource();
|
|
init_content3();
|
|
init_content3();
|
|
init_pagination();
|
|
init_uploads();
|
|
init_path();
|
|
Versions = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.content = new Content3(this._client);
|
|
}
|
|
/**
|
|
* Create a new immutable skill version.
|
|
*/
|
|
create(skillID, body = {}, options) {
|
|
return this._client.post(path`/skills/${skillID}/versions`, maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client, {
|
|
stripFilenames: false
|
|
}));
|
|
}
|
|
/**
|
|
* Get a specific skill version.
|
|
*/
|
|
retrieve(version, params, options) {
|
|
const { skill_id } = params;
|
|
return this._client.get(path`/skills/${skill_id}/versions/${version}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List skill versions for a skill.
|
|
*/
|
|
list(skillID, query = {}, options) {
|
|
return this._client.getAPIList(path`/skills/${skillID}/versions`, CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a skill version.
|
|
*/
|
|
delete(version, params, options) {
|
|
const { skill_id } = params;
|
|
return this._client.delete(path`/skills/${skill_id}/versions/${version}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Versions.Content = Content3;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/skills/skills.mjs
|
|
var Skills;
|
|
var init_skills = __esm({
|
|
"node_modules/openai/resources/skills/skills.mjs"() {
|
|
init_resource();
|
|
init_content2();
|
|
init_content2();
|
|
init_versions();
|
|
init_versions();
|
|
init_pagination();
|
|
init_uploads();
|
|
init_path();
|
|
Skills = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.content = new Content2(this._client);
|
|
this.versions = new Versions(this._client);
|
|
}
|
|
/**
|
|
* Create a new skill.
|
|
*/
|
|
create(body = {}, options) {
|
|
return this._client.post("/skills", maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client, {
|
|
stripFilenames: false
|
|
}));
|
|
}
|
|
/**
|
|
* Get a skill by its ID.
|
|
*/
|
|
retrieve(skillID, options) {
|
|
return this._client.get(path`/skills/${skillID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Update the default version pointer for a skill.
|
|
*/
|
|
update(skillID, body, options) {
|
|
return this._client.post(path`/skills/${skillID}`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* List all skills for the current project.
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/skills", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a skill by its ID.
|
|
*/
|
|
delete(skillID, options) {
|
|
return this._client.delete(path`/skills/${skillID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
Skills.Content = Content2;
|
|
Skills.Versions = Versions;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/uploads/parts.mjs
|
|
var Parts;
|
|
var init_parts = __esm({
|
|
"node_modules/openai/resources/uploads/parts.mjs"() {
|
|
init_resource();
|
|
init_uploads();
|
|
init_path();
|
|
Parts = class extends APIResource {
|
|
/**
|
|
* Adds a
|
|
* [Part](https://developers.openai.com/api/reference/resources/uploads/subresources/parts)
|
|
* to an [Upload](https://developers.openai.com/api/reference/resources/uploads)
|
|
* object. A Part represents a chunk of bytes from the file you are trying to
|
|
* upload.
|
|
*
|
|
* Each Part can be at most 64 MB, and you can add Parts until you hit the Upload
|
|
* maximum of 8 GB.
|
|
*
|
|
* It is possible to add multiple Parts in parallel. You can decide the intended
|
|
* order of the Parts when you
|
|
* [complete the Upload](https://developers.openai.com/api/reference/resources/uploads/methods/complete).
|
|
*/
|
|
create(uploadID, body, options) {
|
|
return this._client.post(path`/uploads/${uploadID}/parts`, multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/uploads/uploads.mjs
|
|
var Uploads;
|
|
var init_uploads3 = __esm({
|
|
"node_modules/openai/resources/uploads/uploads.mjs"() {
|
|
init_resource();
|
|
init_parts();
|
|
init_parts();
|
|
init_path();
|
|
Uploads = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.parts = new Parts(this._client);
|
|
}
|
|
/**
|
|
* Creates an intermediate
|
|
* [Upload](https://developers.openai.com/api/reference/resources/uploads) object
|
|
* that you can add
|
|
* [Parts](https://developers.openai.com/api/reference/resources/uploads/subresources/parts)
|
|
* to. Currently, an Upload can accept at most 8 GB in total and expires after an
|
|
* hour after you create it.
|
|
*
|
|
* Once you complete the Upload, we will create a
|
|
* [File](https://developers.openai.com/api/reference/resources/files) object that
|
|
* contains all the parts you uploaded. This File is usable in the rest of our
|
|
* platform as a regular File object.
|
|
*
|
|
* For certain `purpose` values, the correct `mime_type` must be specified. Please
|
|
* refer to documentation for the
|
|
* [supported MIME types for your use case](https://developers.openai.com/api/docs/guides/tools-file-search#supported-files).
|
|
*
|
|
* For guidance on the proper filename extensions for each purpose, please follow
|
|
* the documentation on
|
|
* [creating a File](https://developers.openai.com/api/reference/resources/files/methods/create).
|
|
*
|
|
* Returns the Upload object with status `pending`.
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/uploads", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Cancels the Upload. No Parts may be added after an Upload is cancelled.
|
|
*
|
|
* Returns the Upload object with status `cancelled`.
|
|
*/
|
|
cancel(uploadID, options) {
|
|
return this._client.post(path`/uploads/${uploadID}/cancel`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Completes the
|
|
* [Upload](https://developers.openai.com/api/reference/resources/uploads).
|
|
*
|
|
* Within the returned Upload object, there is a nested
|
|
* [File](https://developers.openai.com/api/reference/resources/files) object that
|
|
* is ready to use in the rest of the platform.
|
|
*
|
|
* You can specify the order of the Parts by passing in an ordered list of the Part
|
|
* IDs.
|
|
*
|
|
* The number of bytes uploaded upon completion must match the number of bytes
|
|
* initially specified when creating the Upload object. No Parts may be added after
|
|
* an Upload is completed. Returns the Upload object with status `completed`,
|
|
* including an additional `file` property containing the created usable File
|
|
* object.
|
|
*/
|
|
complete(uploadID, body, options) {
|
|
return this._client.post(path`/uploads/${uploadID}/complete`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
Uploads.Parts = Parts;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/vector-store-polling.mjs
|
|
function pollVectorStoreFile(resource, vectorStoreID, fileID, options) {
|
|
return pollWithResponse((headers) => resource.retrieve(fileID, { vector_store_id: vectorStoreID }, { ...options, headers }), ["in_progress"], ["failed", "cancelled", "completed"], options);
|
|
}
|
|
function pollVectorStoreFileBatch(resource, vectorStoreID, batchID, options) {
|
|
return pollWithResponse((headers) => resource.retrieve(batchID, { vector_store_id: vectorStoreID }, { ...options, headers }), ["in_progress"], ["failed", "cancelled", "completed"], options);
|
|
}
|
|
var init_vector_store_polling = __esm({
|
|
"node_modules/openai/lib/vector-store-polling.mjs"() {
|
|
init_polling();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/Util.mjs
|
|
var allSettledWithThrow;
|
|
var init_Util = __esm({
|
|
"node_modules/openai/lib/Util.mjs"() {
|
|
allSettledWithThrow = async (promises) => {
|
|
const results = await Promise.allSettled(promises);
|
|
const rejected = results.filter((result) => result.status === "rejected");
|
|
if (rejected.length) {
|
|
throw Object.defineProperty(new Error(`${rejected.length} promise(s) failed`), "rejections", {
|
|
configurable: true,
|
|
value: rejected.map(({ reason }) => reason),
|
|
writable: true
|
|
});
|
|
}
|
|
const values = [];
|
|
for (const result of results) {
|
|
if (result.status === "fulfilled") {
|
|
values.push(result.value);
|
|
}
|
|
}
|
|
return values;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/vector-store-upload.mjs
|
|
async function uploadAndPollVectorStoreFileBatch(resource, client, vectorStoreId, files, fileIds, options) {
|
|
if (files === null || files === void 0 || files.length === 0) {
|
|
throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");
|
|
}
|
|
const configuredConcurrency = options?.maxConcurrency ?? 5;
|
|
const concurrencyLimit = Math.min(configuredConcurrency, files.length);
|
|
if (concurrencyLimit === 0) {
|
|
throw new RangeError("maxConcurrency must be greater than 0");
|
|
}
|
|
const fileIterator = files.values();
|
|
const allFileIds = [...fileIds];
|
|
async function processFiles(iterator) {
|
|
for (const item of iterator) {
|
|
const fileObj = await client.files.create({ file: item, purpose: "assistants" }, options);
|
|
allFileIds.push(fileObj.id);
|
|
}
|
|
}
|
|
const workers = [];
|
|
workers.length = concurrencyLimit;
|
|
for (let index = 0; index < workers.length; index += 1) {
|
|
workers[index] = processFiles(fileIterator);
|
|
}
|
|
await allSettledWithThrow(workers);
|
|
return await resource.createAndPoll(vectorStoreId, { file_ids: allFileIds }, options);
|
|
}
|
|
var init_vector_store_upload = __esm({
|
|
"node_modules/openai/lib/vector-store-upload.mjs"() {
|
|
init_Util();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/vector-stores/file-batches.mjs
|
|
var FileBatches;
|
|
var init_file_batches = __esm({
|
|
"node_modules/openai/resources/vector-stores/file-batches.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_vector_store_polling();
|
|
init_vector_store_upload();
|
|
init_path();
|
|
FileBatches = class extends APIResource {
|
|
/**
|
|
* Create a vector store file batch.
|
|
*/
|
|
create(vectorStoreID, body, options) {
|
|
return this._client.post(path`/vector_stores/${vectorStoreID}/file_batches`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a vector store file batch.
|
|
*/
|
|
retrieve(batchID, params, options) {
|
|
const { vector_store_id } = params;
|
|
return this._client.get(path`/vector_stores/${vector_store_id}/file_batches/${batchID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Cancel a vector store file batch. This attempts to cancel the processing of
|
|
* files in this batch as soon as possible.
|
|
*/
|
|
cancel(batchID, params, options) {
|
|
const { vector_store_id } = params;
|
|
return this._client.post(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Create a vector store batch and poll until all files have been processed.
|
|
*/
|
|
async createAndPoll(vectorStoreId, body, options) {
|
|
const batch = await this.create(vectorStoreId, body, options);
|
|
return await this.poll(vectorStoreId, batch.id, options);
|
|
}
|
|
/**
|
|
* Returns a list of vector store files in a batch.
|
|
*/
|
|
listFiles(batchID, params, options) {
|
|
const { vector_store_id, ...query } = params;
|
|
return this._client.getAPIList(path`/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Wait for the given file batch to be processed.
|
|
*
|
|
* Note: this will return even if one of the files failed to process, you need to
|
|
* check batch.file_counts.failed_count to handle this case.
|
|
*/
|
|
async poll(vectorStoreID, batchID, options) {
|
|
return await pollVectorStoreFileBatch(this, vectorStoreID, batchID, options);
|
|
}
|
|
/**
|
|
* Uploads the given files concurrently and then creates a vector store file batch.
|
|
*
|
|
* The concurrency limit is configurable using the `maxConcurrency` parameter.
|
|
*/
|
|
async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
|
|
return await uploadAndPollVectorStoreFileBatch(this, this._client, vectorStoreId, files, fileIds, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/vector-stores/files.mjs
|
|
var Files4;
|
|
var init_files4 = __esm({
|
|
"node_modules/openai/resources/vector-stores/files.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_vector_store_polling();
|
|
init_path();
|
|
Files4 = class extends APIResource {
|
|
/**
|
|
* Create a vector store file by attaching a
|
|
* [File](https://developers.openai.com/api/reference/resources/files) to a
|
|
* [vector store](https://developers.openai.com/api/reference/resources/vector_stores).
|
|
*/
|
|
create(vectorStoreID, body, options) {
|
|
return this._client.post(path`/vector_stores/${vectorStoreID}/files`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a vector store file.
|
|
*/
|
|
retrieve(fileID, params, options) {
|
|
const { vector_store_id } = params;
|
|
return this._client.get(path`/vector_stores/${vector_store_id}/files/${fileID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Update attributes on a vector store file.
|
|
*/
|
|
update(fileID, params, options) {
|
|
const { vector_store_id, ...body } = params;
|
|
return this._client.post(path`/vector_stores/${vector_store_id}/files/${fileID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of vector store files.
|
|
*/
|
|
list(vectorStoreID, query = {}, options) {
|
|
return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/files`, CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a vector store file. This will remove the file from the vector store but
|
|
* the file itself will not be deleted. To delete the file, use the
|
|
* [delete file](https://developers.openai.com/api/reference/resources/files/methods/delete)
|
|
* endpoint.
|
|
*/
|
|
delete(fileID, params, options) {
|
|
const { vector_store_id } = params;
|
|
return this._client.delete(path`/vector_stores/${vector_store_id}/files/${fileID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Attach a file to the given vector store and wait for it to be processed.
|
|
*/
|
|
async createAndPoll(vectorStoreId, body, options) {
|
|
const file2 = await this.create(vectorStoreId, body, options);
|
|
return await this.poll(vectorStoreId, file2.id, options);
|
|
}
|
|
/**
|
|
* Wait for the vector store file to finish processing.
|
|
*
|
|
* Note: this will return even if the file failed to process, you need to check
|
|
* file.last_error and file.status to handle these cases
|
|
*/
|
|
async poll(vectorStoreID, fileID, options) {
|
|
return await pollVectorStoreFile(this, vectorStoreID, fileID, options);
|
|
}
|
|
/**
|
|
* Upload a file to the `files` API and then attach it to the given vector store.
|
|
*
|
|
* Note the file will be asynchronously processed (you can use the alternative
|
|
* polling helper method to wait for processing to complete).
|
|
*/
|
|
async upload(vectorStoreId, file2, options) {
|
|
const fileInfo = await this._client.files.create({ file: file2, purpose: "assistants" }, options);
|
|
return this.create(vectorStoreId, { file_id: fileInfo.id }, options);
|
|
}
|
|
/**
|
|
* Add a file to a vector store and poll until processing is complete.
|
|
*/
|
|
async uploadAndPoll(vectorStoreId, file2, options) {
|
|
const fileInfo = await this.upload(vectorStoreId, file2, options);
|
|
return await this.poll(vectorStoreId, fileInfo.id, options);
|
|
}
|
|
/**
|
|
* Retrieve the parsed contents of a vector store file.
|
|
*/
|
|
content(fileID, params, options) {
|
|
const { vector_store_id } = params;
|
|
return this._client.getAPIList(path`/vector_stores/${vector_store_id}/files/${fileID}/content`, Page, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/vector-stores/vector-stores.mjs
|
|
var VectorStores;
|
|
var init_vector_stores = __esm({
|
|
"node_modules/openai/resources/vector-stores/vector-stores.mjs"() {
|
|
init_resource();
|
|
init_file_batches();
|
|
init_file_batches();
|
|
init_files4();
|
|
init_files4();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_path();
|
|
VectorStores = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.files = new Files4(this._client);
|
|
this.fileBatches = new FileBatches(this._client);
|
|
}
|
|
/**
|
|
* Create a vector store.
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/vector_stores", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Retrieves a vector store.
|
|
*/
|
|
retrieve(vectorStoreID, options) {
|
|
return this._client.get(path`/vector_stores/${vectorStoreID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Modifies a vector store.
|
|
*/
|
|
update(vectorStoreID, body, options) {
|
|
return this._client.post(path`/vector_stores/${vectorStoreID}`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns a list of vector stores.
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/vector_stores", CursorPage, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Delete a vector store.
|
|
*/
|
|
delete(vectorStoreID, options) {
|
|
return this._client.delete(path`/vector_stores/${vectorStoreID}`, {
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Search a vector store for relevant chunks based on a query and file attributes
|
|
* filter.
|
|
*/
|
|
search(vectorStoreID, body, options) {
|
|
return this._client.getAPIList(path`/vector_stores/${vectorStoreID}/search`, Page, {
|
|
body,
|
|
method: "post",
|
|
...options,
|
|
headers: buildHeaders([{ "OpenAI-Beta": "assistants=v2" }, options?.headers]),
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
};
|
|
VectorStores.Files = Files4;
|
|
VectorStores.FileBatches = FileBatches;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/videos.mjs
|
|
var Videos;
|
|
var init_videos = __esm({
|
|
"node_modules/openai/resources/videos.mjs"() {
|
|
init_resource();
|
|
init_pagination();
|
|
init_headers2();
|
|
init_uploads();
|
|
init_path();
|
|
Videos = class extends APIResource {
|
|
/**
|
|
* Create a new video generation job from a prompt and optional reference assets.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/videos", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
/**
|
|
* Fetch the latest metadata for a generated video.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
retrieve(videoID, options) {
|
|
return this._client.get(path`/videos/${videoID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* List recently generated videos for the current project.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/videos", ConversationCursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Permanently delete a completed or failed video and its stored assets.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
delete(videoID, options) {
|
|
return this._client.delete(path`/videos/${videoID}`, { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Create a character from an uploaded video.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
createCharacter(body, options) {
|
|
return this._client.post("/videos/characters", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
/**
|
|
* Download the generated video bytes or a derived preview asset.
|
|
*
|
|
* Streams the rendered video content for the specified video job.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
downloadContent(videoID, query = {}, options) {
|
|
return this._client.get(path`/videos/${videoID}/content`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders([{ Accept: "application/binary" }, options?.headers]),
|
|
__security: { bearerAuth: true },
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
/**
|
|
* Create a new video generation job by editing a source video or existing
|
|
* generated video.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
edit(body, options) {
|
|
return this._client.post("/videos/edits", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
/**
|
|
* Create an extension of a completed video.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
extend(body, options) {
|
|
return this._client.post("/videos/extensions", multipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
/**
|
|
* Fetch a character.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
getCharacter(characterID, options) {
|
|
return this._client.get(path`/videos/characters/${characterID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Create a remix of a completed video using a refreshed prompt.
|
|
*
|
|
* @deprecated The Sora API is scheduled to permanently shut down on September 24, 2026.
|
|
*/
|
|
remix(videoID, body, options) {
|
|
return this._client.post(path`/videos/${videoID}/remix`, maybeMultipartFormRequestOptions({ body, ...options, __security: { bearerAuth: true } }, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/lib/webhook-signature.mjs
|
|
function webhookSignatureRequiresSigning(signatureHeader) {
|
|
return signatureHeader.split(" ", MAX_DIRECT_WEBHOOK_VERIFICATIONS + 1).length > MAX_DIRECT_WEBHOOK_VERIFICATIONS;
|
|
}
|
|
function* signatureCandidates(signatureHeader) {
|
|
let start = 0;
|
|
while (start <= signatureHeader.length) {
|
|
const separator = signatureHeader.indexOf(" ", start);
|
|
const candidate = signatureHeader.slice(start, separator === -1 ? void 0 : separator);
|
|
yield candidate.startsWith("v1,") ? candidate.slice(3) : candidate;
|
|
if (separator === -1) {
|
|
break;
|
|
}
|
|
start = separator + 1;
|
|
}
|
|
}
|
|
function decodeSignature(signature) {
|
|
try {
|
|
const signatureBytes = fromBase64(signature);
|
|
return signatureBytes.byteLength === SHA256_SIGNATURE_LENGTH ? signatureBytes : void 0;
|
|
} catch {
|
|
return void 0;
|
|
}
|
|
}
|
|
function firstValidLengthSignature(signatureHeader) {
|
|
for (const signature of signatureCandidates(signatureHeader)) {
|
|
const signatureBytes = decodeSignature(signature);
|
|
if (signatureBytes) {
|
|
return signatureBytes;
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
function selectMatchingSignature(signatureHeader, expectedSignature, firstSignature) {
|
|
let matchingSignature = firstSignature;
|
|
for (const signature of signatureCandidates(signatureHeader)) {
|
|
const signatureBytes = decodeSignature(signature);
|
|
if (!signatureBytes) {
|
|
continue;
|
|
}
|
|
let difference = 0;
|
|
for (const [index, byte] of signatureBytes.entries()) {
|
|
difference |= byte ^ (expectedSignature[index] ?? 0);
|
|
}
|
|
if (difference === 0) {
|
|
matchingSignature = signatureBytes;
|
|
}
|
|
}
|
|
return matchingSignature;
|
|
}
|
|
async function verifyWebhookSignature(payload, signatureHeader, timestamp2, webhookId, secret, tolerance) {
|
|
const timestampSeconds = Number.parseInt(timestamp2, 10);
|
|
if (Number.isNaN(timestampSeconds)) {
|
|
throw new InvalidWebhookSignatureError("Invalid webhook timestamp format");
|
|
}
|
|
const nowSeconds = Math.floor(Date.now() / 1e3);
|
|
if (nowSeconds - timestampSeconds > tolerance) {
|
|
throw new InvalidWebhookSignatureError("Webhook timestamp is too old");
|
|
}
|
|
if (timestampSeconds > nowSeconds + tolerance) {
|
|
throw new InvalidWebhookSignatureError("Webhook timestamp is too new");
|
|
}
|
|
const useBoundedVerification = webhookSignatureRequiresSigning(signatureHeader);
|
|
const firstSignature = useBoundedVerification ? firstValidLengthSignature(signatureHeader) : void 0;
|
|
if (useBoundedVerification && !firstSignature) {
|
|
throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
|
|
}
|
|
const decodedSecret = Uint8Array.from(secret.startsWith("whsec_") ? fromBase64(secret.slice("whsec_".length)) : encodeUTF8(secret));
|
|
const signedPayload = webhookId ? `${webhookId}.${timestamp2}.${payload}` : `${timestamp2}.${payload}`;
|
|
const signedPayloadBytes = Uint8Array.from(encodeUTF8(signedPayload));
|
|
const key = await crypto.subtle.importKey("raw", decodedSecret, { name: "HMAC", hash: "SHA-256" }, false, useBoundedVerification ? ["sign", "verify"] : ["verify"]);
|
|
if (useBoundedVerification && firstSignature) {
|
|
const expectedSignature = new Uint8Array(await crypto.subtle.sign("HMAC", key, signedPayloadBytes));
|
|
const signatureToVerify = selectMatchingSignature(signatureHeader, expectedSignature, firstSignature);
|
|
try {
|
|
if (await crypto.subtle.verify("HMAC", key, Uint8Array.from(signatureToVerify), signedPayloadBytes)) {
|
|
return;
|
|
}
|
|
} catch {
|
|
}
|
|
throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
|
|
}
|
|
for (const signature of signatureCandidates(signatureHeader)) {
|
|
try {
|
|
const signatureBytes = Uint8Array.from(fromBase64(signature));
|
|
const isValid = await crypto.subtle.verify("HMAC", key, signatureBytes, signedPayloadBytes);
|
|
if (isValid) {
|
|
return;
|
|
}
|
|
} catch {
|
|
}
|
|
}
|
|
throw new InvalidWebhookSignatureError("The given webhook signature does not match the expected signature");
|
|
}
|
|
var MAX_DIRECT_WEBHOOK_VERIFICATIONS, SHA256_SIGNATURE_LENGTH;
|
|
var init_webhook_signature = __esm({
|
|
"node_modules/openai/lib/webhook-signature.mjs"() {
|
|
init_error2();
|
|
init_base64();
|
|
init_bytes();
|
|
MAX_DIRECT_WEBHOOK_VERIFICATIONS = 32;
|
|
SHA256_SIGNATURE_LENGTH = 32;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/webhooks/event-types.mjs
|
|
var EventTypes;
|
|
var init_event_types = __esm({
|
|
"node_modules/openai/resources/webhooks/event-types.mjs"() {
|
|
init_resource();
|
|
EventTypes = class extends APIResource {
|
|
/**
|
|
* Returns webhook event types visible to the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const webhookEventTypeList =
|
|
* await client.webhooks.eventTypes.list();
|
|
* ```
|
|
*/
|
|
list(options) {
|
|
return this._client.get("/webhook_event_types", { ...options, __security: { bearerAuth: true } });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/webhooks/webhooks.mjs
|
|
var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader, Webhooks;
|
|
var init_webhooks = __esm({
|
|
"node_modules/openai/resources/webhooks/webhooks.mjs"() {
|
|
init_tslib();
|
|
init_resource();
|
|
init_headers2();
|
|
init_webhook_signature();
|
|
init_event_types();
|
|
init_event_types();
|
|
init_pagination();
|
|
init_path();
|
|
Webhooks = class extends APIResource {
|
|
constructor() {
|
|
super(...arguments);
|
|
_Webhooks_instances.add(this);
|
|
this.eventTypes = new EventTypes(this._client);
|
|
}
|
|
/**
|
|
* Creates a webhook endpoint for the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const webhookEndpointWithSecret =
|
|
* await client.webhooks.create({
|
|
* event_types: ['batch.completed'],
|
|
* name: 'x',
|
|
* url: 'https://',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/webhook_endpoints", { body, ...options, __security: { bearerAuth: true } });
|
|
}
|
|
/**
|
|
* Retrieves a webhook endpoint for the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const webhookEndpoint = await client.webhooks.retrieve(
|
|
* 'whe_123',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(webhookEndpointID, options) {
|
|
return this._client.get(path`/webhook_endpoints/${webhookEndpointID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Updates a webhook endpoint for the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const webhookEndpoint = await client.webhooks.update('whe_123');
|
|
* ```
|
|
*/
|
|
update(webhookEndpointID, body = {}, options) {
|
|
return this._client.post(path`/webhook_endpoints/${webhookEndpointID}`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Returns webhook endpoints for the authenticated project in newest-first order.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const webhookEndpoint of client.webhooks.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/webhook_endpoints", CursorPage, {
|
|
query,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Deletes a webhook endpoint for the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const deletedWebhookEndpoint = await client.webhooks.delete(
|
|
* 'whe_123',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(webhookEndpointID, options) {
|
|
return this._client.delete(path`/webhook_endpoints/${webhookEndpointID}`, {
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Rotates the signing secret for a webhook endpoint in the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const webhookEndpointWithSecret =
|
|
* await client.webhooks.rotateSecret('whe_123');
|
|
* ```
|
|
*/
|
|
rotateSecret(webhookEndpointID, body = {}, options) {
|
|
return this._client.post(path`/webhook_endpoints/${webhookEndpointID}/rotate_secret`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Sends a sample event to a webhook endpoint for the authenticated project.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const webhookEndpointTestResult =
|
|
* await client.webhooks.test('whe_123', {
|
|
* event_type: 'batch.completed',
|
|
* });
|
|
* ```
|
|
*/
|
|
test(webhookEndpointID, body, options) {
|
|
return this._client.post(path`/webhook_endpoints/${webhookEndpointID}/test`, {
|
|
body,
|
|
...options,
|
|
__security: { bearerAuth: true }
|
|
});
|
|
}
|
|
/**
|
|
* Validates that the given payload was sent by OpenAI and parses the payload.
|
|
*/
|
|
async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
|
|
await this.verifySignature(payload, headers, secret, tolerance);
|
|
return JSON.parse(payload);
|
|
}
|
|
/**
|
|
* Validates whether or not the webhook payload was sent by OpenAI.
|
|
*
|
|
* An error will be raised if the webhook payload was not sent by OpenAI.
|
|
*
|
|
* @param payload - The webhook payload
|
|
* @param headers - The webhook headers
|
|
* @param secret - The webhook secret (optional, will use client secret if not provided)
|
|
* @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes)
|
|
*/
|
|
async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) {
|
|
if (typeof crypto === "undefined" || typeof crypto.subtle?.importKey !== "function" || typeof crypto.subtle.verify !== "function") {
|
|
throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
|
|
}
|
|
__classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret);
|
|
const headersObj = buildHeaders([headers]).values;
|
|
const signatureHeader = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-signature");
|
|
const timestamp2 = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-timestamp");
|
|
const webhookId = __classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, "webhook-id");
|
|
if (webhookSignatureRequiresSigning(signatureHeader) && typeof crypto.subtle.sign !== "function") {
|
|
throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");
|
|
}
|
|
return await verifyWebhookSignature(payload, signatureHeader, timestamp2, webhookId, secret, tolerance);
|
|
}
|
|
};
|
|
_Webhooks_instances = /* @__PURE__ */ new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret2(secret) {
|
|
if (typeof secret !== "string" || secret.length === 0) {
|
|
throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`);
|
|
}
|
|
}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader2(headers, name) {
|
|
if (!headers) {
|
|
throw new Error(`Headers are required`);
|
|
}
|
|
const value = headers.get(name);
|
|
if (value === null || value === void 0) {
|
|
throw new Error(`Missing required header: ${name}`);
|
|
}
|
|
return value;
|
|
};
|
|
Webhooks.EventTypes = EventTypes;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/resources/index.mjs
|
|
var init_resources = __esm({
|
|
"node_modules/openai/resources/index.mjs"() {
|
|
init_chat2();
|
|
init_shared();
|
|
init_admin();
|
|
init_audio();
|
|
init_batches();
|
|
init_beta();
|
|
init_completions3();
|
|
init_containers();
|
|
init_content_provenance_checks();
|
|
init_conversations();
|
|
init_embeddings2();
|
|
init_evals();
|
|
init_files3();
|
|
init_fine_tuning();
|
|
init_graders2();
|
|
init_images();
|
|
init_live();
|
|
init_models2();
|
|
init_moderations();
|
|
init_realtime2();
|
|
init_responses2();
|
|
init_safety();
|
|
init_skills();
|
|
init_uploads3();
|
|
init_vector_stores();
|
|
init_videos();
|
|
init_webhooks();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/realtime-credentials.mjs
|
|
async function resolveRealtimeAPIKey(client) {
|
|
let apiKey;
|
|
const isProvider = await client._callApiKey((resolved) => {
|
|
apiKey = resolved;
|
|
});
|
|
return { apiKey: apiKey === void 0 ? client.apiKey : apiKey, isProvider };
|
|
}
|
|
var init_realtime_credentials = __esm({
|
|
"node_modules/openai/internal/realtime-credentials.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/provider.mjs
|
|
function configureProvider(provider2) {
|
|
const definition = providerDefinitions.get(provider2);
|
|
if (!definition) {
|
|
throw new Error("Invalid provider. Providers must be created with createProvider().");
|
|
}
|
|
return definition.configure();
|
|
}
|
|
var providerDefinitionsKey, providerGlobal, existingProviderDefinitions, providerDefinitions;
|
|
var init_provider = __esm({
|
|
"node_modules/openai/internal/provider.mjs"() {
|
|
providerDefinitionsKey = /* @__PURE__ */ Symbol.for("openai.node.providerDefinitions.v1");
|
|
providerGlobal = globalThis;
|
|
existingProviderDefinitions = providerGlobal[providerDefinitionsKey];
|
|
providerDefinitions = existingProviderDefinitions ?? /* @__PURE__ */ new WeakMap();
|
|
if (!existingProviderDefinitions) {
|
|
Object.defineProperty(providerGlobal, providerDefinitionsKey, { value: providerDefinitions });
|
|
}
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/client.mjs
|
|
function isRunningInBrowserOrBrowserWorker() {
|
|
if (isRunningInBrowser())
|
|
return true;
|
|
const scope = globalThis;
|
|
return typeof scope.WorkerGlobalScope === "function" && scope instanceof scope.WorkerGlobalScope && typeof scope.WorkerNavigator === "function" && scope.navigator instanceof scope.WorkerNavigator && typeof scope.navigator?.userAgent === "string" && scope.navigator.userAgent !== "Cloudflare-Workers" && scope.process?.versions?.node === void 0 && scope.Deno === void 0 && scope.Bun === void 0 && scope.EdgeRuntime === void 0 && scope.WebSocketPair === void 0;
|
|
}
|
|
function createRequestController(callerSignal, originalSignal) {
|
|
const controller = new AbortController();
|
|
if (!callerSignal)
|
|
return controller;
|
|
const nativeAbortSignal = globalThis.AbortSignal;
|
|
if (typeof nativeAbortSignal?.any !== "function" || !(callerSignal instanceof nativeAbortSignal)) {
|
|
return controller;
|
|
}
|
|
try {
|
|
const signals = [controller.signal, callerSignal];
|
|
if (originalSignal && originalSignal !== callerSignal) {
|
|
signals.push(originalSignal);
|
|
}
|
|
const composed = nativeAbortSignal.any(signals);
|
|
Object.defineProperty(controller, "signal", { value: composed, configurable: true });
|
|
composedCallerSignals.set(controller, callerSignal);
|
|
} catch {
|
|
}
|
|
return controller;
|
|
}
|
|
function getConnectionErrorMessage(error) {
|
|
if (isUndiciDispatcherVersionMismatchError(error)) {
|
|
return `Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`;
|
|
}
|
|
return void 0;
|
|
}
|
|
function isUndiciDispatcherVersionMismatchError(error) {
|
|
let current = error;
|
|
for (let i = 0; i < 8 && current && typeof current === "object"; i++) {
|
|
const err = current;
|
|
if (err.code === "UND_ERR_INVALID_ARG" && typeof err.message === "string" && err.message.includes("invalid onRequestStart method")) {
|
|
return true;
|
|
}
|
|
current = err.cause;
|
|
}
|
|
return false;
|
|
}
|
|
var _OpenAI_instances, _a3, _OpenAI_encoder, _OpenAI_x509Authentication, _OpenAI_x509Credential, _OpenAI_x509Fetch, _OpenAI_explicitDataResidency, _OpenAI_responseAttempts, _OpenAI_baseURLOverridden, WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER, inheritedDataResidencySelection, OpenAI, composedCallerSignals;
|
|
var init_client = __esm({
|
|
"node_modules/openai/client.mjs"() {
|
|
init_tslib();
|
|
init_uuid();
|
|
init_values();
|
|
init_sleep();
|
|
init_abort2();
|
|
init_errors();
|
|
init_parse();
|
|
init_detect_platform();
|
|
init_shims();
|
|
init_request_options();
|
|
init_query();
|
|
init_version2();
|
|
init_data_residency();
|
|
init_error();
|
|
init_pagination();
|
|
init_workload_identity_auth();
|
|
init_x509_api_origin();
|
|
init_x509_workload_identity_auth();
|
|
init_x509_credential_options();
|
|
init_x509_transport_state();
|
|
init_error();
|
|
init_uploads2();
|
|
init_resources();
|
|
init_api_promise();
|
|
init_realtime_credentials();
|
|
init_batches();
|
|
init_completions3();
|
|
init_content_provenance_checks();
|
|
init_embeddings2();
|
|
init_files3();
|
|
init_images();
|
|
init_models2();
|
|
init_moderations();
|
|
init_videos();
|
|
init_admin();
|
|
init_audio();
|
|
init_beta();
|
|
init_chat();
|
|
init_containers();
|
|
init_conversations();
|
|
init_evals();
|
|
init_fine_tuning();
|
|
init_graders2();
|
|
init_live();
|
|
init_realtime2();
|
|
init_responses2();
|
|
init_safety();
|
|
init_skills();
|
|
init_uploads3();
|
|
init_vector_stores();
|
|
init_webhooks();
|
|
init_detect_platform();
|
|
init_headers2();
|
|
init_provider();
|
|
init_env();
|
|
init_log();
|
|
init_values();
|
|
WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER = "workload-identity-auth";
|
|
inheritedDataResidencySelection = /* @__PURE__ */ Symbol("inheritedDataResidencySelection");
|
|
OpenAI = class {
|
|
/**
|
|
* API Client for interfacing with the OpenAI API.
|
|
*
|
|
* @param {string | null | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? null]
|
|
* @param {string | null | undefined} [opts.adminAPIKey=process.env['OPENAI_ADMIN_KEY'] ?? null]
|
|
* @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
|
|
* @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
|
|
* @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]
|
|
* @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
|
|
* @param {Provider} [opts.provider] - Configure a third-party API provider. Mutually exclusive with top-level authentication and base URL options.
|
|
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
|
|
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
|
|
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
|
|
*/
|
|
constructor(clientOptions = {}) {
|
|
_OpenAI_instances.add(this);
|
|
_OpenAI_encoder.set(this, void 0);
|
|
_OpenAI_x509Authentication.set(this, void 0);
|
|
_OpenAI_x509Credential.set(this, void 0);
|
|
_OpenAI_x509Fetch.set(this, void 0);
|
|
_OpenAI_explicitDataResidency.set(this, false);
|
|
_OpenAI_responseAttempts.set(this, /* @__PURE__ */ new WeakMap());
|
|
this.completions = new Completions2(this);
|
|
this.chat = new Chat(this);
|
|
this.embeddings = new Embeddings(this);
|
|
this.files = new Files3(this);
|
|
this.images = new Images(this);
|
|
this.contentProvenanceChecks = new ContentProvenanceChecks(this);
|
|
this.audio = new Audio(this);
|
|
this.moderations = new Moderations(this);
|
|
this.models = new Models(this);
|
|
this.fineTuning = new FineTuning(this);
|
|
this.graders = new Graders2(this);
|
|
this.vectorStores = new VectorStores(this);
|
|
this.safety = new Safety(this);
|
|
this.webhooks = new Webhooks(this);
|
|
this.beta = new Beta(this);
|
|
this.batches = new Batches(this);
|
|
this.uploads = new Uploads(this);
|
|
this.admin = new Admin(this);
|
|
this.responses = new Responses2(this);
|
|
this.live = new Live(this);
|
|
this.realtime = new Realtime2(this);
|
|
this.conversations = new Conversations(this);
|
|
this.evals = new Evals(this);
|
|
this.containers = new Containers(this);
|
|
this.skills = new Skills(this);
|
|
this.videos = new Videos(this);
|
|
const { credential, options: normalizedOptions } = normalizeX509CredentialOptions(clientOptions);
|
|
clientOptions = normalizedOptions;
|
|
const residencyBaseURL = resolveDataResidency(clientOptions);
|
|
const provider2 = clientOptions.provider;
|
|
const { baseURL = provider2 ? null : readEnv("OPENAI_BASE_URL"), dataResidency: _dataResidency, [inheritedDataResidencySelection]: inheritedResidencySelection = false, apiKey = provider2 ? null : readEnv("OPENAI_API_KEY") ?? null, adminAPIKey = provider2 ? null : readEnv("OPENAI_ADMIN_KEY") ?? null, organization = provider2 ? null : readEnv("OPENAI_ORG_ID") ?? null, project = provider2 ? null : readEnv("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, x509Transport, credential: _credential, ...opts } = clientOptions;
|
|
if (provider2) {
|
|
const conflictingOptions = ["apiKey", "adminAPIKey", "workloadIdentity", "x509Transport", "baseURL", "dataResidency"].filter((key) => (key === "workloadIdentity" ? workloadIdentity : clientOptions[key]) != null);
|
|
if (conflictingOptions.length) {
|
|
throw new OpenAIError(`The \`provider\` option cannot be used with ${conflictingOptions.map((key) => `\`${key}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`);
|
|
}
|
|
}
|
|
const identity = isX509WorkloadIdentity(workloadIdentity) ? { x509: workloadIdentity, legacy: void 0 } : { x509: void 0, legacy: workloadIdentity };
|
|
const x509Identity = identity.x509;
|
|
const usesX509Identity = x509Identity !== void 0;
|
|
const providerRuntime = provider2 ? configureProvider(provider2) : void 0;
|
|
const options = {
|
|
apiKey,
|
|
adminAPIKey,
|
|
organization,
|
|
project,
|
|
webhookSecret,
|
|
workloadIdentity,
|
|
x509Transport,
|
|
provider: provider2,
|
|
...opts,
|
|
baseURL: providerRuntime?.baseURL ?? residencyBaseURL ?? (baseURL || (usesX509Identity ? X509_API_BASE_URL : `https://api.openai.com/v1`))
|
|
};
|
|
if (x509Transport && !usesX509Identity) {
|
|
throw new OpenAIError("An X.509 transport requires an X.509 workload identity.");
|
|
}
|
|
if (usesX509Identity) {
|
|
if (residencyBaseURL !== void 0 || inheritedResidencySelection) {
|
|
throw new OpenAIError("X.509 workload identity does not support data residency selection.");
|
|
}
|
|
if (clientOptions.fetch !== void 0) {
|
|
throw new OpenAIError("X.509 workload identity does not support a custom fetch implementation.");
|
|
}
|
|
assertX509APIOrigin(options.baseURL);
|
|
assertX509RequestOptions(options.fetchOptions);
|
|
if (this.fetchWithAuth !== _a3.prototype.fetchWithAuth || this.fetchWithTimeout !== _a3.prototype.fetchWithTimeout) {
|
|
throw new OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.");
|
|
}
|
|
}
|
|
if (apiKey && workloadIdentity) {
|
|
throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");
|
|
}
|
|
if (!providerRuntime && !apiKey && !adminAPIKey && !workloadIdentity) {
|
|
throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");
|
|
}
|
|
if (!options.dangerouslyAllowBrowser && isRunningInBrowserOrBrowserWorker()) {
|
|
throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
|
|
}
|
|
this.baseURL = options.baseURL;
|
|
__classPrivateFieldSet(this, _OpenAI_explicitDataResidency, residencyBaseURL !== void 0 || inheritedResidencySelection, "f");
|
|
this.timeout = options.timeout ?? _a3.DEFAULT_TIMEOUT;
|
|
this.logger = options.logger ?? console;
|
|
const defaultLogLevel2 = "warn";
|
|
this.logLevel = defaultLogLevel2;
|
|
this.logLevel = parseLogLevel(options.logLevel, "ClientOptions.logLevel", this) ?? parseLogLevel(readEnv("OPENAI_LOG"), "process.env['OPENAI_LOG']", this) ?? defaultLogLevel2;
|
|
this.fetchOptions = options.fetchOptions;
|
|
this.maxRetries = options.maxRetries ?? 2;
|
|
this.fetch = options.fetch ?? getDefaultFetch();
|
|
__classPrivateFieldSet(this, _OpenAI_encoder, FallbackEncoder, "f");
|
|
const customHeadersEnv = provider2 || credential ? void 0 : readEnv("OPENAI_CUSTOM_HEADERS");
|
|
if (customHeadersEnv) {
|
|
const parsed = {};
|
|
for (const line of customHeadersEnv.split("\n")) {
|
|
const colon = line.indexOf(":");
|
|
if (colon >= 0) {
|
|
parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
|
|
}
|
|
}
|
|
options.defaultHeaders = buildHeaders([parsed, options.defaultHeaders]);
|
|
}
|
|
this._options = options;
|
|
this._provider = providerRuntime;
|
|
if (x509Identity) {
|
|
const authentication = new X509WorkloadIdentityAuth(x509Identity, x509Transport, organization, project);
|
|
this._workloadIdentityAuth = authentication;
|
|
__classPrivateFieldSet(this, _OpenAI_x509Authentication, authentication, "f");
|
|
__classPrivateFieldSet(this, _OpenAI_x509Credential, credential, "f");
|
|
__classPrivateFieldSet(this, _OpenAI_x509Fetch, authentication.fetch(), "f");
|
|
this.fetch = __classPrivateFieldGet(this, _OpenAI_x509Fetch, "f");
|
|
markApprovedX509Client2(this);
|
|
} else if (identity.legacy) {
|
|
this._workloadIdentityAuth = new WorkloadIdentityAuth(identity.legacy, this.fetch);
|
|
}
|
|
this.apiKey = typeof apiKey === "string" ? apiKey : null;
|
|
this.adminAPIKey = adminAPIKey;
|
|
this.organization = organization;
|
|
this.project = project;
|
|
this.webhookSecret = webhookSecret;
|
|
}
|
|
/**
|
|
* Create a new client instance re-using the same options given to the current client with optional overriding.
|
|
*/
|
|
withOptions(options) {
|
|
const residencyBaseURL = resolveDataResidency(options);
|
|
const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
|
|
const inheritedOptions = {
|
|
...this._options,
|
|
baseURL: this.baseURL,
|
|
maxRetries: this.maxRetries,
|
|
timeout: this.timeout,
|
|
logger: this.logger,
|
|
logLevel: this.logLevel,
|
|
fetch: __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ? void 0 : this.fetch,
|
|
fetchOptions: this.fetchOptions,
|
|
apiKey: this._options.apiKey,
|
|
adminAPIKey: this.adminAPIKey,
|
|
workloadIdentity: x509Authentication?.identitySnapshot() ?? this._options.workloadIdentity,
|
|
x509Transport: this._options.x509Transport,
|
|
organization: this.organization,
|
|
project: this.project,
|
|
webhookSecret: this.webhookSecret
|
|
};
|
|
const { credential, provider: provider2 } = prepareX509ClientClone(inheritedOptions, options, __classPrivateFieldGet(this, _OpenAI_x509Credential, "f"), x509Authentication !== void 0);
|
|
if (residencyBaseURL !== void 0) {
|
|
delete inheritedOptions.baseURL;
|
|
}
|
|
const clientOptions = {
|
|
...inheritedOptions,
|
|
...options,
|
|
credential,
|
|
provider: provider2,
|
|
[inheritedDataResidencySelection]: __classPrivateFieldGet(this, _OpenAI_explicitDataResidency, "f") && residencyBaseURL === void 0 && !hasOwn(options, "baseURL") && options.credential === void 0 && !provider2
|
|
};
|
|
const client = new this.constructor(clientOptions);
|
|
if (provider2 && new URL(client.baseURL).origin !== new URL(this.baseURL).origin) {
|
|
Object.assign(client._options, {
|
|
defaultHeaders: options.defaultHeaders,
|
|
defaultQuery: options.defaultQuery,
|
|
fetchOptions: options.fetchOptions,
|
|
fetch: options.fetch
|
|
});
|
|
client.fetchOptions = options.fetchOptions;
|
|
client.fetch = options.fetch ?? getDefaultFetch();
|
|
client.organization = options.organization ?? null;
|
|
client.project = options.project ?? null;
|
|
}
|
|
if (__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") && __classPrivateFieldGet(client, _OpenAI_x509Authentication, "f") && this.baseURL === client.baseURL && __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f").matches(__classPrivateFieldGet(client, _OpenAI_x509Authentication, "f"))) {
|
|
client._workloadIdentityAuth = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
|
|
__classPrivateFieldSet(client, _OpenAI_x509Authentication, __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f"), "f");
|
|
__classPrivateFieldSet(client, _OpenAI_x509Fetch, __classPrivateFieldGet(this, _OpenAI_x509Fetch, "f"), "f");
|
|
}
|
|
return client;
|
|
}
|
|
defaultQuery() {
|
|
return this._options.defaultQuery;
|
|
}
|
|
/** @internal Client request headers for each new WebSocket handshake. */
|
|
_buildWebSocketHeaders(authHeaders) {
|
|
return Object.fromEntries(buildHeaders([
|
|
{
|
|
"User-Agent": this.getUserAgent(),
|
|
"OpenAI-Organization": this.organization,
|
|
"OpenAI-Project": this.project
|
|
},
|
|
authHeaders,
|
|
this._options.defaultHeaders
|
|
]).values);
|
|
}
|
|
validateHeaders({ values, nulls }, schemes = {
|
|
bearerAuth: true,
|
|
adminAPIKeyAuth: true
|
|
}) {
|
|
if (values.get("authorization") || values.get("api-key")) {
|
|
return;
|
|
}
|
|
if (nulls.has("authorization") || nulls.has("api-key")) {
|
|
return;
|
|
}
|
|
if (this._workloadIdentityAuth && schemes.bearerAuth) {
|
|
return;
|
|
}
|
|
throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted');
|
|
}
|
|
async authHeaders(opts, schemes = {
|
|
bearerAuth: true,
|
|
adminAPIKeyAuth: true
|
|
}) {
|
|
const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
|
|
if (authentication instanceof X509WorkloadIdentityAuth && schemes.adminAPIKeyAuth && this.adminAPIKey !== null) {
|
|
return await this.adminAPIKeyAuth(opts);
|
|
}
|
|
return buildHeaders([
|
|
schemes.bearerAuth ? await this.bearerAuth(opts) : null,
|
|
schemes.adminAPIKeyAuth ? await this.adminAPIKeyAuth(opts) : null
|
|
]);
|
|
}
|
|
async bearerAuth(opts) {
|
|
const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
|
|
if (authentication) {
|
|
if (authentication instanceof X509WorkloadIdentityAuth) {
|
|
if (authentication === this._workloadIdentityAuth && (this.fetchWithAuth !== _a3.prototype.fetchWithAuth || this.fetchWithTimeout !== _a3.prototype.fetchWithTimeout)) {
|
|
throw new OpenAIError("X.509 workload identity does not support overridden fetch dispatch hooks.");
|
|
}
|
|
const snapshots = authentication.headerSnapshots();
|
|
if (!X509WorkloadIdentityAuth.shouldAuthenticate(opts, snapshots.defaultHeaders, snapshots.requestHeaders)) {
|
|
return void 0;
|
|
}
|
|
}
|
|
const token = authentication instanceof X509WorkloadIdentityAuth ? await authentication.getToken(opts, {
|
|
apiURL: authentication.requestAPIURL(),
|
|
...authentication.headerSnapshots(),
|
|
...authentication.requestSnapshot(),
|
|
signal: authentication.effectiveSignal(),
|
|
...authentication.tenantSnapshot()
|
|
}) : await authentication.getToken();
|
|
return buildHeaders([{ Authorization: `Bearer ${token}` }]);
|
|
}
|
|
const { apiKey } = await resolveRealtimeAPIKey(this);
|
|
if (apiKey == null) {
|
|
return void 0;
|
|
}
|
|
return buildHeaders([{ Authorization: `Bearer ${apiKey}` }]);
|
|
}
|
|
async adminAPIKeyAuth(opts) {
|
|
if (this.adminAPIKey == null) {
|
|
return void 0;
|
|
}
|
|
return buildHeaders([{ Authorization: `Bearer ${this.adminAPIKey}` }]);
|
|
}
|
|
stringifyQuery(query) {
|
|
return stringifyQuery(query);
|
|
}
|
|
getUserAgent() {
|
|
return `${this.constructor.name}/JS ${VERSION}`;
|
|
}
|
|
defaultIdempotencyKey() {
|
|
return `stainless-node-retry-${uuid4()}`;
|
|
}
|
|
makeStatusError(status, error, message, headers) {
|
|
const normalizedError = error && typeof error === "object" && error.error == null ? { error } : error;
|
|
return APIError.generate(status, normalizedError, message, headers);
|
|
}
|
|
_hasApiKeyProvider() {
|
|
return typeof this._options.apiKey === "function";
|
|
}
|
|
/**
|
|
* Resolves a function-based API key and retains the resolved value on this client.
|
|
* Returns whether a provider was invoked. Internal callers can capture this
|
|
* invocation's key before another request updates the shared `apiKey` property.
|
|
* Overrides should forward `capture` or invoke it with their own resolved key
|
|
* to preserve invocation-local credentials in concurrent requests and Realtime factories.
|
|
* @internal
|
|
*/
|
|
async _callApiKey(capture) {
|
|
if (this._provider) {
|
|
capture?.(this.apiKey);
|
|
return false;
|
|
}
|
|
const apiKey = this._options.apiKey;
|
|
if (typeof apiKey !== "function") {
|
|
capture?.(this.apiKey);
|
|
return false;
|
|
}
|
|
let token;
|
|
try {
|
|
token = await apiKey();
|
|
} catch (err) {
|
|
if (err instanceof OpenAIError)
|
|
throw err;
|
|
throw new OpenAIError(
|
|
`Failed to get token from 'apiKey' function: ${err.message}`,
|
|
// @ts-ignore
|
|
{ cause: err }
|
|
);
|
|
}
|
|
if (typeof token !== "string" || !token) {
|
|
throw new OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
|
|
}
|
|
this.apiKey = token;
|
|
capture?.(this.apiKey);
|
|
return true;
|
|
}
|
|
buildURL(path4, query, defaultBaseURL) {
|
|
const baseURL = !__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
|
|
const url = isAbsoluteURL(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4));
|
|
const defaultQuery = this.defaultQuery();
|
|
const pathQuery = Object.fromEntries(url.searchParams);
|
|
if (!isEmptyObj(defaultQuery) || !isEmptyObj(pathQuery)) {
|
|
query = { ...pathQuery, ...defaultQuery, ...query };
|
|
}
|
|
if (typeof query === "object" && query && !Array.isArray(query)) {
|
|
url.search = this.stringifyQuery(query);
|
|
}
|
|
return url.toString();
|
|
}
|
|
/**
|
|
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
|
* Function-based credentials are resolved later, when building authentication
|
|
* headers, including for direct `buildRequest()` calls. Overriding this hook
|
|
* does not bypass that resolution.
|
|
*/
|
|
async prepareOptions(options) {
|
|
}
|
|
/**
|
|
* Used as a callback for mutating the given `RequestInit` object.
|
|
*
|
|
* This is useful for cases where you want to add certain headers based off of
|
|
* the request properties, e.g. `method` or `url`.
|
|
*/
|
|
async prepareRequest(request2, { url, options }) {
|
|
}
|
|
get(path4, opts) {
|
|
return this.methodRequest("get", path4, opts);
|
|
}
|
|
post(path4, opts) {
|
|
return this.methodRequest("post", path4, opts);
|
|
}
|
|
patch(path4, opts) {
|
|
return this.methodRequest("patch", path4, opts);
|
|
}
|
|
put(path4, opts) {
|
|
return this.methodRequest("put", path4, opts);
|
|
}
|
|
delete(path4, opts) {
|
|
return this.methodRequest("delete", path4, opts);
|
|
}
|
|
methodRequest(method, path4, opts) {
|
|
return this.request(Promise.resolve(opts).then((opts2) => {
|
|
return { method, path: path4, ...opts2 };
|
|
}));
|
|
}
|
|
request(options, remainingRetries = null) {
|
|
const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
|
|
const request2 = authentication instanceof X509WorkloadIdentityAuth ? Promise.resolve(options).then((resolved) => authentication.runRequest(() => this.makeRequest(resolved, remainingRetries, void 0), this)) : this.makeRequest(options, remainingRetries, void 0);
|
|
return this.responsePromise(request2);
|
|
}
|
|
responsePromise(request2, parse2 = (client, props) => this.parseResponseWithTimeout(client, props)) {
|
|
const promise = new APIPromise(this, request2, (client, props) => {
|
|
const resume = __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").get(props.controller)?.continueRequest;
|
|
return resume ? resume(() => parse2(client, props)) : parse2(client, props);
|
|
});
|
|
promise.withResponse = async () => {
|
|
const data = await promise;
|
|
const { response } = await request2;
|
|
return { data, response, request_id: response.headers.get("x-request-id") };
|
|
};
|
|
promise._thenUnwrap = (transform) => this.responsePromise(request2, async (client, props) => addRequestID(transform(await parse2(client, props), props), props.response));
|
|
return promise;
|
|
}
|
|
async parseResponseWithTimeout(client, props) {
|
|
if (props.options.stream || props.options.__binaryResponse || props.response.status === 204 || props.response.headers.get("content-length") === "0") {
|
|
return defaultParseResponse(client, props);
|
|
}
|
|
while (true) {
|
|
const attempt = __classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").get(props.controller);
|
|
const timeout = attempt?.timeout ?? props.options.timeout ?? this.timeout;
|
|
const x509Authentication = attempt?.authentication;
|
|
const callerSignal = x509Authentication ? props.controller.signal : props.options.signal;
|
|
const abortError = () => x509Authentication && callerSignal ? this._makeUserAbortError(callerSignal) : new APIUserAbortError();
|
|
let remaining;
|
|
try {
|
|
remaining = x509Authentication?.remainingTimeout(props.options, timeout) ?? Math.max(0, props.startTime + timeout - Date.now());
|
|
} catch (error) {
|
|
const cancellation = callerSignal?.aborted ? abortError() : void 0;
|
|
props.controller.abort();
|
|
void CancelReadableStream(props.response.body).catch(() => void 0);
|
|
throw cancellation ?? error;
|
|
}
|
|
let timer;
|
|
let abortListener;
|
|
let timedOut = false;
|
|
try {
|
|
if (callerSignal?.aborted && attempt?.helperMethod !== "runTools") {
|
|
throw abortError();
|
|
}
|
|
const timeoutPromise = new Promise((_, reject) => {
|
|
timer = setTimeout(() => {
|
|
timedOut = true;
|
|
props.controller.abort();
|
|
reject(new APIConnectionTimeoutError());
|
|
}, remaining);
|
|
if (callerSignal) {
|
|
abortListener = () => {
|
|
if (!timedOut)
|
|
reject(abortError());
|
|
};
|
|
callerSignal.addEventListener("abort", abortListener, { once: true });
|
|
}
|
|
});
|
|
return await Promise.race([defaultParseResponse(client, props), timeoutPromise]);
|
|
} catch (error) {
|
|
if (callerSignal?.aborted && !timedOut) {
|
|
throw abortError();
|
|
}
|
|
if (!timedOut) {
|
|
if (x509Authentication && error instanceof SyntaxError) {
|
|
throw new SyntaxError("X.509 workload identity API response contains invalid JSON.");
|
|
}
|
|
if (x509Authentication && !(error instanceof OpenAIError)) {
|
|
throw new APIConnectionError({
|
|
message: "X.509 workload identity API response body could not be read."
|
|
});
|
|
}
|
|
throw error;
|
|
}
|
|
const retriesRemaining = attempt?.retriesRemaining ?? 0;
|
|
if (!retriesRemaining || attempt?.hasStreamingBody || props.options.__metadata?.["hasStreamingBody"] || globalThis.ReadableStream && props.options.body instanceof globalThis.ReadableStream || typeof props.options.body === "object" && props.options.body !== null && (Symbol.asyncIterator in props.options.body || Symbol.iterator in props.options.body && "next" in props.options.body && typeof props.options.body.next === "function")) {
|
|
throw new APIConnectionTimeoutError();
|
|
}
|
|
if (timer !== void 0)
|
|
clearTimeout(timer);
|
|
if (abortListener)
|
|
callerSignal?.removeEventListener("abort", abortListener);
|
|
abortListener = void 0;
|
|
const next = await this.retryRequest(props.options, retriesRemaining, props.retryOfRequestLogID ?? props.requestLogID, void 0, props.requestSignal);
|
|
Object.assign(props, next);
|
|
} finally {
|
|
if (timer !== void 0)
|
|
clearTimeout(timer);
|
|
if (abortListener)
|
|
callerSignal?.removeEventListener("abort", abortListener);
|
|
}
|
|
}
|
|
}
|
|
/** Keeps terminal X.509 error-body consumption inside the original logical request deadline. */
|
|
async readX509ResponseError(response, options, timeout, controller, authentication) {
|
|
const deadline = new AbortController();
|
|
const callerSignal = controller.signal;
|
|
let timedOut = false;
|
|
const cancel = () => deadline.abort(callerSignal.reason);
|
|
callerSignal.addEventListener("abort", cancel, { once: true });
|
|
if (callerSignal.aborted) {
|
|
cancel();
|
|
}
|
|
try {
|
|
const remaining = authentication.remainingTimeout(options, timeout);
|
|
const expiration = authentication.waitForRetry(remaining, deadline.signal).then(() => {
|
|
throw new APIConnectionTimeoutError();
|
|
});
|
|
const body = await Promise.race([
|
|
response.text().catch(() => "X.509 workload identity API response body could not be read."),
|
|
expiration
|
|
]);
|
|
if (callerSignal.aborted) {
|
|
throw this._makeUserAbortError(callerSignal);
|
|
}
|
|
return body;
|
|
} catch (error) {
|
|
if (error instanceof APIConnectionTimeoutError) {
|
|
timedOut = !callerSignal.aborted;
|
|
controller.abort();
|
|
void CancelReadableStream(response.body).catch(() => void 0);
|
|
}
|
|
if (callerSignal.aborted && !timedOut) {
|
|
throw this._makeUserAbortError(callerSignal);
|
|
}
|
|
throw error;
|
|
} finally {
|
|
callerSignal.removeEventListener("abort", cancel);
|
|
deadline.abort();
|
|
}
|
|
}
|
|
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
|
|
const options = await optionsInput;
|
|
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
if (retriesRemaining == null) {
|
|
retriesRemaining = maxRetries;
|
|
}
|
|
const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
|
|
x509Authentication?.beginRequestPreparation();
|
|
await this.prepareOptions(options);
|
|
x509Authentication?.beginRequestPlanning();
|
|
let built;
|
|
try {
|
|
const candidate = await this.buildRequest(options, {
|
|
retryCount: maxRetries - retriesRemaining
|
|
});
|
|
built = { req: candidate.req, url: candidate.url, timeout: candidate.timeout };
|
|
if (x509Authentication) {
|
|
validatePositiveInteger("timeout", built.timeout);
|
|
x509Authentication.authorizePlannedRequest(built.url, built.req, built.timeout);
|
|
if (X509WorkloadIdentityAuth.isStreamingRequestBody(built.req.body)) {
|
|
options.__metadata = { ...options.__metadata, hasStreamingBody: true };
|
|
}
|
|
await this.prepareRequest(built.req, { url: built.url, options });
|
|
await this._provider?.prepareRequest?.(built.req, { url: built.url, options });
|
|
x509Authentication.beginRequestPlanning();
|
|
x509Authentication.authorizePlannedRequest(built.url, built.req, built.timeout, true);
|
|
if (X509WorkloadIdentityAuth.isStreamingRequestBody(built.req.body)) {
|
|
options.__metadata = { ...options.__metadata, hasStreamingBody: true };
|
|
}
|
|
const callerSignal2 = x509Authentication.requestSnapshot().signal;
|
|
if (callerSignal2?.aborted || built.req.signal?.aborted) {
|
|
throw this._makeUserAbortError(callerSignal2?.aborted ? callerSignal2 : built.req.signal);
|
|
}
|
|
x509Authentication.setEffectiveSignal(built.req.signal || callerSignal2 ? createRequestController(built.req.signal ?? callerSignal2, callerSignal2).signal : void 0);
|
|
x509Authentication.beginRequestNetwork();
|
|
const security2 = options.__security ?? { bearerAuth: true };
|
|
const authenticationHeaders = await this.authHeaders(options, security2);
|
|
const suppliedHeaders = x509Authentication.headerSnapshots();
|
|
const supplied = buildHeaders([suppliedHeaders.defaultHeaders, suppliedHeaders.requestHeaders]);
|
|
for (const [name, value] of authenticationHeaders?.values ?? []) {
|
|
if (!supplied.nulls.has(name) && !built.req.headers.has(name)) {
|
|
built.req.headers.set(name, value);
|
|
}
|
|
}
|
|
this.validateHeaders(buildHeaders([supplied, built.req.headers]), security2);
|
|
}
|
|
} catch (error) {
|
|
x509Authentication?.retireRequestBody();
|
|
if (x509Authentication && retriesRemaining && !options.__metadata?.["hasStreamingBody"] && X509WorkloadIdentityAuth.isRetryableFailure(error)) {
|
|
return await this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? "x509-token-exchange", X509WorkloadIdentityAuth.retryHeaders(error));
|
|
}
|
|
throw error;
|
|
}
|
|
const { req, url } = built;
|
|
const timeout = x509Authentication ? Math.min(built.timeout, x509Authentication.requestSnapshot().timeout) : built.timeout;
|
|
x509Authentication?.bindRequest(options, req, this.adminAPIKey);
|
|
let hasStreamingBody = options.__metadata?.["hasStreamingBody"] === true;
|
|
if (!x509Authentication) {
|
|
await this.prepareRequest(req, { url, options });
|
|
await this._provider?.prepareRequest?.(req, { url, options });
|
|
}
|
|
x509Authentication?.adoptRequestHeaders(req);
|
|
if (x509Authentication && X509WorkloadIdentityAuth.isStreamingRequestBody(req.body)) {
|
|
hasStreamingBody = true;
|
|
}
|
|
const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
|
|
const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
|
|
const startTime = x509Authentication?.requestStartedAt(options) ?? Date.now();
|
|
if (this.logLevel === "debug") {
|
|
const body = typeof req.body === "string" ? { type: "string", length: req.body.length } : req.body;
|
|
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
method: options.method,
|
|
url,
|
|
options: x509Authentication ? { body, ...x509Authentication.requestSnapshot() } : { ...options, body },
|
|
headers: req.headers
|
|
}));
|
|
}
|
|
const callerSignal = x509Authentication ? x509Authentication.requestSnapshot().signal : options.signal;
|
|
if (callerSignal?.aborted || req.signal?.aborted) {
|
|
throw this._makeUserAbortError(callerSignal?.aborted ? callerSignal : req.signal);
|
|
}
|
|
const security = options.__security ?? { bearerAuth: true };
|
|
const controller = x509Authentication || this.fetchWithTimeout === _a3.prototype.fetchWithTimeout ? createRequestController(req.signal ?? (x509Authentication ? callerSignal : void 0), x509Authentication ? callerSignal : void 0) : new AbortController();
|
|
const remainingTimeout = x509Authentication?.remainingTimeout(options, timeout) ?? timeout;
|
|
const fetchWithAuth = x509Authentication ? _a3.prototype.fetchWithAuth : this.fetchWithAuth;
|
|
x509Authentication?.releaseRequestBody(req.body);
|
|
const response = await fetchWithAuth.call(this, url, req, remainingTimeout, controller, security).catch(castToError);
|
|
const headersTime = Date.now();
|
|
if (response instanceof globalThis.Error) {
|
|
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
if (callerSignal?.aborted || req.signal?.aborted) {
|
|
throw this._makeUserAbortError(callerSignal?.aborted ? callerSignal : req.signal);
|
|
}
|
|
const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
|
|
if (retriesRemaining && !hasStreamingBody && (!x509Authentication || isTransientX509ConnectionError2(response))) {
|
|
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
|
|
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
url,
|
|
durationMs: headersTime - startTime,
|
|
message: x509Authentication ? "X.509 workload identity API connection failed." : response.message
|
|
}));
|
|
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, void 0, req.signal);
|
|
}
|
|
const terminalMessage = hasStreamingBody ? "error; streaming body cannot be retried" : "error; no more retries left";
|
|
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${terminalMessage}`);
|
|
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${terminalMessage})`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
url,
|
|
durationMs: headersTime - startTime,
|
|
message: x509Authentication ? "X.509 workload identity API connection failed." : response.message
|
|
}));
|
|
if (response instanceof OAuthError || response instanceof SubjectTokenProviderError) {
|
|
throw response;
|
|
}
|
|
if (isTimeout) {
|
|
const transportCause = "cause" in response ? response.cause : void 0;
|
|
const isHeadersTimeout = typeof transportCause === "object" && transportCause !== null && "code" in transportCause && transportCause.code === "UND_ERR_HEADERS_TIMEOUT";
|
|
const timeoutError2 = isHeadersTimeout ? new APIConnectionTimeoutError({
|
|
message: "Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."
|
|
}) : new APIConnectionTimeoutError();
|
|
if (x509Authentication) {
|
|
throw new APIConnectionTimeoutError();
|
|
}
|
|
throw Object.assign(timeoutError2, { cause: response });
|
|
}
|
|
if (x509Authentication) {
|
|
throw new APIConnectionError({ message: "X.509 workload identity API connection failed." });
|
|
}
|
|
throw new APIConnectionError({
|
|
message: getConnectionErrorMessage(response),
|
|
cause: response
|
|
});
|
|
}
|
|
const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "x-request-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
|
|
const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${redactURL(url)} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
|
|
if (!response.ok) {
|
|
const rejectedX509Credential = response.status === 401 && x509Authentication && security.bearerAuth && x509Authentication.usedWorkloadToken(options);
|
|
if (rejectedX509Credential) {
|
|
x509Authentication.invalidateToken();
|
|
}
|
|
if (response.status === 401 && (x509Authentication || this._workloadIdentityAuth) && security.bearerAuth && (!x509Authentication || x509Authentication.usedWorkloadToken(options)) && (!x509Authentication || retriesRemaining > 0) && !hasStreamingBody && !options.__metadata?.["workloadIdentityTokenRefreshed"]) {
|
|
if (x509Authentication) {
|
|
void CancelReadableStream(response.body).catch(() => void 0);
|
|
} else {
|
|
await CancelReadableStream(response.body);
|
|
this._workloadIdentityAuth?.invalidateToken();
|
|
}
|
|
const replayOptions = {
|
|
...options,
|
|
__metadata: {
|
|
...options.__metadata,
|
|
workloadIdentityTokenRefreshed: true
|
|
}
|
|
};
|
|
return this.makeRequest(replayOptions, x509Authentication ? retriesRemaining - 1 : retriesRemaining, retryOfRequestLogID ?? requestLogID);
|
|
}
|
|
const shouldRetry = rejectedX509Credential && options.__metadata?.["workloadIdentityTokenRefreshed"] ? false : await this.shouldRetry(response);
|
|
if (retriesRemaining && shouldRetry && !hasStreamingBody) {
|
|
const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
|
|
if (x509Authentication) {
|
|
void CancelReadableStream(response.body).catch(() => void 0);
|
|
} else {
|
|
await CancelReadableStream(response.body);
|
|
}
|
|
loggerFor(this).info(`${responseInfo} - ${retryMessage2}`);
|
|
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage2})`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
headers: response.headers,
|
|
durationMs: headersTime - startTime
|
|
}));
|
|
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers, req.signal);
|
|
}
|
|
const retryMessage = shouldRetry ? hasStreamingBody ? `error; streaming body cannot be retried` : `error; no more retries left` : `error; not retryable`;
|
|
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
const errText = x509Authentication ? await this.readX509ResponseError(response, options, timeout, controller, x509Authentication) : await response.text().catch((err2) => castToError(err2).message);
|
|
const errJSON = safeJSON(errText);
|
|
const errMessage = errJSON ? void 0 : errText;
|
|
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
headers: response.headers,
|
|
message: errMessage,
|
|
durationMs: Date.now() - startTime
|
|
}));
|
|
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
|
|
throw err;
|
|
}
|
|
loggerFor(this).info(responseInfo);
|
|
loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
headers: response.headers,
|
|
durationMs: headersTime - startTime
|
|
}));
|
|
const continueRequest = x509Authentication?.continuation();
|
|
x509Authentication?.releaseRequestCredentials();
|
|
__classPrivateFieldGet(this, _OpenAI_responseAttempts, "f").set(controller, {
|
|
timeout,
|
|
retriesRemaining,
|
|
hasStreamingBody,
|
|
...x509Authentication ? { authentication: x509Authentication } : {},
|
|
helperMethod: options.__metadata?.["helperMethod"],
|
|
...continueRequest ? { continueRequest } : {}
|
|
});
|
|
return {
|
|
response,
|
|
options,
|
|
controller,
|
|
requestSignal: req.signal,
|
|
requestLogID,
|
|
retryOfRequestLogID,
|
|
startTime
|
|
};
|
|
}
|
|
getAPIList(path4, Page3, opts) {
|
|
return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path4, ...opts2 })) : { method: "get", path: path4, ...opts });
|
|
}
|
|
requestAPIList(Page3, options) {
|
|
const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") ?? this._workloadIdentityAuth;
|
|
const request2 = authentication instanceof X509WorkloadIdentityAuth ? Promise.resolve(options).then((resolved) => authentication.runRequest(() => this.makeRequest(resolved, null, void 0), this)) : this.makeRequest(options, null, void 0);
|
|
const page = new PagePromise(this, request2, Page3);
|
|
const guarded = this.responsePromise(request2, async (client, props) => {
|
|
const body = await this.parseResponseWithTimeout(client, props);
|
|
return new Page3(client, props.response, body, props.options);
|
|
});
|
|
page.then = guarded.then.bind(guarded);
|
|
page.catch = guarded.catch.bind(guarded);
|
|
page.finally = guarded.finally.bind(guarded);
|
|
page.withResponse = guarded.withResponse.bind(guarded);
|
|
page._thenUnwrap = guarded._thenUnwrap.bind(guarded);
|
|
return page;
|
|
}
|
|
async fetchWithAuth(url, init, timeout, controller, schemes = {
|
|
bearerAuth: true,
|
|
adminAPIKeyAuth: true
|
|
}) {
|
|
if (this._workloadIdentityAuth && !__classPrivateFieldGet(this, _OpenAI_x509Fetch, "f") && schemes.bearerAuth) {
|
|
const headers = init.headers;
|
|
const authHeader = headers.get("Authorization");
|
|
if (authHeader === `Bearer ${WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER}`) {
|
|
const token = await this._workloadIdentityAuth.getToken();
|
|
headers.set("Authorization", `Bearer ${token}`);
|
|
}
|
|
}
|
|
const fetchWithTimeout = __classPrivateFieldGet(this, _OpenAI_x509Fetch, "f") ? _a3.prototype.fetchWithTimeout : this.fetchWithTimeout;
|
|
const response = await fetchWithTimeout.call(this, url, init, timeout, controller);
|
|
return response;
|
|
}
|
|
async fetchWithTimeout(url, init, ms, controller) {
|
|
const { signal, method, ...options } = init || {};
|
|
const abort = this._makeAbort(controller);
|
|
const composed = !!signal && composedCallerSignals.get(controller) === signal;
|
|
const cleanup = signal && !composed ? addRequestAbortListener(signal, abort, controller.signal) : void 0;
|
|
const timeout = setTimeout(abort, ms);
|
|
const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
|
|
const fetchOptions = {
|
|
signal: controller.signal,
|
|
...isReadableBody ? { duplex: "half" } : {},
|
|
method: "GET",
|
|
...options
|
|
};
|
|
if (method) {
|
|
fetchOptions.method = method.toUpperCase();
|
|
}
|
|
try {
|
|
const response = await (__classPrivateFieldGet(this, _OpenAI_x509Fetch, "f") ?? this.fetch).call(void 0, url, fetchOptions);
|
|
if (cleanup) {
|
|
retainRequestAbortCallback(response.body ?? response, abort, controller.signal);
|
|
}
|
|
return response;
|
|
} catch (err) {
|
|
cleanup?.();
|
|
throw err;
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
}
|
|
async shouldRetry(response) {
|
|
const shouldRetryHeader = response.headers.get("x-should-retry");
|
|
if (shouldRetryHeader === "true")
|
|
return true;
|
|
if (shouldRetryHeader === "false")
|
|
return false;
|
|
if (response.status === 408)
|
|
return true;
|
|
if (response.status === 409)
|
|
return true;
|
|
if (response.status === 429)
|
|
return true;
|
|
if (response.status >= 500)
|
|
return true;
|
|
return false;
|
|
}
|
|
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders, requestSignal = options.signal) {
|
|
let timeoutMillis;
|
|
const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
|
|
if (retryAfterMillisHeader) {
|
|
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
|
if (!Number.isNaN(timeoutMs)) {
|
|
timeoutMillis = timeoutMs;
|
|
}
|
|
}
|
|
const retryAfterHeader = responseHeaders?.get("retry-after");
|
|
if (retryAfterHeader && timeoutMillis === void 0) {
|
|
const timeoutSeconds = parseFloat(retryAfterHeader);
|
|
if (!Number.isNaN(timeoutSeconds)) {
|
|
timeoutMillis = timeoutSeconds * 1e3;
|
|
} else {
|
|
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
}
|
|
}
|
|
if (timeoutMillis === void 0 || !Number.isFinite(timeoutMillis) || timeoutMillis < 0 || timeoutMillis > 60 * 1e3) {
|
|
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
}
|
|
const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
|
|
if (x509Authentication) {
|
|
const remaining = x509Authentication.remainingTimeout(options, x509Authentication.requestSnapshot().timeout);
|
|
if (timeoutMillis >= remaining) {
|
|
throw new APIConnectionTimeoutError();
|
|
}
|
|
}
|
|
if (x509Authentication) {
|
|
await x509Authentication.waitForRetry(timeoutMillis, x509Authentication.effectiveSignal());
|
|
} else {
|
|
const retrySignals = requestSignal === options.signal ? [requestSignal] : [requestSignal, options.signal];
|
|
try {
|
|
await sleep(timeoutMillis, ...retrySignals);
|
|
} catch (error) {
|
|
const abortedSignal = retrySignals.find((signal) => signal?.aborted);
|
|
if (abortedSignal) {
|
|
throw this._makeUserAbortError(abortedSignal);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
|
|
}
|
|
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
const initialRetryDelay = 0.5;
|
|
const maxRetryDelay = 8;
|
|
const numRetries = maxRetries - retriesRemaining;
|
|
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
const jitter2 = 1 - Math.random() * 0.25;
|
|
return sleepSeconds * jitter2 * 1e3;
|
|
}
|
|
/**
|
|
* Builds a request, resolving callback credentials when constructing authentication
|
|
* headers, after any subclass request-option rewrites. Calling this method directly
|
|
* also resolves credentials. Complete replacement builders own authentication and
|
|
* can call `this.authHeaders()` to resolve headers with request-local credentials.
|
|
*/
|
|
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
if (__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") && !__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f").inRequest(this)) {
|
|
const authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
|
|
return await authentication.runRequest(async () => {
|
|
const built = await _a3.prototype.buildRequest.call(this, inputOptions, { retryCount });
|
|
authentication.releaseRequestBody(built.req.body);
|
|
return built;
|
|
}, this);
|
|
}
|
|
const options = { ...inputOptions };
|
|
const x509Authentication = __classPrivateFieldGet(this, _OpenAI_x509Authentication, "f");
|
|
const x509Tenant = x509Authentication?.snapshotTenant(this.organization, this.project);
|
|
const x509Headers = x509Authentication?.snapshotHeaders(this._options.defaultHeaders, options.headers);
|
|
if (x509Headers) {
|
|
options.headers = x509Headers.requestHeaders;
|
|
}
|
|
const x509ClientFetchOptions = x509Authentication ? snapshotX509RequestOptions(this.fetchOptions) : void 0;
|
|
const x509RequestFetchOptions = x509Authentication ? snapshotX509RequestOptions(options.fetchOptions) : void 0;
|
|
const { method, path: path4, query, defaultBaseURL } = options;
|
|
const url = this.buildURL(path4, query, defaultBaseURL);
|
|
x509Authentication?.snapshotAPIURL(url);
|
|
const explicitTimeout = "timeout" in options;
|
|
if (explicitTimeout)
|
|
validatePositiveInteger("timeout", options.timeout);
|
|
options.timeout = options.timeout ?? this.timeout;
|
|
if (x509Authentication && x509RequestFetchOptions) {
|
|
x509Authentication.snapshotRequest(options.signal, options.timeout, x509RequestFetchOptions);
|
|
}
|
|
if (x509Authentication) {
|
|
const snapshot = x509Authentication.requestSnapshot();
|
|
options.timeout = snapshot.timeout;
|
|
if (snapshot.signal === void 0) {
|
|
delete options.signal;
|
|
} else {
|
|
options.signal = snapshot.signal;
|
|
}
|
|
}
|
|
const authenticationHeaders = this._provider || x509Authentication ? void 0 : await this.authHeaders(inputOptions, inputOptions.__security ?? { bearerAuth: true });
|
|
const { bodyHeaders, body, isStreamingBody } = this.buildBody({ options });
|
|
if (isStreamingBody) {
|
|
inputOptions.__metadata = {
|
|
...inputOptions.__metadata,
|
|
hasStreamingBody: true
|
|
};
|
|
x509Authentication?.ownRequestBody(body, options.body);
|
|
}
|
|
const reqHeaders = await this.buildHeaders({
|
|
options: inputOptions,
|
|
method,
|
|
bodyHeaders,
|
|
authenticationHeaders,
|
|
retryCount,
|
|
x509Headers,
|
|
x509Timeout: explicitTimeout ? options.timeout : void 0,
|
|
x509Tenant
|
|
});
|
|
const req = {
|
|
method,
|
|
headers: reqHeaders,
|
|
...options.signal && { signal: options.signal },
|
|
...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
|
|
...body && { body },
|
|
...(x509Authentication ? x509ClientFetchOptions : this.fetchOptions) ?? {},
|
|
...(x509Authentication ? x509RequestFetchOptions : options.fetchOptions) ?? {}
|
|
};
|
|
return { req, url, timeout: options.timeout };
|
|
}
|
|
async buildHeaders({ options, method, bodyHeaders, authenticationHeaders, retryCount, x509Headers, x509Timeout, x509Tenant }) {
|
|
let idempotencyHeaders = {};
|
|
if (this.idempotencyHeader && method !== "get") {
|
|
if (!options.idempotencyKey)
|
|
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
|
|
}
|
|
const helperMethod = options.__metadata?.["helperMethod"];
|
|
const timeout = x509Headers ? x509Timeout : options.timeout;
|
|
const headers = buildHeaders([
|
|
idempotencyHeaders,
|
|
{
|
|
Accept: "application/json",
|
|
...!isRunningInBrowserOrBrowserWorker() ? { "User-Agent": this.getUserAgent() } : void 0,
|
|
"X-Stainless-Retry-Count": String(retryCount),
|
|
...timeout ? { "X-Stainless-Timeout": String(Math.trunc(timeout / 1e3)) } : {},
|
|
...getPlatformHeaders(),
|
|
...typeof helperMethod === "string" ? { "X-Stainless-Helper-Method": helperMethod } : {},
|
|
"OpenAI-Organization": x509Tenant ? x509Tenant.organization : this.organization,
|
|
"OpenAI-Project": x509Tenant ? x509Tenant.project : this.project
|
|
},
|
|
// X.509 owns streaming uploads before authentication so it can retire them on failure.
|
|
__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f") && !__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f").isPlanningRequest() ? await this.authHeaders(options, options.__security ?? { bearerAuth: true }) : authenticationHeaders,
|
|
x509Headers?.defaultHeaders ?? this._options.defaultHeaders,
|
|
bodyHeaders,
|
|
x509Headers?.requestHeaders ?? options.headers
|
|
]);
|
|
if (!this._provider && !__classPrivateFieldGet(this, _OpenAI_x509Authentication, "f")?.isPlanningRequest()) {
|
|
this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
|
|
}
|
|
return headers.values;
|
|
}
|
|
_makeAbort(controller) {
|
|
return () => controller.abort();
|
|
}
|
|
_makeUserAbortError(signal) {
|
|
const error = new APIUserAbortError();
|
|
Object.defineProperty(error, "cause", { value: signal.reason, writable: true, configurable: true });
|
|
return error;
|
|
}
|
|
buildBody({ options }) {
|
|
const { body, headers: rawHeaders } = options;
|
|
if (!body) {
|
|
if (body === void 0 && "body" in options) {
|
|
return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers: buildHeaders([rawHeaders]) }), isStreamingBody: false };
|
|
}
|
|
return { bodyHeaders: void 0, body: void 0, isStreamingBody: false };
|
|
}
|
|
const headers = buildHeaders([rawHeaders]);
|
|
const isReadableStream2 = typeof globalThis.ReadableStream !== "undefined" && body instanceof globalThis.ReadableStream;
|
|
const isRetryableBody = !isReadableStream2 && (typeof body === "string" || body instanceof ArrayBuffer || ArrayBuffer.isView(body) || typeof globalThis.Blob !== "undefined" && body instanceof globalThis.Blob || body instanceof URLSearchParams || body instanceof FormData);
|
|
if (
|
|
// Pass raw type verbatim
|
|
ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
|
|
headers.values.has("content-type") || // `Blob` is superset of `File`
|
|
globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
|
|
body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
|
|
body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
|
|
isReadableStream2
|
|
) {
|
|
return { bodyHeaders: void 0, body, isStreamingBody: !isRetryableBody };
|
|
} else if (typeof body === "object" && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function")) {
|
|
return {
|
|
bodyHeaders: void 0,
|
|
body: ReadableStreamFrom(body),
|
|
isStreamingBody: true
|
|
};
|
|
} else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
|
|
return {
|
|
bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
|
|
body: this.stringifyQuery(body),
|
|
isStreamingBody: false
|
|
};
|
|
} else {
|
|
return { ...__classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }), isStreamingBody: false };
|
|
}
|
|
}
|
|
};
|
|
_a3 = OpenAI, _OpenAI_encoder = /* @__PURE__ */ new WeakMap(), _OpenAI_x509Authentication = /* @__PURE__ */ new WeakMap(), _OpenAI_x509Credential = /* @__PURE__ */ new WeakMap(), _OpenAI_x509Fetch = /* @__PURE__ */ new WeakMap(), _OpenAI_explicitDataResidency = /* @__PURE__ */ new WeakMap(), _OpenAI_responseAttempts = /* @__PURE__ */ new WeakMap(), _OpenAI_instances = /* @__PURE__ */ new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() {
|
|
return __classPrivateFieldGet(this, _OpenAI_explicitDataResidency, "f") || this._provider !== void 0 || this.baseURL !== "https://api.openai.com/v1";
|
|
};
|
|
OpenAI.OpenAI = _a3;
|
|
OpenAI.DEFAULT_TIMEOUT = 6e5;
|
|
OpenAI.OpenAIError = OpenAIError;
|
|
OpenAI.APIError = APIError;
|
|
OpenAI.APIConnectionError = APIConnectionError;
|
|
OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError;
|
|
OpenAI.APIUserAbortError = APIUserAbortError;
|
|
OpenAI.NotFoundError = NotFoundError;
|
|
OpenAI.ConflictError = ConflictError;
|
|
OpenAI.RateLimitError = RateLimitError;
|
|
OpenAI.BadRequestError = BadRequestError;
|
|
OpenAI.AuthenticationError = AuthenticationError;
|
|
OpenAI.InternalServerError = InternalServerError;
|
|
OpenAI.PermissionDeniedError = PermissionDeniedError;
|
|
OpenAI.UnprocessableEntityError = UnprocessableEntityError;
|
|
OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError;
|
|
OpenAI.toFile = toFile;
|
|
OpenAI.toStreamingFile = toStreamingFile;
|
|
OpenAI.Completions = Completions2;
|
|
OpenAI.Chat = Chat;
|
|
OpenAI.Embeddings = Embeddings;
|
|
OpenAI.Files = Files3;
|
|
OpenAI.Images = Images;
|
|
OpenAI.ContentProvenanceChecks = ContentProvenanceChecks;
|
|
OpenAI.Audio = Audio;
|
|
OpenAI.Moderations = Moderations;
|
|
OpenAI.Models = Models;
|
|
OpenAI.FineTuning = FineTuning;
|
|
OpenAI.Graders = Graders2;
|
|
OpenAI.VectorStores = VectorStores;
|
|
OpenAI.Safety = Safety;
|
|
OpenAI.Webhooks = Webhooks;
|
|
OpenAI.Beta = Beta;
|
|
OpenAI.Batches = Batches;
|
|
OpenAI.Uploads = Uploads;
|
|
OpenAI.Admin = Admin;
|
|
OpenAI.Responses = Responses2;
|
|
OpenAI.Live = Live;
|
|
OpenAI.Realtime = Realtime2;
|
|
OpenAI.Conversations = Conversations;
|
|
OpenAI.Evals = Evals;
|
|
OpenAI.Containers = Containers;
|
|
OpenAI.Skills = Skills;
|
|
OpenAI.Videos = Videos;
|
|
OpenAI.ConversationCursorPage = ConversationCursorPage;
|
|
OpenAI.CursorPage = CursorPage;
|
|
OpenAI.NextCursorPage = NextCursorPage;
|
|
OpenAI.Page = Page;
|
|
OpenAI.TokenPage = TokenPage;
|
|
composedCallerSignals = /* @__PURE__ */ new WeakMap();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/azure.mjs
|
|
var init_azure = __esm({
|
|
"node_modules/openai/azure.mjs"() {
|
|
init_headers2();
|
|
init_error2();
|
|
init_utils2();
|
|
init_path();
|
|
init_client();
|
|
init_data_residency();
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/internal/bedrock.mjs
|
|
var brand_privateBedrockClient;
|
|
var init_bedrock = __esm({
|
|
"node_modules/openai/internal/bedrock.mjs"() {
|
|
init_error2();
|
|
init_utils2();
|
|
brand_privateBedrockClient = /* @__PURE__ */ Symbol.for("openai.privateBedrockClient");
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/bedrock.mjs
|
|
var _a4;
|
|
var init_bedrock2 = __esm({
|
|
"node_modules/openai/bedrock.mjs"() {
|
|
init_error2();
|
|
init_client();
|
|
init_realtime_credentials();
|
|
init_data_residency();
|
|
init_bedrock();
|
|
init_headers2();
|
|
init_utils2();
|
|
init_ResponsesParser();
|
|
init_resources();
|
|
_a4 = brand_privateBedrockClient;
|
|
}
|
|
});
|
|
|
|
// node_modules/openai/index.mjs
|
|
var init_openai = __esm({
|
|
"node_modules/openai/index.mjs"() {
|
|
init_client();
|
|
init_uploads2();
|
|
init_api_promise();
|
|
init_client();
|
|
init_pagination();
|
|
init_error();
|
|
init_azure();
|
|
init_bedrock2();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/provider-env.js
|
|
function getBunSandboxEnvValue(name) {
|
|
if (typeof process === "undefined" || !process.versions?.bun || Object.keys(process.env).length > 0) {
|
|
return void 0;
|
|
}
|
|
if (procEnvCache === null) {
|
|
procEnvCache = /* @__PURE__ */ new Map();
|
|
try {
|
|
const { readFileSync } = __require("node:fs");
|
|
const data = readFileSync("/proc/self/environ", "utf-8");
|
|
for (const entry of data.split("\0")) {
|
|
const idx = entry.indexOf("=");
|
|
if (idx > 0) {
|
|
procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));
|
|
}
|
|
}
|
|
} catch {
|
|
}
|
|
}
|
|
return procEnvCache.get(name);
|
|
}
|
|
function getProviderEnvValue(name, env) {
|
|
return env?.[name] || (typeof process !== "undefined" ? process.env[name] : void 0) || getBunSandboxEnvValue(name) || void 0;
|
|
}
|
|
var procEnvCache;
|
|
var init_provider_env = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/provider-env.js"() {
|
|
procEnvCache = null;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js
|
|
function isJsonSchemaObject(value) {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
function isStructuredSchema(schema4) {
|
|
if (!isJsonSchemaObject(schema4))
|
|
return false;
|
|
const types = typeof schema4.type === "string" ? [schema4.type] : Array.isArray(schema4.type) ? schema4.type : [];
|
|
return types.includes("object") || types.includes("array") || schema4.properties !== void 0 || schema4.items !== void 0;
|
|
}
|
|
function schemaAllowsNull(schema4) {
|
|
if (!isJsonSchemaObject(schema4))
|
|
return false;
|
|
if (schema4.type === "null" || Array.isArray(schema4.type) && schema4.type.includes("null"))
|
|
return true;
|
|
if (schema4.const === null || Array.isArray(schema4.enum) && schema4.enum.includes(null))
|
|
return true;
|
|
return Array.isArray(schema4.anyOf) && schema4.anyOf.some((variant) => schemaAllowsNull(variant));
|
|
}
|
|
function makeJsonSchemaNodeStrict(schema4, isUnsupportedKeyword) {
|
|
if (!isJsonSchemaObject(schema4)) {
|
|
throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");
|
|
}
|
|
for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) {
|
|
if (schema4[key] !== void 0) {
|
|
throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);
|
|
}
|
|
}
|
|
if (isUnsupportedKeyword) {
|
|
for (const [key, value] of Object.entries(schema4)) {
|
|
if (isUnsupportedKeyword(key, value)) {
|
|
throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`);
|
|
}
|
|
}
|
|
}
|
|
if (schema4.anyOf !== void 0) {
|
|
if (!Array.isArray(schema4.anyOf) || schema4.anyOf.length === 0) {
|
|
throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");
|
|
}
|
|
for (const variant of schema4.anyOf) {
|
|
if (isStructuredSchema(variant)) {
|
|
throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");
|
|
}
|
|
makeJsonSchemaNodeStrict(variant, isUnsupportedKeyword);
|
|
}
|
|
}
|
|
if (schema4.items !== void 0) {
|
|
if (Array.isArray(schema4.items)) {
|
|
throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");
|
|
}
|
|
makeJsonSchemaNodeStrict(schema4.items, isUnsupportedKeyword);
|
|
}
|
|
const isObjectSchema = schema4.type === "object";
|
|
if (schema4.properties !== void 0 && !isObjectSchema) {
|
|
throw new UnsupportedStrictJsonSchemaError("properties require type object");
|
|
}
|
|
if (!isObjectSchema)
|
|
return;
|
|
if (schema4.additionalProperties !== void 0 && schema4.additionalProperties !== false) {
|
|
throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");
|
|
}
|
|
if (schema4.properties !== void 0 && !isJsonSchemaObject(schema4.properties)) {
|
|
throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");
|
|
}
|
|
if (schema4.required !== void 0 && (!Array.isArray(schema4.required) || schema4.required.some((key) => typeof key !== "string"))) {
|
|
throw new UnsupportedStrictJsonSchemaError("object required must be a string array");
|
|
}
|
|
const properties = schema4.properties ?? {};
|
|
const propertyNames = Object.keys(properties);
|
|
const required = new Set(Array.isArray(schema4.required) ? schema4.required : []);
|
|
if ([...required].some((key) => !propertyNames.includes(key))) {
|
|
throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");
|
|
}
|
|
for (const [key, property] of Object.entries(properties)) {
|
|
makeJsonSchemaNodeStrict(property, isUnsupportedKeyword);
|
|
if (!required.has(key) && !schemaAllowsNull(property)) {
|
|
properties[key] = { anyOf: [property, { type: "null" }] };
|
|
}
|
|
}
|
|
schema4.required = propertyNames;
|
|
schema4.additionalProperties = false;
|
|
}
|
|
function makeStrictJsonSchema(schema4, isUnsupportedKeyword) {
|
|
const cloned = structuredClone(schema4);
|
|
if (!isJsonSchemaObject(cloned)) {
|
|
throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
|
|
}
|
|
makeJsonSchemaNodeStrict(cloned, isUnsupportedKeyword);
|
|
if (cloned.type !== "object") {
|
|
throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
|
|
}
|
|
return cloned;
|
|
}
|
|
function prefersJsonSchemaStrictSampling(tool) {
|
|
const config = tool.constrainedSampling;
|
|
return !!config && config.type === "json_schema" && config.strict === "prefer";
|
|
}
|
|
function isStrictToolLimitErrorMessage(message) {
|
|
return STRICT_TOOL_LIMIT_ERROR_MESSAGES.some((limitMessage) => message.includes(limitMessage));
|
|
}
|
|
function getJsonSchemaToolParameters(tool, strict) {
|
|
return strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters;
|
|
}
|
|
function getGrammarToolInput(toolName2, arguments_, inputProperty) {
|
|
const input = arguments_[inputProperty];
|
|
if (typeof input !== "string") {
|
|
throw new Error(`Grammar tool call "${toolName2}" requires argument "${inputProperty}" to be a string.`);
|
|
}
|
|
return input;
|
|
}
|
|
function appendGrammarToolInputJsonDelta(buffer, inputProperty, inputDelta) {
|
|
if (buffer.closed) {
|
|
throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
|
|
}
|
|
if (inputDelta.length === 0)
|
|
return void 0;
|
|
buffer.input += inputDelta;
|
|
return grammarToolInputJsonStart(buffer, inputProperty) + JSON.stringify(inputDelta).slice(1, -1);
|
|
}
|
|
function closeGrammarToolInputJson(buffer, inputProperty, finalInput) {
|
|
if (buffer.closed) {
|
|
if (finalInput === void 0 || finalInput === buffer.input)
|
|
return void 0;
|
|
throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
|
|
}
|
|
if (finalInput !== void 0 && !finalInput.startsWith(buffer.input)) {
|
|
throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);
|
|
}
|
|
const rest = finalInput === void 0 ? "" : finalInput.slice(buffer.input.length);
|
|
if (finalInput !== void 0)
|
|
buffer.input = finalInput;
|
|
buffer.closed = true;
|
|
return `${grammarToolInputJsonStart(buffer, inputProperty)}${JSON.stringify(rest).slice(1, -1)}"}`;
|
|
}
|
|
function grammarToolInputJsonStart(buffer, inputProperty) {
|
|
if (buffer.started)
|
|
return "";
|
|
buffer.started = true;
|
|
return `{${JSON.stringify(inputProperty)}:"`;
|
|
}
|
|
function inferGrammarInputProperty(tool) {
|
|
const schema4 = tool.parameters;
|
|
if (schema4.type !== "object") {
|
|
throw new Error("grammar constrained sampling requires an object parameter schema");
|
|
}
|
|
if (!Array.isArray(schema4.required) || schema4.required.length !== 1 || typeof schema4.required[0] !== "string") {
|
|
throw new Error("grammar constrained sampling requires exactly one required string property");
|
|
}
|
|
const inputProperty = schema4.required[0];
|
|
if (!schema4.properties?.[inputProperty]) {
|
|
throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);
|
|
}
|
|
if (schema4.properties[inputProperty]?.type !== "string") {
|
|
throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);
|
|
}
|
|
return inputProperty;
|
|
}
|
|
function resolveJsonSchemaStrictSampling(tool, supportsStrictMode, isUnsupportedKeyword) {
|
|
const config = tool.constrainedSampling;
|
|
if (!config || config.type !== "json_schema")
|
|
return void 0;
|
|
if (supportsStrictMode) {
|
|
try {
|
|
makeStrictJsonSchema(tool.parameters, isUnsupportedKeyword);
|
|
return true;
|
|
} catch (error) {
|
|
if (!(error instanceof UnsupportedStrictJsonSchemaError))
|
|
throw error;
|
|
if (config.strict !== "require")
|
|
return void 0;
|
|
throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`);
|
|
}
|
|
}
|
|
if (config.strict === "require") {
|
|
throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
|
|
}
|
|
return void 0;
|
|
}
|
|
function resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools) {
|
|
const config = tool.constrainedSampling;
|
|
if (!config || config.type !== "grammar") {
|
|
return void 0;
|
|
}
|
|
if (!supportsOpenAIGrammarTools) {
|
|
return void 0;
|
|
}
|
|
const larkDefinition = config.variants.openai_lark;
|
|
const regexDefinition = config.variants.openai_regex;
|
|
const hasLarkDefinition = typeof larkDefinition === "string" && larkDefinition.trim().length > 0;
|
|
const hasRegexDefinition = typeof regexDefinition === "string" && regexDefinition.trim().length > 0;
|
|
if (!hasLarkDefinition && !hasRegexDefinition) {
|
|
throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);
|
|
}
|
|
try {
|
|
return {
|
|
format: hasLarkDefinition ? "lark" : "regex",
|
|
definition: hasLarkDefinition ? larkDefinition : regexDefinition,
|
|
inputProperty: inferGrammarInputProperty(tool)
|
|
};
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`);
|
|
}
|
|
}
|
|
function createGrammarToolInputProperties(tools, supportsOpenAIGrammarTools) {
|
|
const properties = /* @__PURE__ */ new Map();
|
|
for (const tool of tools ?? []) {
|
|
const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
|
|
if (grammar) {
|
|
properties.set(tool.name, grammar.inputProperty);
|
|
}
|
|
}
|
|
return properties;
|
|
}
|
|
var UnsupportedStrictJsonSchemaError, UNSUPPORTED_STRICT_SCHEMA_KEYS, STRICT_TOOL_LIMIT_ERROR_MESSAGES;
|
|
var init_constrained_sampling = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js"() {
|
|
UnsupportedStrictJsonSchemaError = class extends Error {
|
|
};
|
|
UNSUPPORTED_STRICT_SCHEMA_KEYS = [
|
|
"$ref",
|
|
"$defs",
|
|
"definitions",
|
|
"allOf",
|
|
"oneOf",
|
|
"patternProperties",
|
|
"dependentSchemas",
|
|
"dependencies",
|
|
"unevaluatedProperties",
|
|
"propertyNames",
|
|
"contains",
|
|
"prefixItems",
|
|
"not",
|
|
"if",
|
|
"then",
|
|
"else"
|
|
];
|
|
STRICT_TOOL_LIMIT_ERROR_MESSAGES = [
|
|
"The compiled grammar is too large",
|
|
"Too many strict tools (",
|
|
"Schemas contains too many parameters with union types ("
|
|
];
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.js
|
|
function inferCopilotInitiator(messages) {
|
|
const last = messages[messages.length - 1];
|
|
return last && last.role !== "user" ? "agent" : "user";
|
|
}
|
|
function hasCopilotVisionInput(messages) {
|
|
return messages.some((msg) => {
|
|
if (msg.role === "user" && Array.isArray(msg.content)) {
|
|
return msg.content.some((c) => c.type === "image");
|
|
}
|
|
if (msg.role === "toolResult" && Array.isArray(msg.content)) {
|
|
return msg.content.some((c) => c.type === "image");
|
|
}
|
|
return false;
|
|
});
|
|
}
|
|
function buildCopilotDynamicHeaders(params) {
|
|
const headers = {
|
|
"X-Initiator": inferCopilotInitiator(params.messages),
|
|
"Openai-Intent": "conversation-edits"
|
|
};
|
|
if (params.hasImages) {
|
|
headers["Copilot-Vision-Request"] = "true";
|
|
}
|
|
return headers;
|
|
}
|
|
var init_github_copilot_headers = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/github-copilot-headers.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js
|
|
function clampOpenAIPromptCacheKey(key) {
|
|
if (key === void 0)
|
|
return void 0;
|
|
const chars = Array.from(key);
|
|
if (chars.length <= OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH)
|
|
return key;
|
|
return chars.slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH).join("");
|
|
}
|
|
var OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH;
|
|
var init_openai_prompt_cache = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/openai-prompt-cache.js"() {
|
|
OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/hash.js
|
|
function shortHash(str2) {
|
|
let h1 = 3735928559;
|
|
let h2 = 1103547991;
|
|
for (let i = 0; i < str2.length; i++) {
|
|
const ch = str2.charCodeAt(i);
|
|
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
}
|
|
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
|
|
}
|
|
var init_hash = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/hash.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/sanitize-unicode.js
|
|
function sanitizeSurrogates(text) {
|
|
return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
|
|
}
|
|
var init_sanitize_unicode = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/sanitize-unicode.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/partial-json/dist/options.js
|
|
var require_options = __commonJS({
|
|
"node_modules/partial-json/dist/options.js"(exports) {
|
|
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.Allow = exports.ALL = exports.COLLECTION = exports.ATOM = exports.SPECIAL = exports.INF = exports._INFINITY = exports.INFINITY = exports.NAN = exports.BOOL = exports.NULL = exports.OBJ = exports.ARR = exports.NUM = exports.STR = void 0;
|
|
exports.STR = 1;
|
|
exports.NUM = 2;
|
|
exports.ARR = 4;
|
|
exports.OBJ = 8;
|
|
exports.NULL = 16;
|
|
exports.BOOL = 32;
|
|
exports.NAN = 64;
|
|
exports.INFINITY = 128;
|
|
exports._INFINITY = 256;
|
|
exports.INF = exports.INFINITY | exports._INFINITY;
|
|
exports.SPECIAL = exports.NULL | exports.BOOL | exports.INF | exports.NAN;
|
|
exports.ATOM = exports.STR | exports.NUM | exports.SPECIAL;
|
|
exports.COLLECTION = exports.ARR | exports.OBJ;
|
|
exports.ALL = exports.ATOM | exports.COLLECTION;
|
|
exports.Allow = { STR: exports.STR, NUM: exports.NUM, ARR: exports.ARR, OBJ: exports.OBJ, NULL: exports.NULL, BOOL: exports.BOOL, NAN: exports.NAN, INFINITY: exports.INFINITY, _INFINITY: exports._INFINITY, INF: exports.INF, SPECIAL: exports.SPECIAL, ATOM: exports.ATOM, COLLECTION: exports.COLLECTION, ALL: exports.ALL };
|
|
exports.default = exports.Allow;
|
|
}
|
|
});
|
|
|
|
// node_modules/partial-json/dist/index.js
|
|
var require_dist = __commonJS({
|
|
"node_modules/partial-json/dist/index.js"(exports) {
|
|
"use strict";
|
|
var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === void 0) k2 = k;
|
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
desc = { enumerable: true, get: function() {
|
|
return m[k];
|
|
} };
|
|
}
|
|
Object.defineProperty(o, k2, desc);
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === void 0) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
|
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.Allow = exports.MalformedJSON = exports.PartialJSON = exports.parseJSON = exports.parse = void 0;
|
|
var options_1 = require_options();
|
|
Object.defineProperty(exports, "Allow", { enumerable: true, get: function() {
|
|
return options_1.Allow;
|
|
} });
|
|
__exportStar(require_options(), exports);
|
|
var PartialJSON2 = class extends Error {
|
|
};
|
|
exports.PartialJSON = PartialJSON2;
|
|
var MalformedJSON2 = class extends Error {
|
|
};
|
|
exports.MalformedJSON = MalformedJSON2;
|
|
function parseJSON2(jsonString, allowPartial = options_1.Allow.ALL) {
|
|
if (typeof jsonString !== "string") {
|
|
throw new TypeError(`expecting str, got ${typeof jsonString}`);
|
|
}
|
|
if (!jsonString.trim()) {
|
|
throw new Error(`${jsonString} is empty`);
|
|
}
|
|
return _parseJSON2(jsonString.trim(), allowPartial);
|
|
}
|
|
exports.parseJSON = parseJSON2;
|
|
var _parseJSON2 = (jsonString, allow) => {
|
|
const length = jsonString.length;
|
|
let index = 0;
|
|
const markPartialJSON = (msg) => {
|
|
throw new PartialJSON2(`${msg} at position ${index}`);
|
|
};
|
|
const throwMalformedError = (msg) => {
|
|
throw new MalformedJSON2(`${msg} at position ${index}`);
|
|
};
|
|
const parseAny = () => {
|
|
skipBlank();
|
|
if (index >= length)
|
|
markPartialJSON("Unexpected end of input");
|
|
if (jsonString[index] === '"')
|
|
return parseStr();
|
|
if (jsonString[index] === "{")
|
|
return parseObj();
|
|
if (jsonString[index] === "[")
|
|
return parseArr();
|
|
if (jsonString.substring(index, index + 4) === "null" || options_1.Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
|
|
index += 4;
|
|
return null;
|
|
}
|
|
if (jsonString.substring(index, index + 4) === "true" || options_1.Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
|
|
index += 4;
|
|
return true;
|
|
}
|
|
if (jsonString.substring(index, index + 5) === "false" || options_1.Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
|
|
index += 5;
|
|
return false;
|
|
}
|
|
if (jsonString.substring(index, index + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
|
|
index += 8;
|
|
return Infinity;
|
|
}
|
|
if (jsonString.substring(index, index + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
|
|
index += 9;
|
|
return -Infinity;
|
|
}
|
|
if (jsonString.substring(index, index + 3) === "NaN" || options_1.Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
|
|
index += 3;
|
|
return NaN;
|
|
}
|
|
return parseNum();
|
|
};
|
|
const parseStr = () => {
|
|
const start = index;
|
|
let escape2 = false;
|
|
index++;
|
|
while (index < length && (jsonString[index] !== '"' || escape2 && jsonString[index - 1] === "\\")) {
|
|
escape2 = jsonString[index] === "\\" ? !escape2 : false;
|
|
index++;
|
|
}
|
|
if (jsonString.charAt(index) == '"') {
|
|
try {
|
|
return JSON.parse(jsonString.substring(start, ++index - Number(escape2)));
|
|
} catch (e) {
|
|
throwMalformedError(String(e));
|
|
}
|
|
} else if (options_1.Allow.STR & allow) {
|
|
try {
|
|
return JSON.parse(jsonString.substring(start, index - Number(escape2)) + '"');
|
|
} catch (e) {
|
|
return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"');
|
|
}
|
|
}
|
|
markPartialJSON("Unterminated string literal");
|
|
};
|
|
const parseObj = () => {
|
|
index++;
|
|
skipBlank();
|
|
const obj2 = {};
|
|
try {
|
|
while (jsonString[index] !== "}") {
|
|
skipBlank();
|
|
if (index >= length && options_1.Allow.OBJ & allow)
|
|
return obj2;
|
|
const key = parseStr();
|
|
skipBlank();
|
|
index++;
|
|
try {
|
|
const value = parseAny();
|
|
obj2[key] = value;
|
|
} catch (e) {
|
|
if (options_1.Allow.OBJ & allow)
|
|
return obj2;
|
|
else
|
|
throw e;
|
|
}
|
|
skipBlank();
|
|
if (jsonString[index] === ",")
|
|
index++;
|
|
}
|
|
} catch (e) {
|
|
if (options_1.Allow.OBJ & allow)
|
|
return obj2;
|
|
else
|
|
markPartialJSON("Expected '}' at end of object");
|
|
}
|
|
index++;
|
|
return obj2;
|
|
};
|
|
const parseArr = () => {
|
|
index++;
|
|
const arr2 = [];
|
|
try {
|
|
while (jsonString[index] !== "]") {
|
|
arr2.push(parseAny());
|
|
skipBlank();
|
|
if (jsonString[index] === ",") {
|
|
index++;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
if (options_1.Allow.ARR & allow) {
|
|
return arr2;
|
|
}
|
|
markPartialJSON("Expected ']' at end of array");
|
|
}
|
|
index++;
|
|
return arr2;
|
|
};
|
|
const parseNum = () => {
|
|
if (index === 0) {
|
|
if (jsonString === "-")
|
|
throwMalformedError("Not sure what '-' is");
|
|
try {
|
|
return JSON.parse(jsonString);
|
|
} catch (e) {
|
|
if (options_1.Allow.NUM & allow)
|
|
try {
|
|
return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
|
|
} catch (e2) {
|
|
}
|
|
throwMalformedError(String(e));
|
|
}
|
|
}
|
|
const start = index;
|
|
if (jsonString[index] === "-")
|
|
index++;
|
|
while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1)
|
|
index++;
|
|
if (index == length && !(options_1.Allow.NUM & allow))
|
|
markPartialJSON("Unterminated number literal");
|
|
try {
|
|
return JSON.parse(jsonString.substring(start, index));
|
|
} catch (e) {
|
|
if (jsonString.substring(start, index) === "-")
|
|
markPartialJSON("Not sure what '-' is");
|
|
try {
|
|
return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
|
|
} catch (e2) {
|
|
throwMalformedError(String(e2));
|
|
}
|
|
}
|
|
};
|
|
const skipBlank = () => {
|
|
while (index < length && " \n\r ".includes(jsonString[index])) {
|
|
index++;
|
|
}
|
|
};
|
|
return parseAny();
|
|
};
|
|
var parse2 = parseJSON2;
|
|
exports.parse = parse2;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js
|
|
function isControlCharacter(char) {
|
|
const codePoint = char.codePointAt(0);
|
|
return codePoint !== void 0 && codePoint >= 0 && codePoint <= 31;
|
|
}
|
|
function escapeControlCharacter(char) {
|
|
switch (char) {
|
|
case "\b":
|
|
return "\\b";
|
|
case "\f":
|
|
return "\\f";
|
|
case "\n":
|
|
return "\\n";
|
|
case "\r":
|
|
return "\\r";
|
|
case " ":
|
|
return "\\t";
|
|
default:
|
|
return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;
|
|
}
|
|
}
|
|
function repairJson(json) {
|
|
let repaired = "";
|
|
let inString = false;
|
|
for (let index = 0; index < json.length; index++) {
|
|
const char = json[index];
|
|
if (!inString) {
|
|
repaired += char;
|
|
if (char === '"') {
|
|
inString = true;
|
|
}
|
|
continue;
|
|
}
|
|
if (char === '"') {
|
|
repaired += char;
|
|
inString = false;
|
|
continue;
|
|
}
|
|
if (char === "\\") {
|
|
const nextChar = json[index + 1];
|
|
if (nextChar === void 0) {
|
|
repaired += "\\\\";
|
|
continue;
|
|
}
|
|
if (nextChar === "u") {
|
|
const unicodeDigits = json.slice(index + 2, index + 6);
|
|
if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {
|
|
repaired += `\\u${unicodeDigits}`;
|
|
index += 5;
|
|
continue;
|
|
}
|
|
}
|
|
if (VALID_JSON_ESCAPES.has(nextChar)) {
|
|
repaired += `\\${nextChar}`;
|
|
index += 1;
|
|
continue;
|
|
}
|
|
repaired += "\\\\";
|
|
continue;
|
|
}
|
|
repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;
|
|
}
|
|
return repaired;
|
|
}
|
|
function parseJsonWithRepair(json) {
|
|
try {
|
|
return JSON.parse(json);
|
|
} catch (error) {
|
|
const repairedJson = repairJson(json);
|
|
if (repairedJson !== json) {
|
|
return JSON.parse(repairedJson);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
function parseToolCallArguments(json) {
|
|
if (!json?.trim())
|
|
return { arguments: {} };
|
|
try {
|
|
const parsed = parseJsonWithRepair(json);
|
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
throw new Error("Tool arguments must be a JSON object");
|
|
}
|
|
return { arguments: parsed };
|
|
} catch (error) {
|
|
return {
|
|
arguments: {},
|
|
argumentsError: `${error instanceof Error ? error.message : String(error)}
|
|
|
|
Received arguments:
|
|
${json}`
|
|
};
|
|
}
|
|
}
|
|
var import_partial_json, VALID_JSON_ESCAPES;
|
|
var init_json_parse = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/json-parse.js"() {
|
|
import_partial_json = __toESM(require_dist(), 1);
|
|
VALID_JSON_ESCAPES = /* @__PURE__ */ new Set(['"', "\\", "/", "b", "f", "n", "r", "t"]);
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/streaming-json.js
|
|
function isDelimiter(char) {
|
|
return char === " " || char === " " || char === "\n" || char === "\r" || char === "," || char === ":" || char === "{" || char === "}" || char === "[" || char === "]" || char === '"';
|
|
}
|
|
function isHexDigit(char) {
|
|
return char >= "0" && char <= "9" || char >= "a" && char <= "f" || char >= "A" && char <= "F";
|
|
}
|
|
function scalarValue(token) {
|
|
for (const [literal, value] of LITERALS)
|
|
if (token === literal)
|
|
return value;
|
|
return NUMBER.test(token) ? Number(token) : void 0;
|
|
}
|
|
function pendingScalarValue(token) {
|
|
for (const [literal, value] of LITERALS)
|
|
if (literal.startsWith(token))
|
|
return value;
|
|
if (NUMBER.test(token))
|
|
return Number(token);
|
|
const mantissa = NUMBER_WITHOUT_EXPONENT_DIGITS.exec(token);
|
|
return mantissa === null ? void 0 : Number(mantissa[1]);
|
|
}
|
|
function setSlot(container, slot, value) {
|
|
if (slot.kind === "element")
|
|
container[slot.index] = value;
|
|
else if (slot.kind === "member")
|
|
setMember(container, slot.key, value);
|
|
}
|
|
function setMember(members, key, value) {
|
|
if (key === "__proto__") {
|
|
Object.defineProperty(members, key, { value, writable: true, enumerable: true, configurable: true });
|
|
} else {
|
|
members[key] = value;
|
|
}
|
|
}
|
|
var MAX_REPORTED_DEPTH, ROOT_SLOT, CREDIT_PER_APPEND, CREDIT_PER_CHARACTER, MAX_PENDING_SCALAR_LENGTH, NUMBER, NUMBER_WITHOUT_EXPONENT_DIGITS, LITERALS, QUOTE, BACKSLASH, StreamingJsonParser, ToolCallArgumentsStream, SIMPLE_ESCAPES;
|
|
var init_streaming_json = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/streaming-json.js"() {
|
|
init_json_parse();
|
|
MAX_REPORTED_DEPTH = 32;
|
|
ROOT_SLOT = { kind: "root" };
|
|
CREDIT_PER_APPEND = 256;
|
|
CREDIT_PER_CHARACTER = 8;
|
|
MAX_PENDING_SCALAR_LENGTH = 64;
|
|
NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
|
|
NUMBER_WITHOUT_EXPONENT_DIGITS = /^(-?(?:0|[1-9]\d*)(?:\.\d+)?)[eE][+-]?$/;
|
|
LITERALS = [
|
|
["true", true],
|
|
["false", false],
|
|
["null", null]
|
|
];
|
|
QUOTE = 34;
|
|
BACKSLASH = 92;
|
|
StreamingJsonParser = class {
|
|
#root = void 0;
|
|
#done = false;
|
|
#stack = [];
|
|
#string = void 0;
|
|
#scalar = "";
|
|
#scalarSlot = void 0;
|
|
/** Sum of `size + 1` over the open path: what a fresh snapshot copies. */
|
|
#pathCost = 0;
|
|
#credit = 0;
|
|
#dirty = false;
|
|
#snapshot = void 0;
|
|
/** Changes of the piece being read. */
|
|
#changes = [];
|
|
/**
|
|
* Read the next piece of text; returns the changes it made, in order. Costs time linear in `text.length`.
|
|
*/
|
|
append(text) {
|
|
this.#credit += CREDIT_PER_APPEND + CREDIT_PER_CHARACTER * text.length;
|
|
this.#changes = [];
|
|
if (this.#string !== void 0)
|
|
this.#string.change = void 0;
|
|
let index = 0;
|
|
while (index < text.length && !this.#done) {
|
|
const open = this.#string;
|
|
if (open !== void 0)
|
|
index = this.#readString(open, text, index);
|
|
else if (this.#scalar !== "")
|
|
index = this.#readScalar(text, index);
|
|
else
|
|
this.#structural(text[index++]);
|
|
}
|
|
return this.#changes;
|
|
}
|
|
/**
|
|
* The value of the text read so far: `undefined` before a value starts, otherwise a plain JSON value that never
|
|
* changes afterwards. Returns the previous snapshot while the text read since did not change the value, or while a
|
|
* fresh copy of the open path is not yet paid for (see the module comment).
|
|
*/
|
|
snapshot() {
|
|
if (!this.#dirty)
|
|
return this.#snapshot;
|
|
const pending = this.#pendingScalar();
|
|
const cost = this.#pathCost + (pending === void 0 ? 0 : 1);
|
|
if (cost > this.#credit)
|
|
return this.#snapshot;
|
|
this.#credit -= cost;
|
|
this.#dirty = false;
|
|
this.#snapshot = this.#copyOpenPath(pending);
|
|
return this.#snapshot;
|
|
}
|
|
/** Read string characters from `start` until the string ends or the text does; returns the next index. */
|
|
#readString(open, text, start) {
|
|
let runStart = start;
|
|
for (let index = start; index < text.length; index++) {
|
|
const code = text.charCodeAt(index);
|
|
if (open.escape !== "") {
|
|
if (this.#continueEscape(open, text[index])) {
|
|
runStart = index + 1;
|
|
continue;
|
|
}
|
|
runStart = index;
|
|
}
|
|
if (code === QUOTE) {
|
|
if (index > runStart)
|
|
this.#appendString(open, text.slice(runStart, index));
|
|
this.#endString(open);
|
|
return index + 1;
|
|
}
|
|
if (code === BACKSLASH) {
|
|
if (index > runStart)
|
|
this.#appendString(open, text.slice(runStart, index));
|
|
open.escape = "\\";
|
|
runStart = index + 1;
|
|
}
|
|
}
|
|
if (text.length > runStart)
|
|
this.#appendString(open, text.slice(runStart));
|
|
return text.length;
|
|
}
|
|
/** Read number or literal characters from `start` up to the next delimiter; returns the delimiter's index. */
|
|
#readScalar(text, start) {
|
|
let end = start;
|
|
while (end < text.length && !isDelimiter(text[end]))
|
|
end++;
|
|
if (end > start) {
|
|
this.#scalar += text.slice(start, end);
|
|
if (this.#scalarSlot !== void 0)
|
|
this.#dirty = true;
|
|
}
|
|
if (end < text.length)
|
|
this.#endScalar();
|
|
return end;
|
|
}
|
|
/** Handle one character outside strings. */
|
|
#structural(char) {
|
|
switch (char) {
|
|
case " ":
|
|
case " ":
|
|
case "\n":
|
|
case "\r":
|
|
return;
|
|
case '"':
|
|
this.#startString();
|
|
return;
|
|
case "{":
|
|
case "[":
|
|
this.#openContainer(char === "{" ? {} : []);
|
|
return;
|
|
case "}":
|
|
case "]":
|
|
this.#closeContainer();
|
|
return;
|
|
case ":": {
|
|
const frame = this.#stack.at(-1);
|
|
if (frame !== void 0 && !Array.isArray(frame.container) && frame.phase === "colon")
|
|
frame.phase = "value";
|
|
return;
|
|
}
|
|
case ",": {
|
|
const frame = this.#stack.at(-1);
|
|
if (frame !== void 0)
|
|
frame.phase = Array.isArray(frame.container) ? "value" : "key";
|
|
return;
|
|
}
|
|
default:
|
|
this.#scalar = char;
|
|
this.#scalarSlot = this.#valueSlot();
|
|
if (this.#scalarSlot !== void 0)
|
|
this.#dirty = true;
|
|
}
|
|
}
|
|
/** Where a value starting now goes, or `undefined` when this position takes no value. */
|
|
#valueSlot() {
|
|
const frame = this.#stack.at(-1);
|
|
if (frame === void 0)
|
|
return this.#root === void 0 ? ROOT_SLOT : void 0;
|
|
if (Array.isArray(frame.container))
|
|
return { kind: "element", index: frame.container.length };
|
|
if ((frame.phase === "value" || frame.phase === "colon") && frame.key !== void 0) {
|
|
return { kind: "member", key: frame.key };
|
|
}
|
|
return void 0;
|
|
}
|
|
#startString() {
|
|
const frame = this.#stack.at(-1);
|
|
if (frame !== void 0 && !Array.isArray(frame.container) && (frame.phase === "key" || frame.phase === "comma")) {
|
|
this.#string = { target: "key", slot: void 0, text: "", escape: "", path: void 0, change: void 0 };
|
|
return;
|
|
}
|
|
const slot = this.#valueSlot();
|
|
const path4 = this.#reportedPath(slot);
|
|
this.#string = { target: "value", slot, text: "", escape: "", path: path4, change: void 0 };
|
|
this.#place(slot, "");
|
|
if (path4 !== void 0)
|
|
this.#string.change = this.#report({ kind: "set", path: path4, value: "" });
|
|
}
|
|
/** The path of a value at `slot` in the innermost open container, when its changes are reported. */
|
|
#reportedPath(slot) {
|
|
if (slot === void 0)
|
|
return void 0;
|
|
if (slot.kind === "root")
|
|
return [];
|
|
const frame = this.#stack.at(-1);
|
|
if (!frame.reportsInside)
|
|
return void 0;
|
|
return [...frame.path, slot.kind === "member" ? slot.key : slot.index];
|
|
}
|
|
#report(change) {
|
|
this.#changes.push(change);
|
|
return change;
|
|
}
|
|
/** Continue an escape with `char`; returns false when `char` is not part of it and must be read normally. */
|
|
#continueEscape(open, char) {
|
|
if (open.escape === "\\") {
|
|
const decoded = SIMPLE_ESCAPES[char];
|
|
if (decoded !== void 0) {
|
|
open.escape = "";
|
|
this.#appendString(open, decoded);
|
|
return true;
|
|
}
|
|
if (char === "u") {
|
|
open.escape = "\\u";
|
|
return true;
|
|
}
|
|
open.escape = "";
|
|
this.#appendString(open, "\\");
|
|
return false;
|
|
}
|
|
if (isHexDigit(char)) {
|
|
open.escape += char;
|
|
if (open.escape.length < 6)
|
|
return true;
|
|
const decoded = String.fromCharCode(Number.parseInt(open.escape.slice(2), 16));
|
|
open.escape = "";
|
|
this.#appendString(open, decoded);
|
|
return true;
|
|
}
|
|
const literal = open.escape;
|
|
open.escape = "";
|
|
this.#appendString(open, literal);
|
|
return false;
|
|
}
|
|
#appendString(open, text) {
|
|
open.text += text;
|
|
if (open.target !== "value")
|
|
return;
|
|
this.#place(open.slot, open.text);
|
|
if (open.path === void 0)
|
|
return;
|
|
const change = open.change;
|
|
if (change !== void 0 && this.#changes.at(-1) === change) {
|
|
if (change.kind === "set")
|
|
change.value = change.value + text;
|
|
else
|
|
change.text += text;
|
|
return;
|
|
}
|
|
open.change = this.#report({ kind: "append", path: open.path, text });
|
|
}
|
|
#endString(open) {
|
|
this.#string = void 0;
|
|
const frame = this.#stack.at(-1);
|
|
if (open.target === "key") {
|
|
if (frame === void 0)
|
|
return;
|
|
frame.key = open.text;
|
|
frame.phase = "colon";
|
|
return;
|
|
}
|
|
this.#valueEnded(frame);
|
|
}
|
|
#endScalar() {
|
|
const token = this.#scalar;
|
|
const slot = this.#scalarSlot;
|
|
this.#scalar = "";
|
|
this.#scalarSlot = void 0;
|
|
const value = scalarValue(token);
|
|
if (value !== void 0) {
|
|
this.#place(slot, value);
|
|
const path4 = this.#reportedPath(slot);
|
|
if (path4 !== void 0)
|
|
this.#report({ kind: "set", path: path4, value });
|
|
}
|
|
this.#valueEnded(this.#stack.at(-1));
|
|
}
|
|
/** The value of the unterminated scalar at the end of the text, if it shows. */
|
|
#pendingScalar() {
|
|
const slot = this.#scalarSlot;
|
|
const token = this.#scalar;
|
|
if (slot === void 0 || token === "" || token.length > MAX_PENDING_SCALAR_LENGTH)
|
|
return void 0;
|
|
const value = pendingScalarValue(token);
|
|
return value === void 0 ? void 0 : { slot, value };
|
|
}
|
|
#openContainer(container) {
|
|
const slot = this.#valueSlot();
|
|
const path4 = this.#reportedPath(slot);
|
|
this.#place(slot, container);
|
|
this.#stack.push({
|
|
container,
|
|
slot,
|
|
path: path4,
|
|
reportsInside: path4 !== void 0 && path4.length < MAX_REPORTED_DEPTH,
|
|
size: 0,
|
|
key: void 0,
|
|
phase: Array.isArray(container) ? "value" : "key"
|
|
});
|
|
this.#pathCost += 1;
|
|
this.#dirty = true;
|
|
if (path4 !== void 0)
|
|
this.#report({ kind: "set", path: path4, value: Array.isArray(container) ? [] : {} });
|
|
}
|
|
#closeContainer() {
|
|
const frame = this.#stack.pop();
|
|
if (frame === void 0)
|
|
return;
|
|
this.#pathCost -= frame.size + 1;
|
|
this.#dirty = true;
|
|
if (frame.path !== void 0 && !frame.reportsInside) {
|
|
this.#report({ kind: "set", path: frame.path, value: frame.container });
|
|
}
|
|
this.#valueEnded(this.#stack.at(-1));
|
|
}
|
|
/** A value in `frame`, or the root value when there is no frame, has ended. */
|
|
#valueEnded(frame) {
|
|
if (frame === void 0) {
|
|
if (this.#root !== void 0)
|
|
this.#done = true;
|
|
return;
|
|
}
|
|
frame.phase = "comma";
|
|
}
|
|
/** Set the value at `slot` in the open path; nothing for a value in an invalid position. */
|
|
#place(slot, value) {
|
|
if (slot === void 0)
|
|
return;
|
|
this.#dirty = true;
|
|
if (slot.kind === "root") {
|
|
this.#root = value;
|
|
return;
|
|
}
|
|
const frame = this.#stack.at(-1);
|
|
if (slot.kind === "element") {
|
|
const elements = frame.container;
|
|
if (slot.index === elements.length) {
|
|
frame.size++;
|
|
this.#pathCost++;
|
|
}
|
|
elements[slot.index] = value;
|
|
return;
|
|
}
|
|
const members = frame.container;
|
|
if (!Object.hasOwn(members, slot.key)) {
|
|
frame.size++;
|
|
this.#pathCost++;
|
|
}
|
|
setMember(members, slot.key, value);
|
|
}
|
|
/** A fresh snapshot: copies of the open containers, innermost first, each holding the copy of its open child. */
|
|
#copyOpenPath(pending) {
|
|
if (this.#stack.length === 0)
|
|
return pending?.slot.kind === "root" ? pending.value : this.#root;
|
|
let child;
|
|
let childSlot;
|
|
for (let depth = this.#stack.length - 1; depth >= 0; depth--) {
|
|
const frame = this.#stack[depth];
|
|
const copy = Array.isArray(frame.container) ? frame.container.slice() : { ...frame.container };
|
|
if (depth === this.#stack.length - 1 && pending !== void 0)
|
|
setSlot(copy, pending.slot, pending.value);
|
|
if (child !== void 0 && childSlot !== void 0)
|
|
setSlot(copy, childSlot, child);
|
|
child = copy;
|
|
childSlot = frame.slot;
|
|
}
|
|
return childSlot?.kind === "root" ? child : this.#root;
|
|
}
|
|
};
|
|
ToolCallArgumentsStream = class {
|
|
#text = "";
|
|
#parser = new StreamingJsonParser();
|
|
#snapshot = void 0;
|
|
#arguments = {};
|
|
/** The raw argument text received so far. */
|
|
get text() {
|
|
return this.#text;
|
|
}
|
|
/** Append a piece of argument text; returns the partial arguments, a new object whenever they changed. */
|
|
append(delta) {
|
|
this.#text += delta;
|
|
this.#parser.append(delta);
|
|
return this.#partial();
|
|
}
|
|
/**
|
|
* Take the provider's complete argument text. When it continues the text so far, returns the missing piece as
|
|
* `delta`; otherwise starts over with `text`. Either way returns the partial arguments of `text`.
|
|
*/
|
|
replace(text) {
|
|
if (text.startsWith(this.#text)) {
|
|
const delta = text.slice(this.#text.length);
|
|
return { delta, arguments: delta === "" ? this.#partial() : this.append(delta) };
|
|
}
|
|
this.#text = "";
|
|
this.#parser = new StreamingJsonParser();
|
|
return { delta: void 0, arguments: this.append(text) };
|
|
}
|
|
/** The final arguments: one full parse of the complete text, which reports malformed arguments. */
|
|
finish() {
|
|
return parseToolCallArguments(this.#text);
|
|
}
|
|
#partial() {
|
|
const snapshot = this.#parser.snapshot();
|
|
if (snapshot === this.#snapshot)
|
|
return this.#arguments;
|
|
this.#snapshot = snapshot;
|
|
this.#arguments = typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? snapshot : {};
|
|
return this.#arguments;
|
|
}
|
|
};
|
|
SIMPLE_ESCAPES = {
|
|
'"': '"',
|
|
"\\": "\\",
|
|
"/": "/",
|
|
b: "\b",
|
|
f: "\f",
|
|
n: "\n",
|
|
r: "\r",
|
|
t: " "
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js
|
|
function splitErrorToolResultImages(msg) {
|
|
if (!msg.isError)
|
|
return void 0;
|
|
const images = msg.content.filter((block) => block.type === "image");
|
|
if (images.length === 0)
|
|
return void 0;
|
|
return {
|
|
content: replaceImagesWithPlaceholder(msg.content, ERROR_TOOL_IMAGE_PLACEHOLDER),
|
|
caption: `Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,
|
|
images
|
|
};
|
|
}
|
|
function replaceImagesWithPlaceholder(content, placeholder) {
|
|
const result = [];
|
|
let previousWasPlaceholder = false;
|
|
for (const block of content) {
|
|
if (block.type === "image") {
|
|
if (!previousWasPlaceholder) {
|
|
result.push({ type: "text", text: placeholder });
|
|
}
|
|
previousWasPlaceholder = true;
|
|
continue;
|
|
}
|
|
result.push(block);
|
|
previousWasPlaceholder = block.text === placeholder;
|
|
}
|
|
return result;
|
|
}
|
|
function downgradeUnsupportedImages(messages, model2) {
|
|
if (model2.input.includes("image")) {
|
|
return messages;
|
|
}
|
|
return messages.map((msg) => {
|
|
if (msg.role === "user" && Array.isArray(msg.content)) {
|
|
return {
|
|
...msg,
|
|
content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER)
|
|
};
|
|
}
|
|
if (msg.role === "toolResult") {
|
|
return {
|
|
...msg,
|
|
content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER)
|
|
};
|
|
}
|
|
return msg;
|
|
});
|
|
}
|
|
function transformMessages(messages, model2, normalizeToolCallId2) {
|
|
const toolCallIdMap = /* @__PURE__ */ new Map();
|
|
const normalizedMessages = messages.map((msg) => msg.content == null ? { ...msg, content: [] } : msg);
|
|
const imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model2);
|
|
const transformed = imageAwareMessages.map((msg) => {
|
|
if (msg.role === "system" || msg.role === "user") {
|
|
return msg;
|
|
}
|
|
if (msg.role === "toolResult") {
|
|
const normalizedId = toolCallIdMap.get(msg.toolCallId);
|
|
if (normalizedId && normalizedId !== msg.toolCallId) {
|
|
return { ...msg, toolCallId: normalizedId };
|
|
}
|
|
return msg;
|
|
}
|
|
if (msg.role === "assistant") {
|
|
const assistantMsg = msg;
|
|
const isSameModel = assistantMsg.provider === model2.provider && assistantMsg.api === model2.api && assistantMsg.model === model2.id;
|
|
const transformedContent = assistantMsg.content.flatMap((block) => {
|
|
if (block.type === "thinking") {
|
|
if (!isSameModel)
|
|
return [];
|
|
if (block.redacted || block.thinkingSignature)
|
|
return block;
|
|
if (!block.thinking || block.thinking.trim() === "")
|
|
return [];
|
|
return block;
|
|
}
|
|
if (block.type === "text") {
|
|
if (isSameModel)
|
|
return block;
|
|
return {
|
|
type: "text",
|
|
text: block.text
|
|
};
|
|
}
|
|
if (block.type === "toolCall") {
|
|
const toolCall = block;
|
|
let normalizedToolCall = toolCall;
|
|
if (!isSameModel && toolCall.thoughtSignature) {
|
|
normalizedToolCall = { ...toolCall };
|
|
delete normalizedToolCall.thoughtSignature;
|
|
}
|
|
if (!isSameModel && normalizeToolCallId2) {
|
|
const normalizedId = normalizeToolCallId2(toolCall.id, model2, assistantMsg);
|
|
if (normalizedId !== toolCall.id) {
|
|
toolCallIdMap.set(toolCall.id, normalizedId);
|
|
normalizedToolCall = { ...normalizedToolCall, id: normalizedId };
|
|
}
|
|
}
|
|
return normalizedToolCall;
|
|
}
|
|
return block;
|
|
});
|
|
return {
|
|
...assistantMsg,
|
|
content: transformedContent
|
|
};
|
|
}
|
|
return msg;
|
|
});
|
|
const result = [];
|
|
let pendingToolCalls = [];
|
|
let existingToolResultIds = /* @__PURE__ */ new Set();
|
|
const heldSystemMessages = [];
|
|
const closePendingToolCalls = () => {
|
|
if (pendingToolCalls.length > 0) {
|
|
for (const tc of pendingToolCalls) {
|
|
if (!existingToolResultIds.has(tc.id)) {
|
|
result.push({
|
|
role: "toolResult",
|
|
toolCallId: tc.id,
|
|
toolName: tc.name,
|
|
content: [{ type: "text", text: "No result provided" }],
|
|
isError: true,
|
|
timestamp: Date.now()
|
|
});
|
|
}
|
|
}
|
|
pendingToolCalls = [];
|
|
existingToolResultIds = /* @__PURE__ */ new Set();
|
|
}
|
|
result.push(...heldSystemMessages);
|
|
heldSystemMessages.length = 0;
|
|
};
|
|
for (let i = 0; i < transformed.length; i++) {
|
|
const msg = transformed[i];
|
|
if (msg.role === "assistant") {
|
|
closePendingToolCalls();
|
|
const assistantMsg = msg;
|
|
if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") {
|
|
continue;
|
|
}
|
|
const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
|
|
if (toolCalls.length > 0) {
|
|
pendingToolCalls = toolCalls;
|
|
existingToolResultIds = /* @__PURE__ */ new Set();
|
|
}
|
|
result.push(msg);
|
|
} else if (msg.role === "toolResult") {
|
|
existingToolResultIds.add(msg.toolCallId);
|
|
result.push(msg);
|
|
} else if (msg.role === "system") {
|
|
if (pendingToolCalls.length > 0) {
|
|
heldSystemMessages.push(msg);
|
|
} else {
|
|
result.push(msg);
|
|
}
|
|
} else if (msg.role === "user") {
|
|
closePendingToolCalls();
|
|
result.push(msg);
|
|
} else {
|
|
result.push(msg);
|
|
}
|
|
}
|
|
closePendingToolCalls();
|
|
return result;
|
|
}
|
|
var NON_VISION_USER_IMAGE_PLACEHOLDER, NON_VISION_TOOL_IMAGE_PLACEHOLDER, ERROR_TOOL_IMAGE_PLACEHOLDER;
|
|
var init_transform_messages = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js"() {
|
|
NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
|
|
NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
|
|
ERROR_TOOL_IMAGE_PLACEHOLDER = "(image attached after the tool results)";
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js
|
|
function encodeTextSignatureV1(id, phase) {
|
|
const payload = { v: 1, id };
|
|
if (phase)
|
|
payload.phase = phase;
|
|
return JSON.stringify(payload);
|
|
}
|
|
function parseTextSignature(signature) {
|
|
if (!signature)
|
|
return void 0;
|
|
if (signature.startsWith("{")) {
|
|
try {
|
|
const parsed = JSON.parse(signature);
|
|
if (parsed.v === 1 && typeof parsed.id === "string") {
|
|
if (parsed.phase === "commentary" || parsed.phase === "final_answer") {
|
|
return { id: parsed.id, phase: parsed.phase };
|
|
}
|
|
return { id: parsed.id };
|
|
}
|
|
} catch {
|
|
}
|
|
}
|
|
return { id: signature };
|
|
}
|
|
function convertToolResultOutput(model2, content) {
|
|
const textResult = content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
const images = content.filter((c) => c.type === "image");
|
|
const hasText = textResult.trim().length > 0;
|
|
if (images.length === 0 || !model2.input.includes("image")) {
|
|
return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)");
|
|
}
|
|
const output = [];
|
|
if (hasText) {
|
|
output.push({ type: "input_text", text: sanitizeSurrogates(textResult) });
|
|
}
|
|
for (const image of images) {
|
|
output.push({
|
|
type: "input_image",
|
|
detail: "auto",
|
|
image_url: `data:${image.mimeType};base64,${image.data}`
|
|
});
|
|
}
|
|
return output;
|
|
}
|
|
function getResponsesToolSupport(options) {
|
|
if (options.supportsMidConvoSystemMessages && options.supportsAdditionalTools)
|
|
return "changes";
|
|
return options.supportsToolSearch ? "additions" : "none";
|
|
}
|
|
function renderIncrementalToolsNotice(unavailable2) {
|
|
const notice = "This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";
|
|
return unavailable2.size > 0 ? `${notice}
|
|
Still unavailable: ${[...unavailable2].join(", ")}.` : notice;
|
|
}
|
|
function renderToolRemovalNotice(names) {
|
|
return `The following tools are no longer available. Do not call them:
|
|
${names.map((name) => `- ${name}`).join("\n")}`;
|
|
}
|
|
function convertResponsesMessages(model2, context, allowedToolCallProviders, options) {
|
|
const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);
|
|
const messages = [];
|
|
const normalizeIdPart = (part) => {
|
|
const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;
|
|
return normalized.replace(/_+$/, "");
|
|
};
|
|
const buildForeignResponsesItemId = (itemId) => {
|
|
const normalized = `fc_${shortHash(itemId)}`;
|
|
return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
|
|
};
|
|
const normalizeToolCallId2 = (id, _targetModel, source) => {
|
|
if (!allowedToolCallProviders.has(model2.provider))
|
|
return normalizeIdPart(id);
|
|
if (!id.includes("|"))
|
|
return normalizeIdPart(id);
|
|
const [callId, itemId] = id.split("|");
|
|
const normalizedCallId = normalizeIdPart(callId);
|
|
const isForeignToolCall = source.provider !== model2.provider || source.api !== model2.api;
|
|
let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
|
|
if (!normalizedItemId.startsWith("fc_")) {
|
|
normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
|
|
}
|
|
return `${normalizedCallId}|${normalizedItemId}`;
|
|
};
|
|
const transformedMessages = transformMessages(normalizedContext.messages, model2, normalizeToolCallId2);
|
|
const toolSupport = getResponsesToolSupport(options ?? {});
|
|
const transcriptTools = resolveTranscriptTools(normalizedContext.messages, toolSupport);
|
|
let declaredAdditionalTools = false;
|
|
const unavailableTools = /* @__PURE__ */ new Set();
|
|
const appendSystemToolAdditions = (message, seed) => {
|
|
const tools = message.toolsAdded ?? [];
|
|
for (const tool of tools)
|
|
unavailableTools.delete(tool.name);
|
|
if (tools.length === 0)
|
|
return;
|
|
if (toolSupport === "changes") {
|
|
if (declaredAdditionalTools) {
|
|
messages.push({ role: instructionRole, content: renderIncrementalToolsNotice(unavailableTools) });
|
|
}
|
|
declaredAdditionalTools = true;
|
|
messages.push({
|
|
type: "additional_tools",
|
|
role: "developer",
|
|
tools: convertResponsesTools(tools, options?.toolOptions)
|
|
});
|
|
return;
|
|
}
|
|
if (toolSupport !== "additions")
|
|
return;
|
|
const names = tools.map((tool) => tool.name);
|
|
const callId = `pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;
|
|
messages.push({
|
|
type: "tool_search_call",
|
|
call_id: callId,
|
|
execution: "client",
|
|
status: "completed",
|
|
arguments: { query: names.join(" "), limit: names.length }
|
|
});
|
|
messages.push({
|
|
type: "tool_search_output",
|
|
call_id: callId,
|
|
execution: "client",
|
|
status: "completed",
|
|
tools: convertResponsesTools(tools, { ...options?.toolOptions, toolSearchResult: true })
|
|
});
|
|
};
|
|
const includeInitialSystemMessage = options?.includeSystemPrompt ?? true;
|
|
const pushConfigurationUpdate = (effort) => {
|
|
messages.push({
|
|
type: "configuration_update",
|
|
reasoning: { effort }
|
|
});
|
|
};
|
|
const compat = model2.compat;
|
|
const instructionRole = model2.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
|
|
let msgIndex = 0;
|
|
let sourceIndex = 0;
|
|
let systemIndex = 0;
|
|
for (const msg of transformedMessages) {
|
|
const isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === "system";
|
|
if (msg.role === "system") {
|
|
const anchorsToolChanges = systemIndex++ >= transcriptTools.foldedSystemMessages;
|
|
if (anchorsToolChanges)
|
|
appendSystemToolAdditions(msg, `system:${msgIndex}`);
|
|
if (!isLeadingSystemMessage || includeInitialSystemMessage) {
|
|
const parts = [isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg)];
|
|
if (anchorsToolChanges) {
|
|
const added = new Set((msg.toolsAdded ?? []).map((tool) => tool.name));
|
|
const removed = (msg.toolsRemoved ?? []).map((tool) => tool.name).filter((name) => !added.has(name));
|
|
if (removed.length > 0)
|
|
parts.push(renderToolRemovalNotice(removed));
|
|
for (const name of removed)
|
|
unavailableTools.add(name);
|
|
}
|
|
const text = parts.filter((part) => part.length > 0).join("\n\n");
|
|
if (text.length > 0) {
|
|
messages.push({ role: instructionRole, content: sanitizeSurrogates(text) });
|
|
}
|
|
}
|
|
} else if (msg.role === "user") {
|
|
if (typeof msg.content === "string") {
|
|
messages.push({
|
|
role: "user",
|
|
content: [{ type: "input_text", text: sanitizeSurrogates(msg.content) }]
|
|
});
|
|
} else {
|
|
const content = msg.content.map((item) => {
|
|
if (item.type === "text") {
|
|
return {
|
|
type: "input_text",
|
|
text: sanitizeSurrogates(item.text)
|
|
};
|
|
}
|
|
return {
|
|
type: "input_image",
|
|
detail: "auto",
|
|
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
};
|
|
});
|
|
if (content.length === 0)
|
|
continue;
|
|
messages.push({
|
|
role: "user",
|
|
content
|
|
});
|
|
}
|
|
} else if (msg.role === "assistant") {
|
|
const output = [];
|
|
const assistantMsg = msg;
|
|
const isSameProviderAndApi = assistantMsg.provider === model2.provider && assistantMsg.api === model2.api;
|
|
const isSameModel = isSameProviderAndApi && assistantMsg.model === model2.id;
|
|
const isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model2.id;
|
|
let textBlockIndex = 0;
|
|
for (const block of msg.content) {
|
|
if (block.type === "thinking") {
|
|
if (block.thinkingSignature) {
|
|
const reasoningItem = JSON.parse(block.thinkingSignature);
|
|
output.push(reasoningItem);
|
|
}
|
|
} else if (block.type === "text") {
|
|
const textBlock = block;
|
|
const parsedSignature = parseTextSignature(textBlock.textSignature);
|
|
const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
|
|
textBlockIndex++;
|
|
let msgId = parsedSignature?.id;
|
|
if (!msgId) {
|
|
msgId = fallbackMessageId;
|
|
} else if (msgId.length > 64) {
|
|
msgId = `msg_${shortHash(msgId)}`;
|
|
}
|
|
output.push({
|
|
type: "message",
|
|
role: "assistant",
|
|
content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
|
|
status: "completed",
|
|
id: msgId,
|
|
phase: parsedSignature?.phase
|
|
});
|
|
} else if (block.type === "toolCall") {
|
|
const toolCall = block;
|
|
const [callId, itemIdRaw] = toolCall.id.split("|");
|
|
const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
|
|
let itemId = itemIdRaw;
|
|
const itemIdPrefix = customInputProperty === void 0 ? "fc_" : "ctc_";
|
|
if (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {
|
|
itemId = void 0;
|
|
}
|
|
if (customInputProperty !== void 0) {
|
|
output.push({
|
|
type: "custom_tool_call",
|
|
id: itemId,
|
|
call_id: callId,
|
|
name: toolCall.name,
|
|
input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty)),
|
|
...isSameModel && toolCall.namespace !== void 0 ? { namespace: toolCall.namespace } : {}
|
|
});
|
|
} else {
|
|
output.push({
|
|
type: "function_call",
|
|
id: itemId,
|
|
call_id: callId,
|
|
name: toolCall.name,
|
|
arguments: JSON.stringify(toolCall.arguments),
|
|
...isSameModel && toolCall.namespace !== void 0 ? { namespace: toolCall.namespace } : {}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
if (output.length === 0)
|
|
continue;
|
|
if (options?.configurationUpdateEffort !== void 0 && isSameModel && msg.providerThinkingLevel !== void 0) {
|
|
pushConfigurationUpdate(msg.providerThinkingLevel);
|
|
}
|
|
messages.push(...output);
|
|
} else if (msg.role === "toolResult") {
|
|
const [callId] = msg.toolCallId.split("|");
|
|
const output = convertToolResultOutput(model2, msg.content);
|
|
if (options?.grammarToolInputProperties?.has(msg.toolName)) {
|
|
messages.push({
|
|
type: "custom_tool_call_output",
|
|
call_id: callId,
|
|
output
|
|
});
|
|
} else {
|
|
messages.push({
|
|
type: "function_call_output",
|
|
call_id: callId,
|
|
output
|
|
});
|
|
}
|
|
}
|
|
if (!isLeadingSystemMessage)
|
|
msgIndex++;
|
|
}
|
|
if (options?.configurationUpdateEffort !== void 0)
|
|
pushConfigurationUpdate(options.configurationUpdateEffort);
|
|
return messages;
|
|
}
|
|
function convertResponsesTools(tools, options) {
|
|
const defaultStrict = options?.strict === void 0 ? false : options.strict;
|
|
const supportsStrictMode = options?.supportsStrictMode ?? true;
|
|
const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;
|
|
return tools.map((tool) => {
|
|
const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
|
|
if (grammar) {
|
|
return {
|
|
type: "custom",
|
|
name: tool.name,
|
|
description: tool.description,
|
|
format: {
|
|
type: "grammar",
|
|
syntax: grammar.format,
|
|
definition: grammar.definition
|
|
},
|
|
...options?.toolSearchResult ? { defer_loading: true } : {}
|
|
};
|
|
}
|
|
const constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);
|
|
const strict = constrainedStrict ?? defaultStrict;
|
|
const functionTool = {
|
|
type: "function",
|
|
name: tool.name,
|
|
description: tool.description,
|
|
parameters: getJsonSchemaToolParameters(tool, strict === true),
|
|
...options?.toolSearchResult ? { defer_loading: true } : {}
|
|
};
|
|
if (supportsStrictMode) {
|
|
functionTool.strict = strict;
|
|
}
|
|
return functionTool;
|
|
});
|
|
}
|
|
async function processResponsesStream(openaiStream, output, stream4, model2, options) {
|
|
let sawTerminalResponseEvent = false;
|
|
const outputSlots = /* @__PURE__ */ new Map();
|
|
const unfinishedToolCalls = /* @__PURE__ */ new Set();
|
|
const reasoningBlocksById = /* @__PURE__ */ new Map();
|
|
const applyMessagePhaseStopReason = (item) => {
|
|
if (item.type === "message" && item.phase === "final_answer") {
|
|
output.stopReason = "stop";
|
|
}
|
|
};
|
|
const getSlot = (outputIndex, type) => {
|
|
const slot = outputSlots.get(outputIndex);
|
|
return slot?.type === type ? slot : void 0;
|
|
};
|
|
const pushToolCallDelta = (slot, delta) => {
|
|
if (delta === void 0)
|
|
return;
|
|
stream4.push({
|
|
type: "toolcall_delta",
|
|
contentIndex: slot.contentIndex,
|
|
delta,
|
|
partial: output
|
|
});
|
|
};
|
|
const createSlot = (outputIndex, item) => {
|
|
if (item.type === "reasoning") {
|
|
const block = { type: "thinking", thinking: "" };
|
|
output.content.push(block);
|
|
const slot = {
|
|
type: "thinking",
|
|
block,
|
|
contentIndex: output.content.length - 1
|
|
};
|
|
outputSlots.set(outputIndex, slot);
|
|
stream4.push({ type: "thinking_start", contentIndex: slot.contentIndex, partial: output });
|
|
return slot;
|
|
}
|
|
if (item.type === "message") {
|
|
applyMessagePhaseStopReason(item);
|
|
const block = { type: "text", text: "" };
|
|
output.content.push(block);
|
|
const slot = { type: "text", block, contentIndex: output.content.length - 1 };
|
|
outputSlots.set(outputIndex, slot);
|
|
stream4.push({ type: "text_start", contentIndex: slot.contentIndex, partial: output });
|
|
return slot;
|
|
}
|
|
if (item.type === "function_call") {
|
|
const args = new ToolCallArgumentsStream();
|
|
const block = {
|
|
type: "toolCall",
|
|
id: `${item.call_id}|${item.id}`,
|
|
name: item.name,
|
|
arguments: item.arguments ? args.append(item.arguments) : {},
|
|
...item.namespace !== void 0 ? { namespace: item.namespace } : {}
|
|
};
|
|
output.content.push(block);
|
|
unfinishedToolCalls.add(block);
|
|
const slot = {
|
|
type: "toolCall",
|
|
block,
|
|
contentIndex: output.content.length - 1,
|
|
input: { kind: "json", arguments: args }
|
|
};
|
|
outputSlots.set(outputIndex, slot);
|
|
stream4.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
|
|
return slot;
|
|
}
|
|
if (item.type === "custom_tool_call") {
|
|
const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? "input";
|
|
const input = item.input || "";
|
|
const block = {
|
|
type: "toolCall",
|
|
id: `${item.call_id}|${item.id}`,
|
|
name: item.name,
|
|
arguments: { [inputProperty]: input },
|
|
...item.namespace !== void 0 ? { namespace: item.namespace } : {}
|
|
};
|
|
output.content.push(block);
|
|
unfinishedToolCalls.add(block);
|
|
const slot = {
|
|
type: "toolCall",
|
|
block,
|
|
contentIndex: output.content.length - 1,
|
|
input: customInput(inputProperty, input)
|
|
};
|
|
outputSlots.set(outputIndex, slot);
|
|
stream4.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });
|
|
return slot;
|
|
}
|
|
return void 0;
|
|
};
|
|
const getOrCreateSlot = (outputIndex, item) => {
|
|
return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);
|
|
};
|
|
const backfillReasoningSignatures = (responseOutput) => {
|
|
for (const item of responseOutput) {
|
|
if (item.type !== "reasoning" || !item.encrypted_content)
|
|
continue;
|
|
const block = reasoningBlocksById.get(item.id);
|
|
if (!block?.thinkingSignature)
|
|
continue;
|
|
const storedItem = JSON.parse(block.thinkingSignature);
|
|
if (storedItem.encrypted_content)
|
|
continue;
|
|
block.thinkingSignature = JSON.stringify({
|
|
...storedItem,
|
|
encrypted_content: item.encrypted_content
|
|
});
|
|
}
|
|
};
|
|
const finalizeResponse2 = (response) => {
|
|
sawTerminalResponseEvent = true;
|
|
backfillReasoningSignatures(response.output ?? []);
|
|
if (response?.id) {
|
|
output.responseId = response.id;
|
|
}
|
|
if (response?.usage) {
|
|
const inputDetails = response.usage.input_tokens_details;
|
|
const cachedTokens = inputDetails?.cached_tokens || 0;
|
|
const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;
|
|
output.usage = {
|
|
// OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.
|
|
input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),
|
|
output: response.usage.output_tokens || 0,
|
|
cacheRead: cachedTokens,
|
|
cacheWrite: cacheWriteTokens,
|
|
reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,
|
|
totalTokens: response.usage.total_tokens || 0,
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
};
|
|
}
|
|
calculateCost(model2, output.usage);
|
|
if (options?.applyServiceTierPricing) {
|
|
const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier;
|
|
options.applyServiceTierPricing(output.usage, serviceTier);
|
|
}
|
|
const status = response?.status;
|
|
const incompleteDetails = response?.incomplete_details;
|
|
const incompleteReason = typeof incompleteDetails?.reason === "string" ? incompleteDetails.reason : void 0;
|
|
output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;
|
|
const mappedStop = mapStopReason(status, incompleteReason);
|
|
output.stopReason = mappedStop.stopReason;
|
|
if (mappedStop.errorMessage === void 0)
|
|
delete output.errorMessage;
|
|
else
|
|
output.errorMessage = mappedStop.errorMessage;
|
|
if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
|
|
output.stopReason = "toolUse";
|
|
}
|
|
};
|
|
for await (const event of openaiStream) {
|
|
await options?.onProviderStreamEvent?.(event, model2);
|
|
if (event.type === "response.created") {
|
|
output.responseId = event.response.id;
|
|
} else if (event.type === "response.output_item.added") {
|
|
createSlot(event.output_index, event.item);
|
|
} else if (event.type === "response.reasoning_summary_text.delta") {
|
|
const slot = getSlot(event.output_index, "thinking");
|
|
if (!slot)
|
|
continue;
|
|
slot.block.thinking += event.delta;
|
|
stream4.push({
|
|
type: "thinking_delta",
|
|
contentIndex: slot.contentIndex,
|
|
delta: event.delta,
|
|
partial: output
|
|
});
|
|
} else if (event.type === "response.reasoning_summary_part.done") {
|
|
const slot = getSlot(event.output_index, "thinking");
|
|
if (!slot)
|
|
continue;
|
|
slot.block.thinking += "\n\n";
|
|
stream4.push({
|
|
type: "thinking_delta",
|
|
contentIndex: slot.contentIndex,
|
|
delta: "\n\n",
|
|
partial: output
|
|
});
|
|
} else if (event.type === "response.reasoning_text.delta") {
|
|
const slot = getSlot(event.output_index, "thinking");
|
|
if (!slot)
|
|
continue;
|
|
slot.block.thinking += event.delta;
|
|
stream4.push({
|
|
type: "thinking_delta",
|
|
contentIndex: slot.contentIndex,
|
|
delta: event.delta,
|
|
partial: output
|
|
});
|
|
} else if (event.type === "response.output_text.delta") {
|
|
const slot = getSlot(event.output_index, "text");
|
|
if (!slot)
|
|
continue;
|
|
slot.block.text += event.delta;
|
|
stream4.push({
|
|
type: "text_delta",
|
|
contentIndex: slot.contentIndex,
|
|
delta: event.delta,
|
|
partial: output
|
|
});
|
|
} else if (event.type === "response.refusal.delta") {
|
|
const slot = getSlot(event.output_index, "text");
|
|
if (!slot)
|
|
continue;
|
|
slot.block.text += event.delta;
|
|
stream4.push({
|
|
type: "text_delta",
|
|
contentIndex: slot.contentIndex,
|
|
delta: event.delta,
|
|
partial: output
|
|
});
|
|
} else if (event.type === "response.function_call_arguments.delta") {
|
|
const slot = getSlot(event.output_index, "toolCall");
|
|
if (slot?.input.kind !== "json")
|
|
continue;
|
|
slot.block.arguments = slot.input.arguments.append(event.delta);
|
|
pushToolCallDelta(slot, event.delta);
|
|
} else if (event.type === "response.function_call_arguments.done") {
|
|
const slot = getSlot(event.output_index, "toolCall");
|
|
if (slot?.input.kind !== "json")
|
|
continue;
|
|
const replaced = slot.input.arguments.replace(event.arguments);
|
|
slot.block.arguments = replaced.arguments;
|
|
if (replaced.delta)
|
|
pushToolCallDelta(slot, replaced.delta);
|
|
} else if (event.type === "response.custom_tool_call_input.delta") {
|
|
const slot = getSlot(event.output_index, "toolCall");
|
|
if (slot?.input.kind !== "custom")
|
|
continue;
|
|
pushToolCallDelta(slot, appendCustomInput(slot.block, slot.input, event.delta));
|
|
} else if (event.type === "response.custom_tool_call_input.done") {
|
|
const slot = getSlot(event.output_index, "toolCall");
|
|
if (slot?.input.kind !== "custom")
|
|
continue;
|
|
pushToolCallDelta(slot, closeCustomInput(slot.block, slot.input, event.input));
|
|
} else if (event.type === "response.output_item.done") {
|
|
const item = event.item;
|
|
applyMessagePhaseStopReason(item);
|
|
const slot = getOrCreateSlot(event.output_index, item);
|
|
if (item.type === "reasoning" && slot?.type === "thinking") {
|
|
const summaryText = item.summary?.map((s) => s.text).join("\n\n") || "";
|
|
const contentText2 = item.content?.map((c) => c.text).join("\n\n") || "";
|
|
slot.block.thinking = summaryText || contentText2 || slot.block.thinking;
|
|
slot.block.thinkingSignature = JSON.stringify(item);
|
|
reasoningBlocksById.set(item.id, slot.block);
|
|
stream4.push({
|
|
type: "thinking_end",
|
|
contentIndex: slot.contentIndex,
|
|
content: slot.block.thinking,
|
|
partial: output
|
|
});
|
|
outputSlots.delete(event.output_index);
|
|
} else if (item.type === "message" && slot?.type === "text") {
|
|
slot.block.text = item.content?.map((c) => c.type === "output_text" ? c.text : c.refusal).join("") || "";
|
|
slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
|
|
stream4.push({
|
|
type: "text_end",
|
|
contentIndex: slot.contentIndex,
|
|
content: slot.block.text,
|
|
partial: output
|
|
});
|
|
outputSlots.delete(event.output_index);
|
|
} else if (item.type === "function_call" && slot?.type === "toolCall" && slot.input.kind === "json") {
|
|
if (item.arguments)
|
|
slot.input.arguments.replace(item.arguments);
|
|
Object.assign(slot.block, slot.input.arguments.finish());
|
|
if (item.namespace !== void 0)
|
|
slot.block.namespace = item.namespace;
|
|
unfinishedToolCalls.delete(slot.block);
|
|
stream4.push({
|
|
type: "toolcall_end",
|
|
contentIndex: slot.contentIndex,
|
|
toolCall: slot.block,
|
|
partial: output
|
|
});
|
|
outputSlots.delete(event.output_index);
|
|
} else if (item.type === "custom_tool_call" && slot?.type === "toolCall" && slot.input.kind === "custom") {
|
|
pushToolCallDelta(slot, closeCustomInput(slot.block, slot.input, item.input));
|
|
if (item.namespace !== void 0)
|
|
slot.block.namespace = item.namespace;
|
|
unfinishedToolCalls.delete(slot.block);
|
|
stream4.push({
|
|
type: "toolcall_end",
|
|
contentIndex: slot.contentIndex,
|
|
toolCall: slot.block,
|
|
partial: output
|
|
});
|
|
outputSlots.delete(event.output_index);
|
|
}
|
|
} else if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
finalizeResponse2(event.response);
|
|
} else if (event.type === "error") {
|
|
throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
|
|
} else if (event.type === "response.failed") {
|
|
sawTerminalResponseEvent = true;
|
|
output.rawStopReason = event.response?.status;
|
|
const error = event.response?.error;
|
|
const details = event.response?.incomplete_details;
|
|
const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
|
|
throw new Error(msg);
|
|
}
|
|
}
|
|
if (!sawTerminalResponseEvent) {
|
|
throw new Error("OpenAI Responses stream ended before a terminal response event");
|
|
}
|
|
if (output.stopReason === "toolUse") {
|
|
for (const toolCall of unfinishedToolCalls) {
|
|
throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`);
|
|
}
|
|
}
|
|
}
|
|
function customInput(property, initialInput) {
|
|
const buffer = { input: "", started: false, closed: false };
|
|
return {
|
|
kind: "custom",
|
|
property,
|
|
buffer,
|
|
unsent: appendGrammarToolInputJsonDelta(buffer, property, initialInput) ?? ""
|
|
};
|
|
}
|
|
function appendCustomInput(block, input, delta) {
|
|
return sendCustomInput(block, input, appendGrammarToolInputJsonDelta(input.buffer, input.property, delta));
|
|
}
|
|
function closeCustomInput(block, input, finalInput) {
|
|
return sendCustomInput(block, input, closeGrammarToolInputJson(input.buffer, input.property, finalInput));
|
|
}
|
|
function sendCustomInput(block, input, jsonDelta) {
|
|
block.arguments = { [input.property]: input.buffer.input };
|
|
if (input.unsent === "")
|
|
return jsonDelta;
|
|
const sent = input.unsent + (jsonDelta ?? "");
|
|
input.unsent = "";
|
|
return sent;
|
|
}
|
|
function mapStopReason(status, incompleteReason) {
|
|
if (!status)
|
|
return { stopReason: "stop" };
|
|
switch (status) {
|
|
case "completed":
|
|
return { stopReason: "stop" };
|
|
case "incomplete":
|
|
if (incompleteReason === "max_output_tokens") {
|
|
return { stopReason: "length" };
|
|
}
|
|
return {
|
|
stopReason: "error",
|
|
errorMessage: incompleteReason ? `Response incomplete: ${incompleteReason}` : "Response incomplete without a provider reason"
|
|
};
|
|
case "failed":
|
|
case "cancelled":
|
|
return { stopReason: "error" };
|
|
// These two are wonky ...
|
|
case "in_progress":
|
|
case "queued":
|
|
return { stopReason: "stop" };
|
|
default: {
|
|
const _exhaustive = status;
|
|
throw new Error(`Unhandled stop reason: ${_exhaustive}`);
|
|
}
|
|
}
|
|
}
|
|
var init_openai_responses_shared = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js"() {
|
|
init_models();
|
|
init_hash();
|
|
init_sanitize_unicode();
|
|
init_streaming_json();
|
|
init_text();
|
|
init_transcript();
|
|
init_constrained_sampling();
|
|
init_transform_messages();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/estimate.js
|
|
function calculateContextTokens(usage) {
|
|
return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
|
|
}
|
|
function safeJsonStringify2(value) {
|
|
try {
|
|
return JSON.stringify(value) ?? "undefined";
|
|
} catch {
|
|
return "[unserializable]";
|
|
}
|
|
}
|
|
function estimateTextAndImageContentChars(content) {
|
|
if (typeof content === "string")
|
|
return content.length;
|
|
let chars = 0;
|
|
for (const block of content)
|
|
chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
|
|
return chars;
|
|
}
|
|
function estimateTextTokens(text) {
|
|
return Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
}
|
|
function estimateTextAndImageContentTokens(content) {
|
|
return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
|
|
}
|
|
function estimateMessageTokens(message) {
|
|
let chars = 0;
|
|
if (message.role === "system") {
|
|
return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);
|
|
}
|
|
if (message.role === "user")
|
|
return estimateTextAndImageContentTokens(message.content);
|
|
if (message.role === "toolResult")
|
|
return estimateTextAndImageContentTokens(message.content);
|
|
for (const block of message.content) {
|
|
if (block.type === "text") {
|
|
chars += block.text.length;
|
|
} else if (block.type === "thinking") {
|
|
chars += block.thinking.length;
|
|
} else {
|
|
chars += block.name.length + safeJsonStringify2(block.arguments).length;
|
|
}
|
|
}
|
|
return Math.ceil(chars / CHARS_PER_TOKEN);
|
|
}
|
|
function getLastAssistantUsageInfo(messages) {
|
|
let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;
|
|
let usageInfo;
|
|
for (let i = 0; i < messages.length; i++) {
|
|
const message = messages[i];
|
|
if (message.role === "assistant") {
|
|
const assistant = message;
|
|
const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;
|
|
if (usageAppliesToPrefix && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" && calculateContextTokens(assistant.usage) > 0) {
|
|
usageInfo = { usage: assistant.usage, index: i };
|
|
}
|
|
}
|
|
latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);
|
|
}
|
|
return usageInfo;
|
|
}
|
|
function estimateContextTokens(context) {
|
|
const messages = "messages" in context ? context.messages : context;
|
|
const usageInfo = getLastAssistantUsageInfo(messages);
|
|
if (usageInfo) {
|
|
const usageTokens = calculateContextTokens(usageInfo.usage);
|
|
let trailingTokens = 0;
|
|
for (let i = usageInfo.index + 1; i < messages.length; i++) {
|
|
trailingTokens += estimateMessageTokens(messages[i]);
|
|
}
|
|
return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };
|
|
}
|
|
let tokens = 0;
|
|
for (const message of messages)
|
|
tokens += estimateMessageTokens(message);
|
|
return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };
|
|
}
|
|
function estimateToolsTokens(tools) {
|
|
if (!tools || tools.length === 0)
|
|
return 0;
|
|
return estimateTextTokens(safeJsonStringify2(tools));
|
|
}
|
|
var CHARS_PER_TOKEN, ESTIMATED_IMAGE_CHARS;
|
|
var init_estimate = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/estimate.js"() {
|
|
init_text();
|
|
CHARS_PER_TOKEN = 3.5;
|
|
ESTIMATED_IMAGE_CHARS = 4800;
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/simple-options.js
|
|
function clampMaxTokensToContext(model2, context, maxTokens) {
|
|
if (model2.contextWindow <= 0)
|
|
return Math.max(MIN_MAX_TOKENS, maxTokens);
|
|
const available = model2.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;
|
|
return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));
|
|
}
|
|
function resolveSamplingParams(model2, thinkingLevel, requestParams) {
|
|
const effectiveThinkingLevel = clampThinkingLevel(model2, thinkingLevel);
|
|
const thinkingLevelParams = model2.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];
|
|
return model2.samplingParams || thinkingLevelParams || requestParams ? { ...model2.samplingParams, ...thinkingLevelParams, ...requestParams } : void 0;
|
|
}
|
|
function buildBaseOptions(model2, context, options, apiKey) {
|
|
const samplingParams = resolveSamplingParams(model2, options?.reasoning ?? "off", options?.samplingParams);
|
|
return {
|
|
temperature: options?.temperature,
|
|
samplingParams,
|
|
maxTokens: clampMaxTokensToContext(model2, context, options?.maxTokens ?? model2.maxTokens),
|
|
signal: options?.signal,
|
|
telemetry: options?.telemetry,
|
|
apiKey: apiKey || options?.apiKey,
|
|
fetch: options?.fetch,
|
|
transport: options?.transport,
|
|
cacheRetention: options?.cacheRetention,
|
|
sessionId: options?.sessionId,
|
|
headers: options?.headers,
|
|
identity: options?.identity,
|
|
onPayload: options?.onPayload,
|
|
onResponse: options?.onResponse,
|
|
onProviderStreamEvent: options?.onProviderStreamEvent,
|
|
timeoutMs: options?.timeoutMs,
|
|
websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,
|
|
maxRetries: options?.maxRetries,
|
|
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
metadata: options?.metadata,
|
|
env: options?.env
|
|
};
|
|
}
|
|
function clampReasoning(effort) {
|
|
return effort === "xhigh" || effort === "max" ? "high" : effort;
|
|
}
|
|
function thinkingBudgetForLevel(reasoningLevel, customBudgets) {
|
|
const budgets = { ...DEFAULT_THINKING_BUDGETS, ...customBudgets };
|
|
const level = clampReasoning(reasoningLevel);
|
|
return budgets[level];
|
|
}
|
|
function clampThinkingBudgetToAnswerRoom(thinkingBudget, ceiling) {
|
|
return Math.min(thinkingBudget, Math.max(0, ceiling - MIN_ANSWER_TOKENS));
|
|
}
|
|
function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
|
|
let thinkingBudget = thinkingBudgetForLevel(reasoningLevel, customBudgets);
|
|
const maxTokens = baseMaxTokens === void 0 ? modelMaxTokens : Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);
|
|
if (maxTokens <= thinkingBudget) {
|
|
thinkingBudget = clampThinkingBudgetToAnswerRoom(thinkingBudget, maxTokens);
|
|
}
|
|
return { maxTokens, thinkingBudget };
|
|
}
|
|
var CONTEXT_SAFETY_TOKENS, MIN_MAX_TOKENS, MIN_ANSWER_TOKENS, DEFAULT_THINKING_BUDGETS;
|
|
var init_simple_options = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/simple-options.js"() {
|
|
init_models();
|
|
init_estimate();
|
|
CONTEXT_SAFETY_TOKENS = 4096;
|
|
MIN_MAX_TOKENS = 1;
|
|
MIN_ANSWER_TOKENS = 1024;
|
|
DEFAULT_THINKING_BUDGETS = {
|
|
minimal: 1024,
|
|
low: 2048,
|
|
medium: 8192,
|
|
high: 16384
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js
|
|
var openai_responses_exports = {};
|
|
__export(openai_responses_exports, {
|
|
stream: () => stream,
|
|
streamSimple: () => streamSimple
|
|
});
|
|
function isChatGPTSignIn(model2, apiKey) {
|
|
return model2.provider === "openai" && model2.baseUrl === "https://api.openai.com/v1" && apiKey !== void 0 && !apiKey.startsWith("sk-");
|
|
}
|
|
function hasHeader(headers, name) {
|
|
if (!headers)
|
|
return false;
|
|
const expected = name.toLowerCase();
|
|
for (const [key, value] of Object.entries(headers)) {
|
|
if (key.toLowerCase() === expected && value !== null && value.trim().length > 0)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function getClientApiKey(provider2, apiKey, headers) {
|
|
if (apiKey)
|
|
return apiKey;
|
|
if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization"))
|
|
return "unused";
|
|
throw new Error(`No API key for provider: ${provider2}`);
|
|
}
|
|
function detectSessionAffinityFormat(model2) {
|
|
return model2.provider === "openrouter" || model2.baseUrl.includes("openrouter.ai") ? "openrouter" : "openai";
|
|
}
|
|
function resolveCacheRetention(cacheRetention, env) {
|
|
if (cacheRetention) {
|
|
return cacheRetention;
|
|
}
|
|
if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
|
|
return "long";
|
|
}
|
|
return "short";
|
|
}
|
|
function getCompat(model2) {
|
|
return {
|
|
supportsDeveloperRole: model2.compat?.supportsDeveloperRole ?? true,
|
|
supportsMidConvoSystemMessages: model2.compat?.supportsMidConvoSystemMessages ?? false,
|
|
sessionAffinityFormat: model2.compat?.sessionAffinityFormat ?? detectSessionAffinityFormat(model2),
|
|
supportsLongCacheRetention: model2.compat?.supportsLongCacheRetention ?? true,
|
|
supportsStrictMode: model2.compat?.supportsStrictMode ?? false,
|
|
supportsOpenAIGrammarTools: model2.compat?.supportsOpenAIGrammarTools ?? false,
|
|
supportsAdditionalTools: model2.compat?.supportsAdditionalTools ?? false,
|
|
supportsToolSearch: model2.compat?.supportsToolSearch ?? false,
|
|
supportsExplicitPromptCacheMode: model2.compat?.supportsExplicitPromptCacheMode ?? false,
|
|
supportsMaxOutputTokens: model2.compat?.supportsMaxOutputTokens ?? true,
|
|
supportsMidConvoEffort: model2.compat?.supportsMidConvoEffort ?? false
|
|
};
|
|
}
|
|
function getConfigurationUpdateEffort(model2, options, compat) {
|
|
if (!compat.supportsMidConvoEffort || !options?.reasoningEffort || // Sign in with ChatGPT rejects configuration_update items.
|
|
isChatGPTSignIn(model2, options.apiKey)) {
|
|
return void 0;
|
|
}
|
|
return model2.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
|
|
}
|
|
function getPromptCacheRetention(compat, cacheRetention) {
|
|
return cacheRetention === "long" && compat.supportsLongCacheRetention && !compat.supportsExplicitPromptCacheMode ? "24h" : void 0;
|
|
}
|
|
function getPromptCacheOptions(compat, cacheRetention) {
|
|
if (!compat.supportsExplicitPromptCacheMode)
|
|
return void 0;
|
|
if (cacheRetention === "none")
|
|
return { mode: "explicit" };
|
|
if (cacheRetention === "long" && compat.supportsLongCacheRetention)
|
|
return { ttl: "30m" };
|
|
return void 0;
|
|
}
|
|
function createClient(model2, context, apiKey, optionsHeaders, identity, fetch2, sessionId) {
|
|
const compat = getCompat(model2);
|
|
const headers = { ...getIdentityHeaders(model2, identity), ...model2.headers };
|
|
if (model2.provider === "github-copilot") {
|
|
const hasImages = hasCopilotVisionInput(context.messages);
|
|
const copilotHeaders = buildCopilotDynamicHeaders({
|
|
messages: context.messages,
|
|
hasImages
|
|
});
|
|
Object.assign(headers, copilotHeaders);
|
|
}
|
|
if (sessionId) {
|
|
if (compat.sessionAffinityFormat === "openrouter") {
|
|
headers["x-session-id"] = sessionId;
|
|
} else {
|
|
if (compat.sessionAffinityFormat === "openai") {
|
|
headers.session_id = sessionId;
|
|
}
|
|
headers["x-client-request-id"] = sessionId;
|
|
}
|
|
}
|
|
if (optionsHeaders) {
|
|
Object.assign(headers, optionsHeaders);
|
|
}
|
|
return new OpenAI({
|
|
apiKey,
|
|
baseURL: model2.baseUrl,
|
|
dangerouslyAllowBrowser: true,
|
|
fetch: fetch2,
|
|
defaultHeaders: headers
|
|
});
|
|
}
|
|
function buildParams(model2, context, options, compat, grammarToolInputProperties, configurationUpdateEffort) {
|
|
const transcriptTools = resolveTranscriptTools(context.messages, getResponsesToolSupport(compat));
|
|
const messages = convertResponsesMessages(model2, context, OPENAI_TOOL_CALL_PROVIDERS, {
|
|
grammarToolInputProperties,
|
|
supportsMidConvoSystemMessages: compat.supportsMidConvoSystemMessages,
|
|
supportsAdditionalTools: compat.supportsAdditionalTools,
|
|
supportsToolSearch: compat.supportsToolSearch,
|
|
toolOptions: {
|
|
supportsStrictMode: compat.supportsStrictMode,
|
|
supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools
|
|
},
|
|
configurationUpdateEffort
|
|
});
|
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
|
|
const omitUnsupportedFields = isChatGPTSignIn(model2, options?.apiKey);
|
|
const params = {
|
|
model: model2.id,
|
|
input: messages,
|
|
stream: true,
|
|
prompt_cache_key: cacheRetention === "none" ? void 0 : clampOpenAIPromptCacheKey(options?.sessionId),
|
|
prompt_cache_retention: omitUnsupportedFields ? void 0 : getPromptCacheRetention(compat, cacheRetention),
|
|
prompt_cache_options: omitUnsupportedFields ? void 0 : getPromptCacheOptions(compat, cacheRetention),
|
|
store: false
|
|
};
|
|
if (options?.maxTokens && compat.supportsMaxOutputTokens && !omitUnsupportedFields) {
|
|
params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);
|
|
}
|
|
if (options?.temperature !== void 0 && !omitUnsupportedFields) {
|
|
params.temperature = options?.temperature;
|
|
}
|
|
if (options?.serviceTier !== void 0) {
|
|
params.service_tier = options.serviceTier;
|
|
}
|
|
if (transcriptTools.requestTools.length > 0) {
|
|
params.tools = convertResponsesTools(transcriptTools.requestTools, {
|
|
supportsStrictMode: compat.supportsStrictMode,
|
|
supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools
|
|
});
|
|
}
|
|
if (options?.toolChoice !== void 0) {
|
|
params.tool_choice = options.toolChoice;
|
|
}
|
|
const reasoningEffort = options?.reasoningEffort ?? (options?.reasoningSummary ? "medium" : void 0);
|
|
if (model2.reasoning) {
|
|
if (reasoningEffort) {
|
|
const requestedEffort = options?.reasoningEffort ? model2.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort : reasoningEffort;
|
|
const effort = configurationUpdateEffort === void 0 ? requestedEffort : CONFIGURATION_UPDATE_REQUEST_EFFORT;
|
|
params.reasoning = {
|
|
effort,
|
|
summary: options?.reasoningSummary || "auto"
|
|
};
|
|
params.include = ["reasoning.encrypted_content"];
|
|
} else if (model2.provider !== "github-copilot" && model2.thinkingLevelMap?.off !== null) {
|
|
params.reasoning = {
|
|
effort: model2.thinkingLevelMap?.off ?? "none"
|
|
};
|
|
}
|
|
if (model2.provider === "xai")
|
|
params.include = ["reasoning.encrypted_content"];
|
|
}
|
|
const samplingParams = resolveSamplingParams(model2, reasoningEffort ?? "off", options?.samplingParams);
|
|
if (samplingParams) {
|
|
Object.assign(params, samplingParams);
|
|
}
|
|
return params;
|
|
}
|
|
function getServiceTierCostMultiplier(model2, serviceTier) {
|
|
switch (serviceTier) {
|
|
case "flex":
|
|
return 0.5;
|
|
case "priority":
|
|
case "fast":
|
|
return model2.id === "gpt-5.5" ? 2.5 : 2;
|
|
default:
|
|
return 1;
|
|
}
|
|
}
|
|
function applyServiceTierPricing(usage, serviceTier, model2) {
|
|
const multiplier = getServiceTierCostMultiplier(model2, serviceTier);
|
|
if (multiplier === 1)
|
|
return;
|
|
usage.cost.input *= multiplier;
|
|
usage.cost.output *= multiplier;
|
|
usage.cost.cacheRead *= multiplier;
|
|
usage.cost.cacheWrite *= multiplier;
|
|
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
}
|
|
var OPENAI_TOOL_CALL_PROVIDERS, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS, CHATGPT_USAGE_URL, CHATGPT_WORKSPACE_LIMIT_HINT, CONFIGURATION_UPDATE_REQUEST_EFFORT, stream, streamSimple;
|
|
var init_openai_responses = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/openai-responses.js"() {
|
|
init_openai();
|
|
init_models();
|
|
init_error_body();
|
|
init_event_stream();
|
|
init_headers();
|
|
init_identity();
|
|
init_provider_env();
|
|
init_provider_retry();
|
|
init_transcript();
|
|
init_constrained_sampling();
|
|
init_github_copilot_headers();
|
|
init_openai_prompt_cache();
|
|
init_openai_responses_shared();
|
|
init_simple_options();
|
|
OPENAI_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]);
|
|
OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;
|
|
CHATGPT_USAGE_URL = "https://chatgpt.com/settings/usage";
|
|
CHATGPT_WORKSPACE_LIMIT_HINT = "You've reached your ChatGPT workspace's usage limit. Ask your workspace admin to increase it at admin.openai.com \u2192 Workspace \u2192 Usage limits.";
|
|
CONFIGURATION_UPDATE_REQUEST_EFFORT = "medium";
|
|
stream = (model2, context, options) => {
|
|
const stream4 = new AssistantMessageEventStream();
|
|
const normalizedContext = resolveTranscript(context, getCompat(model2).supportsMidConvoSystemMessages);
|
|
(async () => {
|
|
const compat = getCompat(model2);
|
|
const configurationUpdateEffort = getConfigurationUpdateEffort(model2, options, compat);
|
|
const output = {
|
|
role: "assistant",
|
|
content: [],
|
|
api: model2.api,
|
|
provider: model2.provider,
|
|
model: model2.id,
|
|
...configurationUpdateEffort === void 0 ? {} : { providerThinkingLevel: configurationUpdateEffort },
|
|
usage: {
|
|
input: 0,
|
|
output: 0,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
totalTokens: 0,
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
},
|
|
stopReason: "pending",
|
|
timestamp: Date.now()
|
|
};
|
|
try {
|
|
const apiKey = getClientApiKey(model2.provider, options?.apiKey, options?.headers);
|
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
|
|
const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
|
|
const grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages), compat.supportsOpenAIGrammarTools);
|
|
const client = createClient(model2, normalizedContext, apiKey, options?.headers, options?.identity, options?.fetch, cacheSessionId);
|
|
let params = buildParams(model2, normalizedContext, options, compat, grammarToolInputProperties, configurationUpdateEffort);
|
|
const nextParams = await options?.onPayload?.(params, model2);
|
|
if (nextParams !== void 0) {
|
|
params = nextParams;
|
|
}
|
|
const requestOptions = {
|
|
...options?.signal ? { signal: options.signal } : {},
|
|
...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
|
|
maxRetries: 0
|
|
};
|
|
const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {
|
|
maxRetries: options?.maxRetries,
|
|
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
signal: options?.signal
|
|
});
|
|
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model2);
|
|
stream4.push({ type: "start", partial: output });
|
|
await processResponsesStream(openaiStream, output, stream4, model2, {
|
|
onProviderStreamEvent: options?.onProviderStreamEvent,
|
|
serviceTier: options?.serviceTier,
|
|
grammarToolInputProperties,
|
|
applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model2)
|
|
});
|
|
if (options?.signal?.aborted) {
|
|
throw new Error("Request was aborted");
|
|
}
|
|
if (output.stopReason === "pending") {
|
|
throw new Error("OpenAI Responses stream ended without a stop reason");
|
|
}
|
|
if (output.stopReason === "aborted" || output.stopReason === "error") {
|
|
throw new Error(output.errorMessage || "An unknown error occurred");
|
|
}
|
|
stream4.push({ type: "done", reason: output.stopReason, message: output });
|
|
stream4.end();
|
|
} catch (error) {
|
|
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
const errorMessage2 = formatProviderError(normalizeProviderError(error), `${model2.provider === "openai" ? "OpenAI" : model2.provider} API error`);
|
|
if (errorMessage2.includes("subscription_sharing_usage_limit_exceeded")) {
|
|
output.errorMessage = `${errorMessage2}
|
|
Check your ChatGPT usage: ${CHATGPT_USAGE_URL}`;
|
|
} else if (errorMessage2.includes("subscription_sharing_workplace_individual_usage_limit_exceeded")) {
|
|
output.errorMessage = `${errorMessage2}
|
|
${CHATGPT_WORKSPACE_LIMIT_HINT}`;
|
|
} else {
|
|
output.errorMessage = errorMessage2;
|
|
}
|
|
stream4.push({ type: "error", reason: output.stopReason, error: output });
|
|
stream4.end();
|
|
}
|
|
})();
|
|
return stream4;
|
|
};
|
|
streamSimple = (model2, context, options) => {
|
|
getClientApiKey(model2.provider, options?.apiKey, options?.headers);
|
|
const base = {
|
|
...buildBaseOptions(model2, context, options, options?.apiKey),
|
|
toolChoice: options?.toolChoice
|
|
};
|
|
const clampedReasoning = options?.reasoning ? clampThinkingLevel(model2, options.reasoning) : void 0;
|
|
const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning;
|
|
return stream(model2, context, {
|
|
...base,
|
|
reasoningEffort
|
|
});
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/tslib.mjs
|
|
function __classPrivateFieldSet2(receiver, state2, value, kind, f) {
|
|
if (kind === "m")
|
|
throw new TypeError("Private method is not writable");
|
|
if (kind === "a" && !f)
|
|
throw new TypeError("Private accessor was defined without a setter");
|
|
if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver))
|
|
throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state2.set(receiver, value), value;
|
|
}
|
|
function __classPrivateFieldGet2(receiver, state2, kind, f) {
|
|
if (kind === "a" && !f)
|
|
throw new TypeError("Private accessor was defined without a getter");
|
|
if (typeof state2 === "function" ? receiver !== state2 || !f : !state2.has(receiver))
|
|
throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state2.get(receiver);
|
|
}
|
|
var init_tslib2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/tslib.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/errors.mjs
|
|
function isAbortError2(err) {
|
|
return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
|
|
("name" in err && err.name === "AbortError" || // Expo fetch
|
|
"message" in err && String(err.message).includes("FetchRequestCanceledException"));
|
|
}
|
|
var castToError2;
|
|
var init_errors2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/errors.mjs"() {
|
|
castToError2 = (err) => {
|
|
if (err instanceof Error)
|
|
return err;
|
|
if (typeof err === "object" && err !== null) {
|
|
try {
|
|
const tag = Object.prototype.toString.call(err);
|
|
if (tag === "[object Error]" || tag === "[object DOMException]") {
|
|
const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
|
|
if (err.stack)
|
|
error.stack = err.stack;
|
|
if (err.cause && !error.cause)
|
|
error.cause = err.cause;
|
|
if (err.name)
|
|
error.name = err.name;
|
|
return error;
|
|
}
|
|
} catch {
|
|
}
|
|
try {
|
|
return new Error(JSON.stringify(err));
|
|
} catch {
|
|
}
|
|
}
|
|
return new Error(err);
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/error.mjs
|
|
var AnthropicError, APIError2, APIUserAbortError2, APIConnectionError2, APIConnectionTimeoutError2, RetryableError, BadRequestError2, AuthenticationError2, PermissionDeniedError2, NotFoundError2, ConflictError2, UnprocessableEntityError2, RateLimitError2, InternalServerError2;
|
|
var init_error3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/error.mjs"() {
|
|
init_errors2();
|
|
AnthropicError = /* @__PURE__ */ (() => {
|
|
class AnthropicError2 extends Error {
|
|
}
|
|
return AnthropicError2;
|
|
})();
|
|
APIError2 = class _APIError extends AnthropicError {
|
|
constructor(status, error, message, headers, type) {
|
|
super(`${_APIError.makeMessage(status, error, message)}`);
|
|
this.status = status;
|
|
this.headers = headers;
|
|
this.requestID = headers?.get("request-id");
|
|
this.workspaceID = headers?.get("anthropic-workspace-id");
|
|
this.error = error;
|
|
this.type = type ?? null;
|
|
}
|
|
static makeMessage(status, error, message) {
|
|
const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
|
|
if (status && msg) {
|
|
return `${status} ${msg}`;
|
|
}
|
|
if (status) {
|
|
return `${status} status code (no body)`;
|
|
}
|
|
if (msg) {
|
|
return msg;
|
|
}
|
|
return "(no status code or body)";
|
|
}
|
|
static generate(status, errorResponse, message, headers) {
|
|
if (!status || !headers) {
|
|
return new APIConnectionError2({ message, cause: castToError2(errorResponse) });
|
|
}
|
|
const error = errorResponse;
|
|
const type = error?.["error"]?.["type"];
|
|
if (status === 400) {
|
|
return new BadRequestError2(status, error, message, headers, type);
|
|
}
|
|
if (status === 401) {
|
|
return new AuthenticationError2(status, error, message, headers, type);
|
|
}
|
|
if (status === 403) {
|
|
return new PermissionDeniedError2(status, error, message, headers, type);
|
|
}
|
|
if (status === 404) {
|
|
return new NotFoundError2(status, error, message, headers, type);
|
|
}
|
|
if (status === 409) {
|
|
return new ConflictError2(status, error, message, headers, type);
|
|
}
|
|
if (status === 422) {
|
|
return new UnprocessableEntityError2(status, error, message, headers, type);
|
|
}
|
|
if (status === 429) {
|
|
return new RateLimitError2(status, error, message, headers, type);
|
|
}
|
|
if (status >= 500) {
|
|
return new InternalServerError2(status, error, message, headers, type);
|
|
}
|
|
return new _APIError(status, error, message, headers, type);
|
|
}
|
|
};
|
|
APIUserAbortError2 = class extends APIError2 {
|
|
constructor({ message } = {}) {
|
|
super(void 0, void 0, message || "Request was aborted.", void 0);
|
|
}
|
|
};
|
|
APIConnectionError2 = class extends APIError2 {
|
|
constructor({ message, cause }) {
|
|
super(void 0, void 0, message || "Connection error.", void 0);
|
|
if (cause)
|
|
this.cause = cause;
|
|
}
|
|
};
|
|
APIConnectionTimeoutError2 = class extends APIConnectionError2 {
|
|
constructor({ message } = {}) {
|
|
super({ message: message ?? "Request timed out." });
|
|
}
|
|
};
|
|
RetryableError = class extends AnthropicError {
|
|
constructor(message, { cause } = {}) {
|
|
super(message ?? "Retryable error.");
|
|
if (cause !== void 0)
|
|
this.cause = cause;
|
|
}
|
|
};
|
|
BadRequestError2 = class extends APIError2 {
|
|
};
|
|
AuthenticationError2 = class extends APIError2 {
|
|
};
|
|
PermissionDeniedError2 = class extends APIError2 {
|
|
};
|
|
NotFoundError2 = class extends APIError2 {
|
|
};
|
|
ConflictError2 = class extends APIError2 {
|
|
};
|
|
UnprocessableEntityError2 = class extends APIError2 {
|
|
};
|
|
RateLimitError2 = class extends APIError2 {
|
|
};
|
|
InternalServerError2 = class extends APIError2 {
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/values.mjs
|
|
function maybeObj2(x) {
|
|
if (typeof x !== "object") {
|
|
return {};
|
|
}
|
|
return x ?? {};
|
|
}
|
|
function isEmptyObj2(obj2) {
|
|
if (!obj2)
|
|
return true;
|
|
for (const _k in obj2)
|
|
return false;
|
|
return true;
|
|
}
|
|
function hasOwn2(obj2, key) {
|
|
return Object.prototype.hasOwnProperty.call(obj2, key);
|
|
}
|
|
function isObj2(obj2) {
|
|
return obj2 != null && typeof obj2 === "object" && !Array.isArray(obj2);
|
|
}
|
|
function checkNever(_value) {
|
|
}
|
|
var startsWithSchemeRegexp2, isAbsoluteURL2, isArray2, isReadonlyArray2, validatePositiveInteger2, safeJSON2;
|
|
var init_values2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/values.mjs"() {
|
|
init_error3();
|
|
startsWithSchemeRegexp2 = /^[a-z][a-z0-9+.-]*:/i;
|
|
isAbsoluteURL2 = (url) => {
|
|
return startsWithSchemeRegexp2.test(url);
|
|
};
|
|
isArray2 = (val) => (isArray2 = Array.isArray, isArray2(val));
|
|
isReadonlyArray2 = isArray2;
|
|
validatePositiveInteger2 = (name, n) => {
|
|
if (typeof n !== "number" || !Number.isInteger(n)) {
|
|
throw new AnthropicError(`${name} must be an integer`);
|
|
}
|
|
if (n < 0) {
|
|
throw new AnthropicError(`${name} must be a positive integer`);
|
|
}
|
|
return n;
|
|
};
|
|
safeJSON2 = (text) => {
|
|
try {
|
|
return JSON.parse(text);
|
|
} catch (err) {
|
|
return void 0;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs
|
|
var sleep2;
|
|
var init_sleep2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs"() {
|
|
sleep2 = (ms, signal) => new Promise((resolve) => {
|
|
if (signal?.aborted)
|
|
return resolve();
|
|
const onAbort = () => {
|
|
clearTimeout(timer);
|
|
resolve();
|
|
};
|
|
const timer = setTimeout(() => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
resolve();
|
|
}, ms);
|
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/version.mjs
|
|
var VERSION2;
|
|
var init_version3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/version.mjs"() {
|
|
VERSION2 = "0.129.0";
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
|
|
function getDetectedPlatform2() {
|
|
if (typeof Deno !== "undefined" && Deno.build != null) {
|
|
return "deno";
|
|
}
|
|
if (typeof EdgeRuntime !== "undefined") {
|
|
return "edge";
|
|
}
|
|
if (Object.prototype.toString.call(typeof globalThis.process !== "undefined" ? globalThis.process : 0) === "[object process]") {
|
|
return "node";
|
|
}
|
|
return "unknown";
|
|
}
|
|
function getBrowserInfo2() {
|
|
if (typeof navigator === "undefined" || !navigator) {
|
|
return null;
|
|
}
|
|
const browserPatterns = [
|
|
{ key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
{ key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }
|
|
];
|
|
for (const { key, pattern } of browserPatterns) {
|
|
const match = pattern.exec(navigator.userAgent);
|
|
if (match) {
|
|
const major = match[1] || 0;
|
|
const minor = match[2] || 0;
|
|
const patch = match[3] || 0;
|
|
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
var isRunningInBrowser2, getPlatformProperties2, normalizeArch2, normalizePlatform2, _platformHeaders2, getPlatformHeaders2;
|
|
var init_detect_platform2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs"() {
|
|
init_version3();
|
|
isRunningInBrowser2 = () => {
|
|
return (
|
|
// @ts-ignore
|
|
typeof window !== "undefined" && // @ts-ignore
|
|
typeof window.document !== "undefined" && // @ts-ignore
|
|
typeof navigator !== "undefined"
|
|
);
|
|
};
|
|
getPlatformProperties2 = () => {
|
|
const detectedPlatform = getDetectedPlatform2();
|
|
if (detectedPlatform === "deno") {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION2,
|
|
"X-Stainless-OS": normalizePlatform2(Deno.build.os),
|
|
"X-Stainless-Arch": normalizeArch2(Deno.build.arch),
|
|
"X-Stainless-Runtime": "deno",
|
|
"X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : Deno.version?.deno ?? "unknown"
|
|
};
|
|
}
|
|
if (typeof EdgeRuntime !== "undefined") {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION2,
|
|
"X-Stainless-OS": "Unknown",
|
|
"X-Stainless-Arch": `other:${EdgeRuntime}`,
|
|
"X-Stainless-Runtime": "edge",
|
|
"X-Stainless-Runtime-Version": globalThis.process?.version ?? "unknown"
|
|
};
|
|
}
|
|
if (detectedPlatform === "node") {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION2,
|
|
"X-Stainless-OS": normalizePlatform2(globalThis.process.platform ?? "unknown"),
|
|
"X-Stainless-Arch": normalizeArch2(globalThis.process.arch ?? "unknown"),
|
|
"X-Stainless-Runtime": "node",
|
|
"X-Stainless-Runtime-Version": globalThis.process.version ?? "unknown"
|
|
};
|
|
}
|
|
const browserInfo = getBrowserInfo2();
|
|
if (browserInfo) {
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION2,
|
|
"X-Stainless-OS": "Unknown",
|
|
"X-Stainless-Arch": "unknown",
|
|
"X-Stainless-Runtime": `browser:${browserInfo.browser}`,
|
|
"X-Stainless-Runtime-Version": browserInfo.version
|
|
};
|
|
}
|
|
return {
|
|
"X-Stainless-Lang": "js",
|
|
"X-Stainless-Package-Version": VERSION2,
|
|
"X-Stainless-OS": "Unknown",
|
|
"X-Stainless-Arch": "unknown",
|
|
"X-Stainless-Runtime": "unknown",
|
|
"X-Stainless-Runtime-Version": "unknown"
|
|
};
|
|
};
|
|
normalizeArch2 = (arch) => {
|
|
if (arch === "x32")
|
|
return "x32";
|
|
if (arch === "x86_64" || arch === "x64")
|
|
return "x64";
|
|
if (arch === "arm")
|
|
return "arm";
|
|
if (arch === "aarch64" || arch === "arm64")
|
|
return "arm64";
|
|
if (arch)
|
|
return `other:${arch}`;
|
|
return "unknown";
|
|
};
|
|
normalizePlatform2 = (platform) => {
|
|
platform = platform.toLowerCase();
|
|
if (platform.includes("ios"))
|
|
return "iOS";
|
|
if (platform === "android")
|
|
return "Android";
|
|
if (platform === "darwin")
|
|
return "MacOS";
|
|
if (platform === "win32")
|
|
return "Windows";
|
|
if (platform === "freebsd")
|
|
return "FreeBSD";
|
|
if (platform === "openbsd")
|
|
return "OpenBSD";
|
|
if (platform === "linux")
|
|
return "Linux";
|
|
if (platform)
|
|
return `Other:${platform}`;
|
|
return "Unknown";
|
|
};
|
|
getPlatformHeaders2 = () => {
|
|
return _platformHeaders2 ?? (_platformHeaders2 = getPlatformProperties2());
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/request-signal.mjs
|
|
function makeCleanup(signal, listener) {
|
|
return () => signal.removeEventListener("abort", listener);
|
|
}
|
|
function registerRequestSignalCleanup(controller, signal, listener) {
|
|
cleanups.set(controller, makeCleanup(signal, listener));
|
|
}
|
|
function armAbandonmentBackstop(body, controller) {
|
|
if (cleanups.has(controller))
|
|
registry?.register(body, controller, controller);
|
|
}
|
|
function releaseRequestSignal(controller) {
|
|
const cleanup = cleanups.get(controller);
|
|
if (cleanup) {
|
|
cleanups.delete(controller);
|
|
registry?.unregister(controller);
|
|
cleanup();
|
|
}
|
|
}
|
|
var cleanups, registry;
|
|
var init_request_signal = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/request-signal.mjs"() {
|
|
cleanups = /* @__PURE__ */ new WeakMap();
|
|
registry = typeof globalThis.FinalizationRegistry === "function" ? new globalThis.FinalizationRegistry((controller) => releaseRequestSignal(controller)) : null;
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/shims.mjs
|
|
function getDefaultFetch2() {
|
|
if (typeof fetch !== "undefined") {
|
|
return fetch;
|
|
}
|
|
throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
|
|
}
|
|
function makeReadableStream2(...args) {
|
|
const ReadableStream2 = globalThis.ReadableStream;
|
|
if (typeof ReadableStream2 === "undefined") {
|
|
throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
|
|
}
|
|
return new ReadableStream2(...args);
|
|
}
|
|
function ReadableStreamFrom2(iterable) {
|
|
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
return makeReadableStream2({
|
|
start() {
|
|
},
|
|
async pull(controller) {
|
|
const { done, value } = await iter.next();
|
|
if (done) {
|
|
controller.close();
|
|
} else {
|
|
controller.enqueue(value);
|
|
}
|
|
},
|
|
async cancel() {
|
|
await iter.return?.();
|
|
}
|
|
});
|
|
}
|
|
function ReadableStreamToAsyncIterable2(stream4) {
|
|
if (stream4[Symbol.asyncIterator])
|
|
return stream4;
|
|
const reader = stream4.getReader();
|
|
return {
|
|
async next() {
|
|
try {
|
|
const result = await reader.read();
|
|
if (result?.done)
|
|
reader.releaseLock();
|
|
return result;
|
|
} catch (e) {
|
|
reader.releaseLock();
|
|
throw e;
|
|
}
|
|
},
|
|
async return() {
|
|
const cancelPromise = reader.cancel();
|
|
reader.releaseLock();
|
|
await cancelPromise;
|
|
return { done: true, value: void 0 };
|
|
},
|
|
[Symbol.asyncIterator]() {
|
|
return this;
|
|
}
|
|
};
|
|
}
|
|
async function CancelReadableStream2(stream4) {
|
|
if (stream4 === null || typeof stream4 !== "object")
|
|
return;
|
|
if (stream4[Symbol.asyncIterator]) {
|
|
await stream4[Symbol.asyncIterator]().return?.();
|
|
return;
|
|
}
|
|
const reader = stream4.getReader();
|
|
const cancelPromise = reader.cancel();
|
|
reader.releaseLock();
|
|
await cancelPromise;
|
|
}
|
|
var init_shims2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/shims.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/request-options.mjs
|
|
var FallbackEncoder2;
|
|
var init_request_options2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/request-options.mjs"() {
|
|
FallbackEncoder2 = ({ headers, body }) => {
|
|
return {
|
|
bodyHeaders: {
|
|
"content-type": "application/json"
|
|
},
|
|
body: JSON.stringify(body)
|
|
};
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs
|
|
var default_format2, default_formatter2, formatters2, RFC17382;
|
|
var init_formats2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs"() {
|
|
default_format2 = "RFC3986";
|
|
default_formatter2 = (v) => String(v);
|
|
formatters2 = {
|
|
RFC1738: (v) => String(v).replace(/%20/g, "+"),
|
|
RFC3986: default_formatter2
|
|
};
|
|
RFC17382 = "RFC1738";
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs
|
|
function is_buffer2(obj2) {
|
|
if (!obj2 || typeof obj2 !== "object") {
|
|
return false;
|
|
}
|
|
return !!(obj2.constructor && obj2.constructor.isBuffer && obj2.constructor.isBuffer(obj2));
|
|
}
|
|
function maybe_map2(val, fn) {
|
|
if (isArray2(val)) {
|
|
const mapped = [];
|
|
for (let i = 0; i < val.length; i += 1) {
|
|
mapped.push(fn(val[i]));
|
|
}
|
|
return mapped;
|
|
}
|
|
return fn(val);
|
|
}
|
|
var has2, hex_table2, limit2, encode2;
|
|
var init_utils3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs"() {
|
|
init_formats2();
|
|
init_values2();
|
|
has2 = (obj2, key) => (has2 = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has2(obj2, key));
|
|
hex_table2 = /* @__PURE__ */ (() => {
|
|
const array = [];
|
|
for (let i = 0; i < 256; ++i) {
|
|
array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
|
|
}
|
|
return array;
|
|
})();
|
|
limit2 = 1024;
|
|
encode2 = (str2, _defaultEncoder, charset, _kind, format) => {
|
|
if (str2.length === 0) {
|
|
return str2;
|
|
}
|
|
let string2 = str2;
|
|
if (typeof str2 === "symbol") {
|
|
string2 = Symbol.prototype.toString.call(str2);
|
|
} else if (typeof str2 !== "string") {
|
|
string2 = String(str2);
|
|
}
|
|
if (charset === "iso-8859-1") {
|
|
return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) {
|
|
return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
|
|
});
|
|
}
|
|
let out = "";
|
|
for (let j = 0; j < string2.length; j += limit2) {
|
|
const segment = string2.length >= limit2 ? string2.slice(j, j + limit2) : string2;
|
|
const arr2 = [];
|
|
for (let i = 0; i < segment.length; ++i) {
|
|
let c = segment.charCodeAt(i);
|
|
if (c === 45 || // -
|
|
c === 46 || // .
|
|
c === 95 || // _
|
|
c === 126 || // ~
|
|
c >= 48 && c <= 57 || // 0-9
|
|
c >= 65 && c <= 90 || // a-z
|
|
c >= 97 && c <= 122 || // A-Z
|
|
format === RFC17382 && (c === 40 || c === 41)) {
|
|
arr2[arr2.length] = segment.charAt(i);
|
|
continue;
|
|
}
|
|
if (c < 128) {
|
|
arr2[arr2.length] = hex_table2[c];
|
|
continue;
|
|
}
|
|
if (c < 2048) {
|
|
arr2[arr2.length] = hex_table2[192 | c >> 6] + hex_table2[128 | c & 63];
|
|
continue;
|
|
}
|
|
if (c < 55296 || c >= 57344) {
|
|
arr2[arr2.length] = hex_table2[224 | c >> 12] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63];
|
|
continue;
|
|
}
|
|
i += 1;
|
|
c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
|
|
arr2[arr2.length] = hex_table2[240 | c >> 18] + hex_table2[128 | c >> 12 & 63] + hex_table2[128 | c >> 6 & 63] + hex_table2[128 | c & 63];
|
|
}
|
|
out += arr2.join("");
|
|
}
|
|
return out;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs
|
|
function is_non_nullish_primitive2(v) {
|
|
return typeof v === "string" || typeof v === "number" || typeof v === "boolean" || typeof v === "symbol" || typeof v === "bigint";
|
|
}
|
|
function inner_stringify2(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder3, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {
|
|
let obj2 = object;
|
|
let tmp_sc = sideChannel;
|
|
let step = 0;
|
|
let find_flag = false;
|
|
while ((tmp_sc = tmp_sc.get(sentinel2)) !== void 0 && !find_flag) {
|
|
const pos = tmp_sc.get(object);
|
|
step += 1;
|
|
if (typeof pos !== "undefined") {
|
|
if (pos === step) {
|
|
throw new RangeError("Cyclic object value");
|
|
} else {
|
|
find_flag = true;
|
|
}
|
|
}
|
|
if (typeof tmp_sc.get(sentinel2) === "undefined") {
|
|
step = 0;
|
|
}
|
|
}
|
|
if (typeof filter === "function") {
|
|
obj2 = filter(prefix, obj2);
|
|
} else if (obj2 instanceof Date) {
|
|
obj2 = serializeDate?.(obj2);
|
|
} else if (generateArrayPrefix === "comma" && isArray2(obj2)) {
|
|
obj2 = maybe_map2(obj2, function(value) {
|
|
if (value instanceof Date) {
|
|
return serializeDate?.(value);
|
|
}
|
|
return value;
|
|
});
|
|
}
|
|
if (obj2 === null) {
|
|
if (strictNullHandling) {
|
|
return encoder3 && !encodeValuesOnly ? (
|
|
// @ts-expect-error
|
|
encoder3(prefix, defaults2.encoder, charset, "key", format)
|
|
) : prefix;
|
|
}
|
|
obj2 = "";
|
|
}
|
|
if (is_non_nullish_primitive2(obj2) || is_buffer2(obj2)) {
|
|
if (encoder3) {
|
|
const key_value = encodeValuesOnly ? prefix : encoder3(prefix, defaults2.encoder, charset, "key", format);
|
|
return [
|
|
formatter?.(key_value) + "=" + // @ts-expect-error
|
|
formatter?.(encoder3(obj2, defaults2.encoder, charset, "value", format))
|
|
];
|
|
}
|
|
return [formatter?.(prefix) + "=" + formatter?.(String(obj2))];
|
|
}
|
|
const values = [];
|
|
if (typeof obj2 === "undefined") {
|
|
return values;
|
|
}
|
|
let obj_keys;
|
|
if (generateArrayPrefix === "comma" && isArray2(obj2)) {
|
|
if (encodeValuesOnly && encoder3) {
|
|
obj2 = maybe_map2(obj2, encoder3);
|
|
}
|
|
obj_keys = [{ value: obj2.length > 0 ? obj2.join(",") || null : void 0 }];
|
|
} else if (isArray2(filter)) {
|
|
obj_keys = filter;
|
|
} else {
|
|
const keys = Object.keys(obj2);
|
|
obj_keys = sort ? keys.sort(sort) : keys;
|
|
}
|
|
const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
|
|
const adjusted_prefix = commaRoundTrip && isArray2(obj2) && obj2.length === 1 ? encoded_prefix + "[]" : encoded_prefix;
|
|
if (allowEmptyArrays && isArray2(obj2) && obj2.length === 0) {
|
|
return adjusted_prefix + "[]";
|
|
}
|
|
for (let j = 0; j < obj_keys.length; ++j) {
|
|
const key = obj_keys[j];
|
|
const value = (
|
|
// @ts-ignore
|
|
typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj2[key]
|
|
);
|
|
if (skipNulls && value === null) {
|
|
continue;
|
|
}
|
|
const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key;
|
|
const key_prefix = isArray2(obj2) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]");
|
|
sideChannel.set(object, step);
|
|
const valueSideChannel = /* @__PURE__ */ new WeakMap();
|
|
valueSideChannel.set(sentinel2, sideChannel);
|
|
push_to_array3(values, inner_stringify2(
|
|
value,
|
|
key_prefix,
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
allowEmptyArrays,
|
|
strictNullHandling,
|
|
skipNulls,
|
|
encodeDotInKeys,
|
|
// @ts-ignore
|
|
generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj2) ? null : encoder3,
|
|
filter,
|
|
sort,
|
|
allowDots,
|
|
serializeDate,
|
|
format,
|
|
formatter,
|
|
encodeValuesOnly,
|
|
charset,
|
|
valueSideChannel
|
|
));
|
|
}
|
|
return values;
|
|
}
|
|
function normalize_stringify_options2(opts = defaults2) {
|
|
if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
|
|
throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
|
|
}
|
|
if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
|
|
throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
|
|
}
|
|
if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
|
|
throw new TypeError("Encoder has to be a function.");
|
|
}
|
|
const charset = opts.charset || defaults2.charset;
|
|
if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
|
|
throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
|
|
}
|
|
let format = default_format2;
|
|
if (typeof opts.format !== "undefined") {
|
|
if (!has2(formatters2, opts.format)) {
|
|
throw new TypeError("Unknown format option provided.");
|
|
}
|
|
format = opts.format;
|
|
}
|
|
const formatter = formatters2[format];
|
|
let filter = defaults2.filter;
|
|
if (typeof opts.filter === "function" || isArray2(opts.filter)) {
|
|
filter = opts.filter;
|
|
}
|
|
let arrayFormat;
|
|
if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators2) {
|
|
arrayFormat = opts.arrayFormat;
|
|
} else if ("indices" in opts) {
|
|
arrayFormat = opts.indices ? "indices" : "repeat";
|
|
} else {
|
|
arrayFormat = defaults2.arrayFormat;
|
|
}
|
|
if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
|
|
throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
|
|
}
|
|
const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots;
|
|
return {
|
|
addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix,
|
|
// @ts-ignore
|
|
allowDots,
|
|
allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays,
|
|
arrayFormat,
|
|
charset,
|
|
charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
|
|
commaRoundTrip: !!opts.commaRoundTrip,
|
|
delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter,
|
|
encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode,
|
|
encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys,
|
|
encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder,
|
|
encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly,
|
|
filter,
|
|
format,
|
|
formatter,
|
|
serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate,
|
|
skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls,
|
|
// @ts-ignore
|
|
sort: typeof opts.sort === "function" ? opts.sort : null,
|
|
strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
|
|
};
|
|
}
|
|
function stringify2(object, opts = {}) {
|
|
let obj2 = object;
|
|
const options = normalize_stringify_options2(opts);
|
|
let obj_keys;
|
|
let filter;
|
|
if (typeof options.filter === "function") {
|
|
filter = options.filter;
|
|
obj2 = filter("", obj2);
|
|
} else if (isArray2(options.filter)) {
|
|
filter = options.filter;
|
|
obj_keys = filter;
|
|
}
|
|
const keys = [];
|
|
if (typeof obj2 !== "object" || obj2 === null) {
|
|
return "";
|
|
}
|
|
const generateArrayPrefix = array_prefix_generators2[options.arrayFormat];
|
|
const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
|
|
if (!obj_keys) {
|
|
obj_keys = Object.keys(obj2);
|
|
}
|
|
if (options.sort) {
|
|
obj_keys.sort(options.sort);
|
|
}
|
|
const sideChannel = /* @__PURE__ */ new WeakMap();
|
|
for (let i = 0; i < obj_keys.length; ++i) {
|
|
const key = obj_keys[i];
|
|
if (options.skipNulls && obj2[key] === null) {
|
|
continue;
|
|
}
|
|
push_to_array3(keys, inner_stringify2(
|
|
obj2[key],
|
|
key,
|
|
// @ts-expect-error
|
|
generateArrayPrefix,
|
|
commaRoundTrip,
|
|
options.allowEmptyArrays,
|
|
options.strictNullHandling,
|
|
options.skipNulls,
|
|
options.encodeDotInKeys,
|
|
options.encode ? options.encoder : null,
|
|
options.filter,
|
|
options.sort,
|
|
options.allowDots,
|
|
options.serializeDate,
|
|
options.format,
|
|
options.formatter,
|
|
options.encodeValuesOnly,
|
|
options.charset,
|
|
sideChannel
|
|
));
|
|
}
|
|
const joined = keys.join(options.delimiter);
|
|
let prefix = options.addQueryPrefix === true ? "?" : "";
|
|
if (options.charsetSentinel) {
|
|
if (options.charset === "iso-8859-1") {
|
|
prefix += "utf8=%26%2310003%3B&";
|
|
} else {
|
|
prefix += "utf8=%E2%9C%93&";
|
|
}
|
|
}
|
|
return joined.length > 0 ? prefix + joined : "";
|
|
}
|
|
var array_prefix_generators2, push_to_array3, toISOString2, defaults2, sentinel2;
|
|
var init_stringify2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/qs/stringify.mjs"() {
|
|
init_utils3();
|
|
init_formats2();
|
|
init_values2();
|
|
array_prefix_generators2 = {
|
|
brackets(prefix) {
|
|
return String(prefix) + "[]";
|
|
},
|
|
comma: "comma",
|
|
indices(prefix, key) {
|
|
return String(prefix) + "[" + key + "]";
|
|
},
|
|
repeat(prefix) {
|
|
return String(prefix);
|
|
}
|
|
};
|
|
push_to_array3 = function(arr2, value_or_array) {
|
|
Array.prototype.push.apply(arr2, isArray2(value_or_array) ? value_or_array : [value_or_array]);
|
|
};
|
|
defaults2 = {
|
|
addQueryPrefix: false,
|
|
allowDots: false,
|
|
allowEmptyArrays: false,
|
|
arrayFormat: "indices",
|
|
charset: "utf-8",
|
|
charsetSentinel: false,
|
|
delimiter: "&",
|
|
encode: true,
|
|
encodeDotInKeys: false,
|
|
encoder: encode2,
|
|
encodeValuesOnly: false,
|
|
format: default_format2,
|
|
formatter: default_formatter2,
|
|
/** @deprecated */
|
|
indices: false,
|
|
serializeDate(date) {
|
|
return (toISOString2 ?? (toISOString2 = Function.prototype.call.bind(Date.prototype.toISOString)))(date);
|
|
},
|
|
skipNulls: false,
|
|
strictNullHandling: false
|
|
};
|
|
sentinel2 = {};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/query.mjs
|
|
function stringifyQuery2(query) {
|
|
return stringify2(query, { arrayFormat: "brackets" });
|
|
}
|
|
var init_query2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/query.mjs"() {
|
|
init_stringify2();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/node.browser.mjs
|
|
var node_browser_exports = {};
|
|
__export(node_browser_exports, {
|
|
child_process: () => child_process,
|
|
crypto: () => crypto2,
|
|
fs: () => fs,
|
|
os: () => os,
|
|
path: () => path2,
|
|
stream: () => stream2,
|
|
util: () => util
|
|
});
|
|
function unavailable(module) {
|
|
return new Proxy({}, {
|
|
get(_target, property) {
|
|
if (typeof property === "symbol")
|
|
return void 0;
|
|
throw new AnthropicError(`\`${module}.${property}\` is not available in this environment; it needs a Node.js-compatible runtime`);
|
|
}
|
|
});
|
|
}
|
|
var child_process, crypto2, fs, os, path2, stream2, util;
|
|
var init_node_browser = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/node.browser.mjs"() {
|
|
init_error3();
|
|
child_process = /* @__PURE__ */ unavailable("child_process");
|
|
crypto2 = /* @__PURE__ */ unavailable("crypto");
|
|
fs = /* @__PURE__ */ unavailable("fs");
|
|
os = /* @__PURE__ */ unavailable("os");
|
|
path2 = /* @__PURE__ */ unavailable("path");
|
|
stream2 = /* @__PURE__ */ unavailable("stream");
|
|
util = /* @__PURE__ */ unavailable("util");
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs
|
|
function requireSecureTokenEndpoint(baseURL) {
|
|
if (!baseURL)
|
|
return;
|
|
let u;
|
|
try {
|
|
u = new URL(baseURL);
|
|
} catch (err) {
|
|
throw new WorkloadIdentityError(`Invalid token endpoint base URL "${baseURL}": ${err}`);
|
|
}
|
|
if (u.protocol === "https:")
|
|
return;
|
|
const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
if (u.protocol === "http:" && (host === "localhost" || host === "127.0.0.1" || host === "::1")) {
|
|
return;
|
|
}
|
|
throw new WorkloadIdentityError(`Refusing to send credential over non-https token endpoint "${baseURL}"`);
|
|
}
|
|
async function parseTokenResponse(resp, requestId) {
|
|
const text = await readLimitedText(resp);
|
|
let data;
|
|
try {
|
|
data = JSON.parse(text);
|
|
} catch {
|
|
throw new WorkloadIdentityError(`Token endpoint returned non-JSON response (status ${resp.status})`, resp.status, redactSensitive(text), requestId);
|
|
}
|
|
if (!data.access_token) {
|
|
throw new WorkloadIdentityError(`Token endpoint response missing access_token: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
|
|
}
|
|
if (data.token_type && data.token_type.toLowerCase() !== "bearer") {
|
|
throw new WorkloadIdentityError(`Token endpoint response: unsupported token_type "${data.token_type}" (want Bearer)`, resp.status, redactSensitive(data), requestId);
|
|
}
|
|
return data;
|
|
}
|
|
function redactSensitive(body) {
|
|
if (body == null)
|
|
return body;
|
|
if (typeof body === "string") {
|
|
let parsed;
|
|
try {
|
|
parsed = JSON.parse(body);
|
|
} catch {
|
|
if (body.length <= MAX_ERROR_BODY_CHARS)
|
|
return body;
|
|
return body.slice(0, MAX_ERROR_BODY_CHARS) + `... <${body.length - MAX_ERROR_BODY_CHARS} more chars>`;
|
|
}
|
|
return JSON.stringify(redactSensitive(parsed));
|
|
}
|
|
if (typeof body === "object" && !Array.isArray(body)) {
|
|
const out = {};
|
|
for (const [k, v] of Object.entries(body)) {
|
|
if (SAFE_ERROR_KEYS.has(k))
|
|
out[k] = v;
|
|
}
|
|
return out;
|
|
}
|
|
return null;
|
|
}
|
|
async function checkCredentialsFileSafety(path4, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) {
|
|
if (typeof process === "undefined" || process.platform === "win32")
|
|
return;
|
|
const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
let resolved = path4;
|
|
let st;
|
|
try {
|
|
resolved = await fs3.promises.realpath(path4);
|
|
st = await fs3.promises.stat(resolved);
|
|
} catch {
|
|
return;
|
|
}
|
|
const mode = st.mode & 511;
|
|
if (mode & 18) {
|
|
throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-writable (mode 0o${mode.toString(8)}); this allows other local users to plant tokens. Run \`chmod 600 ${resolved}\`.`);
|
|
}
|
|
if (mode & 36) {
|
|
throw new WorkloadIdentityError(`Credentials file at ${resolved} is group/world-readable (mode 0o${mode.toString(8)}); run \`chmod 600 ${resolved}\` before retrying.`);
|
|
}
|
|
if (typeof process.getuid === "function" && st.uid !== process.getuid()) {
|
|
onWarn(`credentials file at ${resolved} is owned by uid ${st.uid} (current process uid ${process.getuid()}); verify this is intentional.`);
|
|
}
|
|
}
|
|
async function writeCredentialsFileAtomic(targetPath, data) {
|
|
const { fs: fs3, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
const dir = path4.dirname(targetPath);
|
|
await fs3.promises.mkdir(dir, { recursive: true, mode: 448 });
|
|
const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
try {
|
|
const fh = await fs3.promises.open(tmpPath, "w", 384);
|
|
try {
|
|
await fh.writeFile(JSON.stringify(data, null, 2));
|
|
await fh.sync();
|
|
} finally {
|
|
await fh.close();
|
|
}
|
|
await fs3.promises.rename(tmpPath, targetPath);
|
|
} catch (err) {
|
|
await fs3.promises.unlink(tmpPath).catch(() => {
|
|
});
|
|
throw err;
|
|
}
|
|
try {
|
|
const dirFh = await fs3.promises.open(dir, "r");
|
|
try {
|
|
await dirFh.sync();
|
|
} finally {
|
|
await dirFh.close();
|
|
}
|
|
} catch {
|
|
}
|
|
}
|
|
async function readLimitedText(resp) {
|
|
if (!resp.body) {
|
|
return "";
|
|
}
|
|
const reader = resp.body.getReader();
|
|
const chunks = [];
|
|
let received = 0;
|
|
for (; ; ) {
|
|
const { done, value } = await reader.read();
|
|
if (done)
|
|
break;
|
|
if (received + value.length > MAX_TOKEN_RESPONSE_BYTES) {
|
|
const remaining = MAX_TOKEN_RESPONSE_BYTES - received;
|
|
if (remaining > 0)
|
|
chunks.push(value.subarray(0, remaining));
|
|
await reader.cancel();
|
|
break;
|
|
}
|
|
chunks.push(value);
|
|
received += value.length;
|
|
}
|
|
let merged;
|
|
if (chunks.length === 1) {
|
|
merged = chunks[0];
|
|
} else {
|
|
merged = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
let offset = 0;
|
|
for (const c of chunks) {
|
|
merged.set(c, offset);
|
|
offset += c.length;
|
|
}
|
|
}
|
|
return new TextDecoder("utf-8").decode(merged);
|
|
}
|
|
var GRANT_TYPE_JWT_BEARER, GRANT_TYPE_REFRESH_TOKEN, TOKEN_ENDPOINT, OAUTH_API_BETA_HEADER, FEDERATION_BETA_HEADER, ADVISORY_REFRESH_THRESHOLD_IN_SECONDS, MANDATORY_REFRESH_THRESHOLD_IN_SECONDS, ADVISORY_REFRESH_BACKOFF_IN_SECONDS, MAX_TOKEN_RESPONSE_BYTES, MAX_ERROR_BODY_CHARS, SAFE_ERROR_KEYS, WorkloadIdentityError;
|
|
var init_types = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/credentials/types.mjs"() {
|
|
init_error3();
|
|
GRANT_TYPE_JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
|
|
GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
|
|
TOKEN_ENDPOINT = "/v1/oauth/token";
|
|
OAUTH_API_BETA_HEADER = "oauth-2025-04-20";
|
|
FEDERATION_BETA_HEADER = "oidc-federation-2026-04-01";
|
|
ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
|
|
MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
|
|
ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
|
|
MAX_TOKEN_RESPONSE_BYTES = 1 << 20;
|
|
MAX_ERROR_BODY_CHARS = 2e3;
|
|
SAFE_ERROR_KEYS = /* @__PURE__ */ new Set(["error", "error_description", "error_uri"]);
|
|
WorkloadIdentityError = class extends AnthropicError {
|
|
constructor(message, statusCode = null, body = null, requestId = null) {
|
|
super(message);
|
|
this.statusCode = statusCode;
|
|
this.body = body;
|
|
this.requestId = requestId;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/time.mjs
|
|
function nowAsSeconds() {
|
|
return Math.floor(Date.now() / 1e3);
|
|
}
|
|
var init_time = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/time.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs
|
|
var TokenCache;
|
|
var init_token_cache = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs"() {
|
|
init_types();
|
|
init_time();
|
|
TokenCache = class {
|
|
constructor(provider2, onAdvisoryRefreshError) {
|
|
this.cached = null;
|
|
this.pendingRefresh = null;
|
|
this.nextForce = false;
|
|
this.lastAdvisoryError = 0;
|
|
this.provider = provider2;
|
|
this.onAdvisoryRefreshError = onAdvisoryRefreshError;
|
|
}
|
|
async getToken() {
|
|
const force = this.nextForce;
|
|
this.nextForce = false;
|
|
const cached = this.cached;
|
|
if (force || cached == null) {
|
|
const token2 = await this.refresh(force);
|
|
return token2.token;
|
|
}
|
|
if (cached.expiresAt == null) {
|
|
return cached.token;
|
|
}
|
|
const remaining = cached.expiresAt - nowAsSeconds();
|
|
if (remaining > ADVISORY_REFRESH_THRESHOLD_IN_SECONDS) {
|
|
return cached.token;
|
|
}
|
|
if (remaining > MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
|
|
this.backgroundRefresh();
|
|
return cached.token;
|
|
}
|
|
const token = await this.refresh();
|
|
return token.token;
|
|
}
|
|
/**
|
|
* Clears the cached token and marks the next {@link getToken} as a forced
|
|
* refresh, so the underlying provider bypasses any on-disk freshness check.
|
|
* Called after a 401 — the server has just told us the token is bad even
|
|
* if its `expires_at` still looks fresh.
|
|
*/
|
|
invalidate() {
|
|
this.cached = null;
|
|
this.nextForce = true;
|
|
}
|
|
/**
|
|
* Mandatory refresh. Joins any in-flight refresh unless forced — a forced
|
|
* refresh must not coalesce into a non-forced one that may re-serve the
|
|
* same stale disk token.
|
|
*/
|
|
refresh(force = false) {
|
|
if (this.pendingRefresh && !force) {
|
|
return this.pendingRefresh;
|
|
}
|
|
return this.doRefresh(force);
|
|
}
|
|
/**
|
|
* Advisory background refresh. Shares the same in-flight promise as
|
|
* mandatory refreshes for deduplication, but swallows errors so the
|
|
* stale cached token keeps being served. Backs off for
|
|
* {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure so an
|
|
* outage during the advisory window doesn't hammer the token endpoint.
|
|
*/
|
|
backgroundRefresh() {
|
|
if (this.pendingRefresh) {
|
|
return;
|
|
}
|
|
if (nowAsSeconds() - this.lastAdvisoryError < ADVISORY_REFRESH_BACKOFF_IN_SECONDS) {
|
|
return;
|
|
}
|
|
this.doRefresh().catch((err) => {
|
|
this.lastAdvisoryError = nowAsSeconds();
|
|
this.onAdvisoryRefreshError?.(err);
|
|
});
|
|
}
|
|
/**
|
|
* Core refresh. Sets {@link pendingRefresh} so concurrent callers
|
|
* (both advisory and mandatory) coalesce into a single provider call.
|
|
*/
|
|
doRefresh(force = false) {
|
|
this.pendingRefresh = this.provider(force ? { forceRefresh: true } : void 0).then((token) => {
|
|
this.cached = token;
|
|
this.pendingRefresh = null;
|
|
return token;
|
|
}, (err) => {
|
|
this.pendingRefresh = null;
|
|
throw err;
|
|
});
|
|
return this.pendingRefresh;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/env.mjs
|
|
var readEnv2;
|
|
var init_env2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/env.mjs"() {
|
|
readEnv2 = (env) => {
|
|
if (typeof globalThis.process !== "undefined") {
|
|
return globalThis.process.env?.[env]?.trim() || void 0;
|
|
}
|
|
if (typeof globalThis.Deno !== "undefined") {
|
|
return globalThis.Deno.env?.get?.(env)?.trim() || void 0;
|
|
}
|
|
return void 0;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs
|
|
function concatBytes(buffers) {
|
|
let length = 0;
|
|
for (const buffer of buffers) {
|
|
length += buffer.length;
|
|
}
|
|
const output = new Uint8Array(length);
|
|
let index = 0;
|
|
for (const buffer of buffers) {
|
|
output.set(buffer, index);
|
|
index += buffer.length;
|
|
}
|
|
return output;
|
|
}
|
|
function encodeUTF82(str2) {
|
|
let encoder3;
|
|
return (encodeUTF8_2 ?? (encoder3 = new globalThis.TextEncoder(), encodeUTF8_2 = encoder3.encode.bind(encoder3)))(str2);
|
|
}
|
|
function decodeUTF82(bytes2) {
|
|
let decoder3;
|
|
return (decodeUTF8_2 ?? (decoder3 = new globalThis.TextDecoder(), decodeUTF8_2 = decoder3.decode.bind(decoder3)))(bytes2);
|
|
}
|
|
var encodeUTF8_2, decodeUTF8_2;
|
|
var init_bytes2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs
|
|
var fromBase642;
|
|
var init_base642 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs"() {
|
|
init_error3();
|
|
fromBase642 = (str2) => {
|
|
if (typeof globalThis.Buffer !== "undefined") {
|
|
const buf = globalThis.Buffer.from(str2, "base64");
|
|
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
}
|
|
if (typeof atob !== "undefined") {
|
|
const bstr = atob(str2);
|
|
const buf = new Uint8Array(bstr.length);
|
|
for (let i = 0; i < bstr.length; i++) {
|
|
buf[i] = bstr.charCodeAt(i);
|
|
}
|
|
return buf;
|
|
}
|
|
throw new AnthropicError("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined");
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/log.mjs
|
|
function noop2() {
|
|
}
|
|
function makeLogFn2(fnLevel, logger, logLevel) {
|
|
if (!logger || levelNumbers2[fnLevel] > levelNumbers2[logLevel]) {
|
|
return noop2;
|
|
} else {
|
|
return logger[fnLevel].bind(logger);
|
|
}
|
|
}
|
|
function filterLogger(logger, logLevel) {
|
|
const cachedLogger = cachedLoggers2.get(logger);
|
|
if (cachedLogger && cachedLogger[0] === logLevel) {
|
|
return cachedLogger[1];
|
|
}
|
|
const levelLogger = {
|
|
error: makeLogFn2("error", logger, logLevel),
|
|
warn: makeLogFn2("warn", logger, logLevel),
|
|
info: makeLogFn2("info", logger, logLevel),
|
|
debug: makeLogFn2("debug", logger, logLevel)
|
|
};
|
|
cachedLoggers2.set(logger, [logLevel, levelLogger]);
|
|
return levelLogger;
|
|
}
|
|
function loggerFor2(client) {
|
|
const logger = client.logger;
|
|
const logLevel = client.logLevel ?? "off";
|
|
if (!logger) {
|
|
return noopLogger2;
|
|
}
|
|
return filterLogger(logger, logLevel);
|
|
}
|
|
function defaultLogger() {
|
|
const envLevel = readEnv2("ANTHROPIC_LOG");
|
|
if (!cachedDefaultLogger || envLevel !== lastEnvLevel) {
|
|
lastEnvLevel = envLevel;
|
|
cachedDefaultLogger = filterLogger(console, parseLogLevel2(envLevel, "process.env['ANTHROPIC_LOG']", filterLogger(console, defaultLogLevel)) ?? defaultLogLevel);
|
|
}
|
|
return cachedDefaultLogger;
|
|
}
|
|
function debugLogRequestDetails(logger, message, details) {
|
|
if (logger.debug === noop2) {
|
|
return;
|
|
}
|
|
logger.debug(message, formatRequestDetails2(details));
|
|
}
|
|
var defaultLogLevel, levelNumbers2, parseLogLevel2, noopLogger2, cachedLoggers2, lastEnvLevel, cachedDefaultLogger, formatRequestDetails2;
|
|
var init_log2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/log.mjs"() {
|
|
init_values2();
|
|
init_env2();
|
|
defaultLogLevel = "warn";
|
|
levelNumbers2 = {
|
|
off: 0,
|
|
error: 200,
|
|
warn: 300,
|
|
info: 400,
|
|
debug: 500
|
|
};
|
|
parseLogLevel2 = (maybeLevel, sourceName, logger) => {
|
|
if (!maybeLevel) {
|
|
return void 0;
|
|
}
|
|
if (hasOwn2(levelNumbers2, maybeLevel)) {
|
|
return maybeLevel;
|
|
}
|
|
logger.warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers2))}`);
|
|
return void 0;
|
|
};
|
|
noopLogger2 = {
|
|
error: noop2,
|
|
warn: noop2,
|
|
info: noop2,
|
|
debug: noop2
|
|
};
|
|
cachedLoggers2 = /* @__PURE__ */ new WeakMap();
|
|
formatRequestDetails2 = (details) => {
|
|
if (details.options) {
|
|
details.options = { ...details.options };
|
|
delete details.options["headers"];
|
|
}
|
|
if (details.headers) {
|
|
details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
|
|
name,
|
|
name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value
|
|
]));
|
|
}
|
|
if ("retryOfRequestLogID" in details) {
|
|
if (details.retryOfRequestLogID) {
|
|
details.retryOf = details.retryOfRequestLogID;
|
|
}
|
|
delete details.retryOfRequestLogID;
|
|
}
|
|
return details;
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs
|
|
var uuid42;
|
|
var init_uuid2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs"() {
|
|
uuid42 = function() {
|
|
const { crypto: crypto3 } = globalThis;
|
|
if (crypto3?.randomUUID) {
|
|
uuid42 = crypto3.randomUUID.bind(crypto3);
|
|
return crypto3.randomUUID();
|
|
}
|
|
const u8 = new Uint8Array(1);
|
|
const randomByte = crypto3 ? () => crypto3.getRandomValues(u8)[0] : () => Math.random() * 255 & 255;
|
|
return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (c) => (+c ^ randomByte() & 15 >> +c / 4).toString(16));
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils.mjs
|
|
var init_utils4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils.mjs"() {
|
|
init_values2();
|
|
init_base642();
|
|
init_env2();
|
|
init_log2();
|
|
init_uuid2();
|
|
init_sleep2();
|
|
init_query2();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/credentials.mjs
|
|
function validateProfileName(name) {
|
|
if (!name) {
|
|
throw new Error("profile name is empty");
|
|
}
|
|
if (name === "." || name === "..") {
|
|
throw new Error(`profile name "${name}" is not allowed`);
|
|
}
|
|
if (name.includes("/") || name.includes("\\")) {
|
|
throw new Error(`profile name "${name}" must not contain path separators`);
|
|
}
|
|
if (!PROFILE_NAME_PATTERN.test(name)) {
|
|
throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`);
|
|
}
|
|
}
|
|
var CREDENTIALS_FILE_VERSION, PROFILE_NAME_PATTERN, loadConfigWithSource, getCredentialsPath, getRootConfigPath, supportsLocalConfigFiles, getActiveProfileName;
|
|
var init_credentials2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/credentials.mjs"() {
|
|
init_detect_platform2();
|
|
init_utils4();
|
|
CREDENTIALS_FILE_VERSION = "1.0";
|
|
PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
|
|
loadConfigWithSource = async (profile) => {
|
|
var _a6, _b;
|
|
const rootConfigPath = await getRootConfigPath();
|
|
if (rootConfigPath === null) {
|
|
return null;
|
|
}
|
|
const profileName = profile ?? await getActiveProfileName();
|
|
if (profileName === null) {
|
|
return null;
|
|
}
|
|
validateProfileName(profileName);
|
|
const { fs: fs3, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
const configPath = path4.join(rootConfigPath, "configs", `${profileName}.json`);
|
|
let configRaw;
|
|
try {
|
|
configRaw = await fs3.promises.readFile(configPath, "utf-8");
|
|
} catch (err) {
|
|
if (err?.code !== "ENOENT") {
|
|
throw new Error(`failed to read config file ${configPath}: ${err}`);
|
|
}
|
|
configRaw = null;
|
|
}
|
|
if (configRaw === null) {
|
|
const organizationId = readEnv2("ANTHROPIC_ORGANIZATION_ID");
|
|
const identityTokenFile = readEnv2("ANTHROPIC_IDENTITY_TOKEN_FILE");
|
|
const federationRuleId = readEnv2("ANTHROPIC_FEDERATION_RULE_ID");
|
|
if (federationRuleId && organizationId) {
|
|
return {
|
|
fromFile: false,
|
|
config: {
|
|
organization_id: organizationId,
|
|
// A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=""`) is
|
|
// treated as unset — readEnv coerces empty to undefined, and the body
|
|
// builder's truthy check skips it — so `"workspace_id": ""` never goes
|
|
// on the wire.
|
|
workspace_id: readEnv2("ANTHROPIC_WORKSPACE_ID"),
|
|
base_url: readEnv2("ANTHROPIC_BASE_URL"),
|
|
authentication: {
|
|
type: "oidc_federation",
|
|
federation_rule_id: federationRuleId,
|
|
service_account_id: readEnv2("ANTHROPIC_SERVICE_ACCOUNT_ID"),
|
|
identity_token: identityTokenFile ? { source: "file", path: identityTokenFile } : void 0,
|
|
scope: readEnv2("ANTHROPIC_SCOPE")
|
|
}
|
|
}
|
|
};
|
|
}
|
|
return null;
|
|
}
|
|
let config;
|
|
try {
|
|
config = JSON.parse(configRaw);
|
|
} catch (err) {
|
|
throw new Error(`failed to parse config file ${configPath}: ${err}`);
|
|
}
|
|
if (!config.authentication) {
|
|
throw new Error(`config file ${configPath} is missing "authentication"`);
|
|
}
|
|
const authType = config.authentication.type;
|
|
if (authType !== "oidc_federation" && authType !== "user_oauth") {
|
|
throw new Error(`authentication.type "${authType}" is not a known authentication type`);
|
|
}
|
|
config.organization_id ?? (config.organization_id = readEnv2("ANTHROPIC_ORGANIZATION_ID"));
|
|
config.workspace_id ?? (config.workspace_id = readEnv2("ANTHROPIC_WORKSPACE_ID"));
|
|
config.base_url ?? (config.base_url = readEnv2("ANTHROPIC_BASE_URL"));
|
|
(_a6 = config.authentication).scope ?? (_a6.scope = readEnv2("ANTHROPIC_SCOPE"));
|
|
if (config.authentication.type === "oidc_federation") {
|
|
if (!config.authentication.identity_token) {
|
|
const identityTokenFile = readEnv2("ANTHROPIC_IDENTITY_TOKEN_FILE");
|
|
if (identityTokenFile) {
|
|
config.authentication.identity_token = {
|
|
source: "file",
|
|
path: identityTokenFile
|
|
};
|
|
}
|
|
}
|
|
if (!config.authentication.federation_rule_id) {
|
|
config.authentication.federation_rule_id = readEnv2("ANTHROPIC_FEDERATION_RULE_ID") ?? "";
|
|
}
|
|
(_b = config.authentication).service_account_id ?? (_b.service_account_id = readEnv2("ANTHROPIC_SERVICE_ACCOUNT_ID"));
|
|
}
|
|
return { config, fromFile: true };
|
|
};
|
|
getCredentialsPath = async (config, profile) => {
|
|
if (config?.authentication.credentials_path) {
|
|
return config.authentication.credentials_path;
|
|
}
|
|
const rootConfigPath = await getRootConfigPath();
|
|
if (!rootConfigPath) {
|
|
return null;
|
|
}
|
|
const profileName = profile ?? await getActiveProfileName();
|
|
if (!profileName) {
|
|
return null;
|
|
}
|
|
validateProfileName(profileName);
|
|
const { path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
return path4.join(rootConfigPath, "credentials", `${profileName}.json`);
|
|
};
|
|
getRootConfigPath = async () => {
|
|
if (!supportsLocalConfigFiles()) {
|
|
return null;
|
|
}
|
|
const { path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
const configDir = readEnv2("ANTHROPIC_CONFIG_DIR");
|
|
if (configDir) {
|
|
return configDir;
|
|
}
|
|
const os2 = getPlatformHeaders2()["X-Stainless-OS"];
|
|
if (os2 === "Windows") {
|
|
const appData = readEnv2("APPDATA");
|
|
if (appData) {
|
|
return path4.join(appData, "Anthropic");
|
|
}
|
|
const userProfile = readEnv2("USERPROFILE");
|
|
if (userProfile) {
|
|
return path4.join(userProfile, "AppData", "Roaming", "Anthropic");
|
|
}
|
|
return null;
|
|
}
|
|
const xdgConfigHome = readEnv2("XDG_CONFIG_HOME");
|
|
if (xdgConfigHome) {
|
|
return path4.join(xdgConfigHome, "anthropic");
|
|
}
|
|
const home = readEnv2("HOME");
|
|
if (home) {
|
|
return path4.join(home, ".config", "anthropic");
|
|
}
|
|
return null;
|
|
};
|
|
supportsLocalConfigFiles = () => {
|
|
const runtime = getPlatformHeaders2()["X-Stainless-Runtime"];
|
|
return runtime === "node" || runtime === "deno";
|
|
};
|
|
getActiveProfileName = async () => {
|
|
const rootConfigPath = await getRootConfigPath();
|
|
if (!rootConfigPath) {
|
|
return null;
|
|
}
|
|
const profileName = readEnv2("ANTHROPIC_PROFILE");
|
|
if (profileName) {
|
|
return profileName;
|
|
}
|
|
const { fs: fs3, path: path4 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
const filePath = path4.join(rootConfigPath, "active_config");
|
|
try {
|
|
return (await fs3.promises.readFile(filePath, "utf-8")).trim() || "default";
|
|
} catch (err) {
|
|
if (err?.code !== "ENOENT") {
|
|
throw new Error(`failed to read ${filePath}: ${err}`);
|
|
}
|
|
return "default";
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs
|
|
function identityTokenFromFile(path4) {
|
|
if (!path4) {
|
|
throw new AnthropicError("Identity token file path is empty");
|
|
}
|
|
return async () => {
|
|
const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
let content;
|
|
try {
|
|
content = await fs3.promises.readFile(path4, "utf-8");
|
|
} catch (err) {
|
|
throw new AnthropicError(`Failed to read identity token file at ${path4}: ${err}`);
|
|
}
|
|
const token = content.trim();
|
|
if (!token) {
|
|
throw new AnthropicError(`Identity token file at ${path4} is empty`);
|
|
}
|
|
return token;
|
|
};
|
|
}
|
|
function identityTokenFromValue(token) {
|
|
if (!token) {
|
|
throw new AnthropicError("Identity token value is empty");
|
|
}
|
|
return () => token;
|
|
}
|
|
var init_identity_token = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs"() {
|
|
init_error3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs
|
|
function oidcFederationProvider(config) {
|
|
return async () => {
|
|
requireSecureTokenEndpoint(config.baseURL);
|
|
const jwt = await config.identityTokenProvider();
|
|
if (jwt.length > 16 * 1024) {
|
|
throw new WorkloadIdentityError(`Identity token is ${Math.ceil(jwt.length / 1024)} KiB, exceeds the 16 KiB assertion limit`);
|
|
}
|
|
const body = {
|
|
grant_type: GRANT_TYPE_JWT_BEARER,
|
|
assertion: jwt,
|
|
federation_rule_id: config.federationRuleId,
|
|
organization_id: config.organizationId
|
|
};
|
|
if (config.serviceAccountId) {
|
|
body["service_account_id"] = config.serviceAccountId;
|
|
}
|
|
if (config.workspaceId) {
|
|
body["workspace_id"] = config.workspaceId;
|
|
}
|
|
const url = `${config.baseURL}${TOKEN_ENDPOINT}`;
|
|
let resp;
|
|
try {
|
|
resp = await config.fetch(url, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"anthropic-beta": `${OAUTH_API_BETA_HEADER},${FEDERATION_BETA_HEADER}`,
|
|
"User-Agent": config.userAgent || `anthropic-sdk-typescript/${VERSION2} oidcFederationProvider`
|
|
},
|
|
body: JSON.stringify(body)
|
|
});
|
|
} catch (err) {
|
|
throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${err}`);
|
|
}
|
|
const requestId = resp.headers.get("Request-Id");
|
|
if (!resp.ok) {
|
|
const text = await resp.text().catch(() => "");
|
|
const redacted = redactSensitive(text);
|
|
let hint = "";
|
|
if (resp.status === 401) {
|
|
const hintMiddle = config.workspaceId ? "" : "If your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the `workspaceId` option. ";
|
|
hint = ` Ensure your federation rule matches your identity token. ${hintMiddle}View your authentication events in the Workload identity page of Claude Console for more details.`;
|
|
}
|
|
throw new WorkloadIdentityError(`Token exchange failed with status ${resp.status}${requestId ? ` (request-id ${requestId})` : ""}: ${redacted}${hint}`, resp.status, redacted, requestId);
|
|
}
|
|
const data = await parseTokenResponse(resp, requestId);
|
|
const expiresIn = Number(data.expires_in);
|
|
if (!Number.isFinite(expiresIn)) {
|
|
throw new WorkloadIdentityError(`Token endpoint response missing required fields: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
|
|
}
|
|
return {
|
|
token: data.access_token,
|
|
expiresAt: nowAsSeconds() + expiresIn
|
|
};
|
|
};
|
|
}
|
|
var init_oidc_federation = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/credentials/oidc-federation.mjs"() {
|
|
init_types();
|
|
init_time();
|
|
init_version3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs
|
|
function userOAuthProvider(config) {
|
|
return async (opts) => {
|
|
const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning);
|
|
let raw;
|
|
try {
|
|
raw = await fs3.promises.readFile(config.credentialsPath, "utf-8");
|
|
} catch (err) {
|
|
throw new WorkloadIdentityError(`Credentials file not found at ${config.credentialsPath}: ${err}`);
|
|
}
|
|
let creds;
|
|
try {
|
|
creds = JSON.parse(raw);
|
|
} catch (err) {
|
|
throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} is not valid JSON: ${err}`);
|
|
}
|
|
const accessToken = creds.access_token;
|
|
if (!accessToken) {
|
|
throw new WorkloadIdentityError(`Credentials file at ${config.credentialsPath} must include 'access_token'`);
|
|
}
|
|
const expiresAt = creds.expires_at;
|
|
if (!opts?.forceRefresh && (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS)) {
|
|
return { token: accessToken, expiresAt: expiresAt ?? null };
|
|
}
|
|
const refreshToken = creds.refresh_token;
|
|
if (!config.clientId || !refreshToken) {
|
|
throw new WorkloadIdentityError(`Access token at ${config.credentialsPath} has expired and no refresh is available (client_id ${config.clientId ? "set" : "empty"}, refresh_token ${refreshToken ? "set" : "empty"})`);
|
|
}
|
|
requireSecureTokenEndpoint(config.baseURL);
|
|
const body = {
|
|
grant_type: GRANT_TYPE_REFRESH_TOKEN,
|
|
refresh_token: refreshToken,
|
|
client_id: config.clientId
|
|
};
|
|
const url = `${config.baseURL}${TOKEN_ENDPOINT}`;
|
|
let resp;
|
|
try {
|
|
resp = await config.fetch(url, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"anthropic-beta": OAUTH_API_BETA_HEADER,
|
|
"User-Agent": config.userAgent || `anthropic-sdk-typescript/${VERSION2} userOAuthProvider`
|
|
},
|
|
body: JSON.stringify(body)
|
|
});
|
|
} catch (err) {
|
|
throw new WorkloadIdentityError(`User OAuth refresh failed to reach token endpoint: ${err}`);
|
|
}
|
|
const requestId = resp.headers.get("Request-Id");
|
|
if (!resp.ok) {
|
|
const text = await resp.text().catch(() => "");
|
|
throw new WorkloadIdentityError(`User OAuth refresh failed (HTTP ${resp.status}): ${redactSensitive(text)}`, resp.status, redactSensitive(text), requestId);
|
|
}
|
|
const data = await parseTokenResponse(resp, requestId);
|
|
const expiresIn = Number(data.expires_in);
|
|
if (!Number.isFinite(expiresIn)) {
|
|
throw new WorkloadIdentityError(`User OAuth refresh response missing or invalid expires_in: ${JSON.stringify(redactSensitive(data))}`, resp.status, redactSensitive(data), requestId);
|
|
}
|
|
const newExpiresAt = nowAsSeconds() + expiresIn;
|
|
const newRefreshToken = data.refresh_token || refreshToken;
|
|
await writeCredentialsFileAtomic(config.credentialsPath, {
|
|
...creds,
|
|
version: CREDENTIALS_FILE_VERSION,
|
|
type: "oauth_token",
|
|
access_token: data.access_token,
|
|
expires_at: newExpiresAt,
|
|
refresh_token: newRefreshToken
|
|
});
|
|
return { token: data.access_token, expiresAt: newExpiresAt };
|
|
};
|
|
}
|
|
var init_user_oauth = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs"() {
|
|
init_credentials2();
|
|
init_types();
|
|
init_time();
|
|
init_version3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs
|
|
function resolveCredentialsFromConfig(config, options) {
|
|
const credentialsPath = config.authentication.credentials_path ?? null;
|
|
const effectiveBaseURL = (config.base_url || options.baseURL).replace(/\/+$/, "");
|
|
const provider2 = buildProvider(config, credentialsPath, effectiveBaseURL, options);
|
|
const extraHeaders = {};
|
|
if (config.workspace_id && config.authentication.type === "user_oauth") {
|
|
extraHeaders["anthropic-workspace-id"] = config.workspace_id;
|
|
}
|
|
return { provider: provider2, extraHeaders, baseURL: config.base_url || void 0 };
|
|
}
|
|
async function defaultCredentials(options, profile) {
|
|
const loaded = await loadConfigWithSource(profile);
|
|
if (!loaded) {
|
|
return null;
|
|
}
|
|
const { config, fromFile } = loaded;
|
|
const withPath = config.authentication.credentials_path || !fromFile ? config : {
|
|
...config,
|
|
authentication: {
|
|
...config.authentication,
|
|
credentials_path: await getCredentialsPath(config, profile) ?? void 0
|
|
}
|
|
};
|
|
return resolveCredentialsFromConfig(withPath, options);
|
|
}
|
|
function buildProvider(config, credentialsPath, baseURL, options) {
|
|
switch (config.authentication.type) {
|
|
case "oidc_federation": {
|
|
const auth2 = config.authentication;
|
|
const identityProvider = resolveIdentityTokenProvider(auth2);
|
|
if (!identityProvider) {
|
|
throw new WorkloadIdentityError("oidc_federation config requires an identity token (set authentication.identity_token, ANTHROPIC_IDENTITY_TOKEN_FILE, or ANTHROPIC_IDENTITY_TOKEN)");
|
|
}
|
|
if (!auth2.federation_rule_id) {
|
|
throw new WorkloadIdentityError("oidc_federation config requires 'federation_rule_id'. Set it in authentication.federation_rule_id in your profile, or via ANTHROPIC_FEDERATION_RULE_ID (profile takes precedence).");
|
|
}
|
|
if (!config.organization_id) {
|
|
throw new WorkloadIdentityError("oidc_federation config requires organization_id (set ANTHROPIC_ORGANIZATION_ID or config.organization_id)");
|
|
}
|
|
const exchange = oidcFederationProvider({
|
|
identityTokenProvider: identityProvider,
|
|
federationRuleId: auth2.federation_rule_id,
|
|
organizationId: config.organization_id,
|
|
serviceAccountId: auth2.service_account_id,
|
|
workspaceId: config.workspace_id,
|
|
baseURL,
|
|
fetch: options.fetch,
|
|
userAgent: options.userAgent
|
|
});
|
|
if (credentialsPath) {
|
|
return cachedExchangeProvider(exchange, credentialsPath, options.onCacheWriteError, options.onSafetyWarning);
|
|
}
|
|
return exchange;
|
|
}
|
|
case "user_oauth": {
|
|
if (!credentialsPath) {
|
|
throw new WorkloadIdentityError("user_oauth config requires authentication.credentials_path (or load via a profile so it defaults to <config_dir>/credentials/<profile>.json)");
|
|
}
|
|
return userOAuthProvider({
|
|
credentialsPath,
|
|
clientId: config.authentication.client_id,
|
|
baseURL,
|
|
fetch: options.fetch,
|
|
userAgent: options.userAgent,
|
|
onSafetyWarning: options.onSafetyWarning
|
|
});
|
|
}
|
|
default: {
|
|
const t = config.authentication.type;
|
|
throw new WorkloadIdentityError(`authentication.type "${t}" is not a known authentication type`);
|
|
}
|
|
}
|
|
}
|
|
function resolveIdentityTokenProvider(auth2) {
|
|
if (auth2.identity_token) {
|
|
const source = auth2.identity_token.source;
|
|
if (source !== "file") {
|
|
throw new WorkloadIdentityError(`identity_token.source "${source}" is not supported by this SDK version (only "file")`);
|
|
}
|
|
if (!auth2.identity_token.path) {
|
|
throw new WorkloadIdentityError(`identity_token.source "file" requires a non-empty path`);
|
|
}
|
|
return identityTokenFromFile(auth2.identity_token.path);
|
|
}
|
|
const tokenFile = readEnv2("ANTHROPIC_IDENTITY_TOKEN_FILE");
|
|
if (tokenFile) {
|
|
return identityTokenFromFile(tokenFile);
|
|
}
|
|
const tokenValue = readEnv2("ANTHROPIC_IDENTITY_TOKEN");
|
|
if (tokenValue) {
|
|
return identityTokenFromValue(tokenValue);
|
|
}
|
|
return null;
|
|
}
|
|
function cachedExchangeProvider(exchange, credentialsPath, onCacheWriteError, onSafetyWarning) {
|
|
return async (opts) => {
|
|
const { fs: fs3 } = await Promise.resolve().then(() => (init_node_browser(), node_browser_exports));
|
|
await checkCredentialsFileSafety(credentialsPath, onSafetyWarning);
|
|
let existing;
|
|
try {
|
|
const raw = await fs3.promises.readFile(credentialsPath, "utf-8");
|
|
existing = JSON.parse(raw);
|
|
const token = existing?.["access_token"];
|
|
if (token && !opts?.forceRefresh) {
|
|
const expiresAt = existing?.["expires_at"];
|
|
if (expiresAt == null || nowAsSeconds() < expiresAt - MANDATORY_REFRESH_THRESHOLD_IN_SECONDS) {
|
|
return { token, expiresAt: expiresAt ?? null };
|
|
}
|
|
}
|
|
} catch (err) {
|
|
const code = err?.code;
|
|
if (code !== "ENOENT" && !(err instanceof SyntaxError)) {
|
|
onCacheWriteError?.(err);
|
|
}
|
|
}
|
|
const result = await exchange(opts);
|
|
try {
|
|
await writeCredentialsFileAtomic(credentialsPath, {
|
|
...existing ?? {},
|
|
version: CREDENTIALS_FILE_VERSION,
|
|
type: "oauth_token",
|
|
access_token: result.token,
|
|
expires_at: result.expiresAt
|
|
});
|
|
} catch (err) {
|
|
onCacheWriteError?.(err);
|
|
}
|
|
return result;
|
|
};
|
|
}
|
|
var init_credential_chain = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/credentials/credential-chain.mjs"() {
|
|
init_env2();
|
|
init_credentials2();
|
|
init_types();
|
|
init_time();
|
|
init_identity_token();
|
|
init_oidc_federation();
|
|
init_user_oauth();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs
|
|
function findNewlineIndex2(buffer, startIndex) {
|
|
const newline = 10;
|
|
const carriage = 13;
|
|
for (let i = startIndex ?? 0; i < buffer.length; i++) {
|
|
if (buffer[i] === newline) {
|
|
return { preceding: i, index: i + 1, carriage: false };
|
|
}
|
|
if (buffer[i] === carriage) {
|
|
return { preceding: i, index: i + 1, carriage: true };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
var _LineDecoder_buffer2, _LineDecoder_carriageReturnIndex, LineDecoder2;
|
|
var init_line2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs"() {
|
|
init_tslib2();
|
|
init_bytes2();
|
|
LineDecoder2 = /* @__PURE__ */ (() => {
|
|
class LineDecoder3 {
|
|
constructor() {
|
|
_LineDecoder_buffer2.set(this, void 0);
|
|
_LineDecoder_carriageReturnIndex.set(this, void 0);
|
|
__classPrivateFieldSet2(this, _LineDecoder_buffer2, new Uint8Array(), "f");
|
|
__classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex, null, "f");
|
|
}
|
|
decode(chunk) {
|
|
if (chunk == null) {
|
|
return [];
|
|
}
|
|
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? encodeUTF82(chunk) : chunk;
|
|
__classPrivateFieldSet2(this, _LineDecoder_buffer2, concatBytes([__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f"), binaryChunk]), "f");
|
|
const lines = [];
|
|
let patternIndex;
|
|
while ((patternIndex = findNewlineIndex2(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f"), __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f"))) != null) {
|
|
if (patternIndex.carriage && __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") == null) {
|
|
__classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f");
|
|
continue;
|
|
}
|
|
if (__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") != null && (patternIndex.index !== __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) {
|
|
lines.push(decodeUTF82(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(0, __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") - 1)));
|
|
__classPrivateFieldSet2(this, _LineDecoder_buffer2, __classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(__classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f")), "f");
|
|
__classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex, null, "f");
|
|
continue;
|
|
}
|
|
const endIndex = __classPrivateFieldGet2(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
|
|
const line = decodeUTF82(__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(0, endIndex));
|
|
lines.push(line);
|
|
__classPrivateFieldSet2(this, _LineDecoder_buffer2, __classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").subarray(patternIndex.index), "f");
|
|
__classPrivateFieldSet2(this, _LineDecoder_carriageReturnIndex, null, "f");
|
|
}
|
|
return lines;
|
|
}
|
|
flush() {
|
|
if (!__classPrivateFieldGet2(this, _LineDecoder_buffer2, "f").length) {
|
|
return [];
|
|
}
|
|
return this.decode("\n");
|
|
}
|
|
}
|
|
_LineDecoder_buffer2 = /* @__PURE__ */ new WeakMap(), _LineDecoder_carriageReturnIndex = /* @__PURE__ */ new WeakMap();
|
|
LineDecoder3.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
|
|
LineDecoder3.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
return LineDecoder3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/streaming.mjs
|
|
async function* _iterSSEMessages2(response, controller) {
|
|
if (!response.body) {
|
|
controller.abort();
|
|
if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
|
|
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
|
|
}
|
|
throw new AnthropicError(`Attempted to iterate over a response with no body`);
|
|
}
|
|
const sseDecoder = new SSEDecoder2();
|
|
const lineDecoder = new LineDecoder2();
|
|
const iter = ReadableStreamToAsyncIterable2(response.body);
|
|
for await (const chunk of iter) {
|
|
for (const line of lineDecoder.decode(chunk)) {
|
|
const sse = sseDecoder.decode(line);
|
|
if (sse)
|
|
yield sse;
|
|
}
|
|
}
|
|
for (const line of lineDecoder.flush()) {
|
|
const sse = sseDecoder.decode(line);
|
|
if (sse)
|
|
yield sse;
|
|
}
|
|
}
|
|
function partition2(str2, delimiter) {
|
|
const index = str2.indexOf(delimiter);
|
|
if (index !== -1) {
|
|
return [str2.substring(0, index), delimiter, str2.substring(index + delimiter.length)];
|
|
}
|
|
return [str2, "", ""];
|
|
}
|
|
var _Stream_client2, Stream2, SSEDecoder2;
|
|
var init_streaming3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/streaming.mjs"() {
|
|
init_tslib2();
|
|
init_error3();
|
|
init_shims2();
|
|
init_line2();
|
|
init_shims2();
|
|
init_errors2();
|
|
init_values2();
|
|
init_bytes2();
|
|
init_log2();
|
|
init_error3();
|
|
init_request_signal();
|
|
Stream2 = /* @__PURE__ */ (() => {
|
|
class Stream3 {
|
|
constructor(iterator, controller, client) {
|
|
this.iterator = iterator;
|
|
_Stream_client2.set(this, void 0);
|
|
this.controller = controller;
|
|
__classPrivateFieldSet2(this, _Stream_client2, client, "f");
|
|
}
|
|
/**
|
|
* Iterate the raw Server-Sent Events from `response` — `{event, data, raw}`
|
|
* objects, before any JSON parsing or event-name filtering.
|
|
*
|
|
* This reads `response.body` directly (not a clone), so the response is
|
|
* consumed. Use this in middleware that fully replaces the stream body; for
|
|
* read-only observation of parsed events, use `ctx.parse()` instead.
|
|
*/
|
|
static rawEvents(response, controller = new AbortController()) {
|
|
return _iterSSEMessages2(response, controller);
|
|
}
|
|
static fromSSEResponse(response, controller, client) {
|
|
let consumed = false;
|
|
const logger = client ? loggerFor2(client) : console;
|
|
async function* iterator() {
|
|
if (consumed) {
|
|
throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
}
|
|
consumed = true;
|
|
let done = false;
|
|
try {
|
|
for await (const sse of _iterSSEMessages2(response, controller)) {
|
|
if (sse.event === "completion") {
|
|
try {
|
|
yield JSON.parse(sse.data);
|
|
} catch (e) {
|
|
logger.error(`Could not parse message into JSON:`, sse.data);
|
|
logger.error(`From chunk:`, sse.raw);
|
|
throw e;
|
|
}
|
|
}
|
|
if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "user.tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "session.updated" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end" || sse.event === "span.outcome_evaluation_start" || sse.event === "span.outcome_evaluation_ongoing" || sse.event === "span.outcome_evaluation_end" || sse.event === "user.define_outcome" || sse.event === "agent.thread_message_received" || sse.event === "agent.thread_message_sent" || sse.event === "agent.session_thread_message_received" || sse.event === "agent.session_thread_message_sent" || sse.event === "session.thread_created" || sse.event === "session.thread_status_created" || sse.event === "session.thread_status_running" || sse.event === "session.thread_status_idle" || sse.event === "session.thread_status_rescheduled" || sse.event === "session.thread_status_terminated" || sse.event === "event_start" || sse.event === "event_delta" || sse.event === "system.message") {
|
|
try {
|
|
yield JSON.parse(sse.data);
|
|
} catch (e) {
|
|
logger.error(`Could not parse message into JSON:`, sse.data);
|
|
logger.error(`From chunk:`, sse.raw);
|
|
throw e;
|
|
}
|
|
}
|
|
if (sse.event === "ping") {
|
|
continue;
|
|
}
|
|
if (sse.event === "error") {
|
|
const body = safeJSON2(sse.data) ?? sse.data;
|
|
const type = body?.error?.type;
|
|
throw new APIError2(void 0, body, void 0, response.headers, type);
|
|
}
|
|
}
|
|
done = true;
|
|
} catch (e) {
|
|
if (isAbortError2(e))
|
|
return;
|
|
throw e;
|
|
} finally {
|
|
if (!done)
|
|
controller.abort();
|
|
releaseRequestSignal(controller);
|
|
}
|
|
}
|
|
return new Stream3(iterator, controller, client);
|
|
}
|
|
/**
|
|
* Generates a Stream from a newline-separated ReadableStream
|
|
* where each item is a JSON value.
|
|
*/
|
|
static fromReadableStream(readableStream, controller, client) {
|
|
let consumed = false;
|
|
async function* iterLines() {
|
|
const lineDecoder = new LineDecoder2();
|
|
const iter = ReadableStreamToAsyncIterable2(readableStream);
|
|
for await (const chunk of iter) {
|
|
for (const line of lineDecoder.decode(chunk)) {
|
|
yield line;
|
|
}
|
|
}
|
|
for (const line of lineDecoder.flush()) {
|
|
yield line;
|
|
}
|
|
}
|
|
async function* iterator() {
|
|
if (consumed) {
|
|
throw new AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
}
|
|
consumed = true;
|
|
let done = false;
|
|
try {
|
|
for await (const line of iterLines()) {
|
|
if (done)
|
|
continue;
|
|
if (line)
|
|
yield JSON.parse(line);
|
|
}
|
|
done = true;
|
|
} catch (e) {
|
|
if (isAbortError2(e))
|
|
return;
|
|
throw e;
|
|
} finally {
|
|
if (!done)
|
|
controller.abort();
|
|
releaseRequestSignal(controller);
|
|
}
|
|
}
|
|
return new Stream3(iterator, controller, client);
|
|
}
|
|
[(_Stream_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
|
|
return this.iterator();
|
|
}
|
|
/**
|
|
* Splits the stream into two streams which can be
|
|
* independently read from at different speeds.
|
|
*/
|
|
tee() {
|
|
const left = [];
|
|
const right = [];
|
|
const iterator = this.iterator();
|
|
const teeIterator = (queue) => {
|
|
return {
|
|
next: () => {
|
|
if (queue.length === 0) {
|
|
const result = iterator.next();
|
|
left.push(result);
|
|
right.push(result);
|
|
}
|
|
return queue.shift();
|
|
}
|
|
};
|
|
};
|
|
return [
|
|
new Stream3(() => teeIterator(left), this.controller, __classPrivateFieldGet2(this, _Stream_client2, "f")),
|
|
new Stream3(() => teeIterator(right), this.controller, __classPrivateFieldGet2(this, _Stream_client2, "f"))
|
|
];
|
|
}
|
|
/**
|
|
* Converts this stream to a newline-separated ReadableStream of
|
|
* JSON stringified values in the stream
|
|
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
*/
|
|
toReadableStream() {
|
|
const self = this;
|
|
let iter;
|
|
return makeReadableStream2({
|
|
async start() {
|
|
iter = self[Symbol.asyncIterator]();
|
|
},
|
|
async pull(ctrl) {
|
|
try {
|
|
const { value, done } = await iter.next();
|
|
if (done)
|
|
return ctrl.close();
|
|
const bytes2 = encodeUTF82(JSON.stringify(value) + "\n");
|
|
ctrl.enqueue(bytes2);
|
|
} catch (err) {
|
|
ctrl.error(err);
|
|
}
|
|
},
|
|
async cancel() {
|
|
await iter.return?.();
|
|
}
|
|
});
|
|
}
|
|
}
|
|
return Stream3;
|
|
})();
|
|
SSEDecoder2 = class {
|
|
constructor() {
|
|
this.event = null;
|
|
this.data = [];
|
|
this.chunks = [];
|
|
}
|
|
decode(line) {
|
|
if (line.endsWith("\r")) {
|
|
line = line.substring(0, line.length - 1);
|
|
}
|
|
if (!line) {
|
|
if (!this.event && !this.data.length)
|
|
return null;
|
|
const sse = {
|
|
event: this.event,
|
|
data: this.data.join("\n"),
|
|
raw: this.chunks
|
|
};
|
|
this.event = null;
|
|
this.data = [];
|
|
this.chunks = [];
|
|
return sse;
|
|
}
|
|
this.chunks.push(line);
|
|
if (line.startsWith(":")) {
|
|
return null;
|
|
}
|
|
let [fieldname, _, value] = partition2(line, ":");
|
|
if (value.startsWith(" ")) {
|
|
value = value.substring(1);
|
|
}
|
|
if (fieldname === "event") {
|
|
this.event = value;
|
|
} else if (fieldname === "data") {
|
|
this.data.push(value);
|
|
}
|
|
return null;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/parse.mjs
|
|
async function defaultParseResponse2(client, props) {
|
|
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
|
|
const body = await (async () => {
|
|
if (props.options.stream) {
|
|
loggerFor2(client).debug("response", response.status, response.url, response.headers, response.body);
|
|
return Stream2.fromSSEResponse(response, props.controller, client);
|
|
}
|
|
if (response.status === 204) {
|
|
return null;
|
|
}
|
|
if (props.options.__binaryResponse) {
|
|
return response;
|
|
}
|
|
const contentType = response.headers.get("content-type");
|
|
const mediaType = contentType?.split(";")[0]?.trim();
|
|
const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
|
|
if (isJSON) {
|
|
const contentLength = response.headers.get("content-length");
|
|
if (contentLength === "0") {
|
|
return void 0;
|
|
}
|
|
const json = await response.json();
|
|
return addResponseIDs(json, response);
|
|
}
|
|
const text = await response.text();
|
|
return text;
|
|
})().finally(() => {
|
|
if (!props.options.stream && !props.options.__binaryResponse) {
|
|
releaseRequestSignal(props.controller);
|
|
}
|
|
});
|
|
debugLogRequestDetails(loggerFor2(client), `[${requestLogID}] response parsed`, {
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
body,
|
|
durationMs: Date.now() - startTime
|
|
});
|
|
return body;
|
|
}
|
|
function addResponseIDs(value, response) {
|
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
return value;
|
|
}
|
|
return Object.defineProperties(value, {
|
|
_request_id: { value: response.headers.get("request-id"), enumerable: false },
|
|
_workspace_id: { value: response.headers.get("anthropic-workspace-id"), enumerable: false }
|
|
});
|
|
}
|
|
var init_parse2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/parse.mjs"() {
|
|
init_streaming3();
|
|
init_log2();
|
|
init_request_signal();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/middleware.mjs
|
|
function isFetchOriginError(err) {
|
|
return typeof err === "object" && err !== null && fetchOriginErrors.has(err);
|
|
}
|
|
function isRetryableError(err) {
|
|
const seen = /* @__PURE__ */ new Set();
|
|
while (typeof err === "object" && err !== null && !seen.has(err)) {
|
|
seen.add(err);
|
|
if (isFetchOriginError(err) || isAbortError2(err) || err instanceof APIConnectionError2 || err instanceof RetryableError) {
|
|
return true;
|
|
}
|
|
err = err.cause;
|
|
}
|
|
return false;
|
|
}
|
|
function wrapFetchWithMiddleware(fetchFn, middleware, options, client) {
|
|
return async (url, init = {}) => {
|
|
if (middleware.length === 0) {
|
|
return fetchFn.call(void 0, url, init);
|
|
}
|
|
const headers = init.headers instanceof Headers ? init.headers : new Headers(init.headers);
|
|
const response = await applyMiddleware(fetchFn, middleware, options, client)({
|
|
...init,
|
|
headers,
|
|
url: typeof url === "string" ? url : url instanceof URL ? url.href : url.url
|
|
});
|
|
if (response.bodyUsed || response.body?.locked) {
|
|
throw new AnthropicError("middleware consumed the response body; use response.clone() to inspect it, or return new Response(body, response) to consume and replace it");
|
|
}
|
|
return response;
|
|
};
|
|
}
|
|
function createMiddlewareContext(options, client) {
|
|
const cache = /* @__PURE__ */ new WeakMap();
|
|
return {
|
|
options,
|
|
// Resolved per chain, so changes to the client's `logLevel`/`logger`
|
|
// apply to subsequent requests.
|
|
logger: client ? loggerFor2(client) : defaultLogger(),
|
|
parse(response) {
|
|
if (options?.stream && response.ok) {
|
|
return parseMiddlewareResponse(response, options, client);
|
|
}
|
|
let parsed = cache.get(response);
|
|
if (!parsed) {
|
|
parsed = parseMiddlewareResponse(response, options, client);
|
|
cache.set(response, parsed);
|
|
}
|
|
return parsed;
|
|
}
|
|
};
|
|
}
|
|
async function parseMiddlewareResponse(response, options, client) {
|
|
if (response.bodyUsed || response.body?.locked) {
|
|
throw new AnthropicError("cannot ctx.parse() a response whose body was already consumed; call ctx.parse() instead of reading the body, or read via response.clone()");
|
|
}
|
|
if (options?.stream && response.ok) {
|
|
return Stream2.fromSSEResponse(response.clone(), new AbortController(), client);
|
|
}
|
|
if (response.status === 204) {
|
|
return null;
|
|
}
|
|
if (options?.__binaryResponse) {
|
|
return response;
|
|
}
|
|
const contentType = response.headers.get("content-type");
|
|
const mediaType = contentType?.split(";")[0]?.trim();
|
|
const isJSON = mediaType?.includes("application/json") || mediaType?.endsWith("+json");
|
|
if (isJSON) {
|
|
if (response.headers.get("content-length") === "0") {
|
|
return void 0;
|
|
}
|
|
return addResponseIDs(await response.clone().json(), response);
|
|
}
|
|
return await response.clone().text();
|
|
}
|
|
function applyMiddleware(fetchFn, middleware, options, client) {
|
|
let next = async ({ url, ...init }) => {
|
|
try {
|
|
return await fetchFn.call(void 0, url, init);
|
|
} catch (err) {
|
|
const error = castToError2(err);
|
|
fetchOriginErrors.add(error);
|
|
throw error;
|
|
}
|
|
};
|
|
const ctx = createMiddlewareContext(options, client);
|
|
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
const mw = middleware[i];
|
|
const nextInner = next;
|
|
next = async (request2) => mw(request2, nextInner, ctx);
|
|
}
|
|
return next;
|
|
}
|
|
var fetchOriginErrors;
|
|
var init_middleware = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/middleware.mjs"() {
|
|
init_errors2();
|
|
init_parse2();
|
|
init_log2();
|
|
init_error3();
|
|
init_streaming3();
|
|
fetchOriginErrors = /* @__PURE__ */ new WeakSet();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/api-promise.mjs
|
|
var _APIPromise_client2, APIPromise2;
|
|
var init_api_promise2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/api-promise.mjs"() {
|
|
init_tslib2();
|
|
init_parse2();
|
|
APIPromise2 = /* @__PURE__ */ (() => {
|
|
class APIPromise3 extends Promise {
|
|
constructor(client, responsePromise, parseResponse2 = defaultParseResponse2) {
|
|
super((resolve) => {
|
|
resolve(null);
|
|
});
|
|
this.responsePromise = responsePromise;
|
|
this.parseResponse = parseResponse2;
|
|
_APIPromise_client2.set(this, void 0);
|
|
__classPrivateFieldSet2(this, _APIPromise_client2, client, "f");
|
|
}
|
|
_thenUnwrap(transform) {
|
|
return new APIPromise3(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), this.responsePromise, async (client, props) => addResponseIDs(transform(await this.parseResponse(client, props), props), props.response));
|
|
}
|
|
/**
|
|
* Gets the raw `Response` instance instead of parsing the response
|
|
* data.
|
|
*
|
|
* If you want to parse the response body but still get the `Response`
|
|
* instance, you can use {@link withResponse()}.
|
|
*
|
|
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
* to your `tsconfig.json`.
|
|
*/
|
|
asResponse() {
|
|
return this.responsePromise.then((p) => p.response);
|
|
}
|
|
/**
|
|
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
|
|
* returned via the `request-id` header which is useful for debugging requests and resporting
|
|
* issues to Anthropic.
|
|
*
|
|
* If you just want to get the raw `Response` instance without parsing it,
|
|
* you can use {@link asResponse()}.
|
|
*
|
|
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
* to your `tsconfig.json`.
|
|
*/
|
|
async withResponse() {
|
|
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
return {
|
|
data,
|
|
response,
|
|
request_id: response.headers.get("request-id"),
|
|
workspace_id: response.headers.get("anthropic-workspace-id")
|
|
};
|
|
}
|
|
parse() {
|
|
if (!this.parsedPromise) {
|
|
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet2(this, _APIPromise_client2, "f"), data));
|
|
}
|
|
return this.parsedPromise;
|
|
}
|
|
then(onfulfilled, onrejected) {
|
|
return this.parse().then(onfulfilled, onrejected);
|
|
}
|
|
catch(onrejected) {
|
|
return this.parse().catch(onrejected);
|
|
}
|
|
finally(onfinally) {
|
|
return this.parse().finally(onfinally);
|
|
}
|
|
}
|
|
_APIPromise_client2 = /* @__PURE__ */ new WeakMap();
|
|
return APIPromise3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/pagination.mjs
|
|
var _AbstractPage_client2, AbstractPage2, PagePromise2, Page2, PageCursor, BidirectionalPageCursor;
|
|
var init_pagination2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/pagination.mjs"() {
|
|
init_tslib2();
|
|
init_error3();
|
|
init_parse2();
|
|
init_api_promise2();
|
|
init_values2();
|
|
AbstractPage2 = /* @__PURE__ */ (() => {
|
|
class AbstractPage3 {
|
|
constructor(client, response, body, options) {
|
|
_AbstractPage_client2.set(this, void 0);
|
|
__classPrivateFieldSet2(this, _AbstractPage_client2, client, "f");
|
|
this.options = options;
|
|
this.response = response;
|
|
this.body = body;
|
|
}
|
|
hasNextPage() {
|
|
const items = this.getPaginatedItems();
|
|
if (!items.length)
|
|
return false;
|
|
return this.nextPageRequestOptions() != null;
|
|
}
|
|
async getNextPage() {
|
|
const nextOptions = this.nextPageRequestOptions();
|
|
if (!nextOptions) {
|
|
throw new AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
|
|
}
|
|
return await __classPrivateFieldGet2(this, _AbstractPage_client2, "f").requestAPIList(this.constructor, nextOptions);
|
|
}
|
|
async *iterPages() {
|
|
let page = this;
|
|
yield page;
|
|
while (page.hasNextPage()) {
|
|
page = await page.getNextPage();
|
|
yield page;
|
|
}
|
|
}
|
|
async *[(_AbstractPage_client2 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
|
|
for await (const page of this.iterPages()) {
|
|
for (const item of page.getPaginatedItems()) {
|
|
yield item;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return AbstractPage3;
|
|
})();
|
|
PagePromise2 = /* @__PURE__ */ (() => {
|
|
class PagePromise3 extends APIPromise2 {
|
|
constructor(client, request2, Page3) {
|
|
super(client, request2, async (client2, props) => new Page3(client2, props.response, await defaultParseResponse2(client2, props), props.options));
|
|
}
|
|
/**
|
|
* Allow auto-paginating iteration on an unawaited list call, eg:
|
|
*
|
|
* for await (const item of client.items.list()) {
|
|
* console.log(item)
|
|
* }
|
|
*/
|
|
async *[Symbol.asyncIterator]() {
|
|
const page = await this;
|
|
for await (const item of page) {
|
|
yield item;
|
|
}
|
|
}
|
|
}
|
|
return PagePromise3;
|
|
})();
|
|
Page2 = class extends AbstractPage2 {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.has_more = body.has_more || false;
|
|
this.first_id = body.first_id || null;
|
|
this.last_id = body.last_id || null;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
hasNextPage() {
|
|
if (this.has_more === false) {
|
|
return false;
|
|
}
|
|
return super.hasNextPage();
|
|
}
|
|
nextPageRequestOptions() {
|
|
if (this.options.query?.["before_id"]) {
|
|
const first_id = this.first_id;
|
|
if (!first_id) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj2(this.options.query),
|
|
before_id: first_id
|
|
}
|
|
};
|
|
}
|
|
const cursor = this.last_id;
|
|
if (!cursor) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj2(this.options.query),
|
|
after_id: cursor
|
|
}
|
|
};
|
|
}
|
|
};
|
|
PageCursor = class extends AbstractPage2 {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.next_page = body.next_page || null;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
nextPageRequestOptions() {
|
|
const cursor = this.next_page;
|
|
if (!cursor) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj2(this.options.query),
|
|
page: cursor
|
|
}
|
|
};
|
|
}
|
|
};
|
|
BidirectionalPageCursor = class extends AbstractPage2 {
|
|
constructor(client, response, body, options) {
|
|
super(client, response, body, options);
|
|
this.data = body.data || [];
|
|
this.next_page = body.next_page || null;
|
|
this.prev_page = body.prev_page || null;
|
|
}
|
|
getPaginatedItems() {
|
|
return this.data ?? [];
|
|
}
|
|
nextPageRequestOptions() {
|
|
const cursor = this.next_page;
|
|
if (!cursor) {
|
|
return null;
|
|
}
|
|
return {
|
|
...this.options,
|
|
query: {
|
|
...maybeObj2(this.options.query),
|
|
page: cursor
|
|
}
|
|
};
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/uploads.mjs
|
|
function makeFile2(fileBits, fileName, options) {
|
|
checkFileSupport2();
|
|
return new File(fileBits, fileName ?? "", options);
|
|
}
|
|
function getName2(value, stripPath) {
|
|
const val = typeof value === "object" && value !== null && ("name" in value && value.name && String(value.name) || "url" in value && value.url && String(value.url) || "filename" in value && value.filename && String(value.filename) || "path" in value && value.path && String(value.path)) || "";
|
|
return stripPath ? val.split(/[\\/]/).pop() || void 0 : val;
|
|
}
|
|
function supportsFormData2(fetchObject) {
|
|
const fetch2 = typeof fetchObject === "function" ? fetchObject : fetchObject.fetch;
|
|
const cached = supportsFormDataMap2.get(fetch2);
|
|
if (cached)
|
|
return cached;
|
|
const promise = (async () => {
|
|
try {
|
|
const FetchResponse = "Response" in fetch2 ? fetch2.Response : (await fetch2("data:,")).constructor;
|
|
const data = new FormData();
|
|
if (data.toString() === await new FetchResponse(data).text()) {
|
|
return false;
|
|
}
|
|
return true;
|
|
} catch {
|
|
return true;
|
|
}
|
|
})();
|
|
supportsFormDataMap2.set(fetch2, promise);
|
|
return promise;
|
|
}
|
|
var checkFileSupport2, isAsyncIterable2, multipartFormRequestOptions2, supportsFormDataMap2, createForm2, addFormValue2;
|
|
var init_uploads4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/uploads.mjs"() {
|
|
init_shims2();
|
|
checkFileSupport2 = () => {
|
|
if (typeof File === "undefined") {
|
|
const { process: process2 } = globalThis;
|
|
const isOldNode = typeof process2?.versions?.node === "string" && parseInt(process2.versions.node.split(".")) < 20;
|
|
throw new Error("`File` is not defined as a global, which is required for file uploads." + (isOldNode ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
|
|
}
|
|
};
|
|
isAsyncIterable2 = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
|
|
multipartFormRequestOptions2 = async (opts, fetch2, stripFilenames = true) => {
|
|
return { ...opts, body: await createForm2(opts.body, fetch2, stripFilenames) };
|
|
};
|
|
supportsFormDataMap2 = /* @__PURE__ */ new WeakMap();
|
|
createForm2 = async (body, fetch2, stripFilenames = true) => {
|
|
if (!await supportsFormData2(fetch2)) {
|
|
throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
|
|
}
|
|
const form = new FormData();
|
|
await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue2(form, key, value, stripFilenames)));
|
|
return form;
|
|
};
|
|
addFormValue2 = async (form, key, value, stripFilenames) => {
|
|
if (value === void 0)
|
|
return;
|
|
if (value == null) {
|
|
throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`);
|
|
}
|
|
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
form.append(key, String(value));
|
|
} else if (value instanceof Response) {
|
|
let options = {};
|
|
const contentType = value.headers.get("Content-Type");
|
|
if (contentType) {
|
|
options = { type: contentType };
|
|
}
|
|
form.append(key, makeFile2([await value.blob()], getName2(value, stripFilenames), options));
|
|
} else if (isAsyncIterable2(value)) {
|
|
form.append(key, makeFile2([await new Response(ReadableStreamFrom2(value)).blob()], getName2(value, stripFilenames)));
|
|
} else if (value instanceof Blob) {
|
|
const isFile = typeof File !== "undefined" && value instanceof File;
|
|
const name = isFile ? value.name : getName2(value, stripFilenames);
|
|
form.append(key, makeFile2([value], name, { type: value.type }));
|
|
} else if (Array.isArray(value)) {
|
|
await Promise.all(value.map((entry) => addFormValue2(form, key + "[]", entry, stripFilenames)));
|
|
} else if (typeof value.then === "function") {
|
|
throw new TypeError(`Received a Promise for "${key}"; await it first, e.g. \`await toFile(...)\``);
|
|
} else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {
|
|
throw new TypeError(`Received ${value.constructor.name} for "${key}"; to upload raw bytes, wrap them with \`await toFile(bytes, 'filename')\``);
|
|
} else if (typeof value === "object") {
|
|
await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue2(form, `${key}[${name}]`, prop, stripFilenames)));
|
|
} else {
|
|
throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/to-file.mjs
|
|
async function toFile2(value, name, options) {
|
|
checkFileSupport2();
|
|
value = await value;
|
|
name || (name = value instanceof File ? value.name : getName2(value, true));
|
|
if (isFileLike2(value)) {
|
|
if (value instanceof File && name == null && options == null) {
|
|
return value;
|
|
}
|
|
return makeFile2([await value.arrayBuffer()], name ?? value.name, {
|
|
type: value.type,
|
|
lastModified: value.lastModified,
|
|
...options
|
|
});
|
|
}
|
|
if (isResponseLike2(value)) {
|
|
const blob = await value.blob();
|
|
name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
|
|
return makeFile2(await getBytes2(blob), name, options);
|
|
}
|
|
const parts = await getBytes2(value);
|
|
if (!options?.type) {
|
|
const type = parts.find((part) => typeof part === "object" && "type" in part && part.type);
|
|
if (typeof type === "string") {
|
|
options = { ...options, type };
|
|
}
|
|
}
|
|
return makeFile2(parts, name, options);
|
|
}
|
|
async function getBytes2(value) {
|
|
let parts = [];
|
|
if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
|
|
value instanceof ArrayBuffer) {
|
|
parts.push(value);
|
|
} else if (isBlobLike2(value)) {
|
|
parts.push(value instanceof Blob ? value : await value.arrayBuffer());
|
|
} else if (isAsyncIterable2(value)) {
|
|
for await (const chunk of value) {
|
|
parts.push(...await getBytes2(chunk));
|
|
}
|
|
} else {
|
|
const constructor = value?.constructor?.name;
|
|
throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ""}${propsForError2(value)}`);
|
|
}
|
|
return parts;
|
|
}
|
|
function propsForError2(value) {
|
|
if (typeof value !== "object" || value === null)
|
|
return "";
|
|
const props = Object.getOwnPropertyNames(value);
|
|
return `; props: [${props.map((p) => `"${p}"`).join(", ")}]`;
|
|
}
|
|
var isBlobLike2, isFileLike2, isResponseLike2;
|
|
var init_to_file2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/to-file.mjs"() {
|
|
init_uploads4();
|
|
init_uploads4();
|
|
isBlobLike2 = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function";
|
|
isFileLike2 = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike2(value);
|
|
isResponseLike2 = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function";
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/uploads.mjs
|
|
var init_uploads5 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/uploads.mjs"() {
|
|
init_to_file2();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/shared.mjs
|
|
var init_shared2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/shared.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/core/resource.mjs
|
|
var APIResource2;
|
|
var init_resource2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/core/resource.mjs"() {
|
|
APIResource2 = class {
|
|
constructor(client) {
|
|
this._client = client;
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/headers.mjs
|
|
function* iterateHeaders2(headers) {
|
|
if (!headers)
|
|
return;
|
|
if (brand_privateNullableHeaders2 in headers) {
|
|
const { values, nulls } = headers;
|
|
yield* values.entries();
|
|
for (const name of nulls) {
|
|
yield [name, null];
|
|
}
|
|
return;
|
|
}
|
|
let shouldClear = false;
|
|
let iter;
|
|
if (headers instanceof Headers) {
|
|
iter = headers.entries();
|
|
} else if (isReadonlyArray2(headers)) {
|
|
iter = headers;
|
|
} else {
|
|
shouldClear = true;
|
|
iter = Object.entries(headers ?? {});
|
|
}
|
|
for (let row of iter) {
|
|
const name = row[0];
|
|
if (typeof name !== "string")
|
|
throw new TypeError("expected header name to be a string");
|
|
const values = isReadonlyArray2(row[1]) ? row[1] : [row[1]];
|
|
let didClear = false;
|
|
for (const value of values) {
|
|
if (value === void 0)
|
|
continue;
|
|
if (shouldClear && !didClear) {
|
|
didClear = true;
|
|
yield [name, clearSentinel];
|
|
}
|
|
yield [name, value];
|
|
}
|
|
}
|
|
}
|
|
var brand_privateNullableHeaders2, clearSentinel, APPEND_HEADERS, appendHeaderValue, buildHeaders2;
|
|
var init_headers3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/headers.mjs"() {
|
|
init_values2();
|
|
brand_privateNullableHeaders2 = /* @__PURE__ */ Symbol.for("brand.privateNullableHeaders");
|
|
clearSentinel = /* @__PURE__ */ Symbol("clear");
|
|
APPEND_HEADERS = /* @__PURE__ */ new Set(["x-stainless-helper"]);
|
|
appendHeaderValue = (existing, addition) => {
|
|
const tokens = existing ? existing.split(",").map((t) => t.trim()).filter(Boolean) : [];
|
|
for (const tok of addition.split(",").map((t) => t.trim())) {
|
|
if (tok && !tokens.includes(tok))
|
|
tokens.push(tok);
|
|
}
|
|
return tokens.join(", ");
|
|
};
|
|
buildHeaders2 = (newHeaders) => {
|
|
const targetHeaders = new Headers();
|
|
const nullHeaders = /* @__PURE__ */ new Set();
|
|
for (const headers of newHeaders) {
|
|
const seenHeaders = /* @__PURE__ */ new Set();
|
|
for (const [name, value] of iterateHeaders2(headers)) {
|
|
const lowerName = name.toLowerCase();
|
|
if (APPEND_HEADERS.has(lowerName)) {
|
|
if (value === clearSentinel)
|
|
continue;
|
|
if (value === null) {
|
|
targetHeaders.delete(name);
|
|
nullHeaders.add(lowerName);
|
|
} else {
|
|
targetHeaders.set(name, appendHeaderValue(targetHeaders.get(name), value));
|
|
nullHeaders.delete(lowerName);
|
|
}
|
|
continue;
|
|
}
|
|
if (value === clearSentinel || !seenHeaders.has(lowerName)) {
|
|
targetHeaders.delete(name);
|
|
seenHeaders.add(lowerName);
|
|
if (value === clearSentinel)
|
|
continue;
|
|
}
|
|
if (value === null) {
|
|
targetHeaders.delete(name);
|
|
nullHeaders.add(lowerName);
|
|
} else {
|
|
targetHeaders.append(name, value);
|
|
nullHeaders.delete(lowerName);
|
|
}
|
|
}
|
|
}
|
|
return { [brand_privateNullableHeaders2]: true, values: targetHeaders, nulls: nullHeaders };
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
|
|
function encodeURIPath2(str2) {
|
|
return str2.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
|
|
}
|
|
var EMPTY2, createPathTagFunction2, path3;
|
|
var init_path2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/path.mjs"() {
|
|
init_error3();
|
|
EMPTY2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
createPathTagFunction2 = (pathEncoder = encodeURIPath2) => function path4(statics, ...params) {
|
|
if (statics.length === 1)
|
|
return statics[0];
|
|
let postPath = false;
|
|
const invalidSegments = [];
|
|
const path5 = statics.reduce((previousValue, currentValue, index) => {
|
|
if (/[?#]/.test(currentValue)) {
|
|
postPath = true;
|
|
}
|
|
const value = params[index];
|
|
let encoded = (postPath ? encodeURIComponent : pathEncoder)("" + value);
|
|
if (index !== params.length && (value == null || typeof value === "object" && // handle values from other realms
|
|
value.toString === Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY2) ?? EMPTY2)?.toString)) {
|
|
encoded = value + "";
|
|
invalidSegments.push({
|
|
start: previousValue.length + currentValue.length,
|
|
length: encoded.length,
|
|
error: `Value of type ${Object.prototype.toString.call(value).slice(8, -1)} is not a valid path parameter`
|
|
});
|
|
}
|
|
return previousValue + currentValue + (index === params.length ? "" : encoded);
|
|
}, "");
|
|
const pathOnly = path5.split(/[?#]/, 1)[0];
|
|
const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
|
|
let match;
|
|
while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
|
|
invalidSegments.push({
|
|
start: match.index,
|
|
length: match[0].length,
|
|
error: `Value "${match[0]}" can't be safely passed as a path parameter`
|
|
});
|
|
}
|
|
invalidSegments.sort((a, b) => a.start - b.start);
|
|
if (invalidSegments.length > 0) {
|
|
let lastEnd = 0;
|
|
const underline = invalidSegments.reduce((acc, segment) => {
|
|
const spaces = " ".repeat(segment.start - lastEnd);
|
|
const arrows = "^".repeat(segment.length);
|
|
lastEnd = segment.start + segment.length;
|
|
return acc + spaces + arrows;
|
|
}, "");
|
|
throw new AnthropicError(`Path parameters result in path with invalid segments:
|
|
${invalidSegments.map((e) => e.error).join("\n")}
|
|
${path5}
|
|
${underline}`);
|
|
}
|
|
return path5;
|
|
};
|
|
path3 = /* @__PURE__ */ createPathTagFunction2(encodeURIPath2);
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/deployment-runs.mjs
|
|
var DeploymentRuns;
|
|
var init_deployment_runs = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/deployment-runs.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
DeploymentRuns = class extends APIResource2 {
|
|
/**
|
|
* Get Deployment Run
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeploymentRun =
|
|
* await client.beta.deploymentRuns.retrieve(
|
|
* 'deployment_run_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(deploymentRunID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/deployment_runs/${deploymentRunID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Deployment Runs
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsDeploymentRun of client.beta.deploymentRuns.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/deployment_runs?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/deployments.mjs
|
|
var Deployments;
|
|
var init_deployments = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/deployments.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Deployments = class extends APIResource2 {
|
|
/**
|
|
* Create Deployment
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeployment =
|
|
* await client.beta.deployments.create({
|
|
* agent: 'string',
|
|
* environment_id: 'x',
|
|
* initial_events: [
|
|
* {
|
|
* content: [
|
|
* {
|
|
* text: 'Where is my order #1234?',
|
|
* type: 'text',
|
|
* },
|
|
* ],
|
|
* type: 'user.message',
|
|
* },
|
|
* ],
|
|
* name: 'x',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/deployments?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get Deployment
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeployment =
|
|
* await client.beta.deployments.retrieve(
|
|
* 'depl_011CZkZcDH3vPqd7xnEfwTai',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(deploymentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/deployments/${deploymentID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update Deployment
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeployment =
|
|
* await client.beta.deployments.update(
|
|
* 'depl_011CZkZcDH3vPqd7xnEfwTai',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(deploymentID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/deployments/${deploymentID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Deployments
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsDeployment of client.beta.deployments.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/deployments?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive Deployment
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeployment =
|
|
* await client.beta.deployments.archive(
|
|
* 'depl_011CZkZcDH3vPqd7xnEfwTai',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(deploymentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/deployments/${deploymentID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Pause Deployment
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeployment =
|
|
* await client.beta.deployments.pause(
|
|
* 'depl_011CZkZcDH3vPqd7xnEfwTai',
|
|
* );
|
|
* ```
|
|
*/
|
|
pause(deploymentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/deployments/${deploymentID}/pause?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Run Deployment Now
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeploymentRun =
|
|
* await client.beta.deployments.run(
|
|
* 'depl_011CZkZcDH3vPqd7xnEfwTai',
|
|
* );
|
|
* ```
|
|
*/
|
|
run(deploymentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/deployments/${deploymentID}/run?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Unpause Deployment
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeployment =
|
|
* await client.beta.deployments.unpause(
|
|
* 'depl_011CZkZcDH3vPqd7xnEfwTai',
|
|
* );
|
|
* ```
|
|
*/
|
|
unpause(deploymentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/deployments/${deploymentID}/unpause?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/dreams.mjs
|
|
var Dreams;
|
|
var init_dreams = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/dreams.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Dreams = class extends APIResource2 {
|
|
/**
|
|
* Start an asynchronous job that uses past sessions to produce a reorganized
|
|
* version of a memory store and get back the dream to poll for the result.
|
|
*
|
|
* By default the dream writes its result to a new memory store and doesn't change
|
|
* the input memory store. The response has `status` set to `pending` and an empty
|
|
* `outputs` array. Poll the dream until `status` is `completed`, `failed`, or
|
|
* `canceled`.
|
|
*
|
|
* See the
|
|
* [Dreams guide](https://platform.claude.com/docs/en/managed-agents/dreams#create-a-dream)
|
|
* to learn more about creating dreams.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDream = await client.beta.dreams.create({
|
|
* inputs: [{ memory_store_id: 'x', type: 'memory_store' }],
|
|
* model: 'string',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/dreams?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get a dream by ID to check its status, output memory store, and token usage.
|
|
*
|
|
* Archived dreams are returned too.
|
|
*
|
|
* See the
|
|
* [Dreams guide](https://platform.claude.com/docs/en/managed-agents/dreams#track-progress)
|
|
* for how to poll a dream and what each status means.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDream = await client.beta.dreams.retrieve(
|
|
* 'dream_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(dreamID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/dreams/${dreamID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List the dreams in the workspace, newest first.
|
|
*
|
|
* Archived dreams are left out unless `include_archived` is `true`.
|
|
*
|
|
* See the
|
|
* [Dreams guide](https://platform.claude.com/docs/en/managed-agents/dreams#list-dreams)
|
|
* for how to page through dreams.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaDream of client.beta.dreams.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/dreams?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Hide a `completed`, `failed`, or `canceled` dream from the default list of
|
|
* dreams.
|
|
*
|
|
* Archiving a `pending` or `running` dream returns a 400 error, so cancel it
|
|
* first. Archiving an archived dream returns it unchanged. An archived dream can
|
|
* still be fetched by ID. Archiving can't be undone.
|
|
*
|
|
* See the
|
|
* [Dreams guide](https://platform.claude.com/docs/en/managed-agents/dreams#archive-a-dream)
|
|
* to learn more about archiving dreams.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDream = await client.beta.dreams.archive(
|
|
* 'dream_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(dreamID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/dreams/${dreamID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Stop a `pending` or `running` dream.
|
|
*
|
|
* The response shows `status` as `canceled`, unless the dream reached `completed`
|
|
* or `failed` first. `usage` can keep changing after the response. Canceling a
|
|
* `canceled` dream returns it unchanged. Canceling a `completed` or `failed` dream
|
|
* returns a 400 error.
|
|
*
|
|
* See the
|
|
* [Dreams guide](https://platform.claude.com/docs/en/managed-agents/dreams#cancel-a-dream)
|
|
* to learn more about canceling dreams.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDream = await client.beta.dreams.cancel(
|
|
* 'dream_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
cancel(dreamID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/dreams/${dreamID}/cancel?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "dreaming-2026-04-21"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/stainless-helper-header.mjs
|
|
function helperHeader(value) {
|
|
return { [STAINLESS_HELPER_HEADER]: value };
|
|
}
|
|
function wasCreatedByStainlessHelper(value) {
|
|
return typeof value === "object" && value !== null && SDK_HELPER_SYMBOL in value;
|
|
}
|
|
function collectStainlessHelpers(tools, messages) {
|
|
const helpers = /* @__PURE__ */ new Set();
|
|
if (tools) {
|
|
for (const tool of tools) {
|
|
if (wasCreatedByStainlessHelper(tool)) {
|
|
helpers.add(tool[SDK_HELPER_SYMBOL]);
|
|
}
|
|
}
|
|
}
|
|
if (messages) {
|
|
for (const message of messages) {
|
|
if (wasCreatedByStainlessHelper(message)) {
|
|
helpers.add(message[SDK_HELPER_SYMBOL]);
|
|
}
|
|
const content = message.content;
|
|
if (Array.isArray(content)) {
|
|
for (const block of content) {
|
|
if (wasCreatedByStainlessHelper(block)) {
|
|
helpers.add(block[SDK_HELPER_SYMBOL]);
|
|
}
|
|
const definition = block?.tool?.definition;
|
|
if (wasCreatedByStainlessHelper(definition)) {
|
|
helpers.add(definition[SDK_HELPER_SYMBOL]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return Array.from(helpers);
|
|
}
|
|
function stainlessHelperHeader(tools, messages) {
|
|
const helpers = collectStainlessHelpers(tools, messages);
|
|
if (helpers.length === 0)
|
|
return {};
|
|
return { [STAINLESS_HELPER_HEADER]: helpers.join(", ") };
|
|
}
|
|
function stainlessHelperHeaderFromFile(file2) {
|
|
if (wasCreatedByStainlessHelper(file2)) {
|
|
return { [STAINLESS_HELPER_HEADER]: file2[SDK_HELPER_SYMBOL] };
|
|
}
|
|
return {};
|
|
}
|
|
var STAINLESS_HELPER_HEADER, STAINLESS_HELPER_METHOD_HEADER, SDK_HELPER_SYMBOL;
|
|
var init_stainless_helper_header = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/stainless-helper-header.mjs"() {
|
|
STAINLESS_HELPER_HEADER = "x-stainless-helper";
|
|
STAINLESS_HELPER_METHOD_HEADER = "x-stainless-helper-method";
|
|
SDK_HELPER_SYMBOL = /* @__PURE__ */ Symbol("anthropic.sdk.stainlessHelper");
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/files.mjs
|
|
var Files5;
|
|
var init_files5 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/files.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_stainless_helper_header();
|
|
init_uploads4();
|
|
init_path2();
|
|
Files5 = class extends APIResource2 {
|
|
/**
|
|
* List Files
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaFileMetadata of client.beta.files.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/files?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete File
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDeletedFile = await client.beta.files.delete(
|
|
* 'file_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(fileID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/files/${fileID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Download File
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.beta.files.download(
|
|
* 'file_id',
|
|
* );
|
|
*
|
|
* const content = await response.blob();
|
|
* console.log(content);
|
|
* ```
|
|
*/
|
|
download(fileID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/files/${fileID}/content?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
Accept: "application/binary",
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
/**
|
|
* Get File Metadata
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFileMetadata =
|
|
* await client.beta.files.retrieveMetadata('file_id');
|
|
* ```
|
|
*/
|
|
retrieveMetadata(fileID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/files/${fileID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Upload File
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFileMetadata = await client.beta.files.upload({
|
|
* file: fs.createReadStream('path/to/file'),
|
|
* });
|
|
* ```
|
|
*/
|
|
upload(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/files?beta=true", multipartFormRequestOptions2({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
stainlessHelperHeaderFromFile(body.file),
|
|
options?.headers
|
|
])
|
|
}, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/models.mjs
|
|
var Models2;
|
|
var init_models3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/models.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Models2 = class extends APIResource2 {
|
|
/**
|
|
* Get a specific model.
|
|
*
|
|
* The Models API response can be used to determine information about a specific
|
|
* model or resolve a model alias to a model ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaModelInfo = await client.beta.models.retrieve(
|
|
* 'model_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(modelID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/models/${modelID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List available models.
|
|
*
|
|
* The Models API response can be used to determine which models are available for
|
|
* use in the API. More recently released models are listed first.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaModelInfo of client.beta.models.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/models?beta=true", Page2, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/user-profiles.mjs
|
|
var UserProfiles;
|
|
var init_user_profiles = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/user-profiles.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
UserProfiles = class extends APIResource2 {
|
|
/**
|
|
* Create User Profile
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaUserProfile =
|
|
* await client.beta.userProfiles.create();
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/user_profiles?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "user-profiles-2026-08-18"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get User Profile
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaUserProfile =
|
|
* await client.beta.userProfiles.retrieve(
|
|
* 'uprof_011CZkZCu8hGbp5mYRQgUmz9',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(userProfileID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/user_profiles/${userProfileID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "user-profiles-2026-08-18"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update User Profile
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaUserProfile =
|
|
* await client.beta.userProfiles.update(
|
|
* 'uprof_011CZkZCu8hGbp5mYRQgUmz9',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(userProfileID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/user_profiles/${userProfileID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "user-profiles-2026-08-18"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List User Profiles
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaUserProfile of client.beta.userProfiles.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/user_profiles?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "user-profiles-2026-08-18"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Create Enrollment URL
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaUserProfileEnrollmentURL =
|
|
* await client.beta.userProfiles.createEnrollmentURL(
|
|
* 'uprof_011CZkZCu8hGbp5mYRQgUmz9',
|
|
* );
|
|
* ```
|
|
*/
|
|
createEnrollmentURL(userProfileID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/user_profiles/${userProfileID}/enrollment_url?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "user-profiles-2026-08-18"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@stablelib/base64/lib/base64.js
|
|
var require_base64 = __commonJS({
|
|
"node_modules/@stablelib/base64/lib/base64.js"(exports) {
|
|
"use strict";
|
|
var __extends = exports && exports.__extends || /* @__PURE__ */ (function() {
|
|
var extendStatics = function(d, b) {
|
|
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
|
|
d2.__proto__ = b2;
|
|
} || function(d2, b2) {
|
|
for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
|
|
};
|
|
return extendStatics(d, b);
|
|
};
|
|
return function(d, b) {
|
|
extendStatics(d, b);
|
|
function __() {
|
|
this.constructor = d;
|
|
}
|
|
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
|
};
|
|
})();
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var INVALID_BYTE = 256;
|
|
var Coder = (
|
|
/** @class */
|
|
(function() {
|
|
function Coder2(_paddingCharacter) {
|
|
if (_paddingCharacter === void 0) {
|
|
_paddingCharacter = "=";
|
|
}
|
|
this._paddingCharacter = _paddingCharacter;
|
|
}
|
|
Coder2.prototype.encodedLength = function(length) {
|
|
if (!this._paddingCharacter) {
|
|
return (length * 8 + 5) / 6 | 0;
|
|
}
|
|
return (length + 2) / 3 * 4 | 0;
|
|
};
|
|
Coder2.prototype.encode = function(data) {
|
|
var out = "";
|
|
var i = 0;
|
|
for (; i < data.length - 2; i += 3) {
|
|
var c = data[i] << 16 | data[i + 1] << 8 | data[i + 2];
|
|
out += this._encodeByte(c >>> 3 * 6 & 63);
|
|
out += this._encodeByte(c >>> 2 * 6 & 63);
|
|
out += this._encodeByte(c >>> 1 * 6 & 63);
|
|
out += this._encodeByte(c >>> 0 * 6 & 63);
|
|
}
|
|
var left = data.length - i;
|
|
if (left > 0) {
|
|
var c = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0);
|
|
out += this._encodeByte(c >>> 3 * 6 & 63);
|
|
out += this._encodeByte(c >>> 2 * 6 & 63);
|
|
if (left === 2) {
|
|
out += this._encodeByte(c >>> 1 * 6 & 63);
|
|
} else {
|
|
out += this._paddingCharacter || "";
|
|
}
|
|
out += this._paddingCharacter || "";
|
|
}
|
|
return out;
|
|
};
|
|
Coder2.prototype.maxDecodedLength = function(length) {
|
|
if (!this._paddingCharacter) {
|
|
return (length * 6 + 7) / 8 | 0;
|
|
}
|
|
return length / 4 * 3 | 0;
|
|
};
|
|
Coder2.prototype.decodedLength = function(s) {
|
|
return this.maxDecodedLength(s.length - this._getPaddingLength(s));
|
|
};
|
|
Coder2.prototype.decode = function(s) {
|
|
if (s.length === 0) {
|
|
return new Uint8Array(0);
|
|
}
|
|
var paddingLength = this._getPaddingLength(s);
|
|
var length = s.length - paddingLength;
|
|
var out = new Uint8Array(this.maxDecodedLength(length));
|
|
var op = 0;
|
|
var i = 0;
|
|
var haveBad = 0;
|
|
var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
|
|
for (; i < length - 4; i += 4) {
|
|
v0 = this._decodeChar(s.charCodeAt(i + 0));
|
|
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
out[op++] = v0 << 2 | v1 >>> 4;
|
|
out[op++] = v1 << 4 | v2 >>> 2;
|
|
out[op++] = v2 << 6 | v3;
|
|
haveBad |= v0 & INVALID_BYTE;
|
|
haveBad |= v1 & INVALID_BYTE;
|
|
haveBad |= v2 & INVALID_BYTE;
|
|
haveBad |= v3 & INVALID_BYTE;
|
|
}
|
|
if (i < length - 1) {
|
|
v0 = this._decodeChar(s.charCodeAt(i));
|
|
v1 = this._decodeChar(s.charCodeAt(i + 1));
|
|
out[op++] = v0 << 2 | v1 >>> 4;
|
|
haveBad |= v0 & INVALID_BYTE;
|
|
haveBad |= v1 & INVALID_BYTE;
|
|
}
|
|
if (i < length - 2) {
|
|
v2 = this._decodeChar(s.charCodeAt(i + 2));
|
|
out[op++] = v1 << 4 | v2 >>> 2;
|
|
haveBad |= v2 & INVALID_BYTE;
|
|
}
|
|
if (i < length - 3) {
|
|
v3 = this._decodeChar(s.charCodeAt(i + 3));
|
|
out[op++] = v2 << 6 | v3;
|
|
haveBad |= v3 & INVALID_BYTE;
|
|
}
|
|
if (haveBad !== 0) {
|
|
throw new Error("Base64Coder: incorrect characters for decoding");
|
|
}
|
|
return out;
|
|
};
|
|
Coder2.prototype._encodeByte = function(b) {
|
|
var result = b;
|
|
result += 65;
|
|
result += 25 - b >>> 8 & 0 - 65 - 26 + 97;
|
|
result += 51 - b >>> 8 & 26 - 97 - 52 + 48;
|
|
result += 61 - b >>> 8 & 52 - 48 - 62 + 43;
|
|
result += 62 - b >>> 8 & 62 - 43 - 63 + 47;
|
|
return String.fromCharCode(result);
|
|
};
|
|
Coder2.prototype._decodeChar = function(c) {
|
|
var result = INVALID_BYTE;
|
|
result += (42 - c & c - 44) >>> 8 & -INVALID_BYTE + c - 43 + 62;
|
|
result += (46 - c & c - 48) >>> 8 & -INVALID_BYTE + c - 47 + 63;
|
|
result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52;
|
|
result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0;
|
|
result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26;
|
|
return result;
|
|
};
|
|
Coder2.prototype._getPaddingLength = function(s) {
|
|
var paddingLength = 0;
|
|
if (this._paddingCharacter) {
|
|
for (var i = s.length - 1; i >= 0; i--) {
|
|
if (s[i] !== this._paddingCharacter) {
|
|
break;
|
|
}
|
|
paddingLength++;
|
|
}
|
|
if (s.length < 4 || paddingLength > 2) {
|
|
throw new Error("Base64Coder: incorrect padding");
|
|
}
|
|
}
|
|
return paddingLength;
|
|
};
|
|
return Coder2;
|
|
})()
|
|
);
|
|
exports.Coder = Coder;
|
|
var stdCoder = new Coder();
|
|
function encode3(data) {
|
|
return stdCoder.encode(data);
|
|
}
|
|
exports.encode = encode3;
|
|
function decode(s) {
|
|
return stdCoder.decode(s);
|
|
}
|
|
exports.decode = decode;
|
|
var URLSafeCoder = (
|
|
/** @class */
|
|
(function(_super) {
|
|
__extends(URLSafeCoder2, _super);
|
|
function URLSafeCoder2() {
|
|
return _super !== null && _super.apply(this, arguments) || this;
|
|
}
|
|
URLSafeCoder2.prototype._encodeByte = function(b) {
|
|
var result = b;
|
|
result += 65;
|
|
result += 25 - b >>> 8 & 0 - 65 - 26 + 97;
|
|
result += 51 - b >>> 8 & 26 - 97 - 52 + 48;
|
|
result += 61 - b >>> 8 & 52 - 48 - 62 + 45;
|
|
result += 62 - b >>> 8 & 62 - 45 - 63 + 95;
|
|
return String.fromCharCode(result);
|
|
};
|
|
URLSafeCoder2.prototype._decodeChar = function(c) {
|
|
var result = INVALID_BYTE;
|
|
result += (44 - c & c - 46) >>> 8 & -INVALID_BYTE + c - 45 + 62;
|
|
result += (94 - c & c - 96) >>> 8 & -INVALID_BYTE + c - 95 + 63;
|
|
result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52;
|
|
result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0;
|
|
result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26;
|
|
return result;
|
|
};
|
|
return URLSafeCoder2;
|
|
})(Coder)
|
|
);
|
|
exports.URLSafeCoder = URLSafeCoder;
|
|
var urlSafeCoder = new URLSafeCoder();
|
|
function encodeURLSafe(data) {
|
|
return urlSafeCoder.encode(data);
|
|
}
|
|
exports.encodeURLSafe = encodeURLSafe;
|
|
function decodeURLSafe(s) {
|
|
return urlSafeCoder.decode(s);
|
|
}
|
|
exports.decodeURLSafe = decodeURLSafe;
|
|
exports.encodedLength = function(length) {
|
|
return stdCoder.encodedLength(length);
|
|
};
|
|
exports.maxDecodedLength = function(length) {
|
|
return stdCoder.maxDecodedLength(length);
|
|
};
|
|
exports.decodedLength = function(s) {
|
|
return stdCoder.decodedLength(s);
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/fast-sha256/sha256.js
|
|
var require_sha256 = __commonJS({
|
|
"node_modules/fast-sha256/sha256.js"(exports, module) {
|
|
(function(root, factory) {
|
|
var exports2 = {};
|
|
factory(exports2);
|
|
var sha256 = exports2["default"];
|
|
for (var k in exports2) {
|
|
sha256[k] = exports2[k];
|
|
}
|
|
if (typeof module === "object" && typeof module.exports === "object") {
|
|
module.exports = sha256;
|
|
} else if (typeof define === "function" && define.amd) {
|
|
define(function() {
|
|
return sha256;
|
|
});
|
|
} else {
|
|
root.sha256 = sha256;
|
|
}
|
|
})(exports, function(exports2) {
|
|
"use strict";
|
|
exports2.__esModule = true;
|
|
exports2.digestLength = 32;
|
|
exports2.blockSize = 64;
|
|
var K = new Uint32Array([
|
|
1116352408,
|
|
1899447441,
|
|
3049323471,
|
|
3921009573,
|
|
961987163,
|
|
1508970993,
|
|
2453635748,
|
|
2870763221,
|
|
3624381080,
|
|
310598401,
|
|
607225278,
|
|
1426881987,
|
|
1925078388,
|
|
2162078206,
|
|
2614888103,
|
|
3248222580,
|
|
3835390401,
|
|
4022224774,
|
|
264347078,
|
|
604807628,
|
|
770255983,
|
|
1249150122,
|
|
1555081692,
|
|
1996064986,
|
|
2554220882,
|
|
2821834349,
|
|
2952996808,
|
|
3210313671,
|
|
3336571891,
|
|
3584528711,
|
|
113926993,
|
|
338241895,
|
|
666307205,
|
|
773529912,
|
|
1294757372,
|
|
1396182291,
|
|
1695183700,
|
|
1986661051,
|
|
2177026350,
|
|
2456956037,
|
|
2730485921,
|
|
2820302411,
|
|
3259730800,
|
|
3345764771,
|
|
3516065817,
|
|
3600352804,
|
|
4094571909,
|
|
275423344,
|
|
430227734,
|
|
506948616,
|
|
659060556,
|
|
883997877,
|
|
958139571,
|
|
1322822218,
|
|
1537002063,
|
|
1747873779,
|
|
1955562222,
|
|
2024104815,
|
|
2227730452,
|
|
2361852424,
|
|
2428436474,
|
|
2756734187,
|
|
3204031479,
|
|
3329325298
|
|
]);
|
|
function hashBlocks(w, v, p, pos, len) {
|
|
var a, b, c, d, e, f, g, h, u, i, j, t1, t2;
|
|
while (len >= 64) {
|
|
a = v[0];
|
|
b = v[1];
|
|
c = v[2];
|
|
d = v[3];
|
|
e = v[4];
|
|
f = v[5];
|
|
g = v[6];
|
|
h = v[7];
|
|
for (i = 0; i < 16; i++) {
|
|
j = pos + i * 4;
|
|
w[i] = (p[j] & 255) << 24 | (p[j + 1] & 255) << 16 | (p[j + 2] & 255) << 8 | p[j + 3] & 255;
|
|
}
|
|
for (i = 16; i < 64; i++) {
|
|
u = w[i - 2];
|
|
t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10;
|
|
u = w[i - 15];
|
|
t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3;
|
|
w[i] = (t1 + w[i - 7] | 0) + (t2 + w[i - 16] | 0);
|
|
}
|
|
for (i = 0; i < 64; i++) {
|
|
t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i] + w[i] | 0) | 0) | 0;
|
|
t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0;
|
|
h = g;
|
|
g = f;
|
|
f = e;
|
|
e = d + t1 | 0;
|
|
d = c;
|
|
c = b;
|
|
b = a;
|
|
a = t1 + t2 | 0;
|
|
}
|
|
v[0] += a;
|
|
v[1] += b;
|
|
v[2] += c;
|
|
v[3] += d;
|
|
v[4] += e;
|
|
v[5] += f;
|
|
v[6] += g;
|
|
v[7] += h;
|
|
pos += 64;
|
|
len -= 64;
|
|
}
|
|
return pos;
|
|
}
|
|
var Hash = (
|
|
/** @class */
|
|
(function() {
|
|
function Hash2() {
|
|
this.digestLength = exports2.digestLength;
|
|
this.blockSize = exports2.blockSize;
|
|
this.state = new Int32Array(8);
|
|
this.temp = new Int32Array(64);
|
|
this.buffer = new Uint8Array(128);
|
|
this.bufferLength = 0;
|
|
this.bytesHashed = 0;
|
|
this.finished = false;
|
|
this.reset();
|
|
}
|
|
Hash2.prototype.reset = function() {
|
|
this.state[0] = 1779033703;
|
|
this.state[1] = 3144134277;
|
|
this.state[2] = 1013904242;
|
|
this.state[3] = 2773480762;
|
|
this.state[4] = 1359893119;
|
|
this.state[5] = 2600822924;
|
|
this.state[6] = 528734635;
|
|
this.state[7] = 1541459225;
|
|
this.bufferLength = 0;
|
|
this.bytesHashed = 0;
|
|
this.finished = false;
|
|
return this;
|
|
};
|
|
Hash2.prototype.clean = function() {
|
|
for (var i = 0; i < this.buffer.length; i++) {
|
|
this.buffer[i] = 0;
|
|
}
|
|
for (var i = 0; i < this.temp.length; i++) {
|
|
this.temp[i] = 0;
|
|
}
|
|
this.reset();
|
|
};
|
|
Hash2.prototype.update = function(data, dataLength) {
|
|
if (dataLength === void 0) {
|
|
dataLength = data.length;
|
|
}
|
|
if (this.finished) {
|
|
throw new Error("SHA256: can't update because hash was finished.");
|
|
}
|
|
var dataPos = 0;
|
|
this.bytesHashed += dataLength;
|
|
if (this.bufferLength > 0) {
|
|
while (this.bufferLength < 64 && dataLength > 0) {
|
|
this.buffer[this.bufferLength++] = data[dataPos++];
|
|
dataLength--;
|
|
}
|
|
if (this.bufferLength === 64) {
|
|
hashBlocks(this.temp, this.state, this.buffer, 0, 64);
|
|
this.bufferLength = 0;
|
|
}
|
|
}
|
|
if (dataLength >= 64) {
|
|
dataPos = hashBlocks(this.temp, this.state, data, dataPos, dataLength);
|
|
dataLength %= 64;
|
|
}
|
|
while (dataLength > 0) {
|
|
this.buffer[this.bufferLength++] = data[dataPos++];
|
|
dataLength--;
|
|
}
|
|
return this;
|
|
};
|
|
Hash2.prototype.finish = function(out) {
|
|
if (!this.finished) {
|
|
var bytesHashed = this.bytesHashed;
|
|
var left = this.bufferLength;
|
|
var bitLenHi = bytesHashed / 536870912 | 0;
|
|
var bitLenLo = bytesHashed << 3;
|
|
var padLength = bytesHashed % 64 < 56 ? 64 : 128;
|
|
this.buffer[left] = 128;
|
|
for (var i = left + 1; i < padLength - 8; i++) {
|
|
this.buffer[i] = 0;
|
|
}
|
|
this.buffer[padLength - 8] = bitLenHi >>> 24 & 255;
|
|
this.buffer[padLength - 7] = bitLenHi >>> 16 & 255;
|
|
this.buffer[padLength - 6] = bitLenHi >>> 8 & 255;
|
|
this.buffer[padLength - 5] = bitLenHi >>> 0 & 255;
|
|
this.buffer[padLength - 4] = bitLenLo >>> 24 & 255;
|
|
this.buffer[padLength - 3] = bitLenLo >>> 16 & 255;
|
|
this.buffer[padLength - 2] = bitLenLo >>> 8 & 255;
|
|
this.buffer[padLength - 1] = bitLenLo >>> 0 & 255;
|
|
hashBlocks(this.temp, this.state, this.buffer, 0, padLength);
|
|
this.finished = true;
|
|
}
|
|
for (var i = 0; i < 8; i++) {
|
|
out[i * 4 + 0] = this.state[i] >>> 24 & 255;
|
|
out[i * 4 + 1] = this.state[i] >>> 16 & 255;
|
|
out[i * 4 + 2] = this.state[i] >>> 8 & 255;
|
|
out[i * 4 + 3] = this.state[i] >>> 0 & 255;
|
|
}
|
|
return this;
|
|
};
|
|
Hash2.prototype.digest = function() {
|
|
var out = new Uint8Array(this.digestLength);
|
|
this.finish(out);
|
|
return out;
|
|
};
|
|
Hash2.prototype._saveState = function(out) {
|
|
for (var i = 0; i < this.state.length; i++) {
|
|
out[i] = this.state[i];
|
|
}
|
|
};
|
|
Hash2.prototype._restoreState = function(from, bytesHashed) {
|
|
for (var i = 0; i < this.state.length; i++) {
|
|
this.state[i] = from[i];
|
|
}
|
|
this.bytesHashed = bytesHashed;
|
|
this.finished = false;
|
|
this.bufferLength = 0;
|
|
};
|
|
return Hash2;
|
|
})()
|
|
);
|
|
exports2.Hash = Hash;
|
|
var HMAC = (
|
|
/** @class */
|
|
(function() {
|
|
function HMAC2(key) {
|
|
this.inner = new Hash();
|
|
this.outer = new Hash();
|
|
this.blockSize = this.inner.blockSize;
|
|
this.digestLength = this.inner.digestLength;
|
|
var pad = new Uint8Array(this.blockSize);
|
|
if (key.length > this.blockSize) {
|
|
new Hash().update(key).finish(pad).clean();
|
|
} else {
|
|
for (var i = 0; i < key.length; i++) {
|
|
pad[i] = key[i];
|
|
}
|
|
}
|
|
for (var i = 0; i < pad.length; i++) {
|
|
pad[i] ^= 54;
|
|
}
|
|
this.inner.update(pad);
|
|
for (var i = 0; i < pad.length; i++) {
|
|
pad[i] ^= 54 ^ 92;
|
|
}
|
|
this.outer.update(pad);
|
|
this.istate = new Uint32Array(8);
|
|
this.ostate = new Uint32Array(8);
|
|
this.inner._saveState(this.istate);
|
|
this.outer._saveState(this.ostate);
|
|
for (var i = 0; i < pad.length; i++) {
|
|
pad[i] = 0;
|
|
}
|
|
}
|
|
HMAC2.prototype.reset = function() {
|
|
this.inner._restoreState(this.istate, this.inner.blockSize);
|
|
this.outer._restoreState(this.ostate, this.outer.blockSize);
|
|
return this;
|
|
};
|
|
HMAC2.prototype.clean = function() {
|
|
for (var i = 0; i < this.istate.length; i++) {
|
|
this.ostate[i] = this.istate[i] = 0;
|
|
}
|
|
this.inner.clean();
|
|
this.outer.clean();
|
|
};
|
|
HMAC2.prototype.update = function(data) {
|
|
this.inner.update(data);
|
|
return this;
|
|
};
|
|
HMAC2.prototype.finish = function(out) {
|
|
if (this.outer.finished) {
|
|
this.outer.finish(out);
|
|
} else {
|
|
this.inner.finish(out);
|
|
this.outer.update(out, this.digestLength).finish(out);
|
|
}
|
|
return this;
|
|
};
|
|
HMAC2.prototype.digest = function() {
|
|
var out = new Uint8Array(this.digestLength);
|
|
this.finish(out);
|
|
return out;
|
|
};
|
|
return HMAC2;
|
|
})()
|
|
);
|
|
exports2.HMAC = HMAC;
|
|
function hash(data) {
|
|
var h = new Hash().update(data);
|
|
var digest = h.digest();
|
|
h.clean();
|
|
return digest;
|
|
}
|
|
exports2.hash = hash;
|
|
exports2["default"] = hash;
|
|
function hmac(key, data) {
|
|
var h = new HMAC(key).update(data);
|
|
var digest = h.digest();
|
|
h.clean();
|
|
return digest;
|
|
}
|
|
exports2.hmac = hmac;
|
|
function fillBuffer(buffer, hmac2, info, counter) {
|
|
var num2 = counter[0];
|
|
if (num2 === 0) {
|
|
throw new Error("hkdf: cannot expand more");
|
|
}
|
|
hmac2.reset();
|
|
if (num2 > 1) {
|
|
hmac2.update(buffer);
|
|
}
|
|
if (info) {
|
|
hmac2.update(info);
|
|
}
|
|
hmac2.update(counter);
|
|
hmac2.finish(buffer);
|
|
counter[0]++;
|
|
}
|
|
var hkdfSalt = new Uint8Array(exports2.digestLength);
|
|
function hkdf(key, salt, info, length) {
|
|
if (salt === void 0) {
|
|
salt = hkdfSalt;
|
|
}
|
|
if (length === void 0) {
|
|
length = 32;
|
|
}
|
|
var counter = new Uint8Array([1]);
|
|
var okm = hmac(salt, key);
|
|
var hmac_ = new HMAC(okm);
|
|
var buffer = new Uint8Array(hmac_.digestLength);
|
|
var bufpos = buffer.length;
|
|
var out = new Uint8Array(length);
|
|
for (var i = 0; i < length; i++) {
|
|
if (bufpos === buffer.length) {
|
|
fillBuffer(buffer, hmac_, info, counter);
|
|
bufpos = 0;
|
|
}
|
|
out[i] = buffer[bufpos++];
|
|
}
|
|
hmac_.clean();
|
|
buffer.fill(0);
|
|
counter.fill(0);
|
|
return out;
|
|
}
|
|
exports2.hkdf = hkdf;
|
|
function pbkdf2(password, salt, iterations, dkLen) {
|
|
var prf = new HMAC(password);
|
|
var len = prf.digestLength;
|
|
var ctr = new Uint8Array(4);
|
|
var t = new Uint8Array(len);
|
|
var u = new Uint8Array(len);
|
|
var dk = new Uint8Array(dkLen);
|
|
for (var i = 0; i * len < dkLen; i++) {
|
|
var c = i + 1;
|
|
ctr[0] = c >>> 24 & 255;
|
|
ctr[1] = c >>> 16 & 255;
|
|
ctr[2] = c >>> 8 & 255;
|
|
ctr[3] = c >>> 0 & 255;
|
|
prf.reset();
|
|
prf.update(salt);
|
|
prf.update(ctr);
|
|
prf.finish(u);
|
|
for (var j = 0; j < len; j++) {
|
|
t[j] = u[j];
|
|
}
|
|
for (var j = 2; j <= iterations; j++) {
|
|
prf.reset();
|
|
prf.update(u).finish(u);
|
|
for (var k = 0; k < len; k++) {
|
|
t[k] ^= u[k];
|
|
}
|
|
}
|
|
for (var j = 0; j < len && i * len + j < dkLen; j++) {
|
|
dk[i * len + j] = t[j];
|
|
}
|
|
}
|
|
for (var i = 0; i < len; i++) {
|
|
t[i] = u[i] = 0;
|
|
}
|
|
for (var i = 0; i < 4; i++) {
|
|
ctr[i] = 0;
|
|
}
|
|
prf.clean();
|
|
return dk;
|
|
}
|
|
exports2.pbkdf2 = pbkdf2;
|
|
});
|
|
}
|
|
});
|
|
|
|
// node_modules/standardwebhooks/dist/timing_safe_equal.js
|
|
var require_timing_safe_equal = __commonJS({
|
|
"node_modules/standardwebhooks/dist/timing_safe_equal.js"(exports) {
|
|
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.timingSafeEqual = timingSafeEqual;
|
|
function assert(expr, msg = "") {
|
|
if (!expr) {
|
|
throw new Error(msg);
|
|
}
|
|
}
|
|
function timingSafeEqual(a, b) {
|
|
if (a.byteLength !== b.byteLength) {
|
|
return false;
|
|
}
|
|
if (!(a instanceof DataView)) {
|
|
a = new DataView(ArrayBuffer.isView(a) ? a.buffer : a);
|
|
}
|
|
if (!(b instanceof DataView)) {
|
|
b = new DataView(ArrayBuffer.isView(b) ? b.buffer : b);
|
|
}
|
|
assert(a instanceof DataView);
|
|
assert(b instanceof DataView);
|
|
const length = a.byteLength;
|
|
let out = 0;
|
|
let i = -1;
|
|
while (++i < length) {
|
|
out |= a.getUint8(i) ^ b.getUint8(i);
|
|
}
|
|
return out === 0;
|
|
}
|
|
}
|
|
});
|
|
|
|
// node_modules/standardwebhooks/dist/index.js
|
|
var require_dist2 = __commonJS({
|
|
"node_modules/standardwebhooks/dist/index.js"(exports) {
|
|
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.Webhook = exports.WebhookVerificationError = void 0;
|
|
var base64 = require_base64();
|
|
var sha256 = require_sha256();
|
|
var timing_safe_equal_1 = require_timing_safe_equal();
|
|
var WEBHOOK_TOLERANCE_IN_SECONDS = 5 * 60;
|
|
var ExtendableError = class _ExtendableError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
Object.setPrototypeOf(this, _ExtendableError.prototype);
|
|
this.name = "ExtendableError";
|
|
this.stack = new Error(message).stack;
|
|
}
|
|
};
|
|
var WebhookVerificationError = class _WebhookVerificationError extends ExtendableError {
|
|
constructor(message) {
|
|
super(message);
|
|
Object.setPrototypeOf(this, _WebhookVerificationError.prototype);
|
|
this.name = "WebhookVerificationError";
|
|
}
|
|
};
|
|
exports.WebhookVerificationError = WebhookVerificationError;
|
|
var Webhook2 = class _Webhook {
|
|
constructor(secret, options) {
|
|
if ((options === null || options === void 0 ? void 0 : options.format) === "raw") {
|
|
if (secret instanceof Uint8Array) {
|
|
this.key = secret;
|
|
} else {
|
|
this.key = Uint8Array.from(secret, (c) => c.charCodeAt(0));
|
|
}
|
|
} else {
|
|
if (typeof secret !== "string") {
|
|
throw new Error("Expected secret to be of type string");
|
|
}
|
|
if (secret.startsWith(_Webhook.prefix)) {
|
|
secret = secret.substring(_Webhook.prefix.length);
|
|
}
|
|
this.key = base64.decode(secret);
|
|
}
|
|
if (this.key.length === 0) {
|
|
throw new Error("Secret can't be empty.");
|
|
}
|
|
}
|
|
verify(payload, headers, options) {
|
|
var _a6;
|
|
const jsonParse = (_a6 = options === null || options === void 0 ? void 0 : options.jsonParse) !== null && _a6 !== void 0 ? _a6 : true;
|
|
const normalizedHeaders = {};
|
|
for (const key of Object.keys(headers)) {
|
|
normalizedHeaders[key.toLowerCase()] = headers[key];
|
|
}
|
|
const msgId = normalizedHeaders["webhook-id"];
|
|
const msgSignature = normalizedHeaders["webhook-signature"];
|
|
const msgTimestamp = normalizedHeaders["webhook-timestamp"];
|
|
if (!msgSignature || !msgId || !msgTimestamp) {
|
|
throw new WebhookVerificationError("Missing required headers");
|
|
}
|
|
const timestamp2 = this.verifyTimestamp(msgTimestamp);
|
|
const computedSignature = this.sign(msgId, timestamp2, payload);
|
|
const expectedSignature = computedSignature.split(",")[1];
|
|
const passedSignatures = msgSignature.split(" ");
|
|
const encoder3 = new globalThis.TextEncoder();
|
|
for (const versionedSignature of passedSignatures) {
|
|
const [version, signature] = versionedSignature.split(",");
|
|
if (version !== "v1") {
|
|
continue;
|
|
}
|
|
if ((0, timing_safe_equal_1.timingSafeEqual)(encoder3.encode(signature), encoder3.encode(expectedSignature))) {
|
|
const payloadString = payload.toString();
|
|
if (payloadString === "") {
|
|
return void 0;
|
|
}
|
|
if (jsonParse) {
|
|
return JSON.parse(payloadString);
|
|
} else {
|
|
return void 0;
|
|
}
|
|
}
|
|
}
|
|
throw new WebhookVerificationError("No matching signature found");
|
|
}
|
|
sign(msgId, timestamp2, payload) {
|
|
if (typeof payload === "string") {
|
|
} else if (payload.constructor.name === "Buffer") {
|
|
payload = payload.toString();
|
|
} else {
|
|
throw new Error("Expected payload to be of type string or Buffer.");
|
|
}
|
|
const encoder3 = new TextEncoder();
|
|
const timestampNumber = Math.floor(timestamp2.getTime() / 1e3);
|
|
const toSign = encoder3.encode(`${msgId}.${timestampNumber}.${payload}`);
|
|
const expectedSignature = base64.encode(sha256.hmac(this.key, toSign));
|
|
return `v1,${expectedSignature}`;
|
|
}
|
|
verifyTimestamp(timestampHeader) {
|
|
const now = Math.floor(Date.now() / 1e3);
|
|
const timestamp2 = parseInt(timestampHeader, 10);
|
|
if (Number.isNaN(timestamp2)) {
|
|
throw new WebhookVerificationError("Invalid Signature Headers");
|
|
}
|
|
if (now - timestamp2 > WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
throw new WebhookVerificationError("Message timestamp too old");
|
|
}
|
|
if (timestamp2 > now + WEBHOOK_TOLERANCE_IN_SECONDS) {
|
|
throw new WebhookVerificationError("Message timestamp too new");
|
|
}
|
|
return new Date(timestamp2 * 1e3);
|
|
}
|
|
};
|
|
exports.Webhook = Webhook2;
|
|
Webhook2.prefix = "whsec_";
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/webhooks.mjs
|
|
var import_standardwebhooks, Webhooks2;
|
|
var init_webhooks2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/webhooks.mjs"() {
|
|
init_resource2();
|
|
import_standardwebhooks = __toESM(require_dist2(), 1);
|
|
Webhooks2 = class extends APIResource2 {
|
|
/**
|
|
* Parses a webhook payload into an event without verifying its signature. Prefer
|
|
* `unwrap()` unless you have already verified the signature yourself.
|
|
*/
|
|
parseUnverified(body) {
|
|
return JSON.parse(body);
|
|
}
|
|
/**
|
|
* Verifies the webhook signature from the `webhook-id`, `webhook-timestamp` and
|
|
* `webhook-signature` headers using your webhook signing key, then parses the
|
|
* payload into an event. Fails if the signature is missing or invalid.
|
|
*/
|
|
unwrap(body, options) {
|
|
const headers = options?.headers;
|
|
if (headers == null)
|
|
throw new Error("Webhook headers are required in order to verify the signature");
|
|
const keyStr = options.key === void 0 ? this._client.webhookKey : options.key;
|
|
if (!keyStr)
|
|
throw new Error("Webhook key must not be null or empty in order to unwrap");
|
|
const wh = new import_standardwebhooks.Webhook(keyStr);
|
|
wh.verify(body, headers);
|
|
return JSON.parse(body);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/agents/versions.mjs
|
|
var Versions2;
|
|
var init_versions2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/agents/versions.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Versions2 = class extends APIResource2 {
|
|
/**
|
|
* List Agent Versions
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsAgent of client.beta.agents.versions.list(
|
|
* 'agent_011CZkYpogX7uDKUyvBTophP',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(agentID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/agents/${agentID}/versions?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/agents/agents.mjs
|
|
var Agents2;
|
|
var init_agents2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/agents/agents.mjs"() {
|
|
init_resource2();
|
|
init_versions2();
|
|
init_versions2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Agents2 = /* @__PURE__ */ (() => {
|
|
class Agents3 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.versions = new Versions2(this._client);
|
|
}
|
|
/**
|
|
* Create Agent
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsAgent =
|
|
* await client.beta.agents.create({
|
|
* model: 'claude-opus-5',
|
|
* name: 'My First Agent',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/agents?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get Agent
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsAgent =
|
|
* await client.beta.agents.retrieve(
|
|
* 'agent_011CZkYpogX7uDKUyvBTophP',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(agentID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.get(path3`/v1/agents/${agentID}?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update Agent
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsAgent =
|
|
* await client.beta.agents.update(
|
|
* 'agent_011CZkYpogX7uDKUyvBTophP',
|
|
* { description: 'updated' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(agentID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/agents/${agentID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Agents
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsAgent of client.beta.agents.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/agents?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive Agent
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsAgent =
|
|
* await client.beta.agents.archive(
|
|
* 'agent_011CZkYpogX7uDKUyvBTophP',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(agentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/agents/${agentID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Agents3.Versions = Versions2;
|
|
return Agents3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/abort.mjs
|
|
function linkAbort(external, controller) {
|
|
if (!external)
|
|
return () => {
|
|
};
|
|
if (external.aborted) {
|
|
controller.abort();
|
|
return () => {
|
|
};
|
|
}
|
|
const onAbort = () => controller.abort();
|
|
external.addEventListener("abort", onAbort);
|
|
return () => external.removeEventListener("abort", onAbort);
|
|
}
|
|
var init_abort3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/abort.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/backoff.mjs
|
|
function isStatus(e, code) {
|
|
return e instanceof APIError2 && e.status === code;
|
|
}
|
|
function is4xx(e) {
|
|
return e instanceof APIError2 && typeof e.status === "number" && e.status >= 400 && e.status < 500;
|
|
}
|
|
function isFatal4xx(e) {
|
|
return is4xx(e) && !isStatus(e, 408) && !isStatus(e, 409) && !isStatus(e, 429);
|
|
}
|
|
function backoff(attempt, baseMs, capMs) {
|
|
return Math.min(baseMs * 2 ** attempt, capMs);
|
|
}
|
|
function jitter(lowMs, highMs) {
|
|
return lowMs + Math.random() * (highMs - lowMs);
|
|
}
|
|
function applyJitter(ms) {
|
|
return ms * (1 - Math.random() * 0.25);
|
|
}
|
|
var init_backoff = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/backoff.mjs"() {
|
|
init_error3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/helper-client.mjs
|
|
function copyClientForHelper(client, { authToken, helper }) {
|
|
if (!authToken) {
|
|
throw new AnthropicError(`copyClientForHelper: expected a non-empty authToken but received ${JSON.stringify(authToken)}`);
|
|
}
|
|
const internal = client;
|
|
const parentDefaults = internal._options.defaultHeaders;
|
|
const parentAuthExtraHeaders = internal._authState?.extraHeaders;
|
|
const inheritedAuthExtraHeaders = parentAuthExtraHeaders ? Object.fromEntries(Object.entries(parentAuthExtraHeaders).filter(([name]) => {
|
|
const lower = name.toLowerCase();
|
|
return lower !== "authorization" && lower !== "x-api-key";
|
|
})) : void 0;
|
|
const defaultHeaders = buildHeaders2([
|
|
inheritedAuthExtraHeaders,
|
|
parentDefaults,
|
|
{ [STAINLESS_HELPER_HEADER]: helper }
|
|
]);
|
|
return client.withOptions({
|
|
apiKey: null,
|
|
authToken,
|
|
baseURL: client.baseURL,
|
|
credentials: void 0,
|
|
defaultHeaders
|
|
});
|
|
}
|
|
var init_helper_client = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/helper-client.mjs"() {
|
|
init_error3();
|
|
init_headers3();
|
|
init_stainless_helper_header();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/environments/poller.mjs
|
|
function backoff2(attempt) {
|
|
return backoff(attempt, POLL_BACKOFF_BASE_MS, POLL_BACKOFF_CAP_MS);
|
|
}
|
|
function defaultWorkerId() {
|
|
const env = globalThis.process?.env;
|
|
const host = env?.["HOSTNAME"];
|
|
return host ? `${host}-${uuid42()}` : uuid42();
|
|
}
|
|
var _WorkPoller_runnerClient, _WorkPoller_consumed, _WorkPoller_controller, _WorkPoller_detachExternal, _WorkPoller_autoStop, _WorkPoller_drain, _WorkPoller_blockMs, _WorkPoller_reclaimOlderThanMs, _WorkPoller_requestOpts, _IdleLog_log, _IdleLog_environmentId, _IdleLog_idleSince, _IdleLog_lastReport, POLL_BLOCK_MS, POLL_BACKOFF_BASE_MS, POLL_BACKOFF_CAP_MS, IDLE_REPORT_INTERVAL_MS, WorkPoller, IdleLog;
|
|
var init_poller = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/environments/poller.mjs"() {
|
|
init_tslib2();
|
|
init_error3();
|
|
init_log2();
|
|
init_sleep2();
|
|
init_uuid2();
|
|
init_abort3();
|
|
init_headers3();
|
|
init_backoff();
|
|
init_helper_client();
|
|
POLL_BLOCK_MS = 999;
|
|
POLL_BACKOFF_BASE_MS = 1e3;
|
|
POLL_BACKOFF_CAP_MS = 6e4;
|
|
IDLE_REPORT_INTERVAL_MS = 3e5;
|
|
WorkPoller = /* @__PURE__ */ (() => {
|
|
class WorkPoller2 {
|
|
constructor(opts) {
|
|
_WorkPoller_runnerClient.set(this, void 0);
|
|
_WorkPoller_consumed.set(this, false);
|
|
_WorkPoller_controller.set(this, void 0);
|
|
_WorkPoller_detachExternal.set(this, void 0);
|
|
_WorkPoller_autoStop.set(this, void 0);
|
|
_WorkPoller_drain.set(this, void 0);
|
|
_WorkPoller_blockMs.set(this, void 0);
|
|
_WorkPoller_reclaimOlderThanMs.set(this, void 0);
|
|
_WorkPoller_requestOpts.set(this, void 0);
|
|
this.client = opts.client;
|
|
this.environmentId = opts.environmentId;
|
|
this.environmentKey = opts.environmentKey;
|
|
this.workerId = opts.workerId ?? defaultWorkerId();
|
|
__classPrivateFieldSet2(this, _WorkPoller_runnerClient, copyClientForHelper(opts.client, {
|
|
authToken: opts.environmentKey,
|
|
helper: "environments-work-poller"
|
|
}), "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_autoStop, opts.autoStop ?? true, "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_drain, opts.drain ?? false, "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_blockMs, opts.blockMs === void 0 ? POLL_BLOCK_MS : opts.blockMs, "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_reclaimOlderThanMs, opts.reclaimOlderThanMs ?? null, "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_requestOpts, opts.requestOptions, "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_controller, new AbortController(), "f");
|
|
__classPrivateFieldSet2(this, _WorkPoller_detachExternal, linkAbort(opts.signal, __classPrivateFieldGet2(this, _WorkPoller_controller, "f")), "f");
|
|
}
|
|
/** Read-only view of this iterator's abort signal. */
|
|
get signal() {
|
|
return __classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal;
|
|
}
|
|
/** Abort the iterator. The current `for await` will exit cleanly. */
|
|
abort() {
|
|
__classPrivateFieldGet2(this, _WorkPoller_controller, "f").abort();
|
|
}
|
|
async *[(_WorkPoller_runnerClient = /* @__PURE__ */ new WeakMap(), _WorkPoller_consumed = /* @__PURE__ */ new WeakMap(), _WorkPoller_controller = /* @__PURE__ */ new WeakMap(), _WorkPoller_detachExternal = /* @__PURE__ */ new WeakMap(), _WorkPoller_autoStop = /* @__PURE__ */ new WeakMap(), _WorkPoller_drain = /* @__PURE__ */ new WeakMap(), _WorkPoller_blockMs = /* @__PURE__ */ new WeakMap(), _WorkPoller_reclaimOlderThanMs = /* @__PURE__ */ new WeakMap(), _WorkPoller_requestOpts = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
|
|
if (__classPrivateFieldGet2(this, _WorkPoller_consumed, "f")) {
|
|
throw new AnthropicError("Cannot iterate over a consumed WorkPoller");
|
|
}
|
|
__classPrivateFieldSet2(this, _WorkPoller_consumed, true, "f");
|
|
const log = loggerFor2(this.client);
|
|
log.info("poller starting", {
|
|
component: "work-poller",
|
|
environment_id: this.environmentId
|
|
});
|
|
const idle = new IdleLog(log, this.environmentId);
|
|
try {
|
|
let attempt = 0;
|
|
while (!__classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal.aborted) {
|
|
let work;
|
|
try {
|
|
work = await __classPrivateFieldGet2(this, _WorkPoller_runnerClient, "f").beta.environments.work.poll(this.environmentId, {
|
|
"Anthropic-Worker-ID": this.workerId,
|
|
...__classPrivateFieldGet2(this, _WorkPoller_blockMs, "f") !== null ? { block_ms: __classPrivateFieldGet2(this, _WorkPoller_blockMs, "f") } : {},
|
|
...__classPrivateFieldGet2(this, _WorkPoller_reclaimOlderThanMs, "f") !== null ? { reclaim_older_than_ms: __classPrivateFieldGet2(this, _WorkPoller_reclaimOlderThanMs, "f") } : {}
|
|
}, { headers: buildHeaders2([__classPrivateFieldGet2(this, _WorkPoller_requestOpts, "f")?.headers]), signal: __classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal });
|
|
} catch (e) {
|
|
if (__classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal.aborted)
|
|
return;
|
|
if (isFatal4xx(e)) {
|
|
log.error("poll failed permanently, stopping poller", { error: String(e) });
|
|
throw e;
|
|
}
|
|
const wait = applyJitter(backoff2(attempt));
|
|
log.warn("poll failed, backing off", { error: String(e), backoff_ms: wait });
|
|
attempt++;
|
|
await sleep2(wait, __classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal);
|
|
continue;
|
|
}
|
|
attempt = 0;
|
|
if (work == null) {
|
|
if (__classPrivateFieldGet2(this, _WorkPoller_drain, "f"))
|
|
return;
|
|
idle.onEmptyPoll();
|
|
await sleep2(jitter(1e3, 3e3), __classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal);
|
|
continue;
|
|
}
|
|
idle.onClaim();
|
|
log.info("claimed work", {
|
|
component: "work-poller",
|
|
environment_id: this.environmentId,
|
|
work_id: work.id,
|
|
work_type: work.data.type
|
|
});
|
|
try {
|
|
await __classPrivateFieldGet2(this, _WorkPoller_runnerClient, "f").beta.environments.work.ack(work.id, { environment_id: work.environment_id }, { headers: buildHeaders2([__classPrivateFieldGet2(this, _WorkPoller_requestOpts, "f")?.headers]), signal: __classPrivateFieldGet2(this, _WorkPoller_controller, "f").signal });
|
|
} catch (e) {
|
|
log.error("ack failed", { work_id: work.id, error: String(e) });
|
|
continue;
|
|
}
|
|
try {
|
|
yield work;
|
|
} finally {
|
|
if (__classPrivateFieldGet2(this, _WorkPoller_autoStop, "f")) {
|
|
try {
|
|
await __classPrivateFieldGet2(this, _WorkPoller_runnerClient, "f").beta.environments.work.stop(work.id, { environment_id: work.environment_id }, { headers: buildHeaders2([__classPrivateFieldGet2(this, _WorkPoller_requestOpts, "f")?.headers]) });
|
|
} catch (e) {
|
|
if (!isStatus(e, 409))
|
|
log.warn("stop failed", { work_id: work.id, error: String(e) });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} finally {
|
|
__classPrivateFieldGet2(this, _WorkPoller_detachExternal, "f").call(this);
|
|
}
|
|
}
|
|
}
|
|
return WorkPoller2;
|
|
})();
|
|
IdleLog = /* @__PURE__ */ (() => {
|
|
class IdleLog2 {
|
|
constructor(log, environmentId) {
|
|
_IdleLog_log.set(this, void 0);
|
|
_IdleLog_environmentId.set(this, void 0);
|
|
_IdleLog_idleSince.set(this, void 0);
|
|
_IdleLog_lastReport.set(this, 0);
|
|
__classPrivateFieldSet2(this, _IdleLog_log, log, "f");
|
|
__classPrivateFieldSet2(this, _IdleLog_environmentId, environmentId, "f");
|
|
}
|
|
onEmptyPoll() {
|
|
const now = Date.now();
|
|
const fields = { component: "work-poller", environment_id: __classPrivateFieldGet2(this, _IdleLog_environmentId, "f") };
|
|
if (__classPrivateFieldGet2(this, _IdleLog_idleSince, "f") === void 0) {
|
|
__classPrivateFieldSet2(this, _IdleLog_idleSince, __classPrivateFieldSet2(this, _IdleLog_lastReport, now, "f"), "f");
|
|
__classPrivateFieldGet2(this, _IdleLog_log, "f").info("idle; polling for work", fields);
|
|
} else if (now - __classPrivateFieldGet2(this, _IdleLog_lastReport, "f") >= IDLE_REPORT_INTERVAL_MS) {
|
|
__classPrivateFieldSet2(this, _IdleLog_lastReport, now, "f");
|
|
__classPrivateFieldGet2(this, _IdleLog_log, "f").info(`still polling; idle for ${Math.round((now - __classPrivateFieldGet2(this, _IdleLog_idleSince, "f")) / 1e3)}s`, fields);
|
|
} else {
|
|
__classPrivateFieldGet2(this, _IdleLog_log, "f").debug("poll returned no work", fields);
|
|
}
|
|
}
|
|
onClaim() {
|
|
__classPrivateFieldSet2(this, _IdleLog_idleSince, void 0, "f");
|
|
}
|
|
}
|
|
_IdleLog_log = /* @__PURE__ */ new WeakMap(), _IdleLog_environmentId = /* @__PURE__ */ new WeakMap(), _IdleLog_idleSince = /* @__PURE__ */ new WeakMap(), _IdleLog_lastReport = /* @__PURE__ */ new WeakMap();
|
|
return IdleLog2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/async-queue.mjs
|
|
var _AsyncQueue_items, _AsyncQueue_waiters, _AsyncQueue_closed, AsyncQueue;
|
|
var init_async_queue = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/async-queue.mjs"() {
|
|
init_tslib2();
|
|
AsyncQueue = /* @__PURE__ */ (() => {
|
|
class AsyncQueue2 {
|
|
constructor() {
|
|
_AsyncQueue_items.set(this, []);
|
|
_AsyncQueue_waiters.set(this, []);
|
|
_AsyncQueue_closed.set(this, false);
|
|
}
|
|
/** Enqueue an item, or hand it directly to a waiting reader. Returns `false` once closed. */
|
|
push(item) {
|
|
if (__classPrivateFieldGet2(this, _AsyncQueue_closed, "f"))
|
|
return false;
|
|
const w = __classPrivateFieldGet2(this, _AsyncQueue_waiters, "f").shift();
|
|
if (w)
|
|
w({ done: false, value: item });
|
|
else
|
|
__classPrivateFieldGet2(this, _AsyncQueue_items, "f").push(item);
|
|
return true;
|
|
}
|
|
/** Mark the queue done. Idempotent; wakes every pending reader with `done: true`. */
|
|
close() {
|
|
if (__classPrivateFieldGet2(this, _AsyncQueue_closed, "f"))
|
|
return;
|
|
__classPrivateFieldSet2(this, _AsyncQueue_closed, true, "f");
|
|
while (__classPrivateFieldGet2(this, _AsyncQueue_waiters, "f").length > 0) {
|
|
const w = __classPrivateFieldGet2(this, _AsyncQueue_waiters, "f").shift();
|
|
w({ done: true, value: void 0 });
|
|
}
|
|
}
|
|
/**
|
|
* Resolve with the next item, or `done: true` once the queue is closed and
|
|
* drained. When `signal` is supplied, aborting it resolves a pending read
|
|
* with `done: true` (cancellation is pushed down here rather than handled by
|
|
* an outer `Promise.race`).
|
|
*/
|
|
next(signal) {
|
|
if (__classPrivateFieldGet2(this, _AsyncQueue_items, "f").length > 0) {
|
|
return Promise.resolve({ done: false, value: __classPrivateFieldGet2(this, _AsyncQueue_items, "f").shift() });
|
|
}
|
|
if (__classPrivateFieldGet2(this, _AsyncQueue_closed, "f") || signal?.aborted) {
|
|
return Promise.resolve({ done: true, value: void 0 });
|
|
}
|
|
return new Promise((resolve) => {
|
|
const waiter = (r) => {
|
|
signal?.removeEventListener("abort", onAbort);
|
|
resolve(r);
|
|
};
|
|
const onAbort = () => {
|
|
const idx = __classPrivateFieldGet2(this, _AsyncQueue_waiters, "f").indexOf(waiter);
|
|
if (idx >= 0)
|
|
__classPrivateFieldGet2(this, _AsyncQueue_waiters, "f").splice(idx, 1);
|
|
resolve({ done: true, value: void 0 });
|
|
};
|
|
__classPrivateFieldGet2(this, _AsyncQueue_waiters, "f").push(waiter);
|
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
});
|
|
}
|
|
/** Synchronously remove and return the next buffered item, or `undefined` if empty. */
|
|
tryShift() {
|
|
return __classPrivateFieldGet2(this, _AsyncQueue_items, "f").shift();
|
|
}
|
|
}
|
|
_AsyncQueue_items = /* @__PURE__ */ new WeakMap(), _AsyncQueue_waiters = /* @__PURE__ */ new WeakMap(), _AsyncQueue_closed = /* @__PURE__ */ new WeakMap();
|
|
return AsyncQueue2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs
|
|
var ToolError;
|
|
var init_ToolError = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs"() {
|
|
ToolError = /* @__PURE__ */ (() => {
|
|
class ToolError2 extends Error {
|
|
constructor(content) {
|
|
const message = typeof content === "string" ? content : content.map((block) => {
|
|
if (block.type === "text")
|
|
return block.text;
|
|
return `[${block.type}]`;
|
|
}).join(" ");
|
|
super(message);
|
|
this.name = "ToolError";
|
|
this.content = content;
|
|
}
|
|
}
|
|
return ToolError2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/tools/BetaRunnableTool.mjs
|
|
function toolName(tool) {
|
|
return "name" in tool ? tool.name : "mcp_server_name" in tool ? tool.mcp_server_name : tool.type;
|
|
}
|
|
function toolErrorContent(e) {
|
|
return e instanceof ToolError ? e.content : `Error: ${e instanceof Error ? e.message : String(e)}`;
|
|
}
|
|
async function runRunnableTool(tool, rawInput, context) {
|
|
try {
|
|
const input = tool.parse ? tool.parse(rawInput) : rawInput;
|
|
const content = await tool.run(input, context);
|
|
return { content, isError: false };
|
|
} catch (e) {
|
|
return { content: toolErrorContent(e), isError: true };
|
|
}
|
|
}
|
|
var init_BetaRunnableTool = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/tools/BetaRunnableTool.mjs"() {
|
|
init_ToolError();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/tools/SessionToolRunner.mjs
|
|
function isEndTurnIdle(ev) {
|
|
return ev.type === "session.status_idle" && ev.stop_reason?.type === "end_turn";
|
|
}
|
|
function buildResultEvent(ev, isError, content) {
|
|
if (ev.type === "agent.custom_tool_use") {
|
|
return { type: "user.custom_tool_result", custom_tool_use_id: ev.id, is_error: isError, content };
|
|
}
|
|
return { type: "user.tool_result", tool_use_id: ev.id, is_error: isError, content };
|
|
}
|
|
function toSessionContent(content) {
|
|
if (typeof content === "string")
|
|
return [{ type: "text", text: content || "(no output)" }];
|
|
const out = content.map((b) => {
|
|
if (b.type === "text")
|
|
return { type: "text", text: b.text || "(no output)" };
|
|
if (b.type === "image" || b.type === "document")
|
|
return b;
|
|
if (b.type === "search_result") {
|
|
return {
|
|
type: "search_result",
|
|
source: b.source,
|
|
title: b.title,
|
|
content: b.content.map((c) => ({ type: "text", text: c.text })),
|
|
citations: { enabled: b.citations?.enabled ?? false }
|
|
};
|
|
}
|
|
return { type: "text", text: JSON.stringify(b) };
|
|
});
|
|
return out.length > 0 ? out : [{ type: "text", text: "(no output)" }];
|
|
}
|
|
var _IdleClock_maxIdleMs, _IdleClock_onExpire, _IdleClock_blockers, _IdleClock_armPending, _IdleClock_timer, _SessionToolRunner_instances, _SessionToolRunner_consumed, _SessionToolRunner_controller, _SessionToolRunner_detachExternal, _SessionToolRunner_requestOpts, _SessionToolRunner_toolByName, _SessionToolRunner_logger, _SessionToolRunner_seen, _SessionToolRunner_answered, _SessionToolRunner_confirmationVerdicts, _SessionToolRunner_awaitingConfirmation, _SessionToolRunner_results, _SessionToolRunner_inFlightCount, _SessionToolRunner_sendRetryWindowMs, _SessionToolRunner_onIdle, _SessionToolRunner_idleClock, _SessionToolRunner_requestOptions, _SessionToolRunner_streamLoop, _SessionToolRunner_reconcile, _SessionToolRunner_ingestHistory, _SessionToolRunner_handleStreamEvent, _SessionToolRunner_routeToolEvent, _SessionToolRunner_noteConfirmation, _SessionToolRunner_applyVerdict, _SessionToolRunner_surfaceCall, _SessionToolRunner_execute, _SessionToolRunner_sendResult, _SessionToolRunner_drain, STREAM_BACKOFF_START_MS, STREAM_BACKOFF_CAP_MS, TOOL_TIMEOUT_MS, DRAIN_TIMEOUT_MS, SEND_BACKOFF_START_MS, SEND_BACKOFF_CAP_MS, SEND_RETRY_WINDOW_MS, DEFAULT_MAX_IDLE_MS, IdleClock, SessionToolRunner;
|
|
var init_SessionToolRunner = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/tools/SessionToolRunner.mjs"() {
|
|
init_tslib2();
|
|
init_error3();
|
|
init_log2();
|
|
init_sleep2();
|
|
init_backoff();
|
|
init_abort3();
|
|
init_async_queue();
|
|
init_headers3();
|
|
init_stainless_helper_header();
|
|
init_BetaRunnableTool();
|
|
STREAM_BACKOFF_START_MS = 500;
|
|
STREAM_BACKOFF_CAP_MS = 1e4;
|
|
TOOL_TIMEOUT_MS = 12e4;
|
|
DRAIN_TIMEOUT_MS = 3e4;
|
|
SEND_BACKOFF_START_MS = 1e3;
|
|
SEND_BACKOFF_CAP_MS = 3e4;
|
|
SEND_RETRY_WINDOW_MS = 5 * 6e4;
|
|
DEFAULT_MAX_IDLE_MS = 6e4;
|
|
IdleClock = /* @__PURE__ */ (() => {
|
|
class IdleClock2 {
|
|
constructor(maxIdleMs, onExpire) {
|
|
_IdleClock_maxIdleMs.set(this, void 0);
|
|
_IdleClock_onExpire.set(this, void 0);
|
|
_IdleClock_blockers.set(this, /* @__PURE__ */ new Set());
|
|
_IdleClock_armPending.set(this, false);
|
|
_IdleClock_timer.set(this, void 0);
|
|
__classPrivateFieldSet2(this, _IdleClock_maxIdleMs, maxIdleMs, "f");
|
|
__classPrivateFieldSet2(this, _IdleClock_onExpire, onExpire, "f");
|
|
}
|
|
/**
|
|
* Arm on `status_idle{end_turn}`; disarm otherwise. `user.tool_confirmation`
|
|
* is neutral: it signals neither agent activity nor an idle, and its effect
|
|
* on the clock flows through {@link block} / {@link unblock} instead —
|
|
* disarming here would discard the pending arm the verdict is about to
|
|
* settle.
|
|
*/
|
|
noteEvent(ev) {
|
|
if (ev.type === "user.tool_confirmation")
|
|
return;
|
|
if (isEndTurnIdle(ev))
|
|
this.arm();
|
|
else
|
|
this.disarm();
|
|
}
|
|
/** Register gated work that must resolve before an idle countdown starts. */
|
|
block(toolUseId) {
|
|
__classPrivateFieldGet2(this, _IdleClock_blockers, "f").add(toolUseId);
|
|
if (__classPrivateFieldGet2(this, _IdleClock_timer, "f") !== void 0) {
|
|
__classPrivateFieldSet2(this, _IdleClock_armPending, true, "f");
|
|
clearTimeout(__classPrivateFieldGet2(this, _IdleClock_timer, "f"));
|
|
__classPrivateFieldSet2(this, _IdleClock_timer, void 0, "f");
|
|
}
|
|
}
|
|
/**
|
|
* Retire gated work (a no-op for ids never blocked); applies a pending arm —
|
|
* with a fresh full `maxIdleMs` window — once the last blocker retires.
|
|
*/
|
|
unblock(toolUseId) {
|
|
__classPrivateFieldGet2(this, _IdleClock_blockers, "f").delete(toolUseId);
|
|
if (__classPrivateFieldGet2(this, _IdleClock_blockers, "f").size === 0 && __classPrivateFieldGet2(this, _IdleClock_armPending, "f"))
|
|
this.arm();
|
|
}
|
|
/**
|
|
* (Re)start the idle countdown — or, while blockers are outstanding, hold
|
|
* the arm pending instead. Stopping then would drop a held call when its
|
|
* verdict later arrives, or cut the runner off before a released call's
|
|
* result can drive the next turn.
|
|
*/
|
|
arm() {
|
|
if (__classPrivateFieldGet2(this, _IdleClock_maxIdleMs, "f") <= 0)
|
|
return;
|
|
if (__classPrivateFieldGet2(this, _IdleClock_blockers, "f").size > 0) {
|
|
__classPrivateFieldSet2(this, _IdleClock_armPending, true, "f");
|
|
return;
|
|
}
|
|
__classPrivateFieldSet2(this, _IdleClock_armPending, false, "f");
|
|
if (__classPrivateFieldGet2(this, _IdleClock_timer, "f") !== void 0)
|
|
clearTimeout(__classPrivateFieldGet2(this, _IdleClock_timer, "f"));
|
|
__classPrivateFieldSet2(this, _IdleClock_timer, setTimeout(__classPrivateFieldGet2(this, _IdleClock_onExpire, "f"), __classPrivateFieldGet2(this, _IdleClock_maxIdleMs, "f")), "f");
|
|
}
|
|
/**
|
|
* Cancel the idle countdown and any pending arm. Blockers persist — they
|
|
* track real outstanding work, retired only by {@link unblock}.
|
|
*/
|
|
disarm() {
|
|
__classPrivateFieldSet2(this, _IdleClock_armPending, false, "f");
|
|
if (__classPrivateFieldGet2(this, _IdleClock_timer, "f") !== void 0) {
|
|
clearTimeout(__classPrivateFieldGet2(this, _IdleClock_timer, "f"));
|
|
__classPrivateFieldSet2(this, _IdleClock_timer, void 0, "f");
|
|
}
|
|
}
|
|
}
|
|
_IdleClock_maxIdleMs = /* @__PURE__ */ new WeakMap(), _IdleClock_onExpire = /* @__PURE__ */ new WeakMap(), _IdleClock_blockers = /* @__PURE__ */ new WeakMap(), _IdleClock_armPending = /* @__PURE__ */ new WeakMap(), _IdleClock_timer = /* @__PURE__ */ new WeakMap();
|
|
return IdleClock2;
|
|
})();
|
|
SessionToolRunner = /* @__PURE__ */ (() => {
|
|
class SessionToolRunner2 {
|
|
constructor(sessionId, opts) {
|
|
_SessionToolRunner_instances.add(this);
|
|
_SessionToolRunner_consumed.set(this, false);
|
|
_SessionToolRunner_controller.set(this, void 0);
|
|
_SessionToolRunner_detachExternal.set(this, void 0);
|
|
_SessionToolRunner_requestOpts.set(this, void 0);
|
|
_SessionToolRunner_toolByName.set(this, void 0);
|
|
_SessionToolRunner_logger.set(this, void 0);
|
|
_SessionToolRunner_seen.set(this, /* @__PURE__ */ new Set());
|
|
_SessionToolRunner_answered.set(this, /* @__PURE__ */ new Set());
|
|
_SessionToolRunner_confirmationVerdicts.set(this, /* @__PURE__ */ new Map());
|
|
_SessionToolRunner_awaitingConfirmation.set(this, /* @__PURE__ */ new Map());
|
|
_SessionToolRunner_results.set(this, new AsyncQueue());
|
|
_SessionToolRunner_inFlightCount.set(this, 0);
|
|
_SessionToolRunner_sendRetryWindowMs.set(this, SEND_RETRY_WINDOW_MS);
|
|
_SessionToolRunner_onIdle.set(this, null);
|
|
_SessionToolRunner_idleClock.set(this, void 0);
|
|
this.client = opts.client;
|
|
this.sessionId = sessionId;
|
|
this.tools = opts.tools;
|
|
this.maxIdleMs = opts.maxIdleMs ?? DEFAULT_MAX_IDLE_MS;
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_logger, loggerFor2(opts.client), "f");
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_toolByName, new Map(opts.tools.map((t) => [toolName(t), t])), "f");
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_controller, new AbortController(), "f");
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_detachExternal, linkAbort(opts.signal, __classPrivateFieldGet2(this, _SessionToolRunner_controller, "f")), "f");
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_requestOpts, opts.requestOptions, "f");
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_idleClock, new IdleClock(this.maxIdleMs, () => {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("session idle after end_turn; stopping", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId,
|
|
max_idle_ms: this.maxIdleMs
|
|
});
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").abort();
|
|
}), "f");
|
|
}
|
|
/** Read-only view of this runner's abort signal. */
|
|
get signal() {
|
|
return __classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").signal;
|
|
}
|
|
/** Abort the runner. Background tasks will wind down and `for await` will exit cleanly. */
|
|
abort() {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").abort();
|
|
}
|
|
/**
|
|
* @internal
|
|
* `EnvironmentWorker` keeps this equal to the lease TTL each heartbeat
|
|
* reports; applies to a send already retrying.
|
|
*/
|
|
_setSendRetryWindow(ms) {
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_sendRetryWindowMs, ms, "f");
|
|
}
|
|
async *[(_SessionToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_controller = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_detachExternal = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_requestOpts = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_toolByName = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_logger = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_seen = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_answered = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_confirmationVerdicts = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_awaitingConfirmation = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_results = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_inFlightCount = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_sendRetryWindowMs = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_onIdle = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_idleClock = /* @__PURE__ */ new WeakMap(), _SessionToolRunner_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
if (__classPrivateFieldGet2(this, _SessionToolRunner_consumed, "f")) {
|
|
throw new AnthropicError("Cannot iterate over a consumed SessionToolRunner");
|
|
}
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_consumed, true, "f");
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("session tool runner starting", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId
|
|
});
|
|
const streamPromise = __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_streamLoop).call(this).catch((e) => {
|
|
if (!__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").signal.aborted) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").error("stream loop failed", { error: String(e) });
|
|
}
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").abort();
|
|
});
|
|
try {
|
|
while (true) {
|
|
const next = await __classPrivateFieldGet2(this, _SessionToolRunner_results, "f").next(__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").signal);
|
|
if (next.done)
|
|
break;
|
|
yield next.value;
|
|
}
|
|
await streamPromise;
|
|
let pending;
|
|
while ((pending = __classPrivateFieldGet2(this, _SessionToolRunner_results, "f").tryShift()) !== void 0) {
|
|
yield pending;
|
|
}
|
|
} finally {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").abort();
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").disarm();
|
|
await streamPromise;
|
|
try {
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_drain).call(this);
|
|
} catch (e) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").warn("drain failed", { error: String(e) });
|
|
}
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_results, "f").close();
|
|
for (const t of this.tools) {
|
|
try {
|
|
await t.close?.();
|
|
} catch (e) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").warn("tool.close failed", { tool: toolName(t), error: String(e) });
|
|
}
|
|
}
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_detachExternal, "f").call(this);
|
|
}
|
|
}
|
|
}
|
|
_SessionToolRunner_requestOptions = function _SessionToolRunner_requestOptions2() {
|
|
return {
|
|
...__classPrivateFieldGet2(this, _SessionToolRunner_requestOpts, "f"),
|
|
headers: buildHeaders2([helperHeader("session-tool-runner"), __classPrivateFieldGet2(this, _SessionToolRunner_requestOpts, "f")?.headers]),
|
|
signal: __classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").signal
|
|
};
|
|
}, _SessionToolRunner_streamLoop = // ===== event stream =====
|
|
async function _SessionToolRunner_streamLoop2() {
|
|
const ctrl = __classPrivateFieldGet2(this, _SessionToolRunner_controller, "f");
|
|
let backoff3 = STREAM_BACKOFF_START_MS;
|
|
while (!ctrl.signal.aborted) {
|
|
try {
|
|
const stream4 = await this.client.beta.sessions.events.stream(this.sessionId, {}, __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this));
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_reconcile).call(this);
|
|
for await (const ev of stream4) {
|
|
backoff3 = STREAM_BACKOFF_START_MS;
|
|
if (await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_handleStreamEvent).call(this, ev))
|
|
return;
|
|
}
|
|
} catch (e) {
|
|
ctrl.signal.throwIfAborted();
|
|
if (isFatal4xx(e)) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").error("permanent stream failure, shutting down", { error: String(e) });
|
|
ctrl.abort();
|
|
throw e;
|
|
}
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").warn("stream disconnected, reconnecting", {
|
|
error: String(e),
|
|
backoff_ms: backoff3
|
|
});
|
|
}
|
|
ctrl.signal.throwIfAborted();
|
|
await sleep2(backoff3, ctrl.signal);
|
|
backoff3 = Math.min(backoff3 * 2, STREAM_BACKOFF_CAP_MS);
|
|
}
|
|
}, _SessionToolRunner_reconcile = /**
|
|
* Read full history before dispatching so a `tool_use` whose result appears
|
|
* later in the same history is not re-executed. Runs after the live stream is
|
|
* already attached (see {@link SessionToolRunner.#streamLoop}).
|
|
*/
|
|
async function _SessionToolRunner_reconcile2() {
|
|
const ctrl = __classPrivateFieldGet2(this, _SessionToolRunner_controller, "f");
|
|
const pending = [];
|
|
let lastWasEndTurn = false;
|
|
try {
|
|
for await (const ev of this.client.beta.sessions.events.list(this.sessionId, { limit: 1e3 }, __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this))) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_ingestHistory).call(this, ev, pending);
|
|
lastWasEndTurn = isEndTurnIdle(ev);
|
|
}
|
|
} catch (e) {
|
|
ctrl.signal.throwIfAborted();
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").warn("reconcile list failed", { error: String(e) });
|
|
for (const ev of pending)
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_seen, "f").delete(ev.id);
|
|
return;
|
|
}
|
|
const unanswered = pending.filter((ev) => !__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").has(ev.id));
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").disarm();
|
|
for (const ev of unanswered)
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_routeToolEvent).call(this, ev);
|
|
for (const held of [...__classPrivateFieldGet2(this, _SessionToolRunner_awaitingConfirmation, "f").values()]) {
|
|
const verdict = __classPrivateFieldGet2(this, _SessionToolRunner_confirmationVerdicts, "f").get(held.id);
|
|
if (verdict !== void 0)
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, held, verdict);
|
|
}
|
|
const outstanding = unanswered.filter((ev) => !__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").has(ev.id) && !__classPrivateFieldGet2(this, _SessionToolRunner_awaitingConfirmation, "f").has(ev.id));
|
|
if (lastWasEndTurn && outstanding.length === 0)
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").arm();
|
|
else
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").disarm();
|
|
}, _SessionToolRunner_ingestHistory = function _SessionToolRunner_ingestHistory2(ev, pending) {
|
|
if (ev.type === "agent.tool_use" || ev.type === "agent.custom_tool_use") {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_seen, "f").add(ev.id);
|
|
if (!__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").has(ev.id))
|
|
pending.push(ev);
|
|
} else if (ev.type === "user.tool_result") {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").add(ev.tool_use_id);
|
|
} else if (ev.type === "user.custom_tool_result") {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").add(ev.custom_tool_use_id);
|
|
} else if (ev.type === "user.tool_confirmation") {
|
|
if (!__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").has(ev.tool_use_id))
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_confirmationVerdicts, "f").set(ev.tool_use_id, ev.result);
|
|
}
|
|
}, _SessionToolRunner_handleStreamEvent = /** Returns true when the runner should exit. */
|
|
async function _SessionToolRunner_handleStreamEvent2(ev) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").noteEvent(ev);
|
|
switch (ev.type) {
|
|
case "agent.tool_use":
|
|
case "agent.custom_tool_use":
|
|
if (!__classPrivateFieldGet2(this, _SessionToolRunner_seen, "f").has(ev.id)) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_seen, "f").add(ev.id);
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_routeToolEvent).call(this, ev);
|
|
}
|
|
return false;
|
|
case "user.tool_confirmation":
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_noteConfirmation).call(this, ev);
|
|
return false;
|
|
case "user.tool_result":
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").add(ev.tool_use_id);
|
|
return false;
|
|
case "user.custom_tool_result":
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").add(ev.custom_tool_use_id);
|
|
return false;
|
|
case "session.status_terminated":
|
|
case "session.deleted":
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("session terminated", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId
|
|
});
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").abort();
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}, _SessionToolRunner_routeToolEvent = // ===== confirmation gating (always_ask tools) =====
|
|
/**
|
|
* Dispatch `ev`, honoring its evaluated permission. A call the server gated
|
|
* (`evaluated_permission == "ask"`) is held until its `user.tool_confirmation`
|
|
* arrives. Fails closed: only an explicit `allow` verdict releases a gated
|
|
* call; a server-side `deny` overrides any recorded verdict; an unrecognized
|
|
* permission is held like `ask` and an unrecognized verdict is denied.
|
|
*/
|
|
async function _SessionToolRunner_routeToolEvent2(ev) {
|
|
const permission = ev.evaluated_permission;
|
|
const verdict = permission === "deny" ? "deny" : __classPrivateFieldGet2(this, _SessionToolRunner_confirmationVerdicts, "f").get(ev.id);
|
|
if (verdict === void 0) {
|
|
if (permission === void 0 || permission === "allow") {
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_execute).call(this, ev, void 0);
|
|
} else if (!__classPrivateFieldGet2(this, _SessionToolRunner_awaitingConfirmation, "f").has(ev.id)) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("tool call awaiting confirmation; holding", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId,
|
|
tool: ev.name,
|
|
tool_use_id: ev.id
|
|
});
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_awaitingConfirmation, "f").set(ev.id, ev);
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").block(ev.id);
|
|
}
|
|
return;
|
|
}
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, ev, verdict);
|
|
}, _SessionToolRunner_noteConfirmation = /** Record an allow/deny verdict and release the held call it gates, if any. */
|
|
async function _SessionToolRunner_noteConfirmation2(ev) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_confirmationVerdicts, "f").set(ev.tool_use_id, ev.result);
|
|
const held = __classPrivateFieldGet2(this, _SessionToolRunner_awaitingConfirmation, "f").get(ev.tool_use_id);
|
|
if (held === void 0)
|
|
return;
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_applyVerdict).call(this, held, ev.result);
|
|
}, _SessionToolRunner_applyVerdict = /**
|
|
* Dispatch or resolve a gated call according to its verdict.
|
|
*
|
|
* The idle-clock blocker accounting lives here: a denial retires the held
|
|
* call's blocker, while an allow keeps one on the call — taking it now if the
|
|
* verdict was already known when the call was routed, so it was never held —
|
|
* until `#execute` has finished with it. The countdown must not run over
|
|
* gated work that is still in flight.
|
|
*/
|
|
async function _SessionToolRunner_applyVerdict2(ev, verdict) {
|
|
const wasHeld = __classPrivateFieldGet2(this, _SessionToolRunner_awaitingConfirmation, "f").delete(ev.id);
|
|
if (verdict === "allow") {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("tool call confirmed", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId,
|
|
tool: ev.name,
|
|
tool_use_id: ev.id
|
|
});
|
|
if (!wasHeld)
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").block(ev.id);
|
|
try {
|
|
await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_execute).call(this, ev, "allow");
|
|
} finally {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").unblock(ev.id);
|
|
}
|
|
return;
|
|
}
|
|
if (wasHeld)
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_idleClock, "f").unblock(ev.id);
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").add(ev.id);
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("tool call denied; not executing", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId,
|
|
tool: ev.name,
|
|
tool_use_id: ev.id
|
|
});
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, {
|
|
event: ev,
|
|
toolUseId: ev.id,
|
|
name: ev.name,
|
|
isError: false,
|
|
posted: false,
|
|
confirmation: "deny"
|
|
});
|
|
}, _SessionToolRunner_surfaceCall = function _SessionToolRunner_surfaceCall2(call) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_results, "f").push(call);
|
|
}, _SessionToolRunner_execute = // ===== tool execution =====
|
|
async function _SessionToolRunner_execute2(ev, confirmation) {
|
|
var _a6, _b;
|
|
if (__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").has(ev.id))
|
|
return;
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("executing tool", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId,
|
|
tool: ev.name,
|
|
tool_use_id: ev.id
|
|
});
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_inFlightCount, (_a6 = __classPrivateFieldGet2(this, _SessionToolRunner_inFlightCount, "f"), _a6++, _a6), "f");
|
|
try {
|
|
const tool = __classPrivateFieldGet2(this, _SessionToolRunner_toolByName, "f").get(ev.name);
|
|
if (!tool) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").info("tool not owned by this runner; leaving the tool_use_id pending for its owner", {
|
|
component: "session-tool-runner",
|
|
session_id: this.sessionId,
|
|
tool: ev.name,
|
|
tool_use_id: ev.id
|
|
});
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, {
|
|
event: ev,
|
|
toolUseId: ev.id,
|
|
name: ev.name,
|
|
isError: false,
|
|
posted: false,
|
|
confirmation
|
|
});
|
|
return;
|
|
}
|
|
let content;
|
|
let isError;
|
|
const toolCtrl = new AbortController();
|
|
const detachTool = linkAbort(__classPrivateFieldGet2(this, _SessionToolRunner_controller, "f").signal, toolCtrl);
|
|
const timer = setTimeout(() => toolCtrl.abort(), TOOL_TIMEOUT_MS);
|
|
try {
|
|
const outcome = await runRunnableTool(tool, ev.input, {
|
|
toolUse: ev,
|
|
toolUseBlock: ev,
|
|
signal: toolCtrl.signal
|
|
});
|
|
content = outcome.content;
|
|
isError = outcome.isError;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
detachTool();
|
|
}
|
|
const result = buildResultEvent(ev, isError, toSessionContent(content));
|
|
const posted = await __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_sendResult).call(this, result, ev.id);
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_surfaceCall).call(this, {
|
|
event: ev,
|
|
result,
|
|
toolUseId: ev.id,
|
|
name: ev.name,
|
|
isError,
|
|
posted,
|
|
confirmation
|
|
});
|
|
} finally {
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_inFlightCount, (_b = __classPrivateFieldGet2(this, _SessionToolRunner_inFlightCount, "f"), _b--, _b), "f");
|
|
if (__classPrivateFieldGet2(this, _SessionToolRunner_inFlightCount, "f") === 0)
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_onIdle, "f")?.call(this);
|
|
}
|
|
}, _SessionToolRunner_sendResult = async function _SessionToolRunner_sendResult2(result, toolUseId) {
|
|
const ctrl = __classPrivateFieldGet2(this, _SessionToolRunner_controller, "f");
|
|
const start = Date.now();
|
|
let lastErr;
|
|
let attempt = 0;
|
|
while (true) {
|
|
attempt++;
|
|
ctrl.signal.throwIfAborted();
|
|
try {
|
|
await this.client.beta.sessions.events.send(this.sessionId, { events: [result] }, __classPrivateFieldGet2(this, _SessionToolRunner_instances, "m", _SessionToolRunner_requestOptions).call(this));
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_answered, "f").add(toolUseId);
|
|
return true;
|
|
} catch (e) {
|
|
lastErr = e;
|
|
if (isFatal4xx(e))
|
|
break;
|
|
const remainingMs = __classPrivateFieldGet2(this, _SessionToolRunner_sendRetryWindowMs, "f") - (Date.now() - start);
|
|
if (remainingMs <= 0)
|
|
break;
|
|
const waitMs = Math.min(applyJitter(backoff(attempt - 1, SEND_BACKOFF_START_MS, SEND_BACKOFF_CAP_MS)), remainingMs);
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").warn("tool result send failed; retrying", {
|
|
tool_use_id: toolUseId,
|
|
attempt,
|
|
backoff_ms: waitMs,
|
|
error: String(e)
|
|
});
|
|
await sleep2(waitMs, ctrl.signal);
|
|
}
|
|
}
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").error("failed to send tool result", {
|
|
tool_use_id: toolUseId,
|
|
attempts: attempt,
|
|
error: String(lastErr)
|
|
});
|
|
return false;
|
|
}, _SessionToolRunner_drain = /** Wait (bounded) for in-flight tool executions to finish during teardown. */
|
|
async function _SessionToolRunner_drain2() {
|
|
if (__classPrivateFieldGet2(this, _SessionToolRunner_inFlightCount, "f") === 0)
|
|
return;
|
|
await Promise.race([new Promise((r) => __classPrivateFieldSet2(this, _SessionToolRunner_onIdle, r, "f")), sleep2(DRAIN_TIMEOUT_MS)]);
|
|
__classPrivateFieldSet2(this, _SessionToolRunner_onIdle, null, "f");
|
|
if (__classPrivateFieldGet2(this, _SessionToolRunner_inFlightCount, "f") > 0) {
|
|
__classPrivateFieldGet2(this, _SessionToolRunner_logger, "f").warn("drain timeout exceeded");
|
|
}
|
|
};
|
|
return SessionToolRunner2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/tools/agent-toolset/sync-interval.mjs
|
|
function checkMemorySyncInterval(ms, option) {
|
|
if (!(ms >= MIN_MEMORY_SYNC_INTERVAL_MS)) {
|
|
throw new AnthropicError(`${option} must be at least ${MIN_MEMORY_SYNC_INTERVAL_MS}ms (got ${ms}); to run without memory sync, pass \`memorySyncIntervalMs: null\` to the worker instead`);
|
|
}
|
|
}
|
|
var DEFAULT_MEMORY_SYNC_INTERVAL_MS, MIN_MEMORY_SYNC_INTERVAL_MS;
|
|
var init_sync_interval = __esm({
|
|
"node_modules/@anthropic-ai/sdk/tools/agent-toolset/sync-interval.mjs"() {
|
|
init_error3();
|
|
DEFAULT_MEMORY_SYNC_INTERVAL_MS = 15e3;
|
|
MIN_MEMORY_SYNC_INTERVAL_MS = 5e3;
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/tools/agent-toolset/node.browser.mjs
|
|
var node_browser_exports2 = {};
|
|
__export(node_browser_exports2, {
|
|
BashSession: () => BashSession,
|
|
BashTimeoutError: () => BashTimeoutError,
|
|
DEFAULT_MEMORY_SYNC_INTERVAL_MS: () => DEFAULT_MEMORY_SYNC_INTERVAL_MS,
|
|
MARKER_PATH: () => MARKER_PATH,
|
|
MEMORY_FLUSH_TIMEOUT_MS: () => MEMORY_FLUSH_TIMEOUT_MS,
|
|
MIN_MEMORY_SYNC_INTERVAL_MS: () => MIN_MEMORY_SYNC_INTERVAL_MS,
|
|
SessionMemoryError: () => SessionMemoryError,
|
|
SessionMemoryStores: () => SessionMemoryStores,
|
|
betaAgentToolset20260401: () => betaAgentToolset20260401,
|
|
betaBashTool: () => betaBashTool,
|
|
betaEditTool: () => betaEditTool,
|
|
betaGlobTool: () => betaGlobTool,
|
|
betaGrepTool: () => betaGrepTool,
|
|
betaReadTool: () => betaReadTool,
|
|
betaWriteTool: () => betaWriteTool,
|
|
extractSkillArchive: () => extractSkillArchive,
|
|
resolvePath: () => resolvePath,
|
|
setupSkills: () => setupSkills
|
|
});
|
|
function nodeOnly(name) {
|
|
throw new AnthropicError(`${name} requires Node.js or a Node-compatible runtime`);
|
|
}
|
|
function setupSkills(_ctx) {
|
|
return nodeOnly("setupSkills");
|
|
}
|
|
function extractSkillArchive(_resp, _dest) {
|
|
return nodeOnly("extractSkillArchive");
|
|
}
|
|
function betaAgentToolset20260401(_ctx) {
|
|
return nodeOnly("betaAgentToolset20260401");
|
|
}
|
|
function resolvePath(_ctx, _p) {
|
|
return nodeOnly("resolvePath");
|
|
}
|
|
function betaBashTool(_ctx) {
|
|
return nodeOnly("betaBashTool");
|
|
}
|
|
function betaReadTool(_ctx) {
|
|
return nodeOnly("betaReadTool");
|
|
}
|
|
function betaWriteTool(_ctx) {
|
|
return nodeOnly("betaWriteTool");
|
|
}
|
|
function betaEditTool(_ctx) {
|
|
return nodeOnly("betaEditTool");
|
|
}
|
|
function betaGlobTool(_ctx) {
|
|
return nodeOnly("betaGlobTool");
|
|
}
|
|
function betaGrepTool(_ctx) {
|
|
return nodeOnly("betaGrepTool");
|
|
}
|
|
var MEMORY_FLUSH_TIMEOUT_MS, MARKER_PATH, SessionMemoryError, SessionMemoryStores, BashTimeoutError, BashSession;
|
|
var init_node_browser2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/tools/agent-toolset/node.browser.mjs"() {
|
|
init_error3();
|
|
init_sync_interval();
|
|
MEMORY_FLUSH_TIMEOUT_MS = 3e4;
|
|
MARKER_PATH = ".anthropic-memory-store";
|
|
SessionMemoryError = class extends AnthropicError {
|
|
constructor(message, cause) {
|
|
super(message);
|
|
this.name = "SessionMemoryError";
|
|
if (cause !== void 0)
|
|
this.cause = cause;
|
|
}
|
|
};
|
|
SessionMemoryStores = class {
|
|
constructor(_client, _opts) {
|
|
nodeOnly("SessionMemoryStores");
|
|
}
|
|
get roots() {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
get readOnlyRoots() {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
download(_session) {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
finish() {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
/** @internal */
|
|
syncAll(_final) {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
syncIfDue() {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
flushWrites(_signal) {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
dispose() {
|
|
return nodeOnly("SessionMemoryStores");
|
|
}
|
|
};
|
|
BashTimeoutError = class extends AnthropicError {
|
|
constructor(timeoutMs) {
|
|
super(`bash command timed out after ${timeoutMs}ms`);
|
|
this.name = "BashTimeoutError";
|
|
this.timeoutMs = timeoutMs;
|
|
}
|
|
};
|
|
BashSession = class {
|
|
constructor(_dir, _env) {
|
|
nodeOnly("BashSession");
|
|
}
|
|
get closed() {
|
|
return nodeOnly("BashSession");
|
|
}
|
|
exec(_command, _opts = {}) {
|
|
return nodeOnly("BashSession");
|
|
}
|
|
close() {
|
|
nodeOnly("BashSession");
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/environments/worker.mjs
|
|
function hasMemoryStore(session) {
|
|
return session.resources.some((r) => r.type === "memory_store");
|
|
}
|
|
function sessionsTokenFromSecret(secret) {
|
|
if (!secret)
|
|
return null;
|
|
let parsed;
|
|
try {
|
|
const normalized = secret.replace(/-/g, "+").replace(/_/g, "/");
|
|
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
|
|
parsed = JSON.parse(decodeUTF82(fromBase642(padded)));
|
|
} catch {
|
|
return null;
|
|
}
|
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
return null;
|
|
const token = parsed.sessions_token;
|
|
return typeof token === "string" && token !== "" ? token : null;
|
|
}
|
|
async function withTimeout(p, ms) {
|
|
let timer;
|
|
try {
|
|
return await Promise.race([
|
|
p.then(() => false, () => false),
|
|
new Promise((resolve) => {
|
|
timer = setTimeout(() => resolve(true), ms);
|
|
})
|
|
]);
|
|
} finally {
|
|
if (timer !== void 0)
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
async function forceStop(client, work, log, requestOptions) {
|
|
try {
|
|
await client.beta.environments.work.stop(
|
|
work.id,
|
|
{ environment_id: work.environment_id, force: true },
|
|
// Caller's headers pass through; the helper-tag header is on the scoped
|
|
// sub-client's default_headers via copyClientForHelper, so no per-call
|
|
// re-stamping needed.
|
|
{ ...requestOptions, headers: buildHeaders2([requestOptions?.headers]) }
|
|
);
|
|
} catch (e) {
|
|
if (!isStatus(e, 409)) {
|
|
log.error("force-stop on exit failed", { work_id: work.id, error: String(e) });
|
|
}
|
|
}
|
|
}
|
|
function serverLeaseState(e) {
|
|
let node = e instanceof APIError2 ? e.error : void 0;
|
|
for (const key of ["error", "details", "current_state"]) {
|
|
if (!isObj2(node))
|
|
return {};
|
|
node = node[key];
|
|
}
|
|
return isObj2(node) ? node : {};
|
|
}
|
|
async function heartbeatLoop(client, work, lease, logger, requestOptions, onLeaseTtl) {
|
|
let intervalMs = HEARTBEAT_DEFAULT_MS;
|
|
let ttlMs = HEARTBEAT_TTL_DEFAULT_MS;
|
|
let lastSuccessMs = Date.now();
|
|
let last = NO_HEARTBEAT_SENTINEL;
|
|
const beat = async () => {
|
|
const beatCtrl = new AbortController();
|
|
const detach = linkAbort(lease.signal, beatCtrl);
|
|
const cutoff = setTimeout(() => beatCtrl.abort(), intervalMs);
|
|
try {
|
|
const resp = await client.beta.environments.work.heartbeat(work.id, { environment_id: work.environment_id, expected_last_heartbeat: last }, { ...requestOptions, headers: buildHeaders2([requestOptions?.headers]), signal: beatCtrl.signal });
|
|
lastSuccessMs = Date.now();
|
|
last = resp.last_heartbeat;
|
|
if (resp.ttl_seconds > 0) {
|
|
ttlMs = resp.ttl_seconds * 1e3;
|
|
intervalMs = Math.max(1e3, Math.min(ttlMs / 2, HEARTBEAT_DEFAULT_MS));
|
|
onLeaseTtl?.(ttlMs);
|
|
}
|
|
if (resp.state === "stopping" || resp.state === "stopped") {
|
|
logger.info("heartbeat signals shutdown", { work_id: work.id, state: resp.state });
|
|
lease.finish("control_plane_stop");
|
|
}
|
|
if (!resp.lease_extended) {
|
|
logger.warn("lease not extended, shutting down", { work_id: work.id });
|
|
lease.finish("control_plane_stop");
|
|
}
|
|
} catch (e) {
|
|
lease.signal.throwIfAborted();
|
|
if (isStatus(e, 412)) {
|
|
const server = serverLeaseState(e);
|
|
logger.error("lease lost: heartbeat precondition failed", {
|
|
work_id: work.id,
|
|
server_state: server["state"],
|
|
server_ttl_seconds: server["ttl_seconds"],
|
|
server_last_heartbeat: server["last_heartbeat"]
|
|
});
|
|
lease.finish("lease_lost");
|
|
return;
|
|
}
|
|
if (isFatal4xx(e)) {
|
|
logger.error("permanent heartbeat failure", { work_id: work.id, error: String(e) });
|
|
lease.finish("heartbeat_rejected");
|
|
throw e;
|
|
}
|
|
if (Date.now() - lastSuccessMs > ttlMs) {
|
|
logger.error("lease assumed lost: no successful heartbeat in ttl", {
|
|
work_id: work.id,
|
|
ttl_ms: ttlMs,
|
|
error: String(e)
|
|
});
|
|
lease.finish("assumed_lost");
|
|
return;
|
|
}
|
|
logger.warn("transient heartbeat failure", { work_id: work.id, error: String(e) });
|
|
} finally {
|
|
clearTimeout(cutoff);
|
|
detach();
|
|
}
|
|
};
|
|
await beat();
|
|
while (!lease.signal.aborted) {
|
|
await sleep2(intervalMs, lease.signal);
|
|
lease.signal.throwIfAborted();
|
|
await beat();
|
|
}
|
|
}
|
|
var _EnvironmentWorker_instances, _EnvironmentWorker_signal, _EnvironmentWorker_handleItem, _Lease_ctrl, _Lease_endReason, HEARTBEAT_DEFAULT_MS, HEARTBEAT_TTL_DEFAULT_MS, NO_HEARTBEAT_SENTINEL, EnvironmentWorker, Lease;
|
|
var init_worker = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/environments/worker.mjs"() {
|
|
init_tslib2();
|
|
init_error3();
|
|
init_log2();
|
|
init_base642();
|
|
init_bytes2();
|
|
init_env2();
|
|
init_sleep2();
|
|
init_backoff();
|
|
init_abort3();
|
|
init_values2();
|
|
init_headers3();
|
|
init_SessionToolRunner();
|
|
init_poller();
|
|
init_helper_client();
|
|
init_sync_interval();
|
|
HEARTBEAT_DEFAULT_MS = 3e4;
|
|
HEARTBEAT_TTL_DEFAULT_MS = 9e4;
|
|
NO_HEARTBEAT_SENTINEL = "NO_HEARTBEAT";
|
|
EnvironmentWorker = /* @__PURE__ */ (() => {
|
|
class EnvironmentWorker2 {
|
|
constructor(opts) {
|
|
_EnvironmentWorker_instances.add(this);
|
|
_EnvironmentWorker_signal.set(this, void 0);
|
|
if (opts.unrestrictedPaths !== void 0) {
|
|
throw new AnthropicError("The `unrestrictedPaths` option you passed to EnvironmentWorker (or client.beta.environments.work.worker()) is no longer supported. The worker's file tools (read, write, edit, glob, grep) are now always confined to `workdir` plus the session's memory folders. Remove `unrestrictedPaths` from your options; to let the file tools reach any other directory, add it to `AgentToolContext.allowedRoots` from a `tools` factory.");
|
|
}
|
|
this.client = opts.client;
|
|
this.environmentId = opts.environmentId;
|
|
this.environmentKey = opts.environmentKey;
|
|
this.tools = opts.tools;
|
|
this.workdir = opts.workdir ?? process.cwd();
|
|
this.maxFileBytes = opts.maxFileBytes;
|
|
this.maxIdleMs = opts.maxIdleMs;
|
|
if (opts.memorySyncIntervalMs != null) {
|
|
checkMemorySyncInterval(opts.memorySyncIntervalMs, "memorySyncIntervalMs");
|
|
}
|
|
this.memorySyncIntervalMs = opts.memorySyncIntervalMs;
|
|
this.memorySyncDeletions = opts.memorySyncDeletions ?? "enabled";
|
|
this.workerId = opts.workerId;
|
|
this.requestOptions = opts.requestOptions;
|
|
__classPrivateFieldSet2(this, _EnvironmentWorker_signal, opts.signal, "f");
|
|
}
|
|
/**
|
|
* Poll the environment and service each claimed session until the supplied
|
|
* signal (or the one passed to the constructor) aborts. Throws if
|
|
* `environmentId` / `environmentKey` were not provided to the constructor.
|
|
*/
|
|
async run(signal) {
|
|
const { environmentId, environmentKey } = this;
|
|
if (environmentId === void 0 || environmentKey === void 0) {
|
|
throw new AnthropicError("EnvironmentWorker.run: environmentId and environmentKey are required to poll for work");
|
|
}
|
|
const externalSignal = signal ?? __classPrivateFieldGet2(this, _EnvironmentWorker_signal, "f");
|
|
const poller = new WorkPoller({
|
|
client: this.client,
|
|
environmentId,
|
|
environmentKey,
|
|
...this.workerId !== void 0 ? { workerId: this.workerId } : {},
|
|
...externalSignal ? { signal: externalSignal } : {},
|
|
...this.requestOptions !== void 0 ? { requestOptions: this.requestOptions } : {},
|
|
// The per-item handler stops or releases every work item on exit; let it
|
|
// be the single owner of `work.stop` rather than double-posting from the
|
|
// poller.
|
|
autoStop: false
|
|
});
|
|
for await (const work of poller) {
|
|
try {
|
|
await __classPrivateFieldGet2(this, _EnvironmentWorker_instances, "m", _EnvironmentWorker_handleItem).call(this, work, environmentKey, poller.signal);
|
|
} catch (e) {
|
|
if (poller.signal?.aborted)
|
|
throw e;
|
|
loggerFor2(this.client).error("work item failed", { work_id: work.id, error: String(e) });
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* Service a single, already-claimed work item without the poll loop: build the
|
|
* per-session {@link AgentToolContext} (workdir from this worker's options),
|
|
* download the session agent's skills (`setupSkills`), run a
|
|
* {@link SessionToolRunner} for the session while heartbeating the work-item
|
|
* lease, and force-stop the work item on exit (whether the runner finishes
|
|
* normally, throws, or the control plane signals shutdown). The one
|
|
* exception is a lost lease: the item then belongs to the queue or another
|
|
* worker and is left alone.
|
|
*
|
|
* Use this when something else does the claiming — e.g. a `worker poll
|
|
* --on-work` script that hands an already-claimed item to a fresh process. The
|
|
* work id / environment id / session id each fall back to `ANTHROPIC_WORK_ID` /
|
|
* `ANTHROPIC_ENVIRONMENT_ID` / `ANTHROPIC_SESSION_ID` (the env vars that
|
|
* command sets) when not passed; the environment key resolves from this
|
|
* option, then the worker's own `environmentKey`, then
|
|
* `ANTHROPIC_ENVIRONMENT_KEY`, and is needed only when the work item's
|
|
* `secret` yields no sessions token — a host that receives only the
|
|
* per-item secret runs without ever holding the key. With no arguments
|
|
* inside that command it just works. Throws a clear error naming the first
|
|
* required value still missing after resolution, and — rather than ever
|
|
* running unauthenticated — when neither a sessions token nor an
|
|
* environment key resolved. Throws `SessionMemoryError` when the
|
|
* session has memory stores attached but they cannot be mounted — the work
|
|
* item carried no sessions token (unless `memorySyncIntervalMs` turned
|
|
* memory off), or a store failed to download.
|
|
*
|
|
* `workSecret` is the work item's per-item `secret` payload from the poll
|
|
* response, falling back to `ANTHROPIC_WORK_SECRET`; unlike the others it is
|
|
* optional — when present, the sessions token extracted from it is preferred
|
|
* as the Bearer credential for this item's heartbeat / force-stop / session
|
|
* calls; when absent (or undecodable) those calls use the environment key.
|
|
*/
|
|
async handleItem(opts) {
|
|
const workId = opts?.workId ?? readEnv2("ANTHROPIC_WORK_ID");
|
|
const environmentId = opts?.environmentId ?? readEnv2("ANTHROPIC_ENVIRONMENT_ID");
|
|
const sessionId = opts?.sessionId ?? readEnv2("ANTHROPIC_SESSION_ID");
|
|
const environmentKey = (opts?.environmentKey ?? this.environmentKey ?? readEnv2("ANTHROPIC_ENVIRONMENT_KEY")) || void 0;
|
|
const workSecret = opts?.workSecret || readEnv2("ANTHROPIC_WORK_SECRET") || null;
|
|
if (!workId) {
|
|
throw new AnthropicError("handleItem: workId is required \u2014 pass it or set ANTHROPIC_WORK_ID");
|
|
}
|
|
if (!environmentId) {
|
|
throw new AnthropicError("handleItem: environmentId is required \u2014 pass it or set ANTHROPIC_ENVIRONMENT_ID");
|
|
}
|
|
if (!sessionId) {
|
|
throw new AnthropicError("handleItem: sessionId is required \u2014 pass it or set ANTHROPIC_SESSION_ID");
|
|
}
|
|
if (!environmentKey && !workSecret) {
|
|
throw new AnthropicError("handleItem: environmentKey is required when there is no work secret \u2014 pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY");
|
|
}
|
|
const work = {
|
|
id: workId,
|
|
environment_id: environmentId,
|
|
secret: workSecret,
|
|
data: { type: "session", id: sessionId }
|
|
};
|
|
await __classPrivateFieldGet2(this, _EnvironmentWorker_instances, "m", _EnvironmentWorker_handleItem).call(this, work, environmentKey, opts?.signal ?? __classPrivateFieldGet2(this, _EnvironmentWorker_signal, "f"));
|
|
}
|
|
}
|
|
_EnvironmentWorker_signal = /* @__PURE__ */ new WeakMap(), _EnvironmentWorker_instances = /* @__PURE__ */ new WeakSet(), _EnvironmentWorker_handleItem = /**
|
|
* The per-item body shared by {@link EnvironmentWorker.run}'s poll loop and
|
|
* {@link EnvironmentWorker.handleItem}: run a {@link SessionToolRunner} for the
|
|
* work item's session while heartbeating its lease, force-stopping on exit
|
|
* unless the lease was lost. Non-session work items are ignored.
|
|
*
|
|
* When the poll response carried a per-item `secret` (a short-lived payload
|
|
* scoped to this work item), the sessions token extracted from it is
|
|
* preferred over `environmentKey` as the Bearer credential for those
|
|
* per-item calls; a missing/undecodable secret falls back to
|
|
* `environmentKey` unchanged.
|
|
*/
|
|
async function _EnvironmentWorker_handleItem2(work, environmentKey, externalSignal) {
|
|
const log = loggerFor2(this.client);
|
|
const sessionsToken = sessionsTokenFromSecret(work.secret);
|
|
const itemCredential = sessionsToken ?? environmentKey;
|
|
if (itemCredential === void 0) {
|
|
throw new AnthropicError("handleItem: the work item carried a secret payload but no sessions token could be extracted, and there is no environment key to fall back to; the poller must issue a secret whose payload carries `sessions_token`, or provide the environment key (pass it, construct the worker with it, or set ANTHROPIC_ENVIRONMENT_KEY)");
|
|
}
|
|
if (work.secret && sessionsToken === null) {
|
|
log.warn("work item carried a secret payload but no sessions token could be extracted; falling back to the environment key", { work_id: work.id });
|
|
}
|
|
const sessionClient = copyClientForHelper(this.client, {
|
|
authToken: itemCredential,
|
|
helper: "environments-worker"
|
|
});
|
|
const sessionId = work.data.id;
|
|
const ctrl = new AbortController();
|
|
const detachExternal = linkAbort(externalSignal, ctrl);
|
|
const lease = new Lease(ctrl);
|
|
const agentToolset = await Promise.resolve().then(() => (init_node_browser2(), node_browser_exports2));
|
|
let leaseTtlMs;
|
|
let runner;
|
|
const heartbeatPromise = heartbeatLoop(sessionClient, work, lease, log, this.requestOptions, (ttlMs) => {
|
|
leaseTtlMs = ttlMs;
|
|
runner?._setSendRetryWindow(ttlMs);
|
|
}).catch((e) => {
|
|
if (!ctrl.signal.aborted)
|
|
log.error("heartbeat loop failed", { work_id: work.id, error: String(e) });
|
|
ctrl.abort();
|
|
});
|
|
let cleanupSkills = async () => {
|
|
};
|
|
let stores;
|
|
let cleanEnd = false;
|
|
try {
|
|
if (work.data.type !== "session") {
|
|
log.debug("skipping non-session work item", { work_id: work.id, type: work.data.type });
|
|
return;
|
|
}
|
|
const session = await sessionClient.beta.sessions.retrieve(sessionId);
|
|
if (sessionsToken === null && this.memorySyncIntervalMs !== null && hasMemoryStore(session)) {
|
|
throw new agentToolset.SessionMemoryError(`cannot mount the session's memories: the work item carried no sessions token (work_id=${work.id}, session_id=${sessionId}); the memory endpoints reject the environment key, so the poller must issue a per-item \`secret\` carrying \`sessions_token\`, or set \`memorySyncIntervalMs: null\` to run without memory`);
|
|
}
|
|
const ctx = {
|
|
workdir: this.workdir,
|
|
// The scoped sub-client, not the parent: the skill download
|
|
// `setupSkills` performs for this session rides the same per-item
|
|
// credential as every other per-item call.
|
|
client: sessionClient,
|
|
session,
|
|
...this.maxFileBytes !== void 0 ? { maxFileBytes: this.maxFileBytes } : {}
|
|
};
|
|
try {
|
|
cleanupSkills = await agentToolset.setupSkills(ctx);
|
|
} catch (e) {
|
|
log.warn("skill setup failed", { session_id: sessionId, work_id: work.id, error: String(e) });
|
|
}
|
|
if (sessionsToken !== null && this.memorySyncIntervalMs !== null) {
|
|
stores = new agentToolset.SessionMemoryStores(sessionClient, {
|
|
workdir: this.workdir,
|
|
...this.memorySyncIntervalMs !== void 0 ? { syncIntervalMs: this.memorySyncIntervalMs } : {},
|
|
syncDeletions: this.memorySyncDeletions
|
|
});
|
|
await stores.download(session);
|
|
ctx.allowedRoots = stores.roots;
|
|
ctx.readOnlyRoots = stores.readOnlyRoots;
|
|
} else {
|
|
log.debug("memory stores disabled for this item", { work_id: work.id });
|
|
}
|
|
const tools = typeof this.tools === "function" ? this.tools(ctx) : this.tools ?? agentToolset.betaAgentToolset20260401(ctx);
|
|
runner = new SessionToolRunner(sessionId, {
|
|
client: sessionClient,
|
|
tools,
|
|
...this.maxIdleMs !== void 0 ? { maxIdleMs: this.maxIdleMs } : {},
|
|
...this.requestOptions !== void 0 ? { requestOptions: this.requestOptions } : {},
|
|
signal: ctrl.signal
|
|
});
|
|
if (leaseTtlMs !== void 0)
|
|
runner._setSendRetryWindow(leaseTtlMs);
|
|
for await (const _ of runner) {
|
|
if (stores)
|
|
await stores.syncIfDue();
|
|
}
|
|
cleanEnd = !ctrl.signal.aborted;
|
|
} finally {
|
|
try {
|
|
await cleanupSkills().catch((e) => {
|
|
log.warn("skill cleanup failed", { session_id: sessionId, work_id: work.id, error: String(e) });
|
|
});
|
|
} finally {
|
|
if (stores) {
|
|
const boundMs = agentToolset.MEMORY_FLUSH_TIMEOUT_MS;
|
|
if (cleanEnd) {
|
|
const finishCutOff = await withTimeout(stores.finish(), boundMs);
|
|
if (finishCutOff) {
|
|
log.warn(`final memory sync cut off after ${boundMs}ms; the flush that follows still uploads changed files`, { session_id: sessionId, work_id: work.id });
|
|
}
|
|
}
|
|
const flushBound = new AbortController();
|
|
const flushCutOff = await withTimeout(stores.flushWrites(flushBound.signal), boundMs);
|
|
if (flushCutOff) {
|
|
flushBound.abort();
|
|
log.warn(`memory flush cut off after ${boundMs}ms; changed files it had not uploaded yet are not saved`, { session_id: sessionId, work_id: work.id });
|
|
}
|
|
await stores.dispose().catch((e) => {
|
|
log.warn("memory store cleanup failed", {
|
|
session_id: sessionId,
|
|
work_id: work.id,
|
|
error: String(e)
|
|
});
|
|
});
|
|
}
|
|
}
|
|
lease.finish("runner_done");
|
|
detachExternal();
|
|
await heartbeatPromise;
|
|
if (lease.lost) {
|
|
log.info("lease lost; released without stopping it", { session_id: sessionId, work_id: work.id });
|
|
} else {
|
|
await forceStop(sessionClient, work, log, this.requestOptions);
|
|
}
|
|
}
|
|
};
|
|
return EnvironmentWorker2;
|
|
})();
|
|
Lease = /* @__PURE__ */ (() => {
|
|
class Lease2 {
|
|
constructor(ctrl) {
|
|
_Lease_ctrl.set(this, void 0);
|
|
_Lease_endReason.set(this, void 0);
|
|
__classPrivateFieldSet2(this, _Lease_ctrl, ctrl, "f");
|
|
}
|
|
get signal() {
|
|
return __classPrivateFieldGet2(this, _Lease_ctrl, "f").signal;
|
|
}
|
|
finish(reason) {
|
|
__classPrivateFieldSet2(this, _Lease_endReason, __classPrivateFieldGet2(this, _Lease_endReason, "f") ?? reason, "f");
|
|
__classPrivateFieldGet2(this, _Lease_ctrl, "f").abort();
|
|
}
|
|
/** True once the item belongs to the queue or another worker. */
|
|
get lost() {
|
|
return __classPrivateFieldGet2(this, _Lease_endReason, "f") === "lease_lost" || __classPrivateFieldGet2(this, _Lease_endReason, "f") === "assumed_lost";
|
|
}
|
|
}
|
|
_Lease_ctrl = /* @__PURE__ */ new WeakMap(), _Lease_endReason = /* @__PURE__ */ new WeakMap();
|
|
return Lease2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/environments/work.mjs
|
|
var Work;
|
|
var init_work = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/environments/work.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
init_poller();
|
|
init_worker();
|
|
Work = /* @__PURE__ */ (() => {
|
|
class Work2 extends APIResource2 {
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* Retrieve detailed information about a specific work item.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWork =
|
|
* await client.beta.environments.work.retrieve('work_id', {
|
|
* environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* });
|
|
* ```
|
|
*/
|
|
retrieve(workID, params, options) {
|
|
const { environment_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/environments/${environment_id}/work/${workID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* Update work item metadata with merge semantics.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWork =
|
|
* await client.beta.environments.work.update('work_id', {
|
|
* environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* metadata: { foo: 'string' },
|
|
* });
|
|
* ```
|
|
*/
|
|
update(workID, params, options) {
|
|
const { environment_id, betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/environments/${environment_id}/work/${workID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* List work items in an environment.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaSelfHostedWork of client.beta.environments.work.list(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(environmentID, params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/environments/${environmentID}/work?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* Acknowledge receipt of a work item, transitioning it from 'queued' to 'starting'
|
|
* and removing it from the queue.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWork =
|
|
* await client.beta.environments.work.ack('work_id', {
|
|
* environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* });
|
|
* ```
|
|
*/
|
|
ack(workID, params, options) {
|
|
const { environment_id, betas } = params;
|
|
return this._client.post(path3`/v1/environments/${environment_id}/work/${workID}/ack?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* Record a heartbeat for a work item to maintain the lease.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWorkHeartbeatResponse =
|
|
* await client.beta.environments.work.heartbeat('work_id', {
|
|
* environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* });
|
|
* ```
|
|
*/
|
|
heartbeat(workID, params, options) {
|
|
const { environment_id, desired_ttl_seconds, expected_last_heartbeat, betas } = params;
|
|
return this._client.post(path3`/v1/environments/${environment_id}/work/${workID}/heartbeat?beta=true`, {
|
|
query: { desired_ttl_seconds, expected_last_heartbeat },
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ "anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString() },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* Long poll for work items in the queue.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWork =
|
|
* await client.beta.environments.work.poll(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* );
|
|
* ```
|
|
*/
|
|
poll(environmentID, params = {}, options) {
|
|
const { betas, "Anthropic-Worker-ID": anthropicWorkerID, ...query } = params ?? {};
|
|
return this._client.get(path3`/v1/environments/${environmentID}/work/poll?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...anthropicWorkerID != null ? { "Anthropic-Worker-ID": anthropicWorkerID } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get statistics about the work queue for an environment.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWorkQueueStats =
|
|
* await client.beta.environments.work.stats(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* );
|
|
* ```
|
|
*/
|
|
stats(environmentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/environments/${environmentID}/work/stats?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Note: these endpoints are called automatically by the pre-built environment
|
|
* worker provided in the SDKs and CLI, for orchestrating sessions with self-hosted
|
|
* sandbox environments. They are included here as a reference; you do not need to
|
|
* invoke them directly.
|
|
*
|
|
* Stop a work item, initiating graceful or forced shutdown.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSelfHostedWork =
|
|
* await client.beta.environments.work.stop('work_id', {
|
|
* environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* });
|
|
* ```
|
|
*/
|
|
stop(workID, params, options) {
|
|
const { environment_id, betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/environments/${environment_id}/work/${workID}/stop?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Continuously claim work from a self-hosted environment, ack each item,
|
|
* and yield it. Posts `stop` automatically when the consumer's loop body
|
|
* returns or when iteration ends.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* for await (const work of client.beta.environments.work.poller({
|
|
* environmentId,
|
|
* environmentKey,
|
|
* })) {
|
|
* if (work.data.type !== 'session') continue;
|
|
* // ...service the work...
|
|
* }
|
|
* ```
|
|
*/
|
|
poller(opts) {
|
|
return new WorkPoller({ ...opts, client: this._client });
|
|
}
|
|
worker(opts) {
|
|
return new EnvironmentWorker({ ...opts, client: this._client });
|
|
}
|
|
}
|
|
Work2.WorkPoller = WorkPoller;
|
|
Work2.EnvironmentWorker = EnvironmentWorker;
|
|
return Work2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/environments/environments.mjs
|
|
var Environments2;
|
|
var init_environments2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/environments/environments.mjs"() {
|
|
init_resource2();
|
|
init_work();
|
|
init_work();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Environments2 = /* @__PURE__ */ (() => {
|
|
class Environments3 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.work = new Work(this._client);
|
|
}
|
|
/**
|
|
* Create a new environment with the specified configuration.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaEnvironment =
|
|
* await client.beta.environments.create({
|
|
* name: 'python-data-analysis',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/environments?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Retrieve a specific environment by ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaEnvironment =
|
|
* await client.beta.environments.retrieve(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(environmentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/environments/${environmentID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update an existing environment's configuration.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaEnvironment =
|
|
* await client.beta.environments.update(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(environmentID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/environments/${environmentID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List environments with pagination support.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaEnvironment of client.beta.environments.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/environments?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete an environment by ID. Returns a confirmation of the deletion.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaEnvironmentDeleteResponse =
|
|
* await client.beta.environments.delete(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(environmentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/environments/${environmentID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive an environment by ID. Archived environments cannot be used to create new
|
|
* sessions.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaEnvironment =
|
|
* await client.beta.environments.archive(
|
|
* 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(environmentID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/environments/${environmentID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Environments3.Work = Work;
|
|
return Environments3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memories.mjs
|
|
var Memories;
|
|
var init_memories = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memories.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Memories = class extends APIResource2 {
|
|
/**
|
|
* Create a memory
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemory =
|
|
* await client.beta.memoryStores.memories.create(
|
|
* 'memory_store_id',
|
|
* { content: 'content', path: 'xx' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(memoryStoreID, params, options) {
|
|
const { view, betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, {
|
|
query: { view },
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Retrieve a memory
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemory =
|
|
* await client.beta.memoryStores.memories.retrieve(
|
|
* 'memory_id',
|
|
* { memory_store_id: 'memory_store_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(memoryID, params, options) {
|
|
const { memory_store_id, betas, workspace_id, ...query } = params;
|
|
return this._client.get(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update a memory
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemory =
|
|
* await client.beta.memoryStores.memories.update(
|
|
* 'memory_id',
|
|
* { memory_store_id: 'memory_store_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(memoryID, params, options) {
|
|
const { memory_store_id, view, betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, {
|
|
query: { view },
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List memories
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsMemoryListItem of client.beta.memoryStores.memories.list(
|
|
* 'memory_store_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(memoryStoreID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/memory_stores/${memoryStoreID}/memories?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete a memory
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeletedMemory =
|
|
* await client.beta.memoryStores.memories.delete(
|
|
* 'memory_id',
|
|
* { memory_store_id: 'memory_store_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(memoryID, params, options) {
|
|
const { memory_store_id, expected_content_sha256, betas, workspace_id } = params;
|
|
return this._client.delete(path3`/v1/memory_stores/${memory_store_id}/memories/${memoryID}?beta=true`, {
|
|
query: { expected_content_sha256 },
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-versions.mjs
|
|
var MemoryVersions;
|
|
var init_memory_versions = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-versions.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
MemoryVersions = class extends APIResource2 {
|
|
/**
|
|
* Retrieve a memory version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemoryVersion =
|
|
* await client.beta.memoryStores.memoryVersions.retrieve(
|
|
* 'memory_version_id',
|
|
* { memory_store_id: 'memory_store_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(memoryVersionID, params, options) {
|
|
const { memory_store_id, betas, workspace_id, ...query } = params;
|
|
return this._client.get(path3`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List memory versions
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsMemoryVersion of client.beta.memoryStores.memoryVersions.list(
|
|
* 'memory_store_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(memoryStoreID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/memory_stores/${memoryStoreID}/memory_versions?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Redact a memory version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemoryVersion =
|
|
* await client.beta.memoryStores.memoryVersions.redact(
|
|
* 'memory_version_id',
|
|
* { memory_store_id: 'memory_store_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
redact(memoryVersionID, params, options) {
|
|
const { memory_store_id, betas, workspace_id } = params;
|
|
return this._client.post(path3`/v1/memory_stores/${memory_store_id}/memory_versions/${memoryVersionID}/redact?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-stores.mjs
|
|
var MemoryStores;
|
|
var init_memory_stores = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/memory-stores/memory-stores.mjs"() {
|
|
init_resource2();
|
|
init_memories();
|
|
init_memories();
|
|
init_memory_versions();
|
|
init_memory_versions();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
MemoryStores = /* @__PURE__ */ (() => {
|
|
class MemoryStores2 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.memories = new Memories(this._client);
|
|
this.memoryVersions = new MemoryVersions(this._client);
|
|
}
|
|
/**
|
|
* Create a memory store
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemoryStore =
|
|
* await client.beta.memoryStores.create({ name: 'x' });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/memory_stores?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Retrieve a memory store
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemoryStore =
|
|
* await client.beta.memoryStores.retrieve(
|
|
* 'memory_store_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(memoryStoreID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update a memory store
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemoryStore =
|
|
* await client.beta.memoryStores.update('memory_store_id');
|
|
* ```
|
|
*/
|
|
update(memoryStoreID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List memory stores
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsMemoryStore of client.beta.memoryStores.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/memory_stores?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete a memory store
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeletedMemoryStore =
|
|
* await client.beta.memoryStores.delete('memory_store_id');
|
|
* ```
|
|
*/
|
|
delete(memoryStoreID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/memory_stores/${memoryStoreID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive a memory store
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsMemoryStore =
|
|
* await client.beta.memoryStores.archive('memory_store_id');
|
|
* ```
|
|
*/
|
|
archive(memoryStoreID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/memory_stores/${memoryStoreID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "agent-memory-2026-07-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
MemoryStores2.Memories = Memories;
|
|
MemoryStores2.MemoryVersions = MemoryVersions;
|
|
return MemoryStores2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/error.mjs
|
|
var init_error4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/error.mjs"() {
|
|
init_error3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs
|
|
var JSONLDecoder;
|
|
var init_jsonl = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs"() {
|
|
init_error3();
|
|
init_shims2();
|
|
init_line2();
|
|
JSONLDecoder = /* @__PURE__ */ (() => {
|
|
class JSONLDecoder2 {
|
|
constructor(iterator, controller) {
|
|
this.iterator = iterator;
|
|
this.controller = controller;
|
|
}
|
|
async *decoder() {
|
|
const lineDecoder = new LineDecoder2();
|
|
for await (const chunk of this.iterator) {
|
|
for (const line of lineDecoder.decode(chunk)) {
|
|
yield JSON.parse(line);
|
|
}
|
|
}
|
|
for (const line of lineDecoder.flush()) {
|
|
yield JSON.parse(line);
|
|
}
|
|
}
|
|
[Symbol.asyncIterator]() {
|
|
return this.decoder();
|
|
}
|
|
static fromResponse(response, controller) {
|
|
if (!response.body) {
|
|
controller.abort();
|
|
if (typeof globalThis.navigator !== "undefined" && globalThis.navigator.product === "ReactNative") {
|
|
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
|
|
}
|
|
throw new AnthropicError(`Attempted to iterate over a response with no body`);
|
|
}
|
|
return new JSONLDecoder2(ReadableStreamToAsyncIterable2(response.body), controller);
|
|
}
|
|
}
|
|
return JSONLDecoder2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs
|
|
var Batches2;
|
|
var init_batches2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_jsonl();
|
|
init_error4();
|
|
init_path2();
|
|
Batches2 = class extends APIResource2 {
|
|
/**
|
|
* Send a batch of Message creation requests.
|
|
*
|
|
* The Message Batches API can be used to process multiple Messages API requests at
|
|
* once. Once a Message Batch is created, it begins processing immediately. Batches
|
|
* can take up to 24 hours to complete.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaMessageBatch =
|
|
* await client.beta.messages.batches.create({
|
|
* requests: [
|
|
* {
|
|
* custom_id: 'my-custom-id-1',
|
|
* params: {
|
|
* max_tokens: 1024,
|
|
* messages: [
|
|
* { content: 'Hello, world', role: 'user' },
|
|
* ],
|
|
* model: 'claude-opus-5',
|
|
* },
|
|
* },
|
|
* ],
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, user_profile_id, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/messages/batches?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
|
|
...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* This endpoint is idempotent and can be used to poll for Message Batch
|
|
* completion. To access the results of a Message Batch, make a request to the
|
|
* `results_url` field in the response.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaMessageBatch =
|
|
* await client.beta.messages.batches.retrieve(
|
|
* 'message_batch_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(messageBatchID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/messages/batches/${messageBatchID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List all Message Batches within a Workspace. Most recently created batches are
|
|
* returned first.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaMessageBatch of client.beta.messages.batches.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/messages/batches?beta=true", Page2, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete a Message Batch.
|
|
*
|
|
* Message Batches can only be deleted once they've finished processing. If you'd
|
|
* like to delete an in-progress batch, you must first cancel it.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDeletedMessageBatch =
|
|
* await client.beta.messages.batches.delete(
|
|
* 'message_batch_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(messageBatchID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/messages/batches/${messageBatchID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Batches may be canceled any time before processing ends. Once cancellation is
|
|
* initiated, the batch enters a `canceling` state, at which time the system may
|
|
* complete any in-progress, non-interruptible requests before finalizing
|
|
* cancellation.
|
|
*
|
|
* The number of canceled requests is specified in `request_counts`. To determine
|
|
* which requests were canceled, check the individual results within the batch.
|
|
* Note that cancellation may not result in any canceled requests if they were
|
|
* non-interruptible.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaMessageBatch =
|
|
* await client.beta.messages.batches.cancel(
|
|
* 'message_batch_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
cancel(messageBatchID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/messages/batches/${messageBatchID}/cancel?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Streams the results of a Message Batch as a `.jsonl` file.
|
|
*
|
|
* Each line in the file is a JSON object containing the result of a single request
|
|
* in the Message Batch. Results are not guaranteed to be in the same order as
|
|
* requests. Use the `custom_id` field to match results to requests.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaMessageBatchIndividualResponse =
|
|
* await client.beta.messages.batches.results(
|
|
* 'message_batch_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
async results(messageBatchID, params = {}, options) {
|
|
const batch = await this.retrieve(messageBatchID, params, options);
|
|
if (!batch.results_url) {
|
|
throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
|
|
}
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(batch.results_url, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
|
|
Accept: "application/binary",
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
stream: true,
|
|
__binaryResponse: true
|
|
})._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/constants.mjs
|
|
var MODEL_NONSTREAMING_TOKENS;
|
|
var init_constants = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/constants.mjs"() {
|
|
MODEL_NONSTREAMING_TOKENS = {
|
|
"claude-opus-4@20250514": 8192,
|
|
"anthropic.claude-opus-4-1-20250805-v1:0": 8192,
|
|
"claude-opus-4-1@20250805": 8192
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs
|
|
function getOutputFormat(params) {
|
|
return params?.output_format ?? params?.output_config?.format;
|
|
}
|
|
function maybeParseBetaMessage(message, params, opts) {
|
|
const outputFormat = getOutputFormat(params);
|
|
if (!params || !("parse" in (outputFormat ?? {}))) {
|
|
return {
|
|
...message,
|
|
content: message.content.map((block) => {
|
|
if (block.type === "text") {
|
|
const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
|
|
value: null,
|
|
enumerable: false
|
|
});
|
|
return Object.defineProperty(parsedBlock, "parsed", {
|
|
get() {
|
|
opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
|
|
return null;
|
|
},
|
|
enumerable: false
|
|
});
|
|
}
|
|
return block;
|
|
}),
|
|
parsed_output: null
|
|
};
|
|
}
|
|
return parseBetaMessage(message, params, opts);
|
|
}
|
|
function parseBetaMessage(message, params, opts) {
|
|
let firstParsedOutput = null;
|
|
const content = message.content.map((block) => {
|
|
if (block.type === "text") {
|
|
const parsedOutput = parseBetaOutputFormat(params, block.text);
|
|
if (firstParsedOutput === null) {
|
|
firstParsedOutput = parsedOutput;
|
|
}
|
|
const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
|
|
value: parsedOutput,
|
|
enumerable: false
|
|
});
|
|
return Object.defineProperty(parsedBlock, "parsed", {
|
|
get() {
|
|
opts.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");
|
|
return parsedOutput;
|
|
},
|
|
enumerable: false
|
|
});
|
|
}
|
|
return block;
|
|
});
|
|
return {
|
|
...message,
|
|
content,
|
|
parsed_output: firstParsedOutput
|
|
};
|
|
}
|
|
function parseBetaOutputFormat(params, content) {
|
|
const outputFormat = getOutputFormat(params);
|
|
if (outputFormat?.type !== "json_schema") {
|
|
return null;
|
|
}
|
|
try {
|
|
if ("parse" in outputFormat) {
|
|
return outputFormat.parse(content);
|
|
}
|
|
return JSON.parse(content);
|
|
} catch (error) {
|
|
throw new AnthropicError(`Failed to parse structured output: ${error}`);
|
|
}
|
|
}
|
|
var init_beta_parser = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs"() {
|
|
init_error3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/streaming.mjs
|
|
var init_streaming4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/streaming.mjs"() {
|
|
init_streaming3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs
|
|
var tokenize, strip, unstrip, generate, partialParse3;
|
|
var init_parser3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs"() {
|
|
tokenize = (input) => {
|
|
let current = 0;
|
|
let tokens = [];
|
|
while (current < input.length) {
|
|
let char = input[current];
|
|
if (char === "\\") {
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === "{") {
|
|
tokens.push({
|
|
type: "brace",
|
|
value: "{"
|
|
});
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === "}") {
|
|
tokens.push({
|
|
type: "brace",
|
|
value: "}"
|
|
});
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === "[") {
|
|
tokens.push({
|
|
type: "paren",
|
|
value: "["
|
|
});
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === "]") {
|
|
tokens.push({
|
|
type: "paren",
|
|
value: "]"
|
|
});
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === ":") {
|
|
tokens.push({
|
|
type: "separator",
|
|
value: ":"
|
|
});
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === ",") {
|
|
tokens.push({
|
|
type: "delimiter",
|
|
value: ","
|
|
});
|
|
current++;
|
|
continue;
|
|
}
|
|
if (char === '"') {
|
|
const start = current + 1;
|
|
let end = start;
|
|
let danglingQuote = false;
|
|
while (true) {
|
|
end = input.indexOf('"', end);
|
|
if (end === -1) {
|
|
danglingQuote = true;
|
|
break;
|
|
}
|
|
let backslashes = 0;
|
|
let i = end - 1;
|
|
while (i >= start && input[i] === "\\") {
|
|
backslashes++;
|
|
i--;
|
|
}
|
|
if (backslashes % 2 === 0)
|
|
break;
|
|
end++;
|
|
}
|
|
if (danglingQuote) {
|
|
current = input.length;
|
|
} else {
|
|
tokens.push({
|
|
type: "string",
|
|
value: input.slice(start, end)
|
|
});
|
|
current = end + 1;
|
|
}
|
|
continue;
|
|
}
|
|
let WHITESPACE = /\s/;
|
|
if (char && WHITESPACE.test(char)) {
|
|
current++;
|
|
continue;
|
|
}
|
|
let NUMBERS = /[0-9]/;
|
|
if (char && NUMBERS.test(char) || char === "-" || char === ".") {
|
|
let value = "";
|
|
if (char === "-") {
|
|
value += char;
|
|
char = input[++current];
|
|
}
|
|
while (char && (NUMBERS.test(char) || char === "." || // exponent marker, e.g. `1e10` or `1.5E-9`
|
|
char === "e" || char === "E" || // exponent sign, only valid immediately after the exponent marker
|
|
(char === "-" || char === "+") && (value[value.length - 1] === "e" || value[value.length - 1] === "E"))) {
|
|
value += char;
|
|
char = input[++current];
|
|
}
|
|
tokens.push({
|
|
type: "number",
|
|
value,
|
|
unterminated: current === input.length
|
|
});
|
|
continue;
|
|
}
|
|
let LETTERS = /[a-z]/i;
|
|
if (char && LETTERS.test(char)) {
|
|
let value = "";
|
|
while (char && LETTERS.test(char)) {
|
|
if (current === input.length) {
|
|
break;
|
|
}
|
|
value += char;
|
|
char = input[++current];
|
|
}
|
|
if (value == "true" || value == "false" || value === "null") {
|
|
tokens.push({
|
|
type: "name",
|
|
value
|
|
});
|
|
} else {
|
|
current++;
|
|
continue;
|
|
}
|
|
continue;
|
|
}
|
|
current++;
|
|
}
|
|
return tokens;
|
|
};
|
|
strip = (tokens) => {
|
|
let open = [];
|
|
for (const token of tokens) {
|
|
if (token.type === "brace" || token.type === "paren") {
|
|
if (token.value === "{" || token.value === "[") {
|
|
open.push(token.value);
|
|
} else {
|
|
open.pop();
|
|
}
|
|
}
|
|
}
|
|
let innermostOpenBracket = open[open.length - 1];
|
|
let length = tokens.length;
|
|
let JSON_NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?$/;
|
|
while (length > 0) {
|
|
let lastToken = tokens[length - 1];
|
|
switch (lastToken.type) {
|
|
case "separator":
|
|
length--;
|
|
continue;
|
|
case "number":
|
|
if (lastToken.unterminated || !JSON_NUMBER.test(lastToken.value)) {
|
|
length--;
|
|
continue;
|
|
}
|
|
break;
|
|
case "string":
|
|
let tokenBeforeTheLastToken = tokens[length - 2];
|
|
if (innermostOpenBracket === "{" && (tokenBeforeTheLastToken?.type === "delimiter" || tokenBeforeTheLastToken?.type === "brace" && tokenBeforeTheLastToken.value === "{")) {
|
|
length--;
|
|
continue;
|
|
}
|
|
break;
|
|
case "delimiter":
|
|
length--;
|
|
break;
|
|
}
|
|
break;
|
|
}
|
|
return tokens.slice(0, length);
|
|
};
|
|
unstrip = (tokens) => {
|
|
let tail = [];
|
|
tokens.map((token) => {
|
|
if (token.type === "brace") {
|
|
if (token.value === "{") {
|
|
tail.push("}");
|
|
} else {
|
|
tail.splice(tail.lastIndexOf("}"), 1);
|
|
}
|
|
}
|
|
if (token.type === "paren") {
|
|
if (token.value === "[") {
|
|
tail.push("]");
|
|
} else {
|
|
tail.splice(tail.lastIndexOf("]"), 1);
|
|
}
|
|
}
|
|
});
|
|
if (tail.length > 0) {
|
|
tail.reverse().map((item) => {
|
|
if (item === "}") {
|
|
tokens.push({
|
|
type: "brace",
|
|
value: "}"
|
|
});
|
|
} else if (item === "]") {
|
|
tokens.push({
|
|
type: "paren",
|
|
value: "]"
|
|
});
|
|
}
|
|
});
|
|
}
|
|
return tokens;
|
|
};
|
|
generate = (tokens) => {
|
|
let output = "";
|
|
tokens.map((token) => {
|
|
switch (token.type) {
|
|
case "string":
|
|
output += '"' + token.value + '"';
|
|
break;
|
|
default:
|
|
output += token.value;
|
|
break;
|
|
}
|
|
});
|
|
return output;
|
|
};
|
|
partialParse3 = (input) => JSON.parse(generate(unstrip(strip(tokenize(input)))));
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/message-stream-utils.mjs
|
|
function withLazyInput(prev, jsonBuf) {
|
|
const next = {};
|
|
for (const key of Object.keys(prev)) {
|
|
if (key !== "input")
|
|
next[key] = prev[key];
|
|
}
|
|
Object.defineProperty(next, JSON_BUF_PROPERTY, { value: jsonBuf, enumerable: false, writable: true });
|
|
let input;
|
|
let parsed = false;
|
|
Object.defineProperty(next, "input", {
|
|
enumerable: true,
|
|
configurable: true,
|
|
get() {
|
|
if (!parsed) {
|
|
input = jsonBuf ? partialParse3(jsonBuf) : {};
|
|
parsed = true;
|
|
}
|
|
return input;
|
|
}
|
|
});
|
|
return next;
|
|
}
|
|
var JSON_BUF_PROPERTY;
|
|
var init_message_stream_utils = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/message-stream-utils.mjs"() {
|
|
init_parser3();
|
|
JSON_BUF_PROPERTY = "__json_buf";
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs
|
|
function tracksToolInput(content) {
|
|
return content.type === "tool_use" || content.type === "server_tool_use" || content.type === "mcp_tool_use";
|
|
}
|
|
var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_workspace_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, _BetaMessageStream_toolInputParseError, BetaMessageStream;
|
|
var init_BetaMessageStream = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs"() {
|
|
init_tslib2();
|
|
init_stainless_helper_header();
|
|
init_error4();
|
|
init_errors2();
|
|
init_values2();
|
|
init_streaming4();
|
|
init_beta_parser();
|
|
init_message_stream_utils();
|
|
BetaMessageStream = /* @__PURE__ */ (() => {
|
|
class BetaMessageStream2 {
|
|
constructor(params, opts) {
|
|
_BetaMessageStream_instances.add(this);
|
|
this.messages = [];
|
|
this.receivedMessages = [];
|
|
_BetaMessageStream_currentMessageSnapshot.set(this, void 0);
|
|
_BetaMessageStream_params.set(this, null);
|
|
this.controller = new AbortController();
|
|
_BetaMessageStream_connectedPromise.set(this, void 0);
|
|
_BetaMessageStream_resolveConnectedPromise.set(this, () => {
|
|
});
|
|
_BetaMessageStream_rejectConnectedPromise.set(this, () => {
|
|
});
|
|
_BetaMessageStream_endPromise.set(this, void 0);
|
|
_BetaMessageStream_resolveEndPromise.set(this, () => {
|
|
});
|
|
_BetaMessageStream_rejectEndPromise.set(this, () => {
|
|
});
|
|
_BetaMessageStream_listeners.set(this, {});
|
|
_BetaMessageStream_ended.set(this, false);
|
|
_BetaMessageStream_errored.set(this, false);
|
|
_BetaMessageStream_aborted.set(this, false);
|
|
_BetaMessageStream_catchingPromiseCreated.set(this, false);
|
|
_BetaMessageStream_response.set(this, void 0);
|
|
_BetaMessageStream_request_id.set(this, void 0);
|
|
_BetaMessageStream_workspace_id.set(this, void 0);
|
|
_BetaMessageStream_logger.set(this, void 0);
|
|
_BetaMessageStream_handleError.set(this, (error) => {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_errored, true, "f");
|
|
if (isAbortError2(error)) {
|
|
error = new APIUserAbortError2();
|
|
}
|
|
if (error instanceof APIUserAbortError2) {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_aborted, true, "f");
|
|
return this._emit("abort", error);
|
|
}
|
|
if (error instanceof AnthropicError) {
|
|
return this._emit("error", error);
|
|
}
|
|
if (error instanceof Error) {
|
|
const anthropicError = new AnthropicError(error.message);
|
|
anthropicError.cause = error;
|
|
return this._emit("error", anthropicError);
|
|
}
|
|
return this._emit("error", new AnthropicError(String(error)));
|
|
});
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f");
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_rejectConnectedPromise, reject, "f");
|
|
}), "f");
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_resolveEndPromise, resolve, "f");
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_rejectEndPromise, reject, "f");
|
|
}), "f");
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_connectedPromise, "f").catch(() => {
|
|
});
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_endPromise, "f").catch(() => {
|
|
});
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_params, params, "f");
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_logger, opts?.logger ?? console, "f");
|
|
}
|
|
get response() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_response, "f");
|
|
}
|
|
get request_id() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_request_id, "f");
|
|
}
|
|
get workspace_id() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_workspace_id, "f");
|
|
}
|
|
/**
|
|
* Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
|
|
* returned vie the `request-id` header which is useful for debugging requests and resporting
|
|
* issues to Anthropic.
|
|
*
|
|
* This is the same as the `APIPromise.withResponse()` method.
|
|
*
|
|
* This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
|
|
* as no `Response` is available.
|
|
*/
|
|
async withResponse() {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
|
|
const response = await __classPrivateFieldGet2(this, _BetaMessageStream_connectedPromise, "f");
|
|
if (!response) {
|
|
throw new Error("Could not resolve a `Response` object");
|
|
}
|
|
return {
|
|
data: this,
|
|
response,
|
|
request_id: response.headers.get("request-id"),
|
|
workspace_id: response.headers.get("anthropic-workspace-id")
|
|
};
|
|
}
|
|
/**
|
|
* Intended for use on the frontend, consuming a stream produced with
|
|
* `.toReadableStream()` on the backend.
|
|
*
|
|
* Note that messages sent to the model do not appear in `.on('message')`
|
|
* in this context.
|
|
*/
|
|
static fromReadableStream(stream4) {
|
|
const runner = new BetaMessageStream2(null);
|
|
runner._run(() => runner._fromReadableStream(stream4));
|
|
return runner;
|
|
}
|
|
static createMessage(messages, params, options, { logger } = {}) {
|
|
const runner = new BetaMessageStream2(params, { logger });
|
|
for (const message of params.messages) {
|
|
runner._addMessageParam(message);
|
|
}
|
|
__classPrivateFieldSet2(runner, _BetaMessageStream_params, { ...params, stream: true }, "f");
|
|
runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: "stream" } }));
|
|
return runner;
|
|
}
|
|
_run(executor) {
|
|
executor().then(() => {
|
|
this._emitFinal();
|
|
this._emit("end");
|
|
}, __classPrivateFieldGet2(this, _BetaMessageStream_handleError, "f"));
|
|
}
|
|
_addMessageParam(message) {
|
|
this.messages.push(message);
|
|
}
|
|
_addMessage(message, emit = true) {
|
|
this.receivedMessages.push(message);
|
|
if (emit) {
|
|
this._emit("message", message);
|
|
}
|
|
}
|
|
async _createMessage(messages, params, options) {
|
|
const signal = options?.signal;
|
|
let abortHandler;
|
|
if (signal) {
|
|
if (signal.aborted)
|
|
this.controller.abort();
|
|
abortHandler = this.controller.abort.bind(this.controller);
|
|
signal.addEventListener("abort", abortHandler);
|
|
}
|
|
try {
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
|
|
const { response, data: stream4 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
|
|
this._connected(response);
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw new APIUserAbortError2();
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
|
|
} finally {
|
|
if (signal && abortHandler) {
|
|
signal.removeEventListener("abort", abortHandler);
|
|
}
|
|
}
|
|
}
|
|
_connected(response) {
|
|
if (this.ended)
|
|
return;
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_response, response, "f");
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_request_id, response?.headers.get("request-id"), "f");
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_workspace_id, response?.headers.get("anthropic-workspace-id"), "f");
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response);
|
|
this._emit("connect");
|
|
}
|
|
get ended() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_ended, "f");
|
|
}
|
|
get errored() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_errored, "f");
|
|
}
|
|
get aborted() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_aborted, "f");
|
|
}
|
|
abort() {
|
|
this.controller.abort();
|
|
}
|
|
/**
|
|
* Adds the listener function to the end of the listeners array for the event.
|
|
* No checks are made to see if the listener has already been added. Multiple calls passing
|
|
* the same combination of event and listener will result in the listener being added, and
|
|
* called, multiple times.
|
|
* @returns this MessageStream, so that calls can be chained
|
|
*/
|
|
on(event, listener) {
|
|
const listeners = __classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event] = []);
|
|
listeners.push({ listener });
|
|
return this;
|
|
}
|
|
/**
|
|
* Removes the specified listener from the listener array for the event.
|
|
* off() will remove, at most, one instance of a listener from the listener array. If any single
|
|
* listener has been added multiple times to the listener array for the specified event, then
|
|
* off() must be called multiple times to remove each instance.
|
|
* @returns this MessageStream, so that calls can be chained
|
|
*/
|
|
off(event, listener) {
|
|
const listeners = __classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event];
|
|
if (!listeners)
|
|
return this;
|
|
const index = listeners.findIndex((l) => l.listener === listener);
|
|
if (index >= 0)
|
|
listeners.splice(index, 1);
|
|
return this;
|
|
}
|
|
/**
|
|
* Adds a one-time listener function for the event. The next time the event is triggered,
|
|
* this listener is removed and then invoked.
|
|
* @returns this MessageStream, so that calls can be chained
|
|
*/
|
|
once(event, listener) {
|
|
const listeners = __classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event] = []);
|
|
listeners.push({ listener, once: true });
|
|
return this;
|
|
}
|
|
/**
|
|
* This is similar to `.once()`, but returns a Promise that resolves the next time
|
|
* the event is triggered, instead of calling a listener callback.
|
|
* @returns a Promise that resolves the next time given event is triggered,
|
|
* or rejects if an error is emitted. (If you request the 'error' event,
|
|
* returns a promise that resolves with the error).
|
|
*
|
|
* Example:
|
|
*
|
|
* const message = await stream.emitted('message') // rejects if the stream errors
|
|
*/
|
|
emitted(event) {
|
|
return new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
|
|
if (event !== "error")
|
|
this.once("error", reject);
|
|
this.once(event, resolve);
|
|
});
|
|
}
|
|
async done() {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_catchingPromiseCreated, true, "f");
|
|
await __classPrivateFieldGet2(this, _BetaMessageStream_endPromise, "f");
|
|
}
|
|
get currentMessage() {
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_currentMessageSnapshot, "f");
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the the final assistant Message response,
|
|
* or rejects if an error occurred or the stream ended prematurely without producing a Message.
|
|
* If structured outputs were used, this will be a ParsedMessage with a `parsed` field.
|
|
*/
|
|
async finalMessage() {
|
|
await this.done();
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this);
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the the final assistant Message's text response, concatenated
|
|
* together if there are more than one text blocks.
|
|
* Rejects if an error occurred or the stream ended prematurely without producing a Message.
|
|
*/
|
|
async finalText() {
|
|
await this.done();
|
|
return __classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this);
|
|
}
|
|
_emit(event, ...args) {
|
|
if (__classPrivateFieldGet2(this, _BetaMessageStream_ended, "f"))
|
|
return;
|
|
if (event === "end") {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_ended, true, "f");
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_resolveEndPromise, "f").call(this);
|
|
}
|
|
const listeners = __classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event];
|
|
if (listeners) {
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
|
|
listeners.forEach(({ listener }) => listener(...args));
|
|
}
|
|
if (event === "abort") {
|
|
const error = args[0];
|
|
if (!__classPrivateFieldGet2(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
|
|
Promise.reject(error);
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
|
|
this._emit("end");
|
|
return;
|
|
}
|
|
if (event === "error") {
|
|
const error = args[0];
|
|
if (!__classPrivateFieldGet2(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
|
|
Promise.reject(error);
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error);
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error);
|
|
this._emit("end");
|
|
}
|
|
}
|
|
_emitFinal() {
|
|
const finalMessage = this.receivedMessages.at(-1);
|
|
if (finalMessage) {
|
|
this._emit("finalMessage", __classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this));
|
|
}
|
|
}
|
|
async _fromReadableStream(readableStream, options) {
|
|
const signal = options?.signal;
|
|
let abortHandler;
|
|
if (signal) {
|
|
if (signal.aborted)
|
|
this.controller.abort();
|
|
abortHandler = this.controller.abort.bind(this.controller);
|
|
signal.addEventListener("abort", abortHandler);
|
|
}
|
|
try {
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this);
|
|
this._connected(null);
|
|
const stream4 = Stream2.fromReadableStream(readableStream, this.controller);
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw new APIUserAbortError2();
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this);
|
|
} finally {
|
|
if (signal && abortHandler) {
|
|
signal.removeEventListener("abort", abortHandler);
|
|
}
|
|
}
|
|
}
|
|
[(_BetaMessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_params = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_listeners = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_ended = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_errored = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_aborted = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_response = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_request_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_workspace_id = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_logger = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_handleError = /* @__PURE__ */ new WeakMap(), _BetaMessageStream_instances = /* @__PURE__ */ new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage2() {
|
|
if (this.receivedMessages.length === 0) {
|
|
throw new AnthropicError("stream ended without producing a Message with role=assistant");
|
|
}
|
|
return this.receivedMessages.at(-1);
|
|
}, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText2() {
|
|
if (this.receivedMessages.length === 0) {
|
|
throw new AnthropicError("stream ended without producing a Message with role=assistant");
|
|
}
|
|
const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
|
|
if (textBlocks.length === 0) {
|
|
throw new AnthropicError("stream ended without producing a content block with type=text");
|
|
}
|
|
return textBlocks.join(" ");
|
|
}, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest2() {
|
|
if (this.ended)
|
|
return;
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
|
|
}, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent2(event) {
|
|
if (this.ended)
|
|
return;
|
|
const messageSnapshot = __classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event);
|
|
this._emit("streamEvent", event, messageSnapshot);
|
|
switch (event.type) {
|
|
case "content_block_delta": {
|
|
const content = messageSnapshot.content.at(-1);
|
|
switch (event.delta.type) {
|
|
case "text_delta": {
|
|
if (content.type === "text") {
|
|
this._emit("text", event.delta.text, content.text || "");
|
|
}
|
|
break;
|
|
}
|
|
case "citations_delta": {
|
|
if (content.type === "text") {
|
|
this._emit("citation", event.delta.citation, content.citations ?? []);
|
|
}
|
|
break;
|
|
}
|
|
case "input_json_delta": {
|
|
if (tracksToolInput(content) && __classPrivateFieldGet2(this, _BetaMessageStream_listeners, "f").inputJson?.length) {
|
|
let jsonSnapshot;
|
|
try {
|
|
jsonSnapshot = content.input;
|
|
} catch (err) {
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_handleError, "f").call(this, __classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_toolInputParseError).call(this, content, err));
|
|
break;
|
|
}
|
|
this._emit("inputJson", event.delta.partial_json, jsonSnapshot);
|
|
}
|
|
break;
|
|
}
|
|
case "thinking_delta": {
|
|
if (content.type === "thinking") {
|
|
this._emit("thinking", event.delta.thinking, content.thinking);
|
|
}
|
|
break;
|
|
}
|
|
case "signature_delta": {
|
|
if (content.type === "thinking") {
|
|
this._emit("signature", content.signature);
|
|
}
|
|
break;
|
|
}
|
|
case "compaction_delta": {
|
|
if (content.type === "compaction" && content.content) {
|
|
this._emit("compaction", content.content);
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
checkNever(event.delta);
|
|
}
|
|
break;
|
|
}
|
|
case "message_stop": {
|
|
this._addMessageParam(messageSnapshot);
|
|
this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet2(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet2(this, _BetaMessageStream_logger, "f") }), true);
|
|
break;
|
|
}
|
|
case "content_block_stop": {
|
|
this._emit("contentBlock", messageSnapshot.content.at(-1));
|
|
break;
|
|
}
|
|
case "message_start": {
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f");
|
|
break;
|
|
}
|
|
case "content_block_start":
|
|
case "message_delta":
|
|
break;
|
|
}
|
|
}, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest2() {
|
|
if (this.ended) {
|
|
throw new AnthropicError(`stream has ended, this shouldn't happen`);
|
|
}
|
|
const snapshot = __classPrivateFieldGet2(this, _BetaMessageStream_currentMessageSnapshot, "f");
|
|
if (!snapshot) {
|
|
throw new AnthropicError(`request ended without sending any chunks`);
|
|
}
|
|
__classPrivateFieldSet2(this, _BetaMessageStream_currentMessageSnapshot, void 0, "f");
|
|
return maybeParseBetaMessage(snapshot, __classPrivateFieldGet2(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet2(this, _BetaMessageStream_logger, "f") });
|
|
}, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage2(event) {
|
|
let snapshot = __classPrivateFieldGet2(this, _BetaMessageStream_currentMessageSnapshot, "f");
|
|
if (event.type === "message_start") {
|
|
if (snapshot) {
|
|
throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
|
|
}
|
|
return event.message;
|
|
}
|
|
if (!snapshot) {
|
|
throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
|
|
}
|
|
switch (event.type) {
|
|
case "message_stop":
|
|
return snapshot;
|
|
case "message_delta":
|
|
snapshot.stop_reason = event.delta.stop_reason;
|
|
snapshot.stop_sequence = event.delta.stop_sequence;
|
|
snapshot.stop_details = event.delta.stop_details;
|
|
snapshot.usage.output_tokens = event.usage.output_tokens;
|
|
if (event.delta.container != null) {
|
|
snapshot.container = event.delta.container;
|
|
}
|
|
if (event.context_management != null) {
|
|
snapshot.context_management = event.context_management;
|
|
}
|
|
if (event.input_transformations != null) {
|
|
snapshot.input_transformations = event.input_transformations;
|
|
}
|
|
if (event.usage.input_tokens != null) {
|
|
snapshot.usage.input_tokens = event.usage.input_tokens;
|
|
}
|
|
if (event.usage.cache_creation_input_tokens != null) {
|
|
snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
|
|
}
|
|
if (event.usage.cache_read_input_tokens != null) {
|
|
snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
|
|
}
|
|
if (event.usage.server_tool_use != null) {
|
|
snapshot.usage.server_tool_use = event.usage.server_tool_use;
|
|
}
|
|
if (event.usage.iterations != null) {
|
|
snapshot.usage.iterations = event.usage.iterations;
|
|
}
|
|
if (event.usage.fallback_credit != null) {
|
|
snapshot.usage.fallback_credit = event.usage.fallback_credit;
|
|
}
|
|
if (event.usage.output_tokens_details != null) {
|
|
snapshot.usage.output_tokens_details = event.usage.output_tokens_details;
|
|
}
|
|
return snapshot;
|
|
case "content_block_start":
|
|
snapshot.content.push(event.content_block);
|
|
if (event.content_block.type === "fallback") {
|
|
snapshot.model = event.content_block.to.model;
|
|
}
|
|
return snapshot;
|
|
case "content_block_delta": {
|
|
const snapshotContent = snapshot.content.at(event.index);
|
|
switch (event.delta.type) {
|
|
case "text_delta": {
|
|
if (snapshotContent?.type === "text") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
text: (snapshotContent.text || "") + event.delta.text
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "citations_delta": {
|
|
if (snapshotContent?.type === "text") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
citations: [...snapshotContent.citations ?? [], event.delta.citation]
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "input_json_delta": {
|
|
if (snapshotContent && tracksToolInput(snapshotContent)) {
|
|
const jsonBuf = (snapshotContent[JSON_BUF_PROPERTY] || "") + event.delta.partial_json;
|
|
snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf);
|
|
}
|
|
break;
|
|
}
|
|
case "thinking_delta": {
|
|
if (snapshotContent?.type === "thinking") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
thinking: snapshotContent.thinking + event.delta.thinking
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "signature_delta": {
|
|
if (snapshotContent?.type === "thinking") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
signature: event.delta.signature
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "compaction_delta": {
|
|
if (snapshotContent?.type === "compaction") {
|
|
const block = { ...snapshotContent, content: event.delta.content };
|
|
if ("encrypted_content" in event.delta) {
|
|
block.encrypted_content = event.delta.encrypted_content;
|
|
}
|
|
snapshot.content[event.index] = block;
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
checkNever(event.delta);
|
|
}
|
|
return snapshot;
|
|
}
|
|
case "content_block_stop": {
|
|
const snapshotContent = snapshot.content.at(event.index);
|
|
if (snapshotContent && tracksToolInput(snapshotContent) && JSON_BUF_PROPERTY in snapshotContent) {
|
|
let input;
|
|
try {
|
|
input = snapshotContent.input;
|
|
} catch (err) {
|
|
input = {};
|
|
__classPrivateFieldGet2(this, _BetaMessageStream_handleError, "f").call(this, __classPrivateFieldGet2(this, _BetaMessageStream_instances, "m", _BetaMessageStream_toolInputParseError).call(this, snapshotContent, err));
|
|
}
|
|
Object.defineProperty(snapshotContent, "input", {
|
|
value: input,
|
|
enumerable: true,
|
|
configurable: true,
|
|
writable: true
|
|
});
|
|
}
|
|
return snapshot;
|
|
}
|
|
}
|
|
}, _BetaMessageStream_toolInputParseError = function _BetaMessageStream_toolInputParseError2(block, err) {
|
|
const jsonBuf = block[JSON_BUF_PROPERTY];
|
|
return new AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`);
|
|
}, Symbol.asyncIterator)]() {
|
|
const pushQueue = [];
|
|
const readQueue = [];
|
|
let done = false;
|
|
this.on("streamEvent", (event) => {
|
|
const reader = readQueue.shift();
|
|
if (reader) {
|
|
reader.resolve(event);
|
|
} else {
|
|
pushQueue.push(event);
|
|
}
|
|
});
|
|
this.on("end", () => {
|
|
done = true;
|
|
for (const reader of readQueue) {
|
|
reader.resolve(void 0);
|
|
}
|
|
readQueue.length = 0;
|
|
});
|
|
this.on("abort", (err) => {
|
|
done = true;
|
|
for (const reader of readQueue) {
|
|
reader.reject(err);
|
|
}
|
|
readQueue.length = 0;
|
|
});
|
|
this.on("error", (err) => {
|
|
done = true;
|
|
for (const reader of readQueue) {
|
|
reader.reject(err);
|
|
}
|
|
readQueue.length = 0;
|
|
});
|
|
return {
|
|
next: async () => {
|
|
if (!pushQueue.length) {
|
|
if (done) {
|
|
return { value: void 0, done: true };
|
|
}
|
|
return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
|
|
}
|
|
const chunk = pushQueue.shift();
|
|
return { value: chunk, done: false };
|
|
},
|
|
return: async () => {
|
|
this.abort();
|
|
return { value: void 0, done: true };
|
|
}
|
|
};
|
|
}
|
|
toReadableStream() {
|
|
const stream4 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
|
|
return stream4.toReadableStream();
|
|
}
|
|
}
|
|
return BetaMessageStream2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/internal/BetaToolRunnerStream.mjs
|
|
var _BetaToolRunnerStream_instances, _BetaToolRunnerStream_onToolCall, _BetaToolRunnerStream_emitted, _BetaToolRunnerStream_readers, _BetaToolRunnerStream_toolCalls, _BetaToolRunnerStream_closed, _BetaToolRunnerStream_ready, _BetaToolRunnerStream_fallback, _BetaToolRunnerStream_track, _BetaToolRunnerStream_release, _BetaToolRunnerStream_removeReader, BetaToolRunnerStream;
|
|
var init_BetaToolRunnerStream = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/internal/BetaToolRunnerStream.mjs"() {
|
|
init_tslib2();
|
|
init_stainless_helper_header();
|
|
init_BetaMessageStream();
|
|
BetaToolRunnerStream = /* @__PURE__ */ (() => {
|
|
class BetaToolRunnerStream2 extends BetaMessageStream {
|
|
constructor(params, onToolCall) {
|
|
super(params);
|
|
_BetaToolRunnerStream_instances.add(this);
|
|
_BetaToolRunnerStream_onToolCall.set(this, void 0);
|
|
_BetaToolRunnerStream_emitted.set(this, 0);
|
|
_BetaToolRunnerStream_readers.set(this, []);
|
|
_BetaToolRunnerStream_toolCalls.set(this, []);
|
|
_BetaToolRunnerStream_closed.set(this, void 0);
|
|
_BetaToolRunnerStream_ready.set(this, []);
|
|
_BetaToolRunnerStream_fallback.set(this, false);
|
|
__classPrivateFieldSet2(this, _BetaToolRunnerStream_onToolCall, onToolCall, "f");
|
|
}
|
|
/** The `tool_use` blocks that have finished streaming, in the model's order */
|
|
get toolCalls() {
|
|
return __classPrivateFieldGet2(this, _BetaToolRunnerStream_toolCalls, "f");
|
|
}
|
|
/** Sends the request as `client.beta.messages.stream()` does. */
|
|
static start(messages, params, options, onToolCall) {
|
|
const stream4 = new BetaToolRunnerStream2({ ...params, stream: true }, onToolCall);
|
|
for (const message of params.messages) {
|
|
stream4._addMessageParam(message);
|
|
}
|
|
stream4._run(() => stream4._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: "stream" } }));
|
|
return stream4;
|
|
}
|
|
_emit(event, ...args) {
|
|
var _a6;
|
|
if (event !== "streamEvent" || this.ended) {
|
|
super._emit(event, ...args);
|
|
return;
|
|
}
|
|
__classPrivateFieldSet2(this, _BetaToolRunnerStream_emitted, (_a6 = __classPrivateFieldGet2(this, _BetaToolRunnerStream_emitted, "f"), _a6++, _a6), "f");
|
|
const [streamEvent, snapshot] = args;
|
|
const block = streamEvent.type === "content_block_stop" ? snapshot.content[streamEvent.index] : void 0;
|
|
const closed = block?.type === "tool_use" ? block : void 0;
|
|
if (closed) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_toolCalls, "f").push(closed);
|
|
}
|
|
super._emit(event, ...args);
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_track).call(this, streamEvent, closed);
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_release).call(this);
|
|
}
|
|
[(_BetaToolRunnerStream_onToolCall = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_emitted = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_readers = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_toolCalls = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_closed = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_ready = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_fallback = /* @__PURE__ */ new WeakMap(), _BetaToolRunnerStream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
const iterator = super[Symbol.asyncIterator]();
|
|
const reader = { handled: __classPrivateFieldGet2(this, _BetaToolRunnerStream_emitted, "f") };
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_readers, "f").push(reader);
|
|
let holdsEvent = false;
|
|
return {
|
|
next: async () => {
|
|
if (holdsEvent) {
|
|
holdsEvent = false;
|
|
reader.handled++;
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_release).call(this);
|
|
}
|
|
try {
|
|
const result = await iterator.next();
|
|
holdsEvent = !result.done;
|
|
if (result.done) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_removeReader).call(this, reader);
|
|
}
|
|
return result;
|
|
} catch (error) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_removeReader).call(this, reader);
|
|
throw error;
|
|
}
|
|
},
|
|
return: async () => {
|
|
const result = iterator.return?.();
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_removeReader).call(this, reader);
|
|
return await result ?? { value: void 0, done: true };
|
|
}
|
|
};
|
|
}
|
|
}
|
|
_BetaToolRunnerStream_track = function _BetaToolRunnerStream_track2(event, closed) {
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunnerStream_fallback, "f")) {
|
|
return;
|
|
}
|
|
if (event.type === "content_block_start" && event.content_block.type === "fallback") {
|
|
__classPrivateFieldSet2(this, _BetaToolRunnerStream_fallback, true, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunnerStream_closed, void 0, "f");
|
|
return;
|
|
}
|
|
const movedOn = event.type === "content_block_start" || event.type === "message_delta" && event.delta.stop_reason === "tool_use";
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunnerStream_closed, "f") && movedOn) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_ready, "f").push({ toolUse: __classPrivateFieldGet2(this, _BetaToolRunnerStream_closed, "f"), event: __classPrivateFieldGet2(this, _BetaToolRunnerStream_emitted, "f") });
|
|
__classPrivateFieldSet2(this, _BetaToolRunnerStream_closed, void 0, "f");
|
|
}
|
|
if (closed) {
|
|
__classPrivateFieldSet2(this, _BetaToolRunnerStream_closed, closed, "f");
|
|
}
|
|
}, _BetaToolRunnerStream_release = function _BetaToolRunnerStream_release2() {
|
|
if (this.errored || this.controller.signal.aborted) {
|
|
return;
|
|
}
|
|
const handled = Math.min(__classPrivateFieldGet2(this, _BetaToolRunnerStream_emitted, "f"), ...__classPrivateFieldGet2(this, _BetaToolRunnerStream_readers, "f").map((reader) => reader.handled));
|
|
while (__classPrivateFieldGet2(this, _BetaToolRunnerStream_ready, "f")[0] && __classPrivateFieldGet2(this, _BetaToolRunnerStream_ready, "f")[0].event <= handled) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_onToolCall, "f").call(this, __classPrivateFieldGet2(this, _BetaToolRunnerStream_ready, "f").shift().toolUse);
|
|
}
|
|
}, _BetaToolRunnerStream_removeReader = function _BetaToolRunnerStream_removeReader2(reader) {
|
|
const index = __classPrivateFieldGet2(this, _BetaToolRunnerStream_readers, "f").indexOf(reader);
|
|
if (index >= 0) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_readers, "f").splice(index, 1);
|
|
__classPrivateFieldGet2(this, _BetaToolRunnerStream_instances, "m", _BetaToolRunnerStream_release).call(this);
|
|
}
|
|
};
|
|
return BetaToolRunnerStream2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs
|
|
function promiseWithResolvers() {
|
|
let resolve;
|
|
let reject;
|
|
const promise = new Promise((res, rej) => {
|
|
resolve = res;
|
|
reject = rej;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
var init_promise = __esm({
|
|
"node_modules/@anthropic-ai/sdk/internal/utils/promise.mjs"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs
|
|
function rejectCompactionParam(params) {
|
|
if ("compaction" in params && params.compaction != null) {
|
|
throw new AnthropicError("`compaction` cannot be set on a tool runner: every request in the loop would compact again. Call `runner.compactBeforeNextTurn()` when the conversation should be compacted instead.");
|
|
}
|
|
}
|
|
function rejectCompactionControl(params) {
|
|
if ("compactionControl" in params && params.compactionControl != null) {
|
|
throw new AnthropicError("`compactionControl` has been removed from the tool runner. Use server-side compaction instead: call `runner.compactBeforeNextTurn()` when the conversation should be compacted.");
|
|
}
|
|
}
|
|
function rejectRunToolsEagerlyWithoutStream(params) {
|
|
if (params.runToolsEagerly && !params.stream) {
|
|
throw new TypeError("`runToolsEagerly: true` needs `stream: true` in the tool runner's params, because a reply that isn't streamed arrives whole.");
|
|
}
|
|
}
|
|
function rejectCompactionEdit(params) {
|
|
if (params.context_management?.edits?.some((edit) => edit.type.startsWith("compact_"))) {
|
|
throw new AnthropicError("`compactBeforeNextTurn()` can't be used while `context_management` has a compaction edit, because the API doesn't accept a compaction block together with one. Remove the edit first.");
|
|
}
|
|
}
|
|
function withoutCompactionIncompatibleParams(params) {
|
|
const { context_management, stop_sequences, output_format, ...kept } = params;
|
|
const withoutFormat = ({ format, ...outputConfig }) => outputConfig;
|
|
if (kept.tool_choice?.type === "any" || kept.tool_choice?.type === "tool") {
|
|
delete kept.tool_choice;
|
|
}
|
|
if (kept.output_config) {
|
|
kept.output_config = withoutFormat(kept.output_config);
|
|
}
|
|
if (Array.isArray(kept.fallbacks)) {
|
|
kept.fallbacks = kept.fallbacks.map((fallback2) => fallback2.output_config ? { ...fallback2, output_config: withoutFormat(fallback2.output_config) } : fallback2);
|
|
}
|
|
return kept;
|
|
}
|
|
async function generateToolResponse(runnable, available, lastMessage, requestOptions, calls) {
|
|
if (!lastMessage || lastMessage.role !== "assistant" || !lastMessage.content || typeof lastMessage.content === "string") {
|
|
return null;
|
|
}
|
|
const toolUseBlocks = lastMessage.content.filter((content) => content.type === "tool_use");
|
|
if (toolUseBlocks.length === 0) {
|
|
return null;
|
|
}
|
|
const toolResults = await Promise.all(toolUseBlocks.map((toolUse) => {
|
|
const call = calls?.get(toolUse.id);
|
|
if (call?.status === "started") {
|
|
return call.result;
|
|
}
|
|
const result = runToolCall(runnable, available, toolUse, requestOptions);
|
|
calls?.set(toolUse.id, { status: "started", result });
|
|
return result;
|
|
}));
|
|
return {
|
|
role: "user",
|
|
content: toolResults
|
|
};
|
|
}
|
|
async function runToolCall(runnable, available, toolUse, requestOptions) {
|
|
const tool = available.has(toolUse.name) ? runnable.get(toolUse.name) : void 0;
|
|
if (!tool) {
|
|
return toolNotFoundResult(toolUse);
|
|
}
|
|
try {
|
|
let input = toolUse.input;
|
|
if ("parse" in tool && tool.parse) {
|
|
input = tool.parse(input);
|
|
}
|
|
const result = await tool.run(input, {
|
|
toolUse,
|
|
toolUseBlock: toolUse,
|
|
signal: requestOptions?.signal
|
|
});
|
|
return {
|
|
type: "tool_result",
|
|
tool_use_id: toolUse.id,
|
|
content: result
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
type: "tool_result",
|
|
tool_use_id: toolUse.id,
|
|
content: error instanceof ToolError ? error.content : `Error: ${error instanceof Error ? error.message : String(error)}`,
|
|
is_error: true
|
|
};
|
|
}
|
|
}
|
|
function asContentParam(content) {
|
|
return content;
|
|
}
|
|
function toolNotFoundResult(toolUse) {
|
|
return {
|
|
type: "tool_result",
|
|
tool_use_id: toolUse.id,
|
|
content: `Error: Tool '${toolUse.name}' not found`,
|
|
is_error: true
|
|
};
|
|
}
|
|
function applyToolChange(block, available) {
|
|
switch (block.type) {
|
|
case "tool_removal":
|
|
case "tool_addition":
|
|
applyToolReference(block, available);
|
|
break;
|
|
}
|
|
}
|
|
function applyToolReference(block, available) {
|
|
const name = changedToolName(block.tool);
|
|
if (name === void 0)
|
|
return;
|
|
if (block.type === "tool_removal") {
|
|
available.delete(name);
|
|
} else {
|
|
available.add(name);
|
|
}
|
|
}
|
|
function changedToolName(tool) {
|
|
switch (tool.type) {
|
|
case "tool_reference":
|
|
return tool.name;
|
|
case "tool_definition":
|
|
return "name" in tool.definition ? tool.definition.name : void 0;
|
|
default:
|
|
return void 0;
|
|
}
|
|
}
|
|
function determineNextStepFromStopReason(stopReason) {
|
|
if (stopReason === null)
|
|
return "stop";
|
|
switch (stopReason) {
|
|
case "tool_use":
|
|
return "run_tools";
|
|
case "pause_turn":
|
|
// pause_after_compaction hands the turn back before the model answers; sending it back
|
|
// unchanged continues it.
|
|
case "compaction":
|
|
return "resume";
|
|
case "end_turn":
|
|
case "stop_sequence":
|
|
case "max_tokens":
|
|
case "model_context_window_exceeded":
|
|
case "refusal":
|
|
return "stop";
|
|
default:
|
|
checkNever(stopReason);
|
|
return "stop";
|
|
}
|
|
}
|
|
var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_stream, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_compaction, _BetaToolRunner_calls, _BetaToolRunner_lastStopReason, _BetaToolRunner_toolOverrides, _BetaToolRunner_pendingToolChanges, _BetaToolRunner_send, _BetaToolRunner_streamThatStartsTools, _BetaToolRunner_startedCallsSettled, _BetaToolRunner_compact, _BetaToolRunner_runnableTools, _BetaToolRunner_availableToolNames, _BetaToolRunner_recordRemovalsFromHistory, _BetaToolRunner_compactAfterFinalTurn, _BetaToolRunner_generateToolResponse, _BetaToolRunner_flushPendingToolChanges, _BetaToolRunner_pendingToolChangesMessage, BetaToolRunner;
|
|
var init_BetaToolRunner = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs"() {
|
|
init_tslib2();
|
|
init_ToolError();
|
|
init_error3();
|
|
init_BetaToolRunnerStream();
|
|
init_headers3();
|
|
init_promise();
|
|
init_values2();
|
|
init_log2();
|
|
init_stainless_helper_header();
|
|
BetaToolRunner = /* @__PURE__ */ (() => {
|
|
class BetaToolRunner2 {
|
|
constructor(client, params, options) {
|
|
_BetaToolRunner_instances.add(this);
|
|
this.client = client;
|
|
_BetaToolRunner_consumed.set(this, false);
|
|
_BetaToolRunner_mutated.set(this, false);
|
|
_BetaToolRunner_state.set(this, void 0);
|
|
_BetaToolRunner_options.set(this, void 0);
|
|
_BetaToolRunner_message.set(this, void 0);
|
|
_BetaToolRunner_stream.set(this, void 0);
|
|
_BetaToolRunner_toolResponse.set(this, void 0);
|
|
_BetaToolRunner_completion.set(this, void 0);
|
|
_BetaToolRunner_iterationCount.set(this, 0);
|
|
_BetaToolRunner_compaction.set(this, { status: "idle" });
|
|
_BetaToolRunner_calls.set(this, void 0);
|
|
_BetaToolRunner_lastStopReason.set(this, null);
|
|
_BetaToolRunner_toolOverrides.set(this, /* @__PURE__ */ new Map());
|
|
_BetaToolRunner_pendingToolChanges.set(this, []);
|
|
rejectCompactionParam(params);
|
|
rejectCompactionControl(params);
|
|
rejectRunToolsEagerlyWithoutStream(params);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_state, {
|
|
params: {
|
|
// You can't clone the entire params since there are functions as handlers.
|
|
// You also don't really need to clone params.messages, but it probably will prevent a foot gun
|
|
// somewhere.
|
|
...params,
|
|
// Not structuredClone(): it throws on a function, and a runnable tool written by value into a
|
|
// `tool_addition` block has `run`. A JSON copy is the messages as they are sent, which drops it.
|
|
messages: JSON.parse(JSON.stringify(params.messages))
|
|
}
|
|
}, "f");
|
|
const collected = collectStainlessHelpers(params.tools, params.messages);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_options, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
helperHeader("BetaToolRunner"),
|
|
collected.length ? { [STAINLESS_HELPER_HEADER]: collected.join(", ") } : void 0,
|
|
options?.headers
|
|
])
|
|
}, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
|
|
}
|
|
async *[(_BetaToolRunner_consumed = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_mutated = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_state = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_options = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_message = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_stream = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_toolResponse = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_completion = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_iterationCount = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_compaction = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_calls = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_lastStopReason = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_toolOverrides = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_pendingToolChanges = /* @__PURE__ */ new WeakMap(), _BetaToolRunner_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
var _a6;
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_consumed, "f")) {
|
|
throw new AnthropicError("Cannot iterate over a consumed stream");
|
|
}
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_consumed, true, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_mutated, true, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_toolResponse, void 0, "f");
|
|
try {
|
|
while (true) {
|
|
try {
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.max_iterations && __classPrivateFieldGet2(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.max_iterations) {
|
|
break;
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_flushPendingToolChanges).call(this);
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").status === "scheduled" && determineNextStepFromStopReason(__classPrivateFieldGet2(this, _BetaToolRunner_lastStopReason, "f")) !== "resume") {
|
|
yield* __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_compact).call(this, __classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").config);
|
|
continue;
|
|
}
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_mutated, false, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_toolResponse, void 0, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_iterationCount, (_a6 = __classPrivateFieldGet2(this, _BetaToolRunner_iterationCount, "f"), _a6++, _a6), "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_message, void 0, "f");
|
|
const { max_iterations, runToolsEagerly, ...params } = __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params;
|
|
yield* __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_send).call(this, params);
|
|
if (!__classPrivateFieldGet2(this, _BetaToolRunner_mutated, "f")) {
|
|
const message = await __classPrivateFieldGet2(this, _BetaToolRunner_message, "f");
|
|
const nextStep = determineNextStepFromStopReason(message.stop_reason);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_lastStopReason, message.stop_reason, "f");
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages.push({
|
|
role: message.role,
|
|
content: asContentParam(message.content)
|
|
});
|
|
const { container } = __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params;
|
|
if (message.container) {
|
|
if (container == null) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.container = message.container.id;
|
|
} else if (typeof container === "object" && container.id == null) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.container = { ...container, id: message.container.id };
|
|
}
|
|
}
|
|
if (nextStep === "stop") {
|
|
yield* __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_compactAfterFinalTurn).call(this);
|
|
break;
|
|
}
|
|
if (nextStep === "resume") {
|
|
continue;
|
|
}
|
|
} else {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_lastStopReason, null, "f");
|
|
}
|
|
const toolMessage = await __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages.at(-1));
|
|
if (toolMessage) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage);
|
|
} else if (!__classPrivateFieldGet2(this, _BetaToolRunner_mutated, "f")) {
|
|
yield* __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_compactAfterFinalTurn).call(this);
|
|
break;
|
|
}
|
|
} finally {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_stream, "f")?.abort();
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_stream, void 0, "f");
|
|
}
|
|
}
|
|
await __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_startedCallsSettled).call(this);
|
|
if (!__classPrivateFieldGet2(this, _BetaToolRunner_message, "f")) {
|
|
throw new AnthropicError("ToolRunner concluded without a message from the server");
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet2(this, _BetaToolRunner_message, "f"));
|
|
} catch (error) {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_consumed, false, "f");
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_completion, "f").promise.catch(() => {
|
|
});
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_completion, "f").reject(error);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
|
|
throw error;
|
|
}
|
|
}
|
|
setMessagesParams(paramsOrMutator) {
|
|
const params = typeof paramsOrMutator === "function" ? paramsOrMutator(__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params) : paramsOrMutator;
|
|
rejectCompactionParam(params);
|
|
rejectRunToolsEagerlyWithoutStream(params);
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").status !== "idle") {
|
|
rejectCompactionEdit(params);
|
|
}
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").status === "in_flight" && params.messages !== __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages) {
|
|
throw new AnthropicError("Message params can't be changed while the conversation is being compacted, because the compaction response is about to replace them. Change them after this iteration instead.");
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params = params;
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_mutated, true, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_toolResponse, void 0, "f");
|
|
}
|
|
setRequestOptions(optionsOrMutator) {
|
|
if (typeof optionsOrMutator === "function") {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_options, optionsOrMutator(__classPrivateFieldGet2(this, _BetaToolRunner_options, "f")), "f");
|
|
} else {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_options, { ...__classPrivateFieldGet2(this, _BetaToolRunner_options, "f"), ...optionsOrMutator }, "f");
|
|
}
|
|
}
|
|
/**
|
|
* Get the tool response for the last message from the assistant.
|
|
* Avoids redundant tool executions by caching results. With `runToolsEagerly`, it reuses the calls of
|
|
* the reply that have started and runs the rest, including the ones `deferToolCall()` is holding, so that no
|
|
* call runs twice.
|
|
*
|
|
* @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed
|
|
*
|
|
* @example
|
|
* const toolResponse = await runner.generateToolResponse();
|
|
* if (toolResponse) {
|
|
* console.log('Tool results:', toolResponse.content);
|
|
* }
|
|
*/
|
|
async generateToolResponse(signal = __classPrivateFieldGet2(this, _BetaToolRunner_options, "f").signal) {
|
|
const message = await __classPrivateFieldGet2(this, _BetaToolRunner_message, "f") ?? this.params.messages.at(-1);
|
|
if (!message) {
|
|
return null;
|
|
}
|
|
return __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message, signal);
|
|
}
|
|
/**
|
|
* Hold a tool call of the current reply until you are done with the reply, which is when it runs without
|
|
* streaming: at the end of the loop body, or when you call `generateToolResponse()`.
|
|
*
|
|
* With `runToolsEagerly` the runner otherwise starts each call while the reply streams, as soon as
|
|
* the model has moved on from it: when the next block starts, or the reply stops with `tool_use`. A call
|
|
* never starts before your stream listeners and any `for await` over the stream have handled that event, so
|
|
* you can call this from either once you have seen the call. The other calls of the reply still start early.
|
|
* It does nothing for a call that has started, outside the loop body, and without `runToolsEagerly`.
|
|
*
|
|
* @param toolUse - The `tool_use` block of the call, or its id
|
|
*
|
|
* @example
|
|
* for await (const stream of runner) {
|
|
* stream.on('contentBlock', (block) => {
|
|
* if (block.type === 'tool_use' && block.name === 'delete_file') {
|
|
* runner.deferToolCall(block);
|
|
* }
|
|
* });
|
|
* await stream.finalMessage();
|
|
* // No `delete_file` call has started yet.
|
|
* }
|
|
*/
|
|
deferToolCall(toolUse) {
|
|
const id = typeof toolUse === "string" ? toolUse : toolUse.id;
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_calls, "f") && !__classPrivateFieldGet2(this, _BetaToolRunner_calls, "f").has(id)) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_calls, "f").set(id, { status: "held" });
|
|
}
|
|
}
|
|
/**
|
|
* The tool calls of the current reply that `deferToolCall()` is holding, in the model's order, as their
|
|
* `tool_use` blocks. A call is in the list once its block has finished streaming, so read the list when you
|
|
* are done with the stream. A call that has started is not in it. It is empty without
|
|
* `runToolsEagerly`.
|
|
*
|
|
* Held calls are listed whatever the reply's `stop_reason`, because `generateToolResponse()` runs them
|
|
* whatever it is. After `max_tokens` the input of the last call can be cut off.
|
|
*
|
|
* @example
|
|
* for await (const stream of runner) {
|
|
* stream.on('contentBlock', (block) => {
|
|
* if (block.type === 'tool_use' && block.name === 'delete_file') {
|
|
* runner.deferToolCall(block);
|
|
* }
|
|
* });
|
|
* await stream.finalMessage();
|
|
*
|
|
* const held = runner.deferredToolCalls;
|
|
* if (held.length > 0 && !(await confirm(held))) break;
|
|
* }
|
|
*/
|
|
get deferredToolCalls() {
|
|
const stream4 = __classPrivateFieldGet2(this, _BetaToolRunner_stream, "f");
|
|
const calls = __classPrivateFieldGet2(this, _BetaToolRunner_calls, "f");
|
|
if (!(stream4 instanceof BetaToolRunnerStream) || !calls) {
|
|
return [];
|
|
}
|
|
return stream4.toolCalls.filter((toolUse) => calls.get(toolUse.id)?.status === "held");
|
|
}
|
|
/**
|
|
* Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and
|
|
* will wait for an instance to start and go to completion.
|
|
*
|
|
* @returns A promise that resolves to the final BetaMessage when the iterator completes
|
|
*
|
|
* @example
|
|
* // Start consuming the iterator
|
|
* for await (const message of runner) {
|
|
* console.log('Message:', message.content);
|
|
* }
|
|
*
|
|
* // Meanwhile, wait for completion from another part of the code
|
|
* const finalMessage = await runner.done();
|
|
* console.log('Final response:', finalMessage.content);
|
|
*/
|
|
done() {
|
|
return __classPrivateFieldGet2(this, _BetaToolRunner_completion, "f").promise;
|
|
}
|
|
/**
|
|
* Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream:
|
|
* * If the iterator has not been consumed, consume the entire iterator and return the final message from the
|
|
* assistant.
|
|
* * If the iterator has been consumed, waits for it to complete and returns the final message.
|
|
*
|
|
* @returns A promise that resolves to the final BetaMessage from the conversation
|
|
* @throws {AnthropicError} If no messages were processed during the conversation
|
|
*
|
|
* @example
|
|
* const finalMessage = await runner.runUntilDone();
|
|
* console.log('Final response:', finalMessage.content);
|
|
*/
|
|
async runUntilDone() {
|
|
if (!__classPrivateFieldGet2(this, _BetaToolRunner_consumed, "f")) {
|
|
for await (const _ of this) {
|
|
}
|
|
}
|
|
return this.done();
|
|
}
|
|
/**
|
|
* Get the current parameters being used by the ToolRunner.
|
|
*
|
|
* @returns A readonly view of the current ToolRunnerParams
|
|
*
|
|
* @example
|
|
* const currentParams = runner.params;
|
|
* console.log('Current model:', currentParams.model);
|
|
* console.log('Message count:', currentParams.messages.length);
|
|
*/
|
|
get params() {
|
|
return __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params;
|
|
}
|
|
/**
|
|
* Add one or more messages to the conversation history.
|
|
*
|
|
* @param messages - One or more BetaMessageParam objects to add to the conversation
|
|
*
|
|
* @example
|
|
* runner.pushMessages(
|
|
* { role: 'user', content: 'Also, what about the weather in NYC?' }
|
|
* );
|
|
*
|
|
* @example
|
|
* // Adding multiple messages
|
|
* runner.pushMessages(
|
|
* { role: 'user', content: 'What about NYC?' },
|
|
* { role: 'user', content: 'And Boston?' }
|
|
* );
|
|
*/
|
|
pushMessages(...messages) {
|
|
this.setMessagesParams((params) => ({
|
|
...params,
|
|
messages: [...params.messages, ...messages]
|
|
}));
|
|
}
|
|
/**
|
|
* Schedule a compaction of the conversation. Once the current turn has finished, including any tool
|
|
* calls, the runner requests a summary and replaces the message history with the compaction response,
|
|
* which is yielded like any other message. Requires the `compact-2026-09-04` beta.
|
|
*
|
|
* @param compaction - The config to send, as `messages.create()` takes it. Defaults to `{ type: 'summarize' }`
|
|
*
|
|
* @example
|
|
* for await (const message of runner) {
|
|
* if (message.usage.input_tokens > 100_000) {
|
|
* runner.compactBeforeNextTurn();
|
|
* }
|
|
* }
|
|
*/
|
|
compactBeforeNextTurn(compaction) {
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").status === "in_flight") {
|
|
return;
|
|
}
|
|
rejectCompactionEdit(__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_compaction, { status: "scheduled", config: compaction ?? { type: "summarize" } }, "f");
|
|
}
|
|
/**
|
|
* Give the model more tools without changing `params.tools`, which would miss the prompt cache.
|
|
*
|
|
* Each tool's whole definition is sent in a `tool_addition` block with the next request, and a
|
|
* runnable tool replaces a runnable tool of the same name straight away, even for a call already in
|
|
* the message being handled. A call that started while the reply streamed keeps the old one. A raw
|
|
* definition is only sent: the runner never runs it, and stops running a tool of the same name.
|
|
* Requires the `inline-tools-2026-09-15` beta, which the runner does not add for you.
|
|
*
|
|
* @param tools - Runnable tools (for example from `betaZodTool()`) or raw tool definitions
|
|
*
|
|
* @example
|
|
* runner.addTools(queryDatabaseTool);
|
|
*/
|
|
addTools(...tools) {
|
|
for (const tool of tools) {
|
|
if ("name" in tool) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_toolOverrides, "f").set(tool.name, "run" in tool ? tool : null);
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_pendingToolChanges, "f").push({ type: "addition", tool });
|
|
}
|
|
}
|
|
/**
|
|
* Take tools away from the model without changing `params.tools`, which would miss the prompt cache.
|
|
*
|
|
* The tools stop being run straight away: a call to one of them, even one in the message being
|
|
* handled, gets the same "not found" error result as a call to an unknown tool. A call that started
|
|
* while the reply streamed finishes as usual. The model is told in a `tool_removal` block with the
|
|
* next request. Use {@link addTools} to bring a tool back.
|
|
* Requires the `inline-tools-2026-09-15` beta, which the runner does not add for you.
|
|
*
|
|
* @param tools - The tools to remove, or their names
|
|
*
|
|
* @example
|
|
* runner.removeTools('query_database');
|
|
*/
|
|
removeTools(...tools) {
|
|
for (const tool of tools) {
|
|
const name = typeof tool === "string" ? tool : tool.name;
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_toolOverrides, "f").set(name, null);
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_pendingToolChanges, "f").push({ type: "removal", name });
|
|
}
|
|
}
|
|
/**
|
|
* Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone()
|
|
* This allows using `await runner` instead of `await runner.runUntilDone()`
|
|
*/
|
|
then(onfulfilled, onrejected) {
|
|
return this.runUntilDone().then(onfulfilled, onrejected);
|
|
}
|
|
}
|
|
_BetaToolRunner_send = /**
|
|
* Sends one request and yields its message, or its stream when streaming. `#message` and `#stream` are set
|
|
* before the yield, so they are there while the caller handles the item; the loop aborts the stream at the
|
|
* end of the iteration.
|
|
*/
|
|
async function* _BetaToolRunner_send2(params) {
|
|
await __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_startedCallsSettled).call(this);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_calls, void 0, "f");
|
|
if (params.stream) {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_stream, __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.runToolsEagerly ? __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_streamThatStartsTools).call(this, params) : this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet2(this, _BetaToolRunner_options, "f")), "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_message, __classPrivateFieldGet2(this, _BetaToolRunner_stream, "f").finalMessage(), "f");
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_message, "f").catch(() => {
|
|
});
|
|
yield __classPrivateFieldGet2(this, _BetaToolRunner_stream, "f");
|
|
} else {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet2(this, _BetaToolRunner_options, "f")), "f");
|
|
yield __classPrivateFieldGet2(this, _BetaToolRunner_message, "f");
|
|
}
|
|
}, _BetaToolRunner_streamThatStartsTools = function _BetaToolRunner_streamThatStartsTools2(params) {
|
|
const calls = /* @__PURE__ */ new Map();
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_calls, calls, "f");
|
|
return BetaToolRunnerStream.start(this.client.beta.messages, params, __classPrivateFieldGet2(this, _BetaToolRunner_options, "f"), (toolUse) => {
|
|
if (calls.has(toolUse.id)) {
|
|
return;
|
|
}
|
|
const result = runToolCall(__classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_runnableTools).call(this), __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_availableToolNames).call(this), toolUse, __classPrivateFieldGet2(this, _BetaToolRunner_options, "f"));
|
|
result.catch(() => {
|
|
});
|
|
calls.set(toolUse.id, { status: "started", result });
|
|
});
|
|
}, _BetaToolRunner_startedCallsSettled = /** Waits for the calls of the last streamed reply that have started, whether or not their results were sent. */
|
|
async function _BetaToolRunner_startedCallsSettled2() {
|
|
const started = [...__classPrivateFieldGet2(this, _BetaToolRunner_calls, "f")?.values() ?? []].filter((call) => call.status === "started");
|
|
await Promise.allSettled(started.map((call) => call.result));
|
|
}, _BetaToolRunner_compact = async function* _BetaToolRunner_compact2(compaction) {
|
|
rejectCompactionEdit(__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params);
|
|
const { max_iterations, runToolsEagerly, ...requestParams } = __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params;
|
|
const params = withoutCompactionIncompatibleParams(requestParams);
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_compaction, { status: "in_flight" }, "f");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_toolResponse, void 0, "f");
|
|
const lastMessage = __classPrivateFieldGet2(this, _BetaToolRunner_message, "f");
|
|
try {
|
|
yield* __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_send).call(this, { ...params, compaction });
|
|
const message = await __classPrivateFieldGet2(this, _BetaToolRunner_message, "f");
|
|
if (message.content.some((block) => block.type === "compaction" && block.content)) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_recordRemovalsFromHistory).call(this);
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages = [{ role: message.role, content: message.content }];
|
|
} else {
|
|
loggerFor2(this.client).warn("Compaction produced no summary; keeping the conversation as it is.");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_message, lastMessage, "f");
|
|
}
|
|
} finally {
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_compaction, { status: "idle" }, "f");
|
|
}
|
|
}, _BetaToolRunner_runnableTools = function _BetaToolRunner_runnableTools2() {
|
|
const runnable = /* @__PURE__ */ new Map();
|
|
for (const tool of __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.tools) {
|
|
if ("run" in tool) {
|
|
runnable.set(tool.name, tool);
|
|
}
|
|
}
|
|
for (const [name, tool] of __classPrivateFieldGet2(this, _BetaToolRunner_toolOverrides, "f")) {
|
|
if (tool) {
|
|
runnable.set(name, tool);
|
|
} else {
|
|
runnable.delete(name);
|
|
}
|
|
}
|
|
return runnable;
|
|
}, _BetaToolRunner_availableToolNames = function _BetaToolRunner_availableToolNames2() {
|
|
const available = new Set(__classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_runnableTools).call(this).keys());
|
|
for (const message of [...__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages, __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_pendingToolChangesMessage).call(this)]) {
|
|
if (typeof message.content === "string") {
|
|
continue;
|
|
}
|
|
for (const block of message.content) {
|
|
if (message.role === "system") {
|
|
applyToolChange(block, available);
|
|
} else if (message.role === "assistant" && block.type === "compaction") {
|
|
for (const change of block.tool_changes ?? []) {
|
|
applyToolChange(change, available);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return available;
|
|
}, _BetaToolRunner_recordRemovalsFromHistory = function _BetaToolRunner_recordRemovalsFromHistory2() {
|
|
const available = __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_availableToolNames).call(this);
|
|
for (const name of __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_runnableTools).call(this).keys()) {
|
|
if (!available.has(name)) {
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_toolOverrides, "f").set(name, null);
|
|
}
|
|
}
|
|
}, _BetaToolRunner_compactAfterFinalTurn = async function* _BetaToolRunner_compactAfterFinalTurn2() {
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").status !== "scheduled") {
|
|
return;
|
|
}
|
|
const lastContent = __classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages.at(-1)?.content;
|
|
if (Array.isArray(lastContent) && lastContent.some((block) => block.type === "tool_use")) {
|
|
loggerFor2(this.client).warn("The pending compaction was skipped because the last turn ended with tool calls that were not run. Call `compactBeforeNextTurn()` again if you continue the conversation.");
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_compaction, { status: "idle" }, "f");
|
|
return;
|
|
}
|
|
yield* __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_compact).call(this, __classPrivateFieldGet2(this, _BetaToolRunner_compaction, "f").config);
|
|
}, _BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse2(lastMessage, signal = __classPrivateFieldGet2(this, _BetaToolRunner_options, "f").signal) {
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_toolResponse, "f") !== void 0) {
|
|
return __classPrivateFieldGet2(this, _BetaToolRunner_toolResponse, "f");
|
|
}
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_runnableTools).call(this), __classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_availableToolNames).call(this), lastMessage, { ...__classPrivateFieldGet2(this, _BetaToolRunner_options, "f"), signal }, __classPrivateFieldGet2(this, _BetaToolRunner_calls, "f")), "f");
|
|
return __classPrivateFieldGet2(this, _BetaToolRunner_toolResponse, "f");
|
|
}, _BetaToolRunner_flushPendingToolChanges = function _BetaToolRunner_flushPendingToolChanges2() {
|
|
if (__classPrivateFieldGet2(this, _BetaToolRunner_lastStopReason, "f") === "pause_turn" || __classPrivateFieldGet2(this, _BetaToolRunner_pendingToolChanges, "f").length === 0) {
|
|
return;
|
|
}
|
|
__classPrivateFieldGet2(this, _BetaToolRunner_state, "f").params.messages.push(__classPrivateFieldGet2(this, _BetaToolRunner_instances, "m", _BetaToolRunner_pendingToolChangesMessage).call(this));
|
|
__classPrivateFieldSet2(this, _BetaToolRunner_pendingToolChanges, [], "f");
|
|
}, _BetaToolRunner_pendingToolChangesMessage = function _BetaToolRunner_pendingToolChangesMessage2() {
|
|
const content = [];
|
|
for (const change of __classPrivateFieldGet2(this, _BetaToolRunner_pendingToolChanges, "f")) {
|
|
if (change.type === "removal") {
|
|
content.push({ type: "tool_removal", tool: { type: "tool_reference", name: change.name } });
|
|
continue;
|
|
}
|
|
let definition = change.tool;
|
|
if ("run" in change.tool) {
|
|
const { run, parse: parse2, close, ...rest } = change.tool;
|
|
definition = rest;
|
|
}
|
|
content.push({ type: "tool_addition", tool: { type: "tool_definition", definition } });
|
|
}
|
|
return { role: "system", content };
|
|
};
|
|
return BetaToolRunner2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs
|
|
function transformOutputFormat(params) {
|
|
if (!params.output_format) {
|
|
return params;
|
|
}
|
|
if (params.output_config?.format) {
|
|
throw new AnthropicError("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");
|
|
}
|
|
const { output_format, ...rest } = params;
|
|
return {
|
|
...rest,
|
|
output_config: {
|
|
...params.output_config,
|
|
format: output_format
|
|
}
|
|
};
|
|
}
|
|
var DEPRECATED_MODELS, MODELS_TO_WARN_WITH_THINKING_ENABLED, Messages3;
|
|
var init_messages3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs"() {
|
|
init_error4();
|
|
init_batches2();
|
|
init_resource2();
|
|
init_constants();
|
|
init_headers3();
|
|
init_stainless_helper_header();
|
|
init_beta_parser();
|
|
init_BetaMessageStream();
|
|
init_BetaToolRunner();
|
|
init_ToolError();
|
|
init_batches2();
|
|
DEPRECATED_MODELS = {};
|
|
MODELS_TO_WARN_WITH_THINKING_ENABLED = ["claude-mythos-preview", "claude-opus-4-6"];
|
|
Messages3 = /* @__PURE__ */ (() => {
|
|
class Messages5 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.batches = new Batches2(this._client);
|
|
}
|
|
create(params, options) {
|
|
const modifiedParams = transformOutputFormat(params);
|
|
const { betas, user_profile_id, workspace_id, ...body } = modifiedParams;
|
|
if (body.model in DEPRECATED_MODELS) {
|
|
console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
|
|
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
|
|
}
|
|
if (MODELS_TO_WARN_WITH_THINKING_ENABLED.includes(body.model) && body.thinking && body.thinking.type === "enabled") {
|
|
console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
|
|
}
|
|
let timeout = options?.timeout ?? this._client._options.timeout;
|
|
if (!body.stream && timeout == null) {
|
|
const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0;
|
|
timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
|
|
}
|
|
const helperHeader2 = stainlessHelperHeader(body.tools, body.messages);
|
|
return this._client.post("/v1/messages?beta=true", {
|
|
body,
|
|
timeout: timeout ?? 6e5,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
helperHeader2,
|
|
options?.headers
|
|
]),
|
|
stream: modifiedParams.stream ?? false
|
|
});
|
|
}
|
|
/**
|
|
* Send a structured list of input messages with text and/or image content, along with an expected `output_format` and
|
|
* the response will be automatically parsed and available in the `parsed_output` property of the message.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const message = await client.beta.messages.parse({
|
|
* model: 'claude-3-5-sonnet-20241022',
|
|
* max_tokens: 1024,
|
|
* messages: [{ role: 'user', content: 'What is 2+2?' }],
|
|
* output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'),
|
|
* });
|
|
*
|
|
* console.log(message.parsed_output?.answer); // 4
|
|
* ```
|
|
*/
|
|
parse(params, options) {
|
|
options = {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ "anthropic-beta": [...params.betas ?? [], "structured-outputs-2025-12-15"].toString() },
|
|
options?.headers
|
|
])
|
|
};
|
|
return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console }));
|
|
}
|
|
/**
|
|
* Create a Message stream
|
|
*/
|
|
stream(body, options) {
|
|
return BetaMessageStream.createMessage(this, body, options);
|
|
}
|
|
/**
|
|
* Count the number of tokens in a Message.
|
|
*
|
|
* The Token Count API can be used to count the number of tokens in a Message,
|
|
* including tools, images, and documents, without creating it.
|
|
*
|
|
* Learn more about token counting in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaMessageTokensCount =
|
|
* await client.beta.messages.countTokens({
|
|
* messages: [{ content: 'Hello, world', role: 'user' }],
|
|
* model: 'claude-opus-5',
|
|
* });
|
|
* ```
|
|
*/
|
|
countTokens(params, options) {
|
|
const modifiedParams = transformOutputFormat(params);
|
|
const { betas, user_profile_id, workspace_id, ...body } = modifiedParams;
|
|
return this._client.post("/v1/messages/count_tokens?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "token-counting-2024-11-01"].toString(),
|
|
...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
toolRunner(body, options) {
|
|
return new BetaToolRunner(this._client, body, options);
|
|
}
|
|
}
|
|
Messages5.Batches = Batches2;
|
|
Messages5.BetaToolRunner = BetaToolRunner;
|
|
Messages5.ToolError = ToolError;
|
|
return Messages5;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/api-keys.mjs
|
|
var APIKeys3;
|
|
var init_api_keys3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/api-keys.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_path2();
|
|
APIKeys3 = class extends APIResource2 {
|
|
/**
|
|
* Get API Key
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaAPIKey =
|
|
* await client.beta.organization.apiKeys.retrieve(
|
|
* 'api_key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(apiKeyID, options) {
|
|
return this._client.get(path3`/v1/organizations/api_keys/${apiKeyID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* Update API Key
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaAPIKey =
|
|
* await client.beta.organization.apiKeys.update(
|
|
* 'api_key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(apiKeyID, body, options) {
|
|
return this._client.post(path3`/v1/organizations/api_keys/${apiKeyID}?beta=true`, { body, ...options });
|
|
}
|
|
/**
|
|
* List API Keys
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaAPIKey of client.beta.organization.apiKeys.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/v1/organizations/api_keys?beta=true", Page2, {
|
|
query,
|
|
...options
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/compliance-settings.mjs
|
|
var ComplianceSettings;
|
|
var init_compliance_settings = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/compliance-settings.mjs"() {
|
|
init_resource2();
|
|
ComplianceSettings = class extends APIResource2 {
|
|
/**
|
|
* Retrieve your organization's Compliance Settings.
|
|
*
|
|
* Compliance Settings is a singleton resource: there is exactly one per
|
|
* organization, addressed without an identifier. The `state` field reflects
|
|
* whether the Compliance API is enabled. An organization with a parent
|
|
* organization reads the state inherited from the parent's configuration.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaComplianceSettings =
|
|
* await client.beta.organization.complianceSettings.retrieve();
|
|
* ```
|
|
*/
|
|
retrieve(options) {
|
|
return this._client.get("/v1/organizations/compliance_settings?beta=true", options);
|
|
}
|
|
/**
|
|
* Update your organization's Compliance Settings.
|
|
*
|
|
* Setting `state` to `enabled` turns on the Compliance API and begins capturing
|
|
* organization activity events. Setting it to `disabled` turns both off. `state`
|
|
* reflects whether the Compliance API is enabled.
|
|
*
|
|
* A request that sets `state` to its current value succeeds and leaves the
|
|
* resource unchanged. A `disabled` request stays in effect until a later `enabled`
|
|
* request or the organization's next provisioning action that enables Access
|
|
* Transparency: enabling Access Transparency also enables the Compliance API,
|
|
* which serves its activity events, so such provisioning (including re-runs)
|
|
* re-enables the Compliance API even after a `disabled` request. Automated
|
|
* provisioning never disables compliance settings.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaComplianceSettings =
|
|
* await client.beta.organization.complianceSettings.update({
|
|
* state: { type: 'enabled' },
|
|
* });
|
|
* ```
|
|
*/
|
|
update(body, options) {
|
|
return this._client.post("/v1/organizations/compliance_settings?beta=true", { body, ...options });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/external-keys.mjs
|
|
var ExternalKeys;
|
|
var init_external_keys = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/external-keys.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_path2();
|
|
ExternalKeys = class extends APIResource2 {
|
|
/**
|
|
* Create an external key config owned by the caller's organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaExternalKey =
|
|
* await client.beta.organization.externalKeys.create({
|
|
* provider_config: {
|
|
* kms_arn:
|
|
* 'arn:aws:kms:us-east-1:111122223333:key/abcd1234-5678-90ab-cdef-000011112222',
|
|
* type: 'aws',
|
|
* },
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/v1/organizations/external_keys?beta=true", { body, ...options });
|
|
}
|
|
/**
|
|
* Retrieve a single external key config in the caller's organization by ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaExternalKey =
|
|
* await client.beta.organization.externalKeys.retrieve(
|
|
* 'external_key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(externalKeyID, options) {
|
|
return this._client.get(path3`/v1/organizations/external_keys/${externalKeyID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* Partially update an external key config. Omitted fields are left unchanged.
|
|
*
|
|
* `display_name` is always editable. `geo` and `provider_config` cannot be changed
|
|
* once any workspace references this config, because previously encrypted data
|
|
* requires the original key identity to decrypt.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaExternalKey =
|
|
* await client.beta.organization.externalKeys.update(
|
|
* 'external_key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(externalKeyID, body, options) {
|
|
return this._client.post(path3`/v1/organizations/external_keys/${externalKeyID}?beta=true`, {
|
|
body,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* List external key configs in the caller's organization.
|
|
*
|
|
* Results are ordered by creation time (newest first). Use the `next_page` cursor
|
|
* from the response to fetch subsequent pages.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaExternalKey of client.beta.organization.externalKeys.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/v1/organizations/external_keys?beta=true", PageCursor, {
|
|
query,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* Delete an external key config.
|
|
*
|
|
* The request is rejected if any workspace still references this config.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const externalKey =
|
|
* await client.beta.organization.externalKeys.delete(
|
|
* 'external_key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(externalKeyID, options) {
|
|
return this._client.delete(path3`/v1/organizations/external_keys/${externalKeyID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* Validate an external key config against the customer's KMS.
|
|
*
|
|
* Anthropic performs an encrypt/decrypt roundtrip against the configured KMS key
|
|
* and waits up to 30 seconds for the result. The response status is `success` if
|
|
* the roundtrip succeeded, or `failure` with an error message if it failed or
|
|
* timed out.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response =
|
|
* await client.beta.organization.externalKeys.validate(
|
|
* 'external_key_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
validate(externalKeyID, options) {
|
|
return this._client.post(path3`/v1/organizations/external_keys/${externalKeyID}/validate?beta=true`, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/invites.mjs
|
|
var Invites2;
|
|
var init_invites2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/invites.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_path2();
|
|
Invites2 = class extends APIResource2 {
|
|
/**
|
|
* Invite a user to join the organization by email.
|
|
*
|
|
* On plans that draw members from a finite pool of purchased seats, the invite
|
|
* automatically consumes a seat from the lowest tier with availability; there is
|
|
* no seat-tier parameter. When no seat is free the request fails with a 400 error
|
|
* rather than purchasing a seat.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaOrganizationInvite =
|
|
* await client.beta.organization.invites.create({
|
|
* email: 'user@emaildomain.com',
|
|
* role: 'user',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(body, options) {
|
|
return this._client.post("/v1/organizations/invites?beta=true", { body, ...options });
|
|
}
|
|
/**
|
|
* Retrieve an invite by ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaOrganizationInvite =
|
|
* await client.beta.organization.invites.retrieve(
|
|
* 'invite_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(inviteID, options) {
|
|
return this._client.get(path3`/v1/organizations/invites/${inviteID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* List the organization's invites.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaOrganizationInvite of client.beta.organization.invites.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/v1/organizations/invites?beta=true", Page2, {
|
|
query,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* Delete a pending invite.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const invite =
|
|
* await client.beta.organization.invites.delete(
|
|
* 'invite_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(inviteID, options) {
|
|
return this._client.delete(path3`/v1/organizations/invites/${inviteID}?beta=true`, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/rate-limits.mjs
|
|
var RateLimits2;
|
|
var init_rate_limits2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/rate-limits.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
RateLimits2 = class extends APIResource2 {
|
|
/**
|
|
* List Messages API rate limits for your organization.
|
|
*
|
|
* Each entry corresponds to one rate-limit group (either a model family or an
|
|
* API-surface category such as the Files API or Message Batches) and contains the
|
|
* set of limiter values that apply to it.
|
|
*
|
|
* When `limit` is omitted, every matching entry is returned in a single page; when
|
|
* `limit` truncates the result, follow `next_page` to fetch the remaining entries.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaOrganizationRateLimit of client.beta.organization.rateLimits.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/v1/organizations/rate_limits?beta=true", PageCursor, { query, ...options });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/users.mjs
|
|
var Users4;
|
|
var init_users4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/users.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_path2();
|
|
Users4 = class extends APIResource2 {
|
|
/**
|
|
* Retrieve a member of the organization by user ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaOrganizationUser =
|
|
* await client.beta.organization.users.retrieve('user_id');
|
|
* ```
|
|
*/
|
|
retrieve(userID, options) {
|
|
return this._client.get(path3`/v1/organizations/users/${userID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* Update a member's organization role.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaOrganizationUser =
|
|
* await client.beta.organization.users.update('user_id', {
|
|
* role: 'user',
|
|
* });
|
|
* ```
|
|
*/
|
|
update(userID, body, options) {
|
|
return this._client.post(path3`/v1/organizations/users/${userID}?beta=true`, { body, ...options });
|
|
}
|
|
/**
|
|
* List the organization's members.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaOrganizationUser of client.beta.organization.users.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/v1/organizations/users?beta=true", Page2, {
|
|
query,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* Remove a member from the organization.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const user = await client.beta.organization.users.remove(
|
|
* 'user_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
remove(userID, options) {
|
|
return this._client.delete(path3`/v1/organizations/users/${userID}?beta=true`, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/issuers.mjs
|
|
var Issuers;
|
|
var init_issuers = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/issuers.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Issuers = class extends APIResource2 {
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Register an OIDC issuer that Anthropic will trust for workload identity
|
|
* federation in your organization.
|
|
*
|
|
* The `jwks` field controls how the issuer's signing keys are obtained and takes
|
|
* one of three shapes selected by `type`: `discovery` (resolve keys through OIDC
|
|
* discovery), `explicit_url` (fetch keys from a fixed JWKS URL), or `inline`
|
|
* (provide a static key set). When `jwks.type` is `discovery` and no
|
|
* `discovery_base` is set, the issuer URL must be publicly reachable over HTTPS so
|
|
* Anthropic can fetch the discovery document; for `explicit_url` and `inline`
|
|
* modes the issuer URL is only matched as the JWT's `iss` claim and is not
|
|
* fetched.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationIssuer =
|
|
* await client.beta.organization.federation.issuers.create({
|
|
* issuer_url: 'x',
|
|
* name: 'x',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post("/v1/organizations/federation_issuers?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Retrieve a federation issuer by its ID (`fdis_...`).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationIssuer =
|
|
* await client.beta.organization.federation.issuers.retrieve(
|
|
* 'federation_issuer_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(federationIssuerID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.get(path3`/v1/organizations/federation_issuers/${federationIssuerID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Partially update a federation issuer.
|
|
*
|
|
* Setting `jwks` replaces the full JWKS shape at once. Archived issuers cannot be
|
|
* updated; this returns 400. Create a new issuer instead.
|
|
*
|
|
* Updating an issuer that backs a rule with a scope outside `workspace:developer`
|
|
* or `workspace:inference` requires a Console session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationIssuer =
|
|
* await client.beta.organization.federation.issuers.update(
|
|
* 'federation_issuer_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(federationIssuerID, params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/federation_issuers/${federationIssuerID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* List federation issuers in your organization.
|
|
*
|
|
* Archived issuers are excluded unless `include_archived=true`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaFederationIssuer of client.beta.organization.federation.issuers.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/organizations/federation_issuers?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Archive a federation issuer.
|
|
*
|
|
* Idempotent; re-archiving returns the issuer with its original `archived_at`.
|
|
* Rejected with 400 if any live (non-archived) federation rule still references
|
|
* the issuer; archive those rules first (a rule's issuer cannot be changed), or
|
|
* recreate them against another issuer.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationIssuer =
|
|
* await client.beta.organization.federation.issuers.archive(
|
|
* 'federation_issuer_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(federationIssuerID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.post(path3`/v1/organizations/federation_issuers/${federationIssuerID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/rules/workspaces.mjs
|
|
var Workspaces;
|
|
var init_workspaces = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/rules/workspaces.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Workspaces = class extends APIResource2 {
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* List workspaces where this federation rule is enabled.
|
|
*
|
|
* Returns all workspace enablements in a single response; the `limit` and `page`
|
|
* parameters are accepted but have no effect, and `next_page` is always `null`.
|
|
* Returns explicit per-workspace enablements only; for rules with
|
|
* `applies_to_all_workspaces` or a legacy single `workspace_id`, check those
|
|
* fields on the rule itself.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaFederationRuleWorkspace of client.beta.organization.federation.rules.workspaces.list(
|
|
* 'federation_rule_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(federationRuleID, params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/organizations/federation_rules/${federationRuleID}/workspaces?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Enable a federation rule for a workspace.
|
|
*
|
|
* Idempotent; re-enabling returns the existing enablement. The rule and workspace
|
|
* must both belong to your organization. Membership of the rule's target service
|
|
* account in this workspace is not checked at enablement: token exchange into this
|
|
* workspace is rejected unless the target is a member (it is implicitly a member
|
|
* of the default workspace). Archived rules are rejected with 400. OAuth callers
|
|
* may only manage rules whose `oauth_scope` is `workspace:developer` or
|
|
* `workspace:inference`; other scopes require a Console session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationRuleWorkspace =
|
|
* await client.beta.organization.federation.rules.workspaces.add(
|
|
* 'federation_rule_id',
|
|
* { workspace_id: 'workspace_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
add(federationRuleID, params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/federation_rules/${federationRuleID}/workspaces?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Disable a federation rule for a workspace.
|
|
*
|
|
* Idempotent; succeeds even if the enablement was already removed. OAuth callers
|
|
* may only manage rules whose `oauth_scope` is `workspace:developer` or
|
|
* `workspace:inference`; other scopes require a Console session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const workspace =
|
|
* await client.beta.organization.federation.rules.workspaces.remove(
|
|
* 'workspace_id',
|
|
* { federation_rule_id: 'federation_rule_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
remove(workspaceID, params, options) {
|
|
const { federation_rule_id, betas } = params;
|
|
return this._client.delete(path3`/v1/organizations/federation_rules/${federation_rule_id}/workspaces/${workspaceID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/rules/rules.mjs
|
|
var Rules;
|
|
var init_rules = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/rules/rules.mjs"() {
|
|
init_resource2();
|
|
init_workspaces();
|
|
init_workspaces();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Rules = /* @__PURE__ */ (() => {
|
|
class Rules2 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.workspaces = new Workspaces(this._client);
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Create a federation rule owned by your organization.
|
|
*
|
|
* The referenced issuer and the target service account must already exist in the
|
|
* same organization; invalid references are rejected with a 400 error. The
|
|
* workspace reference is validated. Membership is not checked at rule creation:
|
|
* token exchange resolves a single enabled workspace per call and is rejected
|
|
* unless the target service account is a member of that workspace (it is
|
|
* implicitly a member of the default workspace). Rules on well-known shared
|
|
* issuers (GitHub Actions, GitLab, Buildkite, Terraform Cloud, Google) must
|
|
* constrain tenant identity via an identity-bearing claim, a tenant-pinning
|
|
* subject prefix (such as `repo:YOUR_ORG/...`), or a CEL condition referencing one
|
|
* of those identity claims (e.g. `claims.repository_owner`). OAuth callers may
|
|
* only manage rules whose `oauth_scope` is `workspace:developer` or
|
|
* `workspace:inference`; other scopes require a Console session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationRule =
|
|
* await client.beta.organization.federation.rules.create({
|
|
* issuer_id: 'issuer_id',
|
|
* match: {},
|
|
* name: 'x',
|
|
* oauth_scope: 'x',
|
|
* target: {
|
|
* service_account_id: 'svac_01SDCCSbTxrXDpWc1phhtcfK',
|
|
* type: 'service_account',
|
|
* },
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post("/v1/organizations/federation_rules?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Retrieve a federation rule by its ID (`fdrl_...`).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationRule =
|
|
* await client.beta.organization.federation.rules.retrieve(
|
|
* 'federation_rule_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(federationRuleID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.get(path3`/v1/organizations/federation_rules/${federationRuleID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Partially update a federation rule.
|
|
*
|
|
* `issuer_id` is immutable. `match` and `target` are replaced as whole objects
|
|
* when set. Referenced service accounts and workspaces must exist in your
|
|
* organization; invalid references are rejected with a 400 error. Archived rules
|
|
* cannot be updated; this returns 400. Create a new rule instead. Rules on
|
|
* well-known shared issuers (GitHub Actions, GitLab, Buildkite, Terraform Cloud,
|
|
* Google) must constrain tenant identity via an identity-bearing claim, a
|
|
* tenant-pinning subject prefix (such as `repo:YOUR_ORG/...`), or a CEL condition
|
|
* referencing one of those identity claims (e.g. `claims.repository_owner`). On
|
|
* these issuers the requirement is re-checked on every update; if an existing
|
|
* rule's stored match does not yet constrain tenant identity, any update (even a
|
|
* rename or description change) must also supply a conforming `match` in the same
|
|
* request. OAuth callers may only manage rules whose `oauth_scope` is
|
|
* `workspace:developer` or `workspace:inference`; other scopes require a Console
|
|
* session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationRule =
|
|
* await client.beta.organization.federation.rules.update(
|
|
* 'federation_rule_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(federationRuleID, params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/federation_rules/${federationRuleID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* List federation rules in your organization.
|
|
*
|
|
* Optionally filter by issuer with `issuer_id`. Archived rules are excluded unless
|
|
* `include_archived=true`.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaFederationRule of client.beta.organization.federation.rules.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/organizations/federation_rules?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Archive a federation rule.
|
|
*
|
|
* Token exchange through this rule stops immediately. Idempotent; re-archiving
|
|
* returns the rule with its original `archived_at`. Archiving clears the rule's
|
|
* workspace targeting (`workspace_id` and `workspace_ids` are emptied). Tokens
|
|
* already minted before archive remain valid until they expire. OAuth callers may
|
|
* only manage rules whose `oauth_scope` is `workspace:developer` or
|
|
* `workspace:inference`; other scopes require a Console session.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaFederationRule =
|
|
* await client.beta.organization.federation.rules.archive(
|
|
* 'federation_rule_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(federationRuleID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.post(path3`/v1/organizations/federation_rules/${federationRuleID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Rules2.Workspaces = Workspaces;
|
|
return Rules2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/federation.mjs
|
|
var Federation;
|
|
var init_federation = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/federation/federation.mjs"() {
|
|
init_resource2();
|
|
init_issuers();
|
|
init_issuers();
|
|
init_rules();
|
|
init_rules();
|
|
Federation = /* @__PURE__ */ (() => {
|
|
class Federation2 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.issuers = new Issuers(this._client);
|
|
this.rules = new Rules(this._client);
|
|
}
|
|
}
|
|
Federation2.Issuers = Issuers;
|
|
Federation2.Rules = Rules;
|
|
return Federation2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/service-accounts/workspaces.mjs
|
|
var Workspaces2;
|
|
var init_workspaces2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/service-accounts/workspaces.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Workspaces2 = class extends APIResource2 {
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* List the workspaces a service account is a member of.
|
|
*
|
|
* Each entry includes the service account's `workspace_role` in that workspace.
|
|
* Use `limit` and the `next_page` cursor to paginate. When the service account has
|
|
* no explicit default-workspace membership, the implicit (`implicit: true`)
|
|
* membership is returned as the first entry on the first page; with `limit=1` the
|
|
* first page may return up to 2 entries (the implicit entry plus one explicit
|
|
* membership) so a pagination cursor can be derived. Memberships are returned only
|
|
* while the service account is active. Without a `page` cursor, an archived
|
|
* service account returns an empty list. A `page` cursor that does not match an
|
|
* active membership returns a 400 invalid-request error. A cursor stops matching
|
|
* when the membership is removed, the workspace is deleted, or the service account
|
|
* is archived. Restart pagination from the first page to recover.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaServiceAccountWorkspaceMember of client.beta.organization.serviceAccounts.workspaces.list(
|
|
* 'service_account_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(serviceAccountID, params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/organizations/service_accounts/${serviceAccountID}/workspaces?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Add a service account to a workspace with the given `workspace_role`.
|
|
*
|
|
* Mirror of `POST /workspaces/{workspace_id}/service_accounts`, addressed from the
|
|
* service-account side; both create the same membership. If the service account is
|
|
* already an explicit member of the workspace, its `workspace_role` is replaced
|
|
* with the value supplied here. Archived workspaces return 400. Archived service
|
|
* accounts cannot be added and are rejected.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccountWorkspaceMember =
|
|
* await client.beta.organization.serviceAccounts.workspaces.add(
|
|
* 'service_account_id',
|
|
* {
|
|
* workspace_id: 'workspace_id',
|
|
* workspace_role: 'workspace_admin',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
add(serviceAccountID, params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/service_accounts/${serviceAccountID}/workspaces?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Remove a service account from a workspace.
|
|
*
|
|
* Mirror of
|
|
* `DELETE /workspaces/{workspace_id}/service_accounts/{service_account_id}`,
|
|
* addressed from the service-account side. Removal is idempotent (returns 200 even
|
|
* if the membership was already removed). A DELETE against the implicit
|
|
* default-workspace membership returns 200 but is a no-op and the membership
|
|
* persists; deleting an explicit default-workspace row reverts to the implicit
|
|
* `workspace_user` membership. Archived workspaces return 400.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const workspace =
|
|
* await client.beta.organization.serviceAccounts.workspaces.remove(
|
|
* 'workspace_id',
|
|
* { service_account_id: 'service_account_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
remove(workspaceID, params, options) {
|
|
const { service_account_id, betas } = params;
|
|
return this._client.delete(path3`/v1/organizations/service_accounts/${service_account_id}/workspaces/${workspaceID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/service-accounts/service-accounts.mjs
|
|
var ServiceAccounts2;
|
|
var init_service_accounts2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/service-accounts/service-accounts.mjs"() {
|
|
init_resource2();
|
|
init_workspaces2();
|
|
init_workspaces2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
ServiceAccounts2 = /* @__PURE__ */ (() => {
|
|
class ServiceAccounts4 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.workspaces = new Workspaces2(this._client);
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Create a service account.
|
|
*
|
|
* A service account is a named workload identity that federation rules target.
|
|
* `organization_role` is `developer` (default) or `admin`; a rule may only be
|
|
* created or retargeted to grant `org:admin` scope when the target's
|
|
* `organization_role` is `admin`. Creating an `admin`-role service account
|
|
* requires an interactive credential (a user OAuth token or a Console session) — a
|
|
* workload may only create `developer`-role service accounts.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccount =
|
|
* await client.beta.organization.serviceAccounts.create({
|
|
* name: 'ci-deploy-bot',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post("/v1/organizations/service_accounts?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Retrieve a service account by its ID (`svac_...`).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccount =
|
|
* await client.beta.organization.serviceAccounts.retrieve(
|
|
* 'service_account_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(serviceAccountID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.get(path3`/v1/organizations/service_accounts/${serviceAccountID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Update a service account.
|
|
*
|
|
* Only `description` and `organization_role` are mutable; `name` cannot be
|
|
* changed. Archived service accounts cannot be updated; this returns 400. Setting
|
|
* `organization_role` to `admin` (even when unchanged) requires an interactive
|
|
* credential (a user OAuth token or a Console session).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccount =
|
|
* await client.beta.organization.serviceAccounts.update(
|
|
* 'service_account_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(serviceAccountID, params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/service_accounts/${serviceAccountID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* List service accounts in the caller's organization.
|
|
*
|
|
* Results are ordered by creation time, newest first. Use `limit` and the
|
|
* `next_page` cursor to paginate; set `include_archived=true` to include archived
|
|
* service accounts.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaServiceAccount of client.beta.organization.serviceAccounts.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/organizations/service_accounts?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Archive a service account.
|
|
*
|
|
* Idempotent; re-archiving returns the service account with its original
|
|
* `archived_at`. Rejected with 400 if any live (non-archived) federation rule
|
|
* still targets this service account, same as issuer archival; archive those rules
|
|
* first or change their target to another service account.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccount =
|
|
* await client.beta.organization.serviceAccounts.archive(
|
|
* 'service_account_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(serviceAccountID, params = {}, options) {
|
|
const { betas } = params ?? {};
|
|
return this._client.post(path3`/v1/organizations/service_accounts/${serviceAccountID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
ServiceAccounts4.Workspaces = Workspaces2;
|
|
return ServiceAccounts4;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/members.mjs
|
|
var Members;
|
|
var init_members = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/members.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_path2();
|
|
Members = class extends APIResource2 {
|
|
/**
|
|
* Get Workspace Member
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspaceMember =
|
|
* await client.beta.organization.workspaces.members.retrieve(
|
|
* 'user_id',
|
|
* { workspace_id: 'workspace_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(userID, params, options) {
|
|
const { workspace_id } = params;
|
|
return this._client.get(path3`/v1/organizations/workspaces/${workspace_id}/members/${userID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* Update Workspace Member
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspaceMember =
|
|
* await client.beta.organization.workspaces.members.update(
|
|
* 'user_id',
|
|
* {
|
|
* workspace_id: 'workspace_id',
|
|
* workspace_role: 'workspace_admin',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(userID, params, options) {
|
|
const { workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/workspaces/${workspace_id}/members/${userID}?beta=true`, {
|
|
body,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* List Workspace Members
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaWorkspaceMember of client.beta.organization.workspaces.members.list(
|
|
* 'workspace_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(workspaceID, query = {}, options) {
|
|
return this._client.getAPIList(path3`/v1/organizations/workspaces/${workspaceID}/members?beta=true`, Page2, { query, ...options });
|
|
}
|
|
/**
|
|
* Create Workspace Member
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspaceMember =
|
|
* await client.beta.organization.workspaces.members.add(
|
|
* 'workspace_id',
|
|
* {
|
|
* user_id: 'user_01WCz1FkmYMm4gnmykNKUu3Q',
|
|
* workspace_role: 'workspace_admin',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
add(workspaceID, body, options) {
|
|
return this._client.post(path3`/v1/organizations/workspaces/${workspaceID}/members?beta=true`, {
|
|
body,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* Delete Workspace Member
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const member =
|
|
* await client.beta.organization.workspaces.members.remove(
|
|
* 'user_id',
|
|
* { workspace_id: 'workspace_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
remove(userID, params, options) {
|
|
const { workspace_id } = params;
|
|
return this._client.delete(path3`/v1/organizations/workspaces/${workspace_id}/members/${userID}?beta=true`, options);
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/rate-limits.mjs
|
|
var RateLimits3;
|
|
var init_rate_limits3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/rate-limits.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_path2();
|
|
RateLimits3 = class extends APIResource2 {
|
|
/**
|
|
* List a workspace's rate limits.
|
|
*
|
|
* By default, returns only the groups and limiter types that have a
|
|
* workspace-level override. With `include_inherited=true`, returns every group
|
|
* with organization-level limits the workspace can see, listing for each the
|
|
* values it inherits from the organization as well as its own overrides. Each
|
|
* value's `source` says which it is.
|
|
*
|
|
* When `limit` is omitted, every matching entry is returned in a single page; when
|
|
* `limit` truncates the result, follow `next_page` to fetch the remaining entries.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaWorkspaceRateLimit of client.beta.organization.workspaces.rateLimits.list(
|
|
* 'workspace_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(workspaceID, query = {}, options) {
|
|
return this._client.getAPIList(path3`/v1/organizations/workspaces/${workspaceID}/rate_limits?beta=true`, PageCursor, { query, ...options });
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/service-accounts.mjs
|
|
var ServiceAccounts3;
|
|
var init_service_accounts3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/service-accounts.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
ServiceAccounts3 = class extends APIResource2 {
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Retrieve a service account's membership in a workspace.
|
|
*
|
|
* Returns the membership record, including the service account's `workspace_role`
|
|
* in this workspace. Archived workspaces return 400. For the default workspace,
|
|
* returns the implicit (`implicit: true`) membership when no explicit membership
|
|
* exists; an explicitly added membership is returned with its assigned role. An
|
|
* archived service account returns 404.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccountWorkspaceMember =
|
|
* await client.beta.organization.workspaces.serviceAccounts.retrieve(
|
|
* 'service_account_id',
|
|
* { workspace_id: 'workspace_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(serviceAccountID, params, options) {
|
|
const { workspace_id, betas } = params;
|
|
return this._client.get(path3`/v1/organizations/workspaces/${workspace_id}/service_accounts/${serviceAccountID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Change a service account's role in a workspace.
|
|
*
|
|
* The new `workspace_role` replaces the current one. Only explicit memberships can
|
|
* be updated; to set a role on the implicit default-workspace membership, add the
|
|
* service account explicitly with
|
|
* `POST /workspaces/{workspace_id}/service_accounts`. Archived workspaces
|
|
* return 400. Archived service accounts cannot be updated and are rejected.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccountWorkspaceMember =
|
|
* await client.beta.organization.workspaces.serviceAccounts.update(
|
|
* 'service_account_id',
|
|
* {
|
|
* workspace_id: 'workspace_id',
|
|
* workspace_role: 'workspace_admin',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(serviceAccountID, params, options) {
|
|
const { workspace_id, betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/workspaces/${workspace_id}/service_accounts/${serviceAccountID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* List the service accounts that are members of a workspace.
|
|
*
|
|
* Each entry includes the service account's `workspace_role`. Use `limit` and the
|
|
* `next_page` cursor to paginate. Archived workspaces return 400; use
|
|
* `GET /service_accounts/{id}/workspaces` to audit memberships of an archived
|
|
* workspace. The implicit default-workspace membership is not included in this
|
|
* list. Memberships of archived service accounts are omitted from the results.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaServiceAccountWorkspaceMember of client.beta.organization.workspaces.serviceAccounts.list(
|
|
* 'workspace_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(workspaceID, params = {}, options) {
|
|
const { betas, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/organizations/workspaces/${workspaceID}/service_accounts?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Add a service account to a workspace with the given `workspace_role`.
|
|
*
|
|
* The role determines what the service account can do in the workspace and which
|
|
* workspace-scoped permissions it can be granted when authenticating through
|
|
* federation. Every service account is already an implicit `workspace_user` member
|
|
* of the default workspace; adding it explicitly assigns a chosen role. If the
|
|
* service account is already an explicit member of the workspace, its
|
|
* `workspace_role` is replaced with the value supplied here. Archived workspaces
|
|
* return 400. Archived service accounts cannot be added and are rejected.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaServiceAccountWorkspaceMember =
|
|
* await client.beta.organization.workspaces.serviceAccounts.add(
|
|
* 'workspace_id',
|
|
* {
|
|
* service_account_id: 'service_account_id',
|
|
* workspace_role: 'workspace_admin',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
add(workspaceID, params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post(path3`/v1/organizations/workspaces/${workspaceID}/service_accounts?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* **Requires an OAuth access token with the `org:admin` scope**, from
|
|
* `ant auth login --scope org:admin` or a workload identity federation rule; Admin
|
|
* API keys are not accepted. See
|
|
* [Manage WIF with the Admin API](/docs/en/manage-claude/wif-admin-api).
|
|
*
|
|
* Remove a service account from a workspace.
|
|
*
|
|
* Removal is idempotent (returns 200 even if the membership was already removed).
|
|
* A DELETE against the implicit default-workspace membership returns 200 but is a
|
|
* no-op and the membership persists; deleting an explicit default-workspace row
|
|
* reverts to the implicit `workspace_user` membership. Archived workspaces
|
|
* return 400.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const serviceAccount =
|
|
* await client.beta.organization.workspaces.serviceAccounts.remove(
|
|
* 'service_account_id',
|
|
* { workspace_id: 'workspace_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
remove(serviceAccountID, params, options) {
|
|
const { workspace_id, betas } = params;
|
|
return this._client.delete(path3`/v1/organizations/workspaces/${workspace_id}/service_accounts/${serviceAccountID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/workspaces.mjs
|
|
var Workspaces3;
|
|
var init_workspaces3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/workspaces/workspaces.mjs"() {
|
|
init_resource2();
|
|
init_members();
|
|
init_members();
|
|
init_rate_limits3();
|
|
init_rate_limits3();
|
|
init_service_accounts3();
|
|
init_service_accounts3();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Workspaces3 = /* @__PURE__ */ (() => {
|
|
class Workspaces4 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.rateLimits = new RateLimits3(this._client);
|
|
this.members = new Members(this._client);
|
|
this.serviceAccounts = new ServiceAccounts3(this._client);
|
|
}
|
|
/**
|
|
* Create Workspace
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspace =
|
|
* await client.beta.organization.workspaces.create({
|
|
* name: 'x',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, ...body } = params;
|
|
return this._client.post("/v1/organizations/workspaces?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get Workspace
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspace =
|
|
* await client.beta.organization.workspaces.retrieve(
|
|
* 'workspace_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(workspaceID, options) {
|
|
return this._client.get(path3`/v1/organizations/workspaces/${workspaceID}?beta=true`, options);
|
|
}
|
|
/**
|
|
* Update Workspace
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspace =
|
|
* await client.beta.organization.workspaces.update(
|
|
* 'workspace_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(workspaceID, body, options) {
|
|
return this._client.post(path3`/v1/organizations/workspaces/${workspaceID}?beta=true`, {
|
|
body,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* List Workspaces
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaWorkspace of client.beta.organization.workspaces.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(query = {}, options) {
|
|
return this._client.getAPIList("/v1/organizations/workspaces?beta=true", Page2, {
|
|
query,
|
|
...options
|
|
});
|
|
}
|
|
/**
|
|
* Archive Workspace
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaWorkspace =
|
|
* await client.beta.organization.workspaces.archive(
|
|
* 'workspace_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(workspaceID, options) {
|
|
return this._client.post(path3`/v1/organizations/workspaces/${workspaceID}/archive?beta=true`, options);
|
|
}
|
|
}
|
|
Workspaces4.RateLimits = RateLimits3;
|
|
Workspaces4.Members = Members;
|
|
Workspaces4.ServiceAccounts = ServiceAccounts3;
|
|
return Workspaces4;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/organization/organization.mjs
|
|
var Organization2;
|
|
var init_organization2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/organization/organization.mjs"() {
|
|
init_resource2();
|
|
init_api_keys3();
|
|
init_api_keys3();
|
|
init_compliance_settings();
|
|
init_compliance_settings();
|
|
init_external_keys();
|
|
init_external_keys();
|
|
init_invites2();
|
|
init_invites2();
|
|
init_rate_limits2();
|
|
init_rate_limits2();
|
|
init_users4();
|
|
init_users4();
|
|
init_federation();
|
|
init_federation();
|
|
init_service_accounts2();
|
|
init_service_accounts2();
|
|
init_workspaces3();
|
|
init_workspaces3();
|
|
Organization2 = /* @__PURE__ */ (() => {
|
|
class Organization3 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.apiKeys = new APIKeys3(this._client);
|
|
this.externalKeys = new ExternalKeys(this._client);
|
|
this.federation = new Federation(this._client);
|
|
this.invites = new Invites2(this._client);
|
|
this.serviceAccounts = new ServiceAccounts2(this._client);
|
|
this.users = new Users4(this._client);
|
|
this.workspaces = new Workspaces3(this._client);
|
|
this.rateLimits = new RateLimits2(this._client);
|
|
this.complianceSettings = new ComplianceSettings(this._client);
|
|
}
|
|
/**
|
|
* Retrieve information about the organization associated with the authenticated
|
|
* API key.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaOrganization =
|
|
* await client.beta.organization.retrieve();
|
|
* ```
|
|
*/
|
|
retrieve(options) {
|
|
return this._client.get("/v1/organizations/me?beta=true", options);
|
|
}
|
|
}
|
|
Organization3.APIKeys = APIKeys3;
|
|
Organization3.ExternalKeys = ExternalKeys;
|
|
Organization3.Federation = Federation;
|
|
Organization3.Invites = Invites2;
|
|
Organization3.ServiceAccounts = ServiceAccounts2;
|
|
Organization3.Users = Users4;
|
|
Organization3.Workspaces = Workspaces3;
|
|
Organization3.RateLimits = RateLimits2;
|
|
Organization3.ComplianceSettings = ComplianceSettings;
|
|
return Organization3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/sessions/events.mjs
|
|
var Events2;
|
|
var init_events2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/sessions/events.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
init_SessionToolRunner();
|
|
Events2 = /* @__PURE__ */ (() => {
|
|
class Events4 extends APIResource2 {
|
|
/**
|
|
* List Events
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsSessionEvent of client.beta.sessions.events.list(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/sessions/${sessionID}/events?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Send Events
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSendSessionEvents =
|
|
* await client.beta.sessions.events.send(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* {
|
|
* events: [
|
|
* {
|
|
* content: [
|
|
* {
|
|
* text: 'Where is my order #1234?',
|
|
* type: 'text',
|
|
* },
|
|
* ],
|
|
* type: 'user.message',
|
|
* },
|
|
* ],
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
send(sessionID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/sessions/${sessionID}/events?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Stream Events
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsStreamSessionEvents =
|
|
* await client.beta.sessions.events.stream(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* );
|
|
* ```
|
|
*/
|
|
stream(sessionID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.get(path3`/v1/sessions/${sessionID}/events/stream?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
stream: true
|
|
});
|
|
}
|
|
/**
|
|
* Attach to a session and dispatch every incoming `agent.tool_use` and
|
|
* `agent.custom_tool_use` event to a local tool registry, sending the matching
|
|
* result back (`user.tool_result` / `user.custom_tool_result`). The
|
|
* sessions-side counterpart to `client.beta.messages.toolRunner`: yields one
|
|
* entry per completed tool call so callers can observe each dispatch (and
|
|
* `break` to abort cleanly).
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* import { betaAgentToolset20260401 } from '@anthropic-ai/sdk/tools/agent-toolset/node';
|
|
*
|
|
* for await (const call of client.beta.sessions.events.toolRunner(work.data.id, {
|
|
* tools: [...betaAgentToolset20260401({ workdir }), myTool],
|
|
* })) {
|
|
* console.log(`${call.name} -> ${call.isError ? 'error' : 'ok'}`);
|
|
* }
|
|
* ```
|
|
*/
|
|
toolRunner(sessionID, opts) {
|
|
return new SessionToolRunner(sessionID, { ...opts, client: this._client });
|
|
}
|
|
}
|
|
Events4.SessionToolRunner = SessionToolRunner;
|
|
return Events4;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/sessions/resources.mjs
|
|
var Resources;
|
|
var init_resources2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/sessions/resources.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Resources = class extends APIResource2 {
|
|
/**
|
|
* Get Session Resource
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const resource =
|
|
* await client.beta.sessions.resources.retrieve(
|
|
* 'sesrsc_011CZkZBJq5dWxk9fVLNcPht',
|
|
* { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(resourceID, params, options) {
|
|
const { session_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update Session Resource
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const resource =
|
|
* await client.beta.sessions.resources.update(
|
|
* 'sesrsc_011CZkZBJq5dWxk9fVLNcPht',
|
|
* {
|
|
* session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* authorization_token: 'ghp_exampletoken',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(resourceID, params, options) {
|
|
const { session_id, betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Session Resources
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsSessionResource of client.beta.sessions.resources.list(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/sessions/${sessionID}/resources?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Session Resource
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeleteSessionResource =
|
|
* await client.beta.sessions.resources.delete(
|
|
* 'sesrsc_011CZkZBJq5dWxk9fVLNcPht',
|
|
* { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(resourceID, params, options) {
|
|
const { session_id, betas, workspace_id } = params;
|
|
return this._client.delete(path3`/v1/sessions/${session_id}/resources/${resourceID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Add Session Resource
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsFileResource =
|
|
* await client.beta.sessions.resources.add(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* {
|
|
* file_id: 'file_011CNha8iCJcU1wXNR6q4V8w',
|
|
* type: 'file',
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
add(sessionID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/sessions/${sessionID}/resources?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/events.mjs
|
|
var Events3;
|
|
var init_events3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/events.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Events3 = class extends APIResource2 {
|
|
/**
|
|
* List Session Thread Events
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsSessionEvent of client.beta.sessions.threads.events.list(
|
|
* 'sthr_011CZkZVWa6oIjw0rgXZpnBt',
|
|
* { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(threadID, params, options) {
|
|
const { session_id, betas, workspace_id, ...query } = params;
|
|
return this._client.getAPIList(path3`/v1/sessions/${session_id}/threads/${threadID}/events?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Stream Session Thread Events
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsStreamSessionThreadEvents =
|
|
* await client.beta.sessions.threads.events.stream(
|
|
* 'sthr_011CZkZVWa6oIjw0rgXZpnBt',
|
|
* { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },
|
|
* );
|
|
* ```
|
|
*/
|
|
stream(threadID, params, options) {
|
|
const { session_id, betas, workspace_id, ...query } = params;
|
|
return this._client.get(path3`/v1/sessions/${session_id}/threads/${threadID}/stream?beta=true`, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
stream: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/threads.mjs
|
|
var Threads3;
|
|
var init_threads3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/sessions/threads/threads.mjs"() {
|
|
init_resource2();
|
|
init_events3();
|
|
init_events3();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Threads3 = /* @__PURE__ */ (() => {
|
|
class Threads4 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.events = new Events3(this._client);
|
|
}
|
|
/**
|
|
* Get Session Thread
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSessionThread =
|
|
* await client.beta.sessions.threads.retrieve(
|
|
* 'sthr_011CZkZVWa6oIjw0rgXZpnBt',
|
|
* { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(threadID, params, options) {
|
|
const { session_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/sessions/${session_id}/threads/${threadID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Session Threads
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsSessionThread of client.beta.sessions.threads.list(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(sessionID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/sessions/${sessionID}/threads?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive Session Thread
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSessionThread =
|
|
* await client.beta.sessions.threads.archive(
|
|
* 'sthr_011CZkZVWa6oIjw0rgXZpnBt',
|
|
* { session_id: 'sesn_011CZkZAtmR3yMPDzynEDxu7' },
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(threadID, params, options) {
|
|
const { session_id, betas, workspace_id } = params;
|
|
return this._client.post(path3`/v1/sessions/${session_id}/threads/${threadID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Threads4.Events = Events3;
|
|
return Threads4;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/sessions/sessions.mjs
|
|
var Sessions5;
|
|
var init_sessions5 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/sessions/sessions.mjs"() {
|
|
init_resource2();
|
|
init_events2();
|
|
init_events2();
|
|
init_resources2();
|
|
init_resources2();
|
|
init_threads3();
|
|
init_threads3();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Sessions5 = /* @__PURE__ */ (() => {
|
|
class Sessions6 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.events = new Events2(this._client);
|
|
this.resources = new Resources(this._client);
|
|
this.threads = new Threads3(this._client);
|
|
}
|
|
/**
|
|
* Create Session
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSession =
|
|
* await client.beta.sessions.create({
|
|
* agent: 'agent_011CZkYpogX7uDKUyvBTophP',
|
|
* environment_id: 'env_011CZkZ9X2dpNyB7HsEFoRfW',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/sessions?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get Session
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSession =
|
|
* await client.beta.sessions.retrieve(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(sessionID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/sessions/${sessionID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update Session
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSession =
|
|
* await client.beta.sessions.update(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(sessionID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/sessions/${sessionID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Sessions
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsSession of client.beta.sessions.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/sessions?beta=true", BidirectionalPageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Session
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeletedSession =
|
|
* await client.beta.sessions.delete(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(sessionID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/sessions/${sessionID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive Session
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsSession =
|
|
* await client.beta.sessions.archive(
|
|
* 'sesn_011CZkZAtmR3yMPDzynEDxu7',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(sessionID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/sessions/${sessionID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Sessions6.Events = Events2;
|
|
Sessions6.Resources = Resources;
|
|
Sessions6.Threads = Threads3;
|
|
return Sessions6;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs
|
|
var Versions3;
|
|
var init_versions3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_uploads4();
|
|
init_path2();
|
|
Versions3 = class extends APIResource2 {
|
|
/**
|
|
* Create Skill Version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSkillVersion =
|
|
* await client.beta.skills.versions.create('skill_id', {
|
|
* files: [fs.createReadStream('path/to/file')],
|
|
* });
|
|
* ```
|
|
*/
|
|
create(skillID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions2({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
}, this._client, false));
|
|
}
|
|
/**
|
|
* Get Skill Version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSkillVersion =
|
|
* await client.beta.skills.versions.retrieve('version', {
|
|
* skill_id: 'skill_id',
|
|
* });
|
|
* ```
|
|
*/
|
|
retrieve(version, params, options) {
|
|
const { skill_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/skills/${skill_id}/versions/${version}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Skill Versions
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaSkillVersion of client.beta.skills.versions.list(
|
|
* 'skill_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(skillID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/skills/${skillID}/versions?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Skill Version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDeletedSkillVersion =
|
|
* await client.beta.skills.versions.delete('version', {
|
|
* skill_id: 'skill_id',
|
|
* });
|
|
* ```
|
|
*/
|
|
delete(version, params, options) {
|
|
const { skill_id, betas, workspace_id } = params;
|
|
return this._client.delete(path3`/v1/skills/${skill_id}/versions/${version}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Download a skill version's content as a zip archive.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.beta.skills.versions.download(
|
|
* 'version',
|
|
* { skill_id: 'skill_id' },
|
|
* );
|
|
*
|
|
* const content = await response.blob();
|
|
* console.log(content);
|
|
* ```
|
|
*/
|
|
download(version, params, options) {
|
|
const { skill_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/skills/${skill_id}/versions/${version}/content?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
Accept: "application/binary",
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs
|
|
var Skills2;
|
|
var init_skills2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs"() {
|
|
init_resource2();
|
|
init_versions3();
|
|
init_versions3();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_uploads4();
|
|
init_path2();
|
|
Skills2 = /* @__PURE__ */ (() => {
|
|
class Skills4 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.versions = new Versions3(this._client);
|
|
}
|
|
/**
|
|
* Create Skill
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSkill = await client.beta.skills.create({
|
|
* files: [fs.createReadStream('path/to/file')],
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/skills?beta=true", multipartFormRequestOptions2({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
}, this._client, false));
|
|
}
|
|
/**
|
|
* Get Skill
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaSkill = await client.beta.skills.retrieve(
|
|
* 'skill_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(skillID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/skills/${skillID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Skills
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaSkill of client.beta.skills.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/skills?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Skill
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaDeletedSkill = await client.beta.skills.delete(
|
|
* 'skill_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(skillID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/skills/${skillID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Skills4.Versions = Versions3;
|
|
return Skills4;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/tunnels/certificates.mjs
|
|
var Certificates3;
|
|
var init_certificates3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/tunnels/certificates.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Certificates3 = class extends APIResource2 {
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Registers a public CA certificate on a tunnel. Anthropic verifies the gateway's
|
|
* server certificate against this CA when it terminates the inner TLS session. A
|
|
* tunnel holds at most two non-archived certificates.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnelCertificate =
|
|
* await client.beta.tunnels.certificates.create(
|
|
* 'tunnel_id',
|
|
* { ca_certificate_pem: 'ca_certificate_pem' },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(tunnelID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/tunnels/${tunnelID}/certificates?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Fetches a tunnel certificate by ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnelCertificate =
|
|
* await client.beta.tunnels.certificates.retrieve(
|
|
* 'certificate_id',
|
|
* { tunnel_id: 'tunnel_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(certificateID, params, options) {
|
|
const { tunnel_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/tunnels/${tunnel_id}/certificates/${certificateID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Lists the certificates registered on a tunnel. Archived certificates are
|
|
* excluded unless include_archived is set.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaTunnelCertificate of client.beta.tunnels.certificates.list(
|
|
* 'tunnel_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(tunnelID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/tunnels/${tunnelID}/certificates?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Archives a tunnel certificate, removing it from the set Anthropic trusts for the
|
|
* tunnel. The certificate record is retained. Archiving the last non-archived
|
|
* certificate is permitted; the tunnel rejects MCP traffic until a new certificate
|
|
* is added.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnelCertificate =
|
|
* await client.beta.tunnels.certificates.archive(
|
|
* 'certificate_id',
|
|
* { tunnel_id: 'tunnel_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(certificateID, params, options) {
|
|
const { tunnel_id, betas, workspace_id } = params;
|
|
return this._client.post(path3`/v1/tunnels/${tunnel_id}/certificates/${certificateID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/tunnels/tunnels.mjs
|
|
var Tunnels;
|
|
var init_tunnels = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/tunnels/tunnels.mjs"() {
|
|
init_resource2();
|
|
init_certificates3();
|
|
init_certificates3();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Tunnels = /* @__PURE__ */ (() => {
|
|
class Tunnels2 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.certificates = new Certificates3(this._client);
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Creates a tunnel. Creation allocates a fresh hostname and provisions the tunnel;
|
|
* it is not idempotent. The new tunnel rejects MCP traffic until at least one CA
|
|
* certificate is added.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnel = await client.beta.tunnels.create();
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/tunnels?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Fetches a tunnel by ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnel = await client.beta.tunnels.retrieve(
|
|
* 'tunnel_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(tunnelID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/tunnels/${tunnelID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Lists tunnels. Results are ordered by creation time, newest first; archived
|
|
* tunnels are excluded unless include_archived is set.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaTunnel of client.beta.tunnels.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/tunnels?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Archives a tunnel. Archival is irreversible: every non-archived certificate on
|
|
* the tunnel is archived in the same operation, the hostname is retired and never
|
|
* re-allocated, and the tunnel token is invalidated. Retrying against an
|
|
* already-archived tunnel returns the existing record unchanged.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnel = await client.beta.tunnels.archive(
|
|
* 'tunnel_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(tunnelID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/tunnels/${tunnelID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Reveals a tunnel's connector token. The value is fetched live on each call;
|
|
* Anthropic does not store it. Repeated calls return the same value until the
|
|
* token is rotated. Exposed as POST so the token does not appear in intermediary
|
|
* access logs.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnelToken =
|
|
* await client.beta.tunnels.revealToken('tunnel_id');
|
|
* ```
|
|
*/
|
|
revealToken(tunnelID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/tunnels/${tunnelID}/reveal_token?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* The Tunnels API is in research preview. It requires the
|
|
* `anthropic-beta: mcp-tunnels-2026-06-22` header and may change without a
|
|
* deprecation period. It supersedes the Admin API endpoints at
|
|
* `/v1/organizations/tunnels`, which remain available during a migration window.
|
|
*
|
|
* Rotates a tunnel's connector token. Rotation invalidates the current token for
|
|
* new connections and returns a fresh value; established connections are not
|
|
* severed. A connector restarted after rotation must use the new value.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaTunnelToken =
|
|
* await client.beta.tunnels.rotateToken('tunnel_id');
|
|
* ```
|
|
*/
|
|
rotateToken(tunnelID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/tunnels/${tunnelID}/rotate_token?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "mcp-tunnels-2026-06-22"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Tunnels2.Certificates = Certificates3;
|
|
return Tunnels2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/vaults/credentials.mjs
|
|
var Credentials2;
|
|
var init_credentials3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/vaults/credentials.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Credentials2 = class extends APIResource2 {
|
|
/**
|
|
* Create Credential
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsCredential =
|
|
* await client.beta.vaults.credentials.create(
|
|
* 'vlt_011CZkZDLs7fYzm1hXNPeRjv',
|
|
* {
|
|
* auth: {
|
|
* token: 'bearer_exampletoken',
|
|
* mcp_server_url:
|
|
* 'https://example-server.modelcontextprotocol.io/sse',
|
|
* type: 'static_bearer',
|
|
* },
|
|
* },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(vaultID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/vaults/${vaultID}/credentials?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get Credential
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsCredential =
|
|
* await client.beta.vaults.credentials.retrieve(
|
|
* 'vcrd_011CZkZEMt8gZan2iYOQfSkw',
|
|
* { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(credentialID, params, options) {
|
|
const { vault_id, betas, workspace_id } = params;
|
|
return this._client.get(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update Credential
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsCredential =
|
|
* await client.beta.vaults.credentials.update(
|
|
* 'vcrd_011CZkZEMt8gZan2iYOQfSkw',
|
|
* { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },
|
|
* );
|
|
* ```
|
|
*/
|
|
update(credentialID, params, options) {
|
|
const { vault_id, betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Credentials
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsCredential of client.beta.vaults.credentials.list(
|
|
* 'vlt_011CZkZDLs7fYzm1hXNPeRjv',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(vaultID, params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/vaults/${vaultID}/credentials?beta=true`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Credential
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeletedCredential =
|
|
* await client.beta.vaults.credentials.delete(
|
|
* 'vcrd_011CZkZEMt8gZan2iYOQfSkw',
|
|
* { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(credentialID, params, options) {
|
|
const { vault_id, betas, workspace_id } = params;
|
|
return this._client.delete(path3`/v1/vaults/${vault_id}/credentials/${credentialID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive Credential
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsCredential =
|
|
* await client.beta.vaults.credentials.archive(
|
|
* 'vcrd_011CZkZEMt8gZan2iYOQfSkw',
|
|
* { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(credentialID, params, options) {
|
|
const { vault_id, betas, workspace_id } = params;
|
|
return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Validate Credential
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsCredentialValidation =
|
|
* await client.beta.vaults.credentials.mcpOAuthValidate(
|
|
* 'vcrd_011CZkZEMt8gZan2iYOQfSkw',
|
|
* { vault_id: 'vlt_011CZkZDLs7fYzm1hXNPeRjv' },
|
|
* );
|
|
* ```
|
|
*/
|
|
mcpOAuthValidate(credentialID, params, options) {
|
|
const { vault_id, betas, workspace_id } = params;
|
|
return this._client.post(path3`/v1/vaults/${vault_id}/credentials/${credentialID}/mcp_oauth_validate?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/vaults/vaults.mjs
|
|
var Vaults2;
|
|
var init_vaults2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/vaults/vaults.mjs"() {
|
|
init_resource2();
|
|
init_credentials3();
|
|
init_credentials3();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Vaults2 = /* @__PURE__ */ (() => {
|
|
class Vaults3 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.credentials = new Credentials2(this._client);
|
|
}
|
|
/**
|
|
* Create Vault
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsVault =
|
|
* await client.beta.vaults.create({
|
|
* display_name: 'Example vault',
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/vaults?beta=true", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Get Vault
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsVault =
|
|
* await client.beta.vaults.retrieve(
|
|
* 'vlt_011CZkZDLs7fYzm1hXNPeRjv',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(vaultID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/vaults/${vaultID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Update Vault
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsVault =
|
|
* await client.beta.vaults.update(
|
|
* 'vlt_011CZkZDLs7fYzm1hXNPeRjv',
|
|
* );
|
|
* ```
|
|
*/
|
|
update(vaultID, params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/vaults/${vaultID}?beta=true`, {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Vaults
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const betaManagedAgentsVault of client.beta.vaults.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/vaults?beta=true", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Vault
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsDeletedVault =
|
|
* await client.beta.vaults.delete(
|
|
* 'vlt_011CZkZDLs7fYzm1hXNPeRjv',
|
|
* );
|
|
* ```
|
|
*/
|
|
delete(vaultID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/vaults/${vaultID}?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Archive Vault
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const betaManagedAgentsVault =
|
|
* await client.beta.vaults.archive(
|
|
* 'vlt_011CZkZDLs7fYzm1hXNPeRjv',
|
|
* );
|
|
* ```
|
|
*/
|
|
archive(vaultID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/vaults/${vaultID}/archive?beta=true`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
"anthropic-beta": [...betas ?? [], "managed-agents-2026-04-01"].toString(),
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Vaults3.Credentials = Credentials2;
|
|
return Vaults3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs
|
|
var Beta2;
|
|
var init_beta2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs"() {
|
|
init_resource2();
|
|
init_deployment_runs();
|
|
init_deployment_runs();
|
|
init_deployments();
|
|
init_deployments();
|
|
init_dreams();
|
|
init_dreams();
|
|
init_files5();
|
|
init_files5();
|
|
init_models3();
|
|
init_models3();
|
|
init_user_profiles();
|
|
init_user_profiles();
|
|
init_webhooks2();
|
|
init_webhooks2();
|
|
init_agents2();
|
|
init_agents2();
|
|
init_environments2();
|
|
init_environments2();
|
|
init_memory_stores();
|
|
init_memory_stores();
|
|
init_messages3();
|
|
init_messages3();
|
|
init_organization2();
|
|
init_organization2();
|
|
init_sessions5();
|
|
init_sessions5();
|
|
init_skills2();
|
|
init_skills2();
|
|
init_tunnels();
|
|
init_tunnels();
|
|
init_vaults2();
|
|
init_vaults2();
|
|
Beta2 = /* @__PURE__ */ (() => {
|
|
class Beta3 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.models = new Models2(this._client);
|
|
this.messages = new Messages3(this._client);
|
|
this.agents = new Agents2(this._client);
|
|
this.environments = new Environments2(this._client);
|
|
this.sessions = new Sessions5(this._client);
|
|
this.deployments = new Deployments(this._client);
|
|
this.deploymentRuns = new DeploymentRuns(this._client);
|
|
this.vaults = new Vaults2(this._client);
|
|
this.memoryStores = new MemoryStores(this._client);
|
|
this.files = new Files5(this._client);
|
|
this.skills = new Skills2(this._client);
|
|
this.webhooks = new Webhooks2(this._client);
|
|
this.userProfiles = new UserProfiles(this._client);
|
|
this.dreams = new Dreams(this._client);
|
|
this.tunnels = new Tunnels(this._client);
|
|
this.organization = new Organization2(this._client);
|
|
}
|
|
}
|
|
Beta3.Models = Models2;
|
|
Beta3.Messages = Messages3;
|
|
Beta3.Agents = Agents2;
|
|
Beta3.Environments = Environments2;
|
|
Beta3.Sessions = Sessions5;
|
|
Beta3.Deployments = Deployments;
|
|
Beta3.DeploymentRuns = DeploymentRuns;
|
|
Beta3.Vaults = Vaults2;
|
|
Beta3.MemoryStores = MemoryStores;
|
|
Beta3.Files = Files5;
|
|
Beta3.Skills = Skills2;
|
|
Beta3.Webhooks = Webhooks2;
|
|
Beta3.UserProfiles = UserProfiles;
|
|
Beta3.Dreams = Dreams;
|
|
Beta3.Tunnels = Tunnels;
|
|
Beta3.Organization = Organization2;
|
|
return Beta3;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/completions.mjs
|
|
var Completions3;
|
|
var init_completions4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/completions.mjs"() {
|
|
init_resource2();
|
|
init_headers3();
|
|
Completions3 = class extends APIResource2 {
|
|
create(params, options) {
|
|
const { betas, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/complete", {
|
|
body,
|
|
timeout: this._client._options.timeout ?? 6e5,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
stream: params.stream ?? false
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/files.mjs
|
|
var Files6;
|
|
var init_files6 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/files.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_stainless_helper_header();
|
|
init_uploads4();
|
|
init_path2();
|
|
Files6 = class extends APIResource2 {
|
|
/**
|
|
* List Files
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const fileMetadata of client.files.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/files", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete File
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const deletedFile = await client.files.delete('file_id');
|
|
* ```
|
|
*/
|
|
delete(fileID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/files/${fileID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Download File
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const response = await client.files.download('file_id');
|
|
*
|
|
* const content = await response.blob();
|
|
* console.log(content);
|
|
* ```
|
|
*/
|
|
download(fileID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/files/${fileID}/content`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
Accept: "application/binary",
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
__binaryResponse: true
|
|
});
|
|
}
|
|
/**
|
|
* Get File Metadata
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fileMetadata = await client.files.retrieveMetadata(
|
|
* 'file_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieveMetadata(fileID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/files/${fileID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Upload File
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const fileMetadata = await client.files.upload({
|
|
* file: fs.createReadStream('path/to/file'),
|
|
* });
|
|
* ```
|
|
*/
|
|
upload(params, options) {
|
|
const { workspace_id, ...body } = params;
|
|
return this._client.post("/v1/files", multipartFormRequestOptions2({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
stainlessHelperHeaderFromFile(body.file),
|
|
options?.headers
|
|
])
|
|
}, this._client));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/parser.mjs
|
|
function getOutputFormat2(params) {
|
|
return params?.output_config?.format;
|
|
}
|
|
function maybeParseMessage(message, params, opts) {
|
|
const outputFormat = getOutputFormat2(params);
|
|
if (!params || !("parse" in (outputFormat ?? {}))) {
|
|
return {
|
|
...message,
|
|
content: message.content.map((block) => {
|
|
if (block.type === "text") {
|
|
const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
|
|
value: null,
|
|
enumerable: false
|
|
});
|
|
return parsedBlock;
|
|
}
|
|
return block;
|
|
}),
|
|
parsed_output: null
|
|
};
|
|
}
|
|
return parseMessage(message, params, opts);
|
|
}
|
|
function parseMessage(message, params, opts) {
|
|
let firstParsedOutput = null;
|
|
const content = message.content.map((block) => {
|
|
if (block.type === "text") {
|
|
const parsedOutput = parseOutputFormat(params, block.text);
|
|
if (firstParsedOutput === null) {
|
|
firstParsedOutput = parsedOutput;
|
|
}
|
|
const parsedBlock = Object.defineProperty({ ...block }, "parsed_output", {
|
|
value: parsedOutput,
|
|
enumerable: false
|
|
});
|
|
return parsedBlock;
|
|
}
|
|
return block;
|
|
});
|
|
return {
|
|
...message,
|
|
content,
|
|
parsed_output: firstParsedOutput
|
|
};
|
|
}
|
|
function parseOutputFormat(params, content) {
|
|
const outputFormat = getOutputFormat2(params);
|
|
if (outputFormat?.type !== "json_schema") {
|
|
return null;
|
|
}
|
|
try {
|
|
if ("parse" in outputFormat) {
|
|
return outputFormat.parse(content);
|
|
}
|
|
return JSON.parse(content);
|
|
} catch (error) {
|
|
throw new AnthropicError(`Failed to parse structured output: ${error}`);
|
|
}
|
|
}
|
|
var init_parser4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/parser.mjs"() {
|
|
init_error3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs
|
|
function tracksToolInput2(content) {
|
|
return content.type === "tool_use" || content.type === "server_tool_use";
|
|
}
|
|
var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_workspace_id, _MessageStream_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, MessageStream;
|
|
var init_MessageStream = __esm({
|
|
"node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs"() {
|
|
init_tslib2();
|
|
init_stainless_helper_header();
|
|
init_errors2();
|
|
init_values2();
|
|
init_error4();
|
|
init_streaming4();
|
|
init_parser4();
|
|
init_message_stream_utils();
|
|
MessageStream = /* @__PURE__ */ (() => {
|
|
class MessageStream2 {
|
|
constructor(params, opts) {
|
|
_MessageStream_instances.add(this);
|
|
this.messages = [];
|
|
this.receivedMessages = [];
|
|
_MessageStream_currentMessageSnapshot.set(this, void 0);
|
|
_MessageStream_params.set(this, null);
|
|
this.controller = new AbortController();
|
|
_MessageStream_connectedPromise.set(this, void 0);
|
|
_MessageStream_resolveConnectedPromise.set(this, () => {
|
|
});
|
|
_MessageStream_rejectConnectedPromise.set(this, () => {
|
|
});
|
|
_MessageStream_endPromise.set(this, void 0);
|
|
_MessageStream_resolveEndPromise.set(this, () => {
|
|
});
|
|
_MessageStream_rejectEndPromise.set(this, () => {
|
|
});
|
|
_MessageStream_listeners.set(this, {});
|
|
_MessageStream_ended.set(this, false);
|
|
_MessageStream_errored.set(this, false);
|
|
_MessageStream_aborted.set(this, false);
|
|
_MessageStream_catchingPromiseCreated.set(this, false);
|
|
_MessageStream_response.set(this, void 0);
|
|
_MessageStream_request_id.set(this, void 0);
|
|
_MessageStream_workspace_id.set(this, void 0);
|
|
_MessageStream_logger.set(this, void 0);
|
|
_MessageStream_handleError.set(this, (error) => {
|
|
__classPrivateFieldSet2(this, _MessageStream_errored, true, "f");
|
|
if (isAbortError2(error)) {
|
|
error = new APIUserAbortError2();
|
|
}
|
|
if (error instanceof APIUserAbortError2) {
|
|
__classPrivateFieldSet2(this, _MessageStream_aborted, true, "f");
|
|
return this._emit("abort", error);
|
|
}
|
|
if (error instanceof AnthropicError) {
|
|
return this._emit("error", error);
|
|
}
|
|
if (error instanceof Error) {
|
|
const anthropicError = new AnthropicError(error.message);
|
|
anthropicError.cause = error;
|
|
return this._emit("error", anthropicError);
|
|
}
|
|
return this._emit("error", new AnthropicError(String(error)));
|
|
});
|
|
__classPrivateFieldSet2(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet2(this, _MessageStream_resolveConnectedPromise, resolve, "f");
|
|
__classPrivateFieldSet2(this, _MessageStream_rejectConnectedPromise, reject, "f");
|
|
}), "f");
|
|
__classPrivateFieldSet2(this, _MessageStream_endPromise, new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet2(this, _MessageStream_resolveEndPromise, resolve, "f");
|
|
__classPrivateFieldSet2(this, _MessageStream_rejectEndPromise, reject, "f");
|
|
}), "f");
|
|
__classPrivateFieldGet2(this, _MessageStream_connectedPromise, "f").catch(() => {
|
|
});
|
|
__classPrivateFieldGet2(this, _MessageStream_endPromise, "f").catch(() => {
|
|
});
|
|
__classPrivateFieldSet2(this, _MessageStream_params, params, "f");
|
|
__classPrivateFieldSet2(this, _MessageStream_logger, opts?.logger ?? console, "f");
|
|
}
|
|
get response() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_response, "f");
|
|
}
|
|
get request_id() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_request_id, "f");
|
|
}
|
|
get workspace_id() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_workspace_id, "f");
|
|
}
|
|
/**
|
|
* Returns the `MessageStream` data, the raw `Response` instance and the ID of the request,
|
|
* returned vie the `request-id` header which is useful for debugging requests and resporting
|
|
* issues to Anthropic.
|
|
*
|
|
* This is the same as the `APIPromise.withResponse()` method.
|
|
*
|
|
* This method will raise an error if you created the stream using `MessageStream.fromReadableStream`
|
|
* as no `Response` is available.
|
|
*/
|
|
async withResponse() {
|
|
__classPrivateFieldSet2(this, _MessageStream_catchingPromiseCreated, true, "f");
|
|
const response = await __classPrivateFieldGet2(this, _MessageStream_connectedPromise, "f");
|
|
if (!response) {
|
|
throw new Error("Could not resolve a `Response` object");
|
|
}
|
|
return {
|
|
data: this,
|
|
response,
|
|
request_id: response.headers.get("request-id"),
|
|
workspace_id: response.headers.get("anthropic-workspace-id")
|
|
};
|
|
}
|
|
/**
|
|
* Intended for use on the frontend, consuming a stream produced with
|
|
* `.toReadableStream()` on the backend.
|
|
*
|
|
* Note that messages sent to the model do not appear in `.on('message')`
|
|
* in this context.
|
|
*/
|
|
static fromReadableStream(stream4) {
|
|
const runner = new MessageStream2(null);
|
|
runner._run(() => runner._fromReadableStream(stream4));
|
|
return runner;
|
|
}
|
|
static createMessage(messages, params, options, { logger } = {}) {
|
|
const runner = new MessageStream2(params, { logger });
|
|
for (const message of params.messages) {
|
|
runner._addMessageParam(message);
|
|
}
|
|
__classPrivateFieldSet2(runner, _MessageStream_params, { ...params, stream: true }, "f");
|
|
runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: "stream" } }));
|
|
return runner;
|
|
}
|
|
_run(executor) {
|
|
executor().then(() => {
|
|
this._emitFinal();
|
|
this._emit("end");
|
|
}, __classPrivateFieldGet2(this, _MessageStream_handleError, "f"));
|
|
}
|
|
_addMessageParam(message) {
|
|
this.messages.push(message);
|
|
}
|
|
_addMessage(message, emit = true) {
|
|
this.receivedMessages.push(message);
|
|
if (emit) {
|
|
this._emit("message", message);
|
|
}
|
|
}
|
|
async _createMessage(messages, params, options) {
|
|
const signal = options?.signal;
|
|
let abortHandler;
|
|
if (signal) {
|
|
if (signal.aborted)
|
|
this.controller.abort();
|
|
abortHandler = this.controller.abort.bind(this.controller);
|
|
signal.addEventListener("abort", abortHandler);
|
|
}
|
|
try {
|
|
__classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
|
|
const { response, data: stream4 } = await messages.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }).withResponse();
|
|
this._connected(response);
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw new APIUserAbortError2();
|
|
}
|
|
__classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
|
|
} finally {
|
|
if (signal && abortHandler) {
|
|
signal.removeEventListener("abort", abortHandler);
|
|
}
|
|
}
|
|
}
|
|
_connected(response) {
|
|
if (this.ended)
|
|
return;
|
|
__classPrivateFieldSet2(this, _MessageStream_response, response, "f");
|
|
__classPrivateFieldSet2(this, _MessageStream_request_id, response?.headers.get("request-id"), "f");
|
|
__classPrivateFieldSet2(this, _MessageStream_workspace_id, response?.headers.get("anthropic-workspace-id"), "f");
|
|
__classPrivateFieldGet2(this, _MessageStream_resolveConnectedPromise, "f").call(this, response);
|
|
this._emit("connect");
|
|
}
|
|
get ended() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_ended, "f");
|
|
}
|
|
get errored() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_errored, "f");
|
|
}
|
|
get aborted() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_aborted, "f");
|
|
}
|
|
abort() {
|
|
this.controller.abort();
|
|
}
|
|
/**
|
|
* Adds the listener function to the end of the listeners array for the event.
|
|
* No checks are made to see if the listener has already been added. Multiple calls passing
|
|
* the same combination of event and listener will result in the listener being added, and
|
|
* called, multiple times.
|
|
* @returns this MessageStream, so that calls can be chained
|
|
*/
|
|
on(event, listener) {
|
|
const listeners = __classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event] = []);
|
|
listeners.push({ listener });
|
|
return this;
|
|
}
|
|
/**
|
|
* Removes the specified listener from the listener array for the event.
|
|
* off() will remove, at most, one instance of a listener from the listener array. If any single
|
|
* listener has been added multiple times to the listener array for the specified event, then
|
|
* off() must be called multiple times to remove each instance.
|
|
* @returns this MessageStream, so that calls can be chained
|
|
*/
|
|
off(event, listener) {
|
|
const listeners = __classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event];
|
|
if (!listeners)
|
|
return this;
|
|
const index = listeners.findIndex((l) => l.listener === listener);
|
|
if (index >= 0)
|
|
listeners.splice(index, 1);
|
|
return this;
|
|
}
|
|
/**
|
|
* Adds a one-time listener function for the event. The next time the event is triggered,
|
|
* this listener is removed and then invoked.
|
|
* @returns this MessageStream, so that calls can be chained
|
|
*/
|
|
once(event, listener) {
|
|
const listeners = __classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event] = []);
|
|
listeners.push({ listener, once: true });
|
|
return this;
|
|
}
|
|
/**
|
|
* This is similar to `.once()`, but returns a Promise that resolves the next time
|
|
* the event is triggered, instead of calling a listener callback.
|
|
* @returns a Promise that resolves the next time given event is triggered,
|
|
* or rejects if an error is emitted. (If you request the 'error' event,
|
|
* returns a promise that resolves with the error).
|
|
*
|
|
* Example:
|
|
*
|
|
* const message = await stream.emitted('message') // rejects if the stream errors
|
|
*/
|
|
emitted(event) {
|
|
return new Promise((resolve, reject) => {
|
|
__classPrivateFieldSet2(this, _MessageStream_catchingPromiseCreated, true, "f");
|
|
if (event !== "error")
|
|
this.once("error", reject);
|
|
this.once(event, resolve);
|
|
});
|
|
}
|
|
async done() {
|
|
__classPrivateFieldSet2(this, _MessageStream_catchingPromiseCreated, true, "f");
|
|
await __classPrivateFieldGet2(this, _MessageStream_endPromise, "f");
|
|
}
|
|
get currentMessage() {
|
|
return __classPrivateFieldGet2(this, _MessageStream_currentMessageSnapshot, "f");
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the the final assistant Message response,
|
|
* or rejects if an error occurred or the stream ended prematurely without producing a Message.
|
|
* If structured outputs were used, this will be a ParsedMessage with a `parsed_output` field.
|
|
*/
|
|
async finalMessage() {
|
|
await this.done();
|
|
return __classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this);
|
|
}
|
|
/**
|
|
* @returns a promise that resolves with the the final assistant Message's text response, concatenated
|
|
* together if there are more than one text blocks.
|
|
* Rejects if an error occurred or the stream ended prematurely without producing a Message.
|
|
*/
|
|
async finalText() {
|
|
await this.done();
|
|
return __classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this);
|
|
}
|
|
_emit(event, ...args) {
|
|
if (__classPrivateFieldGet2(this, _MessageStream_ended, "f"))
|
|
return;
|
|
if (event === "end") {
|
|
__classPrivateFieldSet2(this, _MessageStream_ended, true, "f");
|
|
__classPrivateFieldGet2(this, _MessageStream_resolveEndPromise, "f").call(this);
|
|
}
|
|
const listeners = __classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event];
|
|
if (listeners) {
|
|
__classPrivateFieldGet2(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once);
|
|
listeners.forEach(({ listener }) => listener(...args));
|
|
}
|
|
if (event === "abort") {
|
|
const error = args[0];
|
|
if (!__classPrivateFieldGet2(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
|
|
Promise.reject(error);
|
|
}
|
|
__classPrivateFieldGet2(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
|
|
__classPrivateFieldGet2(this, _MessageStream_rejectEndPromise, "f").call(this, error);
|
|
this._emit("end");
|
|
return;
|
|
}
|
|
if (event === "error") {
|
|
const error = args[0];
|
|
if (!__classPrivateFieldGet2(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) {
|
|
Promise.reject(error);
|
|
}
|
|
__classPrivateFieldGet2(this, _MessageStream_rejectConnectedPromise, "f").call(this, error);
|
|
__classPrivateFieldGet2(this, _MessageStream_rejectEndPromise, "f").call(this, error);
|
|
this._emit("end");
|
|
}
|
|
}
|
|
_emitFinal() {
|
|
const finalMessage = this.receivedMessages.at(-1);
|
|
if (finalMessage) {
|
|
this._emit("finalMessage", __classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this));
|
|
}
|
|
}
|
|
async _fromReadableStream(readableStream, options) {
|
|
const signal = options?.signal;
|
|
let abortHandler;
|
|
if (signal) {
|
|
if (signal.aborted)
|
|
this.controller.abort();
|
|
abortHandler = this.controller.abort.bind(this.controller);
|
|
signal.addEventListener("abort", abortHandler);
|
|
}
|
|
try {
|
|
__classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this);
|
|
this._connected(null);
|
|
const stream4 = Stream2.fromReadableStream(readableStream, this.controller);
|
|
for await (const event of stream4) {
|
|
__classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event);
|
|
}
|
|
if (stream4.controller.signal?.aborted) {
|
|
throw new APIUserAbortError2();
|
|
}
|
|
__classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this);
|
|
} finally {
|
|
if (signal && abortHandler) {
|
|
signal.removeEventListener("abort", abortHandler);
|
|
}
|
|
}
|
|
}
|
|
[(_MessageStream_currentMessageSnapshot = /* @__PURE__ */ new WeakMap(), _MessageStream_params = /* @__PURE__ */ new WeakMap(), _MessageStream_connectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_endPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _MessageStream_listeners = /* @__PURE__ */ new WeakMap(), _MessageStream_ended = /* @__PURE__ */ new WeakMap(), _MessageStream_errored = /* @__PURE__ */ new WeakMap(), _MessageStream_aborted = /* @__PURE__ */ new WeakMap(), _MessageStream_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _MessageStream_response = /* @__PURE__ */ new WeakMap(), _MessageStream_request_id = /* @__PURE__ */ new WeakMap(), _MessageStream_workspace_id = /* @__PURE__ */ new WeakMap(), _MessageStream_logger = /* @__PURE__ */ new WeakMap(), _MessageStream_handleError = /* @__PURE__ */ new WeakMap(), _MessageStream_instances = /* @__PURE__ */ new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage2() {
|
|
if (this.receivedMessages.length === 0) {
|
|
throw new AnthropicError("stream ended without producing a Message with role=assistant");
|
|
}
|
|
return this.receivedMessages.at(-1);
|
|
}, _MessageStream_getFinalText = function _MessageStream_getFinalText2() {
|
|
if (this.receivedMessages.length === 0) {
|
|
throw new AnthropicError("stream ended without producing a Message with role=assistant");
|
|
}
|
|
const textBlocks = this.receivedMessages.at(-1).content.filter((block) => block.type === "text").map((block) => block.text);
|
|
if (textBlocks.length === 0) {
|
|
throw new AnthropicError("stream ended without producing a content block with type=text");
|
|
}
|
|
return textBlocks.join(" ");
|
|
}, _MessageStream_beginRequest = function _MessageStream_beginRequest2() {
|
|
if (this.ended)
|
|
return;
|
|
__classPrivateFieldSet2(this, _MessageStream_currentMessageSnapshot, void 0, "f");
|
|
}, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent2(event) {
|
|
if (this.ended)
|
|
return;
|
|
const messageSnapshot = __classPrivateFieldGet2(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event);
|
|
this._emit("streamEvent", event, messageSnapshot);
|
|
switch (event.type) {
|
|
case "content_block_delta": {
|
|
const content = messageSnapshot.content.at(-1);
|
|
switch (event.delta.type) {
|
|
case "text_delta": {
|
|
if (content.type === "text") {
|
|
this._emit("text", event.delta.text, content.text || "");
|
|
}
|
|
break;
|
|
}
|
|
case "citations_delta": {
|
|
if (content.type === "text") {
|
|
this._emit("citation", event.delta.citation, content.citations ?? []);
|
|
}
|
|
break;
|
|
}
|
|
case "input_json_delta": {
|
|
if (tracksToolInput2(content) && __classPrivateFieldGet2(this, _MessageStream_listeners, "f").inputJson?.length) {
|
|
this._emit("inputJson", event.delta.partial_json, content.input);
|
|
}
|
|
break;
|
|
}
|
|
case "thinking_delta": {
|
|
if (content.type === "thinking") {
|
|
this._emit("thinking", event.delta.thinking, content.thinking);
|
|
}
|
|
break;
|
|
}
|
|
case "signature_delta": {
|
|
if (content.type === "thinking") {
|
|
this._emit("signature", content.signature);
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
checkNever(event.delta);
|
|
}
|
|
break;
|
|
}
|
|
case "message_stop": {
|
|
this._addMessageParam(messageSnapshot);
|
|
this._addMessage(maybeParseMessage(messageSnapshot, __classPrivateFieldGet2(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet2(this, _MessageStream_logger, "f") }), true);
|
|
break;
|
|
}
|
|
case "content_block_stop": {
|
|
this._emit("contentBlock", messageSnapshot.content.at(-1));
|
|
break;
|
|
}
|
|
case "message_start": {
|
|
__classPrivateFieldSet2(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f");
|
|
break;
|
|
}
|
|
case "content_block_start":
|
|
case "message_delta":
|
|
break;
|
|
}
|
|
}, _MessageStream_endRequest = function _MessageStream_endRequest2() {
|
|
if (this.ended) {
|
|
throw new AnthropicError(`stream has ended, this shouldn't happen`);
|
|
}
|
|
const snapshot = __classPrivateFieldGet2(this, _MessageStream_currentMessageSnapshot, "f");
|
|
if (!snapshot) {
|
|
throw new AnthropicError(`request ended without sending any chunks`);
|
|
}
|
|
__classPrivateFieldSet2(this, _MessageStream_currentMessageSnapshot, void 0, "f");
|
|
return maybeParseMessage(snapshot, __classPrivateFieldGet2(this, _MessageStream_params, "f"), { logger: __classPrivateFieldGet2(this, _MessageStream_logger, "f") });
|
|
}, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage2(event) {
|
|
let snapshot = __classPrivateFieldGet2(this, _MessageStream_currentMessageSnapshot, "f");
|
|
if (event.type === "message_start") {
|
|
if (snapshot) {
|
|
throw new AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`);
|
|
}
|
|
return event.message;
|
|
}
|
|
if (!snapshot) {
|
|
throw new AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`);
|
|
}
|
|
switch (event.type) {
|
|
case "message_stop":
|
|
return snapshot;
|
|
case "message_delta":
|
|
snapshot.stop_reason = event.delta.stop_reason;
|
|
snapshot.stop_sequence = event.delta.stop_sequence;
|
|
snapshot.stop_details = event.delta.stop_details;
|
|
snapshot.usage.output_tokens = event.usage.output_tokens;
|
|
if (event.delta.container != null) {
|
|
snapshot.container = event.delta.container;
|
|
}
|
|
if (event.usage.input_tokens != null) {
|
|
snapshot.usage.input_tokens = event.usage.input_tokens;
|
|
}
|
|
if (event.usage.cache_creation_input_tokens != null) {
|
|
snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens;
|
|
}
|
|
if (event.usage.cache_read_input_tokens != null) {
|
|
snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens;
|
|
}
|
|
if (event.usage.server_tool_use != null) {
|
|
snapshot.usage.server_tool_use = event.usage.server_tool_use;
|
|
}
|
|
if (event.usage.output_tokens_details != null) {
|
|
snapshot.usage.output_tokens_details = event.usage.output_tokens_details;
|
|
}
|
|
return snapshot;
|
|
case "content_block_start":
|
|
snapshot.content.push({ ...event.content_block });
|
|
return snapshot;
|
|
case "content_block_delta": {
|
|
const snapshotContent = snapshot.content.at(event.index);
|
|
switch (event.delta.type) {
|
|
case "text_delta": {
|
|
if (snapshotContent?.type === "text") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
text: (snapshotContent.text || "") + event.delta.text
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "citations_delta": {
|
|
if (snapshotContent?.type === "text") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
citations: [...snapshotContent.citations ?? [], event.delta.citation]
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "input_json_delta": {
|
|
if (snapshotContent && tracksToolInput2(snapshotContent)) {
|
|
const jsonBuf = (snapshotContent[JSON_BUF_PROPERTY] || "") + event.delta.partial_json;
|
|
snapshot.content[event.index] = withLazyInput(snapshotContent, jsonBuf);
|
|
}
|
|
break;
|
|
}
|
|
case "thinking_delta": {
|
|
if (snapshotContent?.type === "thinking") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
thinking: snapshotContent.thinking + event.delta.thinking
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
case "signature_delta": {
|
|
if (snapshotContent?.type === "thinking") {
|
|
snapshot.content[event.index] = {
|
|
...snapshotContent,
|
|
signature: event.delta.signature
|
|
};
|
|
}
|
|
break;
|
|
}
|
|
default:
|
|
checkNever(event.delta);
|
|
}
|
|
return snapshot;
|
|
}
|
|
case "content_block_stop": {
|
|
const snapshotContent = snapshot.content.at(event.index);
|
|
if (snapshotContent && tracksToolInput2(snapshotContent) && JSON_BUF_PROPERTY in snapshotContent) {
|
|
Object.defineProperty(snapshotContent, "input", {
|
|
value: snapshotContent.input,
|
|
enumerable: true,
|
|
configurable: true,
|
|
writable: true
|
|
});
|
|
}
|
|
return snapshot;
|
|
}
|
|
}
|
|
}, Symbol.asyncIterator)]() {
|
|
const pushQueue = [];
|
|
const readQueue = [];
|
|
let done = false;
|
|
this.on("streamEvent", (event) => {
|
|
const reader = readQueue.shift();
|
|
if (reader) {
|
|
reader.resolve(event);
|
|
} else {
|
|
pushQueue.push(event);
|
|
}
|
|
});
|
|
this.on("end", () => {
|
|
done = true;
|
|
for (const reader of readQueue) {
|
|
reader.resolve(void 0);
|
|
}
|
|
readQueue.length = 0;
|
|
});
|
|
this.on("abort", (err) => {
|
|
done = true;
|
|
for (const reader of readQueue) {
|
|
reader.reject(err);
|
|
}
|
|
readQueue.length = 0;
|
|
});
|
|
this.on("error", (err) => {
|
|
done = true;
|
|
for (const reader of readQueue) {
|
|
reader.reject(err);
|
|
}
|
|
readQueue.length = 0;
|
|
});
|
|
return {
|
|
next: async () => {
|
|
if (!pushQueue.length) {
|
|
if (done) {
|
|
return { value: void 0, done: true };
|
|
}
|
|
return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true });
|
|
}
|
|
const chunk = pushQueue.shift();
|
|
return { value: chunk, done: false };
|
|
},
|
|
return: async () => {
|
|
this.abort();
|
|
return { value: void 0, done: true };
|
|
}
|
|
};
|
|
}
|
|
toReadableStream() {
|
|
const stream4 = new Stream2(this[Symbol.asyncIterator].bind(this), this.controller);
|
|
return stream4.toReadableStream();
|
|
}
|
|
}
|
|
return MessageStream2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs
|
|
var Batches3;
|
|
var init_batches3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_jsonl();
|
|
init_error4();
|
|
init_path2();
|
|
Batches3 = class extends APIResource2 {
|
|
/**
|
|
* Send a batch of Message creation requests.
|
|
*
|
|
* The Message Batches API can be used to process multiple Messages API requests at
|
|
* once. Once a Message Batch is created, it begins processing immediately. Batches
|
|
* can take up to 24 hours to complete.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const messageBatch = await client.messages.batches.create({
|
|
* requests: [
|
|
* {
|
|
* custom_id: 'my-custom-id-1',
|
|
* params: {
|
|
* max_tokens: 1024,
|
|
* messages: [
|
|
* { content: 'Hello, world', role: 'user' },
|
|
* ],
|
|
* model: 'claude-opus-5',
|
|
* },
|
|
* },
|
|
* ],
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { user_profile_id, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/messages/batches", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* This endpoint is idempotent and can be used to poll for Message Batch
|
|
* completion. To access the results of a Message Batch, make a request to the
|
|
* `results_url` field in the response.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const messageBatch = await client.messages.batches.retrieve(
|
|
* 'message_batch_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(messageBatchID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/messages/batches/${messageBatchID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List all Message Batches within a Workspace. Most recently created batches are
|
|
* returned first.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const messageBatch of client.messages.batches.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/messages/batches", Page2, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete a Message Batch.
|
|
*
|
|
* Message Batches can only be deleted once they've finished processing. If you'd
|
|
* like to delete an in-progress batch, you must first cancel it.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const deletedMessageBatch =
|
|
* await client.messages.batches.delete('message_batch_id');
|
|
* ```
|
|
*/
|
|
delete(messageBatchID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/messages/batches/${messageBatchID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Batches may be canceled any time before processing ends. Once cancellation is
|
|
* initiated, the batch enters a `canceling` state, at which time the system may
|
|
* complete any in-progress, non-interruptible requests before finalizing
|
|
* cancellation.
|
|
*
|
|
* The number of canceled requests is specified in `request_counts`. To determine
|
|
* which requests were canceled, check the individual results within the batch.
|
|
* Note that cancellation may not result in any canceled requests if they were
|
|
* non-interruptible.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const messageBatch = await client.messages.batches.cancel(
|
|
* 'message_batch_id',
|
|
* );
|
|
* ```
|
|
*/
|
|
cancel(messageBatchID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.post(path3`/v1/messages/batches/${messageBatchID}/cancel`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Streams the results of a Message Batch as a `.jsonl` file.
|
|
*
|
|
* Each line in the file is a JSON object containing the result of a single request
|
|
* in the Message Batch. Results are not guaranteed to be in the same order as
|
|
* requests. Use the `custom_id` field to match results to requests.
|
|
*
|
|
* Learn more about the Message Batches API in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const messageBatchIndividualResponse =
|
|
* await client.messages.batches.results('message_batch_id');
|
|
* ```
|
|
*/
|
|
async results(messageBatchID, params = {}, options) {
|
|
const batch = await this.retrieve(messageBatchID, params, options);
|
|
if (!batch.results_url) {
|
|
throw new AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`);
|
|
}
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.get(batch.results_url, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
Accept: "application/binary",
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
]),
|
|
stream: true,
|
|
__binaryResponse: true
|
|
})._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller));
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs
|
|
var Messages4, DEPRECATED_MODELS2, MODELS_TO_WARN_WITH_THINKING_ENABLED2;
|
|
var init_messages4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs"() {
|
|
init_resource2();
|
|
init_headers3();
|
|
init_stainless_helper_header();
|
|
init_MessageStream();
|
|
init_parser4();
|
|
init_batches3();
|
|
init_batches3();
|
|
init_constants();
|
|
Messages4 = /* @__PURE__ */ (() => {
|
|
class Messages5 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.batches = new Batches3(this._client);
|
|
}
|
|
create(params, options) {
|
|
const { user_profile_id, workspace_id, ...body } = params;
|
|
if (body.model in DEPRECATED_MODELS2) {
|
|
console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]}
|
|
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
|
|
}
|
|
if (MODELS_TO_WARN_WITH_THINKING_ENABLED2.includes(body.model) && body.thinking && body.thinking.type === "enabled") {
|
|
console.warn(`Using Claude with ${body.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
|
|
}
|
|
let timeout = options?.timeout ?? this._client._options.timeout;
|
|
if (!body.stream && timeout == null) {
|
|
const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? void 0;
|
|
timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
|
|
}
|
|
const helperHeader2 = stainlessHelperHeader(body.tools, body.messages);
|
|
return this._client.post("/v1/messages", {
|
|
body,
|
|
timeout: timeout ?? 6e5,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
helperHeader2,
|
|
options?.headers
|
|
]),
|
|
stream: params.stream ?? false
|
|
});
|
|
}
|
|
/**
|
|
* Send a structured list of input messages with text and/or image content, along with an expected `output_config.format` and
|
|
* the response will be automatically parsed and available in the `parsed_output` property of the message.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const message = await client.messages.parse({
|
|
* model: 'claude-sonnet-4-5-20250929',
|
|
* max_tokens: 1024,
|
|
* messages: [{ role: 'user', content: 'What is 2+2?' }],
|
|
* output_config: {
|
|
* format: zodOutputFormat(z.object({ answer: z.number() })),
|
|
* },
|
|
* });
|
|
*
|
|
* console.log(message.parsed_output?.answer); // 4
|
|
* ```
|
|
*/
|
|
parse(params, options) {
|
|
return this.create(params, options).then((message) => parseMessage(message, params, { logger: this._client.logger ?? console }));
|
|
}
|
|
/**
|
|
* Create a Message stream.
|
|
*
|
|
* If `output_config.format` is provided with a parseable format (like `zodOutputFormat()`),
|
|
* the final message will include a `parsed_output` property with the parsed content.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const stream = client.messages.stream({
|
|
* model: 'claude-sonnet-4-5-20250929',
|
|
* max_tokens: 1024,
|
|
* messages: [{ role: 'user', content: 'What is 2+2?' }],
|
|
* output_config: {
|
|
* format: zodOutputFormat(z.object({ answer: z.number() })),
|
|
* },
|
|
* });
|
|
*
|
|
* const message = await stream.finalMessage();
|
|
* console.log(message.parsed_output?.answer); // 4
|
|
* ```
|
|
*/
|
|
stream(body, options) {
|
|
return MessageStream.createMessage(this, body, options, { logger: this._client.logger ?? console });
|
|
}
|
|
/**
|
|
* Count the number of tokens in a Message.
|
|
*
|
|
* The Token Count API can be used to count the number of tokens in a Message,
|
|
* including tools, images, and documents, without creating it.
|
|
*
|
|
* Learn more about token counting in our
|
|
* [user guide](https://platform.claude.com/docs/en/build-with-claude/token-counting)
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const messageTokensCount =
|
|
* await client.messages.countTokens({
|
|
* messages: [{ content: 'Hello, world', role: 'user' }],
|
|
* model: 'claude-opus-5',
|
|
* });
|
|
* ```
|
|
*/
|
|
countTokens(params, options) {
|
|
const { user_profile_id, workspace_id, ...body } = params;
|
|
return this._client.post("/v1/messages/count_tokens", {
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Messages5.Batches = Batches3;
|
|
return Messages5;
|
|
})();
|
|
DEPRECATED_MODELS2 = {};
|
|
MODELS_TO_WARN_WITH_THINKING_ENABLED2 = ["claude-mythos-preview", "claude-opus-4-6"];
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/models.mjs
|
|
var Models3;
|
|
var init_models4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/models.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_path2();
|
|
Models3 = class extends APIResource2 {
|
|
/**
|
|
* Get a specific model.
|
|
*
|
|
* The Models API response can be used to determine information about a specific
|
|
* model or resolve a model alias to a model ID.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const modelInfo = await client.models.retrieve('model_id');
|
|
* ```
|
|
*/
|
|
retrieve(modelID, params = {}, options) {
|
|
const { betas, workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/models/${modelID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List available models.
|
|
*
|
|
* The Models API response can be used to determine which models are available for
|
|
* use in the API. More recently released models are listed first.
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const modelInfo of client.models.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { betas, workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/models", Page2, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{
|
|
...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : void 0,
|
|
...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0
|
|
},
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/skills/versions.mjs
|
|
var Versions4;
|
|
var init_versions4 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/skills/versions.mjs"() {
|
|
init_resource2();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_uploads4();
|
|
init_path2();
|
|
Versions4 = class extends APIResource2 {
|
|
/**
|
|
* Create Skill Version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const skillVersion = await client.skills.versions.create(
|
|
* 'skill_id',
|
|
* { files: [fs.createReadStream('path/to/file')] },
|
|
* );
|
|
* ```
|
|
*/
|
|
create(skillID, params, options) {
|
|
const { workspace_id, ...body } = params;
|
|
return this._client.post(path3`/v1/skills/${skillID}/versions`, multipartFormRequestOptions2({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
}, this._client, false));
|
|
}
|
|
/**
|
|
* Get Skill Version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const skillVersion = await client.skills.versions.retrieve(
|
|
* 'version',
|
|
* { skill_id: 'skill_id' },
|
|
* );
|
|
* ```
|
|
*/
|
|
retrieve(version, params, options) {
|
|
const { skill_id, workspace_id } = params;
|
|
return this._client.get(path3`/v1/skills/${skill_id}/versions/${version}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Skill Versions
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const skillVersion of client.skills.versions.list(
|
|
* 'skill_id',
|
|
* )) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(skillID, params = {}, options) {
|
|
const { workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList(path3`/v1/skills/${skillID}/versions`, PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Skill Version
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const deletedSkillVersion =
|
|
* await client.skills.versions.delete('version', {
|
|
* skill_id: 'skill_id',
|
|
* });
|
|
* ```
|
|
*/
|
|
delete(version, params, options) {
|
|
const { skill_id, workspace_id } = params;
|
|
return this._client.delete(path3`/v1/skills/${skill_id}/versions/${version}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
};
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/skills/skills.mjs
|
|
var Skills3;
|
|
var init_skills3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/skills/skills.mjs"() {
|
|
init_resource2();
|
|
init_versions4();
|
|
init_versions4();
|
|
init_pagination2();
|
|
init_headers3();
|
|
init_uploads4();
|
|
init_path2();
|
|
Skills3 = /* @__PURE__ */ (() => {
|
|
class Skills4 extends APIResource2 {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.versions = new Versions4(this._client);
|
|
}
|
|
/**
|
|
* Create Skill
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const skill = await client.skills.create({
|
|
* files: [fs.createReadStream('path/to/file')],
|
|
* });
|
|
* ```
|
|
*/
|
|
create(params, options) {
|
|
const { workspace_id, ...body } = params;
|
|
return this._client.post("/v1/skills", multipartFormRequestOptions2({
|
|
body,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
}, this._client, false));
|
|
}
|
|
/**
|
|
* Get Skill
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const skill = await client.skills.retrieve('skill_id');
|
|
* ```
|
|
*/
|
|
retrieve(skillID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.get(path3`/v1/skills/${skillID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* List Skills
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* // Automatically fetches more pages as needed.
|
|
* for await (const skill of client.skills.list()) {
|
|
* // ...
|
|
* }
|
|
* ```
|
|
*/
|
|
list(params = {}, options) {
|
|
const { workspace_id, ...query } = params ?? {};
|
|
return this._client.getAPIList("/v1/skills", PageCursor, {
|
|
query,
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
/**
|
|
* Delete Skill
|
|
*
|
|
* @example
|
|
* ```ts
|
|
* const deletedSkill = await client.skills.delete('skill_id');
|
|
* ```
|
|
*/
|
|
delete(skillID, params = {}, options) {
|
|
const { workspace_id } = params ?? {};
|
|
return this._client.delete(path3`/v1/skills/${skillID}`, {
|
|
...options,
|
|
headers: buildHeaders2([
|
|
{ ...workspace_id != null ? { "anthropic-workspace-id": workspace_id } : void 0 },
|
|
options?.headers
|
|
])
|
|
});
|
|
}
|
|
}
|
|
Skills4.Versions = Versions4;
|
|
return Skills4;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/resources/index.mjs
|
|
var init_resources3 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/resources/index.mjs"() {
|
|
init_shared2();
|
|
init_beta2();
|
|
init_completions4();
|
|
init_files6();
|
|
init_messages4();
|
|
init_models4();
|
|
init_skills3();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/client.mjs
|
|
var _BaseAnthropic_instances, _a5, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden, HUMAN_PROMPT, AI_PROMPT, BaseAnthropic, Anthropic;
|
|
var init_client2 = __esm({
|
|
"node_modules/@anthropic-ai/sdk/client.mjs"() {
|
|
init_tslib2();
|
|
init_values2();
|
|
init_sleep2();
|
|
init_errors2();
|
|
init_detect_platform2();
|
|
init_request_signal();
|
|
init_shims2();
|
|
init_request_options2();
|
|
init_query2();
|
|
init_version3();
|
|
init_error3();
|
|
init_types();
|
|
init_token_cache();
|
|
init_credential_chain();
|
|
init_middleware();
|
|
init_pagination2();
|
|
init_uploads5();
|
|
init_resources3();
|
|
init_api_promise2();
|
|
init_completions4();
|
|
init_files6();
|
|
init_models4();
|
|
init_beta2();
|
|
init_messages4();
|
|
init_skills3();
|
|
init_detect_platform2();
|
|
init_headers3();
|
|
init_env2();
|
|
init_log2();
|
|
init_values2();
|
|
HUMAN_PROMPT = "\\n\\nHuman:";
|
|
AI_PROMPT = "\\n\\nAssistant:";
|
|
BaseAnthropic = /* @__PURE__ */ (() => {
|
|
class BaseAnthropic2 {
|
|
/**
|
|
* The active credential provider. Default credential resolution runs once
|
|
* at construction time. If it fails, the error is surfaced on every
|
|
* request and the client must be reconstructed — there is no retry path.
|
|
*
|
|
* Clones returned by {@link withOptions} share the parent's auth state
|
|
* (provider, token cache, pending resolution, and any resolution error)
|
|
* unless the caller passes an explicit `apiKey`, `authToken`,
|
|
* `credentials`, `config`, or `profile` override.
|
|
*/
|
|
get credentials() {
|
|
return this._authState.provider;
|
|
}
|
|
/**
|
|
* API Client for interfacing with the Anthropic API.
|
|
*
|
|
* @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null]
|
|
* @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
|
|
* @param {string | null | undefined} [opts.webhookKey=process.env['ANTHROPIC_WEBHOOK_SIGNING_KEY'] ?? null]
|
|
* @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API.
|
|
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
|
|
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
|
|
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
* @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
|
|
*/
|
|
constructor({ baseURL = readEnv2("ANTHROPIC_BASE_URL"), apiKey, authToken, webhookKey = readEnv2("ANTHROPIC_WEBHOOK_SIGNING_KEY") ?? null, ...opts } = {}) {
|
|
_BaseAnthropic_instances.add(this);
|
|
this._requestAuthFlags = /* @__PURE__ */ new WeakMap();
|
|
_BaseAnthropic_encoder.set(this, void 0);
|
|
if (apiKey === void 0) {
|
|
apiKey = opts.profile != null ? null : readEnv2("ANTHROPIC_API_KEY") ?? null;
|
|
}
|
|
if (authToken === void 0) {
|
|
authToken = opts.profile != null ? null : readEnv2("ANTHROPIC_AUTH_TOKEN") ?? null;
|
|
}
|
|
if (opts.profile != null && (opts.credentials != null || opts.config != null)) {
|
|
throw new TypeError("Pass at most one of `profile`, `credentials`, or `config`.");
|
|
}
|
|
const options = {
|
|
apiKey,
|
|
authToken,
|
|
webhookKey,
|
|
...opts,
|
|
baseURL: baseURL || `https://api.anthropic.com`
|
|
};
|
|
if (!options.dangerouslyAllowBrowser && isRunningInBrowser2()) {
|
|
throw new AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n");
|
|
}
|
|
this.baseURL = options.baseURL;
|
|
this._baseURLIsExplicit = opts.__baseURLIsExplicit ?? !!baseURL;
|
|
this.timeout = options.timeout ?? _a5.DEFAULT_TIMEOUT;
|
|
this.logger = options.logger ?? console;
|
|
this.logLevel = defaultLogLevel;
|
|
this.logLevel = parseLogLevel2(options.logLevel, "ClientOptions.logLevel", loggerFor2(this)) ?? parseLogLevel2(readEnv2("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", loggerFor2(this)) ?? defaultLogLevel;
|
|
this.fetchOptions = options.fetchOptions;
|
|
this.maxRetries = validatePositiveInteger2("maxRetries", options.maxRetries ?? 2);
|
|
this.fetch = options.fetch ?? getDefaultFetch2();
|
|
__classPrivateFieldSet2(this, _BaseAnthropic_encoder, FallbackEncoder2, "f");
|
|
this.middleware = [...options.middleware ?? []];
|
|
const customHeadersEnv = readEnv2("ANTHROPIC_CUSTOM_HEADERS");
|
|
if (customHeadersEnv) {
|
|
const parsed = {};
|
|
for (const line of customHeadersEnv.split("\n")) {
|
|
const colon = line.indexOf(":");
|
|
if (colon >= 0) {
|
|
parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
|
|
}
|
|
}
|
|
options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
|
|
}
|
|
const inherited = opts.__auth;
|
|
delete options.__auth;
|
|
delete options.__baseURLIsExplicit;
|
|
this._options = options;
|
|
this.apiKey = typeof apiKey === "string" ? apiKey : null;
|
|
this.authToken = authToken;
|
|
this.webhookKey = webhookKey;
|
|
if (inherited) {
|
|
this._authState = inherited;
|
|
if (!this._baseURLIsExplicit && inherited.baseURL) {
|
|
this.baseURL = inherited.baseURL;
|
|
}
|
|
} else {
|
|
this._authState = { provider: null, tokenCache: null, resolution: null, error: null, extraHeaders: {} };
|
|
if (this.apiKey == null && this.authToken == null) {
|
|
const credentials = options.credentials ?? null;
|
|
if (credentials) {
|
|
this._authState.provider = credentials;
|
|
this._authState.tokenCache = this._makeTokenCache(credentials);
|
|
} else if (options.config != null) {
|
|
const result = resolveCredentialsFromConfig(options.config, this._credentialResolverOptions());
|
|
this._authState.provider = result.provider;
|
|
this._authState.tokenCache = this._makeTokenCache(result.provider);
|
|
this._authState.extraHeaders = result.extraHeaders;
|
|
this._applyCredentialBaseURL(result.baseURL);
|
|
} else if (options.profile != null) {
|
|
this._authState.resolution = this._resolveDefaultCredentials(options.profile);
|
|
} else if (this._shouldResolveDefaultCredentials()) {
|
|
this._authState.resolution = this._resolveDefaultCredentials();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* Whether to lazily resolve auth from the default credential chain when no
|
|
* explicit auth is configured. Called once from the constructor, so
|
|
* overrides must not depend on subclass instance state. Subclasses that
|
|
* bring their own auth scheme return false so unrelated local credentials
|
|
* are never resolved or allowed to supply a base URL.
|
|
*/
|
|
_shouldResolveDefaultCredentials() {
|
|
return true;
|
|
}
|
|
/**
|
|
* Stores a profile/config-supplied base URL on the shared auth state and, if
|
|
* the caller did not pin `baseURL` via constructor option or env, adopts it
|
|
* as this client's outbound API host. Precedence: ctor opt > env > profile >
|
|
* hardcoded default.
|
|
*/
|
|
_applyCredentialBaseURL(baseURL) {
|
|
if (!baseURL)
|
|
return;
|
|
const normalized = baseURL.replace(/\/+$/, "");
|
|
this._authState.baseURL = normalized;
|
|
if (!this._baseURLIsExplicit) {
|
|
this.baseURL = normalized;
|
|
}
|
|
}
|
|
/**
|
|
* Options bag passed into the credential chain. `baseURL` here is only the
|
|
* fallback host for the token-exchange POST when the config itself omits
|
|
* `base_url`; the chain returns the config's own `base_url` (if any) on
|
|
* {@link CredentialResult.baseURL}, which {@link _applyCredentialBaseURL}
|
|
* then adopts for outbound API requests. The two are deliberately decoupled
|
|
* so this fallback never round-trips into precedence.
|
|
*/
|
|
_credentialResolverOptions() {
|
|
return {
|
|
baseURL: this.baseURL,
|
|
fetch: this._credentialsFetch(),
|
|
userAgent: this.getUserAgent(),
|
|
onCacheWriteError: (err) => {
|
|
loggerFor2(this).debug("credential cache write failed (best-effort)", err);
|
|
},
|
|
onSafetyWarning: (msg) => {
|
|
loggerFor2(this).warn(msg);
|
|
}
|
|
};
|
|
}
|
|
/**
|
|
* A `Fetch` for first-party credential token-exchange requests (OIDC
|
|
* federation jwt-bearer grants, user-OAuth refresh grants) that routes
|
|
* through this client's middleware chain, so middleware observes token
|
|
* traffic like any other request. Only client-level middleware applies:
|
|
* a minted token is shared across requests, so attributing the exchange
|
|
* to any one request's per-request middleware would be arbitrary. For the
|
|
* same reason, `ctx.options` is undefined for these requests.
|
|
*/
|
|
_credentialsFetch() {
|
|
return wrapFetchWithMiddleware(this.fetch, this.middleware, void 0, this);
|
|
}
|
|
_makeTokenCache(provider2) {
|
|
return new TokenCache(provider2, (err) => {
|
|
loggerFor2(this).debug("advisory token refresh failed; serving cached token", err);
|
|
});
|
|
}
|
|
/**
|
|
* Create a new client instance re-using the same options given to the
|
|
* current client with optional overriding.
|
|
*/
|
|
withOptions(options) {
|
|
const overridesStructuredAuth = "credentials" in options || "config" in options || "profile" in options;
|
|
const overridesAuth = "apiKey" in options || "authToken" in options || overridesStructuredAuth;
|
|
const internal = {
|
|
...this._options,
|
|
// Only forward baseURL when the caller (or env) explicitly chose it.
|
|
// For a non-explicit parent, this.baseURL may have been mutated to the
|
|
// profile-resolved host; pinning that as the clone's options.baseURL
|
|
// would make _options on the clone misreport caller intent and would
|
|
// leave the clone stuck on the parent's host across an auth override.
|
|
// The clone instead receives the construction-time value via
|
|
// ...this._options above and re-adopts the profile host through the
|
|
// shared _authState.baseURL + __baseURLIsExplicit=false path.
|
|
...this._baseURLIsExplicit ? { baseURL: this.baseURL } : {},
|
|
maxRetries: this.maxRetries,
|
|
timeout: this.timeout,
|
|
logger: this.logger,
|
|
logLevel: this.logLevel,
|
|
fetch: this.fetch,
|
|
fetchOptions: this.fetchOptions,
|
|
middleware: this.middleware,
|
|
apiKey: this.apiKey,
|
|
authToken: this.authToken,
|
|
webhookKey: this.webhookKey,
|
|
// credentials: this.credentials is a no-op when __auth is shared (the
|
|
// ctor takes the inherited path and ignores options.credentials); when
|
|
// overridesAuth is true via apiKey/authToken only, it lets the clone
|
|
// build a fresh TokenCache around the parent's provider.
|
|
credentials: this.credentials,
|
|
// When the caller passes a structured-credential override, drop inherited
|
|
// structured-credential options so only `...options` supplies them —
|
|
// otherwise an inherited `credentials`/`config`/`profile` would trip the
|
|
// mutual-exclusion check or precedence over the override.
|
|
...overridesStructuredAuth ? { credentials: void 0, config: void 0, profile: void 0 } : {},
|
|
...options,
|
|
// Always set __auth so any stale value from ...this._options is
|
|
// overwritten. undefined means "build fresh auth from these options".
|
|
__auth: overridesAuth ? void 0 : this._authState,
|
|
__baseURLIsExplicit: "baseURL" in options ? true : this._baseURLIsExplicit
|
|
};
|
|
return new this.constructor(internal);
|
|
}
|
|
/**
|
|
* Lazily resolves credentials from config files or environment variables.
|
|
* Called once from the constructor when no explicit auth is provided, or
|
|
* when an explicit `profile` was passed (in which case a missing/unresolved
|
|
* profile is surfaced as an error instead of falling through to "no auth").
|
|
* The returned promise is stored and awaited on the first request.
|
|
*/
|
|
async _resolveDefaultCredentials(profile) {
|
|
try {
|
|
const result = await defaultCredentials(this._credentialResolverOptions(), profile);
|
|
if (result) {
|
|
this._authState.provider = result.provider;
|
|
this._authState.tokenCache = this._makeTokenCache(result.provider);
|
|
this._authState.extraHeaders = result.extraHeaders;
|
|
this._applyCredentialBaseURL(result.baseURL);
|
|
} else if (profile != null) {
|
|
throw new AnthropicError(`Profile "${profile}" could not be resolved (no <config_dir>/configs/${profile}.json found).`);
|
|
}
|
|
} catch (err) {
|
|
this._authState.error = err;
|
|
} finally {
|
|
this._authState.resolution = null;
|
|
}
|
|
}
|
|
defaultQuery() {
|
|
return this._options.defaultQuery;
|
|
}
|
|
validateHeaders({ values, nulls }) {
|
|
if (values.get("x-api-key") || values.get("authorization")) {
|
|
return;
|
|
}
|
|
if (this._authState.error) {
|
|
throw this._authState.error;
|
|
}
|
|
if (this._authState.tokenCache || this._authState.resolution) {
|
|
return;
|
|
}
|
|
if (this.apiKey && values.get("x-api-key")) {
|
|
return;
|
|
}
|
|
if (nulls.has("x-api-key")) {
|
|
return;
|
|
}
|
|
if (this.authToken && values.get("authorization")) {
|
|
return;
|
|
}
|
|
if (nulls.has("authorization")) {
|
|
return;
|
|
}
|
|
throw new Error('Could not resolve authentication method. Expected one of apiKey, authToken, credentials, config, or profile to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
|
|
}
|
|
_authFlags(opts) {
|
|
let flags = this._requestAuthFlags.get(opts);
|
|
if (!flags) {
|
|
flags = { usedTokenCache: false, didRefreshFor401: false };
|
|
this._requestAuthFlags.set(opts, flags);
|
|
}
|
|
return flags;
|
|
}
|
|
async authHeaders(opts) {
|
|
if (this._authState.resolution) {
|
|
await this._authState.resolution;
|
|
}
|
|
if (this._authState.error) {
|
|
return void 0;
|
|
}
|
|
if (this._authState.tokenCache && this.apiKey == null) {
|
|
const token = await this._authState.tokenCache.getToken();
|
|
this._authFlags(opts).usedTokenCache = true;
|
|
return buildHeaders2([{ Authorization: `Bearer ${token}` }]);
|
|
}
|
|
return buildHeaders2([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]);
|
|
}
|
|
async apiKeyAuth(opts) {
|
|
if (this.apiKey == null) {
|
|
return void 0;
|
|
}
|
|
return buildHeaders2([{ "X-Api-Key": this.apiKey }]);
|
|
}
|
|
async bearerAuth(opts) {
|
|
if (this.authToken == null) {
|
|
return void 0;
|
|
}
|
|
return buildHeaders2([{ Authorization: `Bearer ${this.authToken}` }]);
|
|
}
|
|
stringifyQuery(query) {
|
|
return stringifyQuery2(query);
|
|
}
|
|
getUserAgent() {
|
|
return `Anthropic/JS ${VERSION2}`;
|
|
}
|
|
makeStatusError(status, error, message, headers) {
|
|
return APIError2.generate(status, error, message, headers);
|
|
}
|
|
buildURL(path4, query, defaultBaseURL) {
|
|
const baseURL = !__classPrivateFieldGet2(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL || this.baseURL;
|
|
const url = isAbsoluteURL2(path4) ? new URL(path4) : new URL(baseURL + (baseURL.endsWith("/") && path4.startsWith("/") ? path4.slice(1) : path4));
|
|
const defaultQuery = this.defaultQuery();
|
|
const pathQuery = Object.fromEntries(url.searchParams);
|
|
if (!isEmptyObj2(defaultQuery) || !isEmptyObj2(pathQuery)) {
|
|
query = { ...pathQuery, ...defaultQuery, ...query };
|
|
}
|
|
if (typeof query === "object" && query && !Array.isArray(query)) {
|
|
url.search = this.stringifyQuery(query);
|
|
}
|
|
return url.toString();
|
|
}
|
|
_calculateNonstreamingTimeout(maxTokens) {
|
|
const defaultTimeout = 10 * 60;
|
|
const expectedTimeout = 60 * 60 * maxTokens / 128e3;
|
|
if (expectedTimeout > defaultTimeout) {
|
|
throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
|
|
}
|
|
return defaultTimeout * 1e3;
|
|
}
|
|
/**
|
|
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
|
*/
|
|
async prepareOptions(options) {
|
|
}
|
|
/**
|
|
* Used as a callback for mutating the given `RequestInit` object.
|
|
*
|
|
* This is useful for cases where you want to add certain headers based off of
|
|
* the request properties, e.g. `method` or `url`.
|
|
*
|
|
* Runs after all middleware (including {@link backendMiddleware}),
|
|
* immediately before each underlying fetch call, so it sees exactly what
|
|
* goes over the wire. Middleware may replay a request by calling `next()`
|
|
* more than once, so this hook can run multiple times per attempt:
|
|
* overrides must be idempotent and overwrite headers from a previous
|
|
* invocation rather than append to them.
|
|
*/
|
|
async prepareRequest(request2, { url, options }) {
|
|
if (this._authState.tokenCache && this.apiKey == null) {
|
|
const headers = request2.headers instanceof Headers ? request2.headers : new Headers(request2.headers);
|
|
for (const [k, v] of Object.entries(this._authState.extraHeaders)) {
|
|
if (!headers.has(k))
|
|
headers.set(k, v);
|
|
}
|
|
const existing = headers.get("anthropic-beta")?.split(",").map((s) => s.trim());
|
|
if (!existing?.includes(OAUTH_API_BETA_HEADER)) {
|
|
headers.set("anthropic-beta", [...existing ?? [], OAUTH_API_BETA_HEADER].join(","));
|
|
}
|
|
request2.headers = headers;
|
|
}
|
|
}
|
|
/**
|
|
* Internal {@link Middleware} composed innermost in the chain — inside both
|
|
* client-level and per-request middleware, immediately around the underlying
|
|
* `fetch`. Subclasses for third-party backends override this to adapt the
|
|
* canonical Anthropic-shaped request to the backend's wire shape (URL/body
|
|
* rewriting, request signing) and to normalize the wire response back to the
|
|
* canonical shape (e.g. AWS EventStream to SSE).
|
|
*
|
|
* Running inside the user's middleware means user middleware always observes
|
|
* canonical Anthropic-shaped traffic, and the adaptation re-runs (e.g.
|
|
* re-signs) on every `next()` invocation, covering whatever the middleware
|
|
* mutated.
|
|
*
|
|
* Errors thrown here follow the middleware error policy: they propagate to
|
|
* the caller as-is — no retries, no `APIConnectionError` wrapping — unless
|
|
* retryable (see {@link Middleware}); throw a `RetryableError` to opt into
|
|
* the retry path.
|
|
*/
|
|
backendMiddleware() {
|
|
return [];
|
|
}
|
|
get(path4, opts) {
|
|
return this.methodRequest("get", path4, opts);
|
|
}
|
|
post(path4, opts) {
|
|
return this.methodRequest("post", path4, opts);
|
|
}
|
|
patch(path4, opts) {
|
|
return this.methodRequest("patch", path4, opts);
|
|
}
|
|
put(path4, opts) {
|
|
return this.methodRequest("put", path4, opts);
|
|
}
|
|
delete(path4, opts) {
|
|
return this.methodRequest("delete", path4, opts);
|
|
}
|
|
methodRequest(method, path4, opts) {
|
|
return this.request(Promise.resolve(opts).then((opts2) => {
|
|
return { method, path: path4, ...opts2 };
|
|
}));
|
|
}
|
|
request(options, remainingRetries = null) {
|
|
return new APIPromise2(this, this.makeRequest(options, remainingRetries, void 0));
|
|
}
|
|
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
|
|
const options = await optionsInput;
|
|
let maxRetries = validatePositiveInteger2("maxRetries", options.maxRetries ?? this.maxRetries);
|
|
if (this.isStreamBody(options.body)) {
|
|
maxRetries = 0;
|
|
}
|
|
if (retriesRemaining == null) {
|
|
retriesRemaining = maxRetries;
|
|
this._requestAuthFlags.delete(options);
|
|
}
|
|
await this.prepareOptions(options);
|
|
const { req, url, timeout } = await this.buildRequest(options, {
|
|
retryCount: maxRetries - retriesRemaining
|
|
});
|
|
const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
|
|
const retryLogStr = retryOfRequestLogID === void 0 ? "" : `, retryOf: ${retryOfRequestLogID}`;
|
|
const startTime = Date.now();
|
|
if (options.signal?.aborted) {
|
|
throw new APIUserAbortError2();
|
|
}
|
|
const controller = new AbortController();
|
|
const response = await this.fetchWithTimeout(url, req, timeout, controller, options, {
|
|
requestLogID,
|
|
retryOfRequestLogID
|
|
}).catch(castToError2);
|
|
const headersTime = Date.now();
|
|
if (response instanceof globalThis.Error) {
|
|
releaseRequestSignal(controller);
|
|
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
if (options.signal?.aborted) {
|
|
throw new APIUserAbortError2();
|
|
}
|
|
const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
|
|
const hasMiddleware = this.middleware.length > 0 || !!options.middleware?.length || this.backendMiddleware().length > 0;
|
|
if (hasMiddleware && !isTimeout && !isRetryableError(response)) {
|
|
loggerFor2(this).info(`[${requestLogID}] middleware error (not retryable)`);
|
|
debugLogRequestDetails(loggerFor2(this), `[${requestLogID}] middleware error (not retryable)`, {
|
|
retryOfRequestLogID,
|
|
url,
|
|
durationMs: headersTime - startTime,
|
|
message: response.message
|
|
});
|
|
throw response;
|
|
}
|
|
if (retriesRemaining) {
|
|
loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
|
|
debugLogRequestDetails(loggerFor2(this), `[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, {
|
|
retryOfRequestLogID,
|
|
url,
|
|
durationMs: headersTime - startTime,
|
|
message: response.message
|
|
});
|
|
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
|
|
}
|
|
loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - error; no more retries left`);
|
|
debugLogRequestDetails(loggerFor2(this), `[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (error; no more retries left)`, {
|
|
retryOfRequestLogID,
|
|
url,
|
|
durationMs: headersTime - startTime,
|
|
message: response.message
|
|
});
|
|
if (isTimeout) {
|
|
throw new APIConnectionTimeoutError2();
|
|
}
|
|
if (hasMiddleware && !isFetchOriginError(response)) {
|
|
throw response;
|
|
}
|
|
throw new APIConnectionError2({ cause: response });
|
|
}
|
|
const specialHeaders = [...response.headers.entries()].filter(([name]) => name === "request-id" || name === "anthropic-workspace-id").map(([name, value]) => ", " + name + ": " + JSON.stringify(value)).join("");
|
|
const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? "succeeded" : "failed"} with status ${response.status} in ${headersTime - startTime}ms`;
|
|
if (!response.ok) {
|
|
const shouldRetry = await this.shouldRetry(response, options);
|
|
if (retriesRemaining && shouldRetry) {
|
|
const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`;
|
|
await CancelReadableStream2(response.body);
|
|
releaseRequestSignal(controller);
|
|
loggerFor2(this).info(`${responseInfo} - ${retryMessage2}`);
|
|
debugLogRequestDetails(loggerFor2(this), `[${requestLogID}] response error (${retryMessage2})`, {
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
headers: response.headers,
|
|
durationMs: headersTime - startTime
|
|
});
|
|
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
|
|
}
|
|
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
|
|
loggerFor2(this).info(`${responseInfo} - ${retryMessage}`);
|
|
const errText = await response.text().catch((err2) => castToError2(err2).message);
|
|
const errJSON = safeJSON2(errText);
|
|
const errMessage = errJSON ? void 0 : errText;
|
|
debugLogRequestDetails(loggerFor2(this), `[${requestLogID}] response error (${retryMessage})`, {
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
headers: response.headers,
|
|
message: errMessage,
|
|
durationMs: Date.now() - startTime
|
|
});
|
|
releaseRequestSignal(controller);
|
|
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
|
|
throw err;
|
|
}
|
|
loggerFor2(this).info(responseInfo);
|
|
debugLogRequestDetails(loggerFor2(this), `[${requestLogID}] response start`, {
|
|
retryOfRequestLogID,
|
|
url: response.url,
|
|
status: response.status,
|
|
headers: response.headers,
|
|
durationMs: headersTime - startTime
|
|
});
|
|
armAbandonmentBackstop(response.body ?? response, controller);
|
|
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
|
|
}
|
|
getAPIList(path4, Page3, opts) {
|
|
return this.requestAPIList(Page3, opts && "then" in opts ? opts.then((opts2) => ({ method: "get", path: path4, ...opts2 })) : { method: "get", path: path4, ...opts });
|
|
}
|
|
requestAPIList(Page3, options) {
|
|
const request2 = this.makeRequest(options, null, void 0);
|
|
return new PagePromise2(this, request2, Page3);
|
|
}
|
|
async fetchWithTimeout(url, init, ms, controller, requestOptions, logCtx) {
|
|
const { signal, method, ...options } = init || {};
|
|
const abort = this._makeAbort(controller);
|
|
if (signal) {
|
|
signal.addEventListener("abort", abort, { once: true });
|
|
registerRequestSignalCleanup(controller, signal, abort);
|
|
}
|
|
const isReadableBody = globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream || typeof options.body === "object" && options.body !== null && Symbol.asyncIterator in options.body;
|
|
const fetchOptions = {
|
|
signal: controller.signal,
|
|
...isReadableBody ? { duplex: "half" } : {},
|
|
method: "GET",
|
|
...options
|
|
};
|
|
if (method) {
|
|
fetchOptions.method = method.toUpperCase();
|
|
}
|
|
const baseFetch = this.fetch;
|
|
const timedFetch = async (innerUrl, innerInit) => {
|
|
const timeout = setTimeout(abort, ms);
|
|
try {
|
|
return await baseFetch.call(void 0, innerUrl, innerInit);
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
}
|
|
};
|
|
const innerFetch = requestOptions === void 0 ? timedFetch : (async (innerUrl, innerInit = {}) => {
|
|
const innerUrlStr = typeof innerUrl === "string" ? innerUrl : innerUrl instanceof URL ? innerUrl.href : innerUrl.url;
|
|
innerInit.headers = innerInit.headers instanceof Headers ? innerInit.headers : new Headers(innerInit.headers);
|
|
await this.prepareRequest(innerInit, { url: innerUrlStr, options: requestOptions });
|
|
if (logCtx) {
|
|
debugLogRequestDetails(loggerFor2(this), `[${logCtx.requestLogID}] sending request`, {
|
|
retryOfRequestLogID: logCtx.retryOfRequestLogID,
|
|
method: innerInit.method,
|
|
url: innerUrlStr,
|
|
options: requestOptions,
|
|
headers: innerInit.headers
|
|
});
|
|
}
|
|
return timedFetch(innerUrl, innerInit);
|
|
});
|
|
const requestMiddleware = requestOptions?.middleware;
|
|
const backendMiddleware = this.backendMiddleware();
|
|
const allMiddleware = requestMiddleware?.length || backendMiddleware.length ? [...this.middleware, ...requestMiddleware ?? [], ...backendMiddleware] : this.middleware;
|
|
return await wrapFetchWithMiddleware(innerFetch, allMiddleware, requestOptions, this)(url, fetchOptions);
|
|
}
|
|
async shouldRetry(response, options) {
|
|
const flags = this._authFlags(options);
|
|
if (response.status === 401 && this._authState.tokenCache && flags.usedTokenCache && !flags.didRefreshFor401) {
|
|
flags.didRefreshFor401 = true;
|
|
this._authState.tokenCache.invalidate();
|
|
return true;
|
|
}
|
|
const shouldRetryHeader = response.headers.get("x-should-retry");
|
|
if (shouldRetryHeader === "true")
|
|
return true;
|
|
if (shouldRetryHeader === "false")
|
|
return false;
|
|
if (response.status === 408)
|
|
return true;
|
|
if (response.status === 409)
|
|
return true;
|
|
if (response.status === 429)
|
|
return true;
|
|
if (response.status >= 500)
|
|
return true;
|
|
return false;
|
|
}
|
|
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
|
|
let timeoutMillis;
|
|
const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
|
|
if (retryAfterMillisHeader) {
|
|
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
|
if (!Number.isNaN(timeoutMs)) {
|
|
timeoutMillis = timeoutMs;
|
|
}
|
|
}
|
|
const retryAfterHeader = responseHeaders?.get("retry-after");
|
|
if (retryAfterHeader && !timeoutMillis) {
|
|
const timeoutSeconds = parseFloat(retryAfterHeader);
|
|
if (!Number.isNaN(timeoutSeconds)) {
|
|
timeoutMillis = timeoutSeconds * 1e3;
|
|
} else {
|
|
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
}
|
|
}
|
|
if (timeoutMillis === void 0 || !(timeoutMillis > 0 && timeoutMillis <= 2 ** 31 - 1)) {
|
|
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
}
|
|
await sleep2(timeoutMillis, options.signal ?? void 0);
|
|
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
|
|
}
|
|
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
const initialRetryDelay = 0.5;
|
|
const maxRetryDelay = 8;
|
|
const numRetries = maxRetries - retriesRemaining;
|
|
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
const jitter2 = 1 - Math.random() * 0.25;
|
|
return sleepSeconds * jitter2 * 1e3;
|
|
}
|
|
calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) {
|
|
const maxTime = 60 * 60 * 1e3;
|
|
const defaultTime = 60 * 10 * 1e3;
|
|
const expectedTime = maxTime * maxTokens / 128e3;
|
|
if (expectedTime > defaultTime || maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens) {
|
|
throw new AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
|
|
}
|
|
return defaultTime;
|
|
}
|
|
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
const options = { ...inputOptions };
|
|
const { method, path: path4, query, defaultBaseURL } = options;
|
|
if (this._authState.resolution) {
|
|
await this._authState.resolution;
|
|
}
|
|
if (!this._baseURLIsExplicit && this._authState.baseURL && this.baseURL !== this._authState.baseURL) {
|
|
this.baseURL = this._authState.baseURL;
|
|
}
|
|
const url = this.buildURL(path4, query, defaultBaseURL);
|
|
if ("timeout" in options)
|
|
validatePositiveInteger2("timeout", options.timeout);
|
|
options.timeout = options.timeout ?? this.timeout;
|
|
const { bodyHeaders, body } = this.buildBody({ options });
|
|
const reqHeaders = await this.buildHeaders({
|
|
options: inputOptions,
|
|
method,
|
|
bodyHeaders,
|
|
retryCount,
|
|
timeout: options.timeout
|
|
});
|
|
const req = {
|
|
method,
|
|
headers: reqHeaders,
|
|
...options.signal && { signal: options.signal },
|
|
...globalThis.ReadableStream && body instanceof globalThis.ReadableStream && { duplex: "half" },
|
|
...body && { body },
|
|
...this.fetchOptions ?? {},
|
|
...options.fetchOptions ?? {}
|
|
};
|
|
return { req, url, timeout: options.timeout };
|
|
}
|
|
async buildHeaders({ options, method, bodyHeaders, retryCount, timeout }) {
|
|
const headers = buildHeaders2([
|
|
{
|
|
Accept: "application/json",
|
|
"User-Agent": this.getUserAgent(),
|
|
"X-Stainless-Retry-Count": String(retryCount),
|
|
"X-Stainless-Timeout": String(Math.trunc(timeout / 1e3)),
|
|
...getPlatformHeaders2(),
|
|
...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0,
|
|
"anthropic-version": "2023-06-01"
|
|
},
|
|
await this.authHeaders(options),
|
|
this._options.defaultHeaders,
|
|
bodyHeaders,
|
|
options.headers
|
|
]);
|
|
this.validateHeaders(headers);
|
|
return headers.values;
|
|
}
|
|
_makeAbort(controller) {
|
|
return () => controller.abort();
|
|
}
|
|
buildBody({ options: { body, headers: rawHeaders } }) {
|
|
if (!body) {
|
|
return { bodyHeaders: void 0, body: void 0 };
|
|
}
|
|
const headers = buildHeaders2([rawHeaders]);
|
|
if (
|
|
// Pass raw type verbatim
|
|
ArrayBuffer.isView(body) || body instanceof ArrayBuffer || body instanceof DataView || typeof body === "string" && // Preserve legacy string encoding behavior for now
|
|
headers.values.has("content-type") || // `Blob` is superset of `File`
|
|
globalThis.Blob && body instanceof globalThis.Blob || // `FormData` -> `multipart/form-data`
|
|
body instanceof FormData || // `URLSearchParams` -> `application/x-www-form-urlencoded`
|
|
body instanceof URLSearchParams || // Send chunked stream (each chunk has own `length`)
|
|
globalThis.ReadableStream && body instanceof globalThis.ReadableStream
|
|
) {
|
|
return { bodyHeaders: void 0, body };
|
|
} else if (this.isStreamBody(body)) {
|
|
return { bodyHeaders: void 0, body: ReadableStreamFrom2(body) };
|
|
} else if (typeof body === "object" && headers.values.get("content-type") === "application/x-www-form-urlencoded") {
|
|
return {
|
|
bodyHeaders: { "content-type": "application/x-www-form-urlencoded" },
|
|
body: this.stringifyQuery(body)
|
|
};
|
|
} else {
|
|
return __classPrivateFieldGet2(this, _BaseAnthropic_encoder, "f").call(this, { body, headers });
|
|
}
|
|
}
|
|
/**
|
|
* Whether `body` is sent as a stream, which can be read only once:
|
|
* a `ReadableStream`, an async iterable or an iterator.
|
|
*/
|
|
isStreamBody(body) {
|
|
if (globalThis.ReadableStream && body instanceof globalThis.ReadableStream) {
|
|
return true;
|
|
}
|
|
return typeof body === "object" && body !== null && (Symbol.asyncIterator in body || Symbol.iterator in body && "next" in body && typeof body.next === "function");
|
|
}
|
|
}
|
|
_a5 = BaseAnthropic2, _BaseAnthropic_encoder = /* @__PURE__ */ new WeakMap(), _BaseAnthropic_instances = /* @__PURE__ */ new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden2() {
|
|
return this.baseURL !== "https://api.anthropic.com";
|
|
};
|
|
BaseAnthropic2.Anthropic = _a5;
|
|
BaseAnthropic2.DEFAULT_TIMEOUT = 6e5;
|
|
BaseAnthropic2.AnthropicError = AnthropicError;
|
|
BaseAnthropic2.APIError = APIError2;
|
|
BaseAnthropic2.APIConnectionError = APIConnectionError2;
|
|
BaseAnthropic2.APIConnectionTimeoutError = APIConnectionTimeoutError2;
|
|
BaseAnthropic2.APIUserAbortError = APIUserAbortError2;
|
|
BaseAnthropic2.NotFoundError = NotFoundError2;
|
|
BaseAnthropic2.ConflictError = ConflictError2;
|
|
BaseAnthropic2.RateLimitError = RateLimitError2;
|
|
BaseAnthropic2.BadRequestError = BadRequestError2;
|
|
BaseAnthropic2.AuthenticationError = AuthenticationError2;
|
|
BaseAnthropic2.InternalServerError = InternalServerError2;
|
|
BaseAnthropic2.PermissionDeniedError = PermissionDeniedError2;
|
|
BaseAnthropic2.UnprocessableEntityError = UnprocessableEntityError2;
|
|
BaseAnthropic2.toFile = toFile2;
|
|
BaseAnthropic2.HUMAN_PROMPT = HUMAN_PROMPT;
|
|
BaseAnthropic2.AI_PROMPT = AI_PROMPT;
|
|
return BaseAnthropic2;
|
|
})();
|
|
Anthropic = /* @__PURE__ */ (() => {
|
|
class Anthropic2 extends BaseAnthropic {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.completions = new Completions3(this);
|
|
this.messages = new Messages4(this);
|
|
this.models = new Models3(this);
|
|
this.files = new Files6(this);
|
|
this.skills = new Skills3(this);
|
|
this.beta = new Beta2(this);
|
|
}
|
|
}
|
|
Anthropic2.Completions = Completions3;
|
|
Anthropic2.Messages = Messages4;
|
|
Anthropic2.Models = Models3;
|
|
Anthropic2.Files = Files6;
|
|
Anthropic2.Skills = Skills3;
|
|
Anthropic2.Beta = Beta2;
|
|
return Anthropic2;
|
|
})();
|
|
}
|
|
});
|
|
|
|
// node_modules/@anthropic-ai/sdk/index.mjs
|
|
var init_sdk = __esm({
|
|
"node_modules/@anthropic-ai/sdk/index.mjs"() {
|
|
init_client2();
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/env-api-keys.js
|
|
var __rewriteRelativeImportExtension3, _existsSync, _homedir, _join, dynamicImport, NODE_FS_SPECIFIER, NODE_OS_SPECIFIER, NODE_PATH_SPECIFIER, ANTHROPIC_AUTH_TOKEN_ENV, ANTHROPIC_OAUTH_TOKEN_ENV, ANTHROPIC_API_KEY_ENV, ANTHROPIC_FEDERATION_RULE_ID_ENV, ANTHROPIC_ORGANIZATION_ID_ENV, ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, ANTHROPIC_WORKSPACE_ID_ENV;
|
|
var init_env_api_keys = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/env-api-keys.js"() {
|
|
__rewriteRelativeImportExtension3 = function(path4, preserveJsx) {
|
|
if (typeof path4 === "string" && /^\.\.?\//.test(path4)) {
|
|
return path4.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
|
|
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
|
|
});
|
|
}
|
|
return path4;
|
|
};
|
|
_existsSync = null;
|
|
_homedir = null;
|
|
_join = null;
|
|
dynamicImport = (specifier) => import(__rewriteRelativeImportExtension3(specifier));
|
|
NODE_FS_SPECIFIER = "node:fs";
|
|
NODE_OS_SPECIFIER = "node:os";
|
|
NODE_PATH_SPECIFIER = "node:path";
|
|
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
|
|
dynamicImport(NODE_FS_SPECIFIER).then((m) => {
|
|
_existsSync = m.existsSync;
|
|
});
|
|
dynamicImport(NODE_OS_SPECIFIER).then((m) => {
|
|
_homedir = m.homedir;
|
|
});
|
|
dynamicImport(NODE_PATH_SPECIFIER).then((m) => {
|
|
_join = m.join;
|
|
});
|
|
}
|
|
ANTHROPIC_AUTH_TOKEN_ENV = "ANTHROPIC_AUTH_TOKEN";
|
|
ANTHROPIC_OAUTH_TOKEN_ENV = "ANTHROPIC_OAUTH_TOKEN";
|
|
ANTHROPIC_API_KEY_ENV = "ANTHROPIC_API_KEY";
|
|
ANTHROPIC_FEDERATION_RULE_ID_ENV = "ANTHROPIC_FEDERATION_RULE_ID";
|
|
ANTHROPIC_ORGANIZATION_ID_ENV = "ANTHROPIC_ORGANIZATION_ID";
|
|
ANTHROPIC_SERVICE_ACCOUNT_ID_ENV = "ANTHROPIC_SERVICE_ACCOUNT_ID";
|
|
ANTHROPIC_IDENTITY_TOKEN_FILE_ENV = "ANTHROPIC_IDENTITY_TOKEN_FILE";
|
|
ANTHROPIC_WORKSPACE_ID_ENV = "ANTHROPIC_WORKSPACE_ID";
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/utils/openrouter-cost.js
|
|
function isValidCost(value) {
|
|
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
}
|
|
function isOpenRouterModel(model2) {
|
|
return model2.provider === "openrouter" || model2.baseUrl.includes("openrouter.ai");
|
|
}
|
|
function applyOpenRouterReportedCost(usage, reported) {
|
|
if (!isValidCost(reported.cost))
|
|
return;
|
|
if (reported.is_byok === false) {
|
|
usage.cost.total = reported.cost;
|
|
usage.cost.totalFromProvider = true;
|
|
return;
|
|
}
|
|
if (reported.is_byok === true) {
|
|
const details = reported.cost_details;
|
|
if (!details)
|
|
return;
|
|
let upstreamCost = details.upstream_inference_cost;
|
|
if (upstreamCost === null) {
|
|
if (!isValidCost(details.upstream_inference_prompt_cost) || !isValidCost(details.upstream_inference_completions_cost)) {
|
|
return;
|
|
}
|
|
upstreamCost = details.upstream_inference_prompt_cost + details.upstream_inference_completions_cost;
|
|
}
|
|
if (!isValidCost(upstreamCost))
|
|
return;
|
|
usage.cost.total = reported.cost + upstreamCost;
|
|
usage.cost.totalFromProvider = true;
|
|
}
|
|
}
|
|
var init_openrouter_cost = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/utils/openrouter-cost.js"() {
|
|
}
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js
|
|
var anthropic_messages_exports = {};
|
|
__export(anthropic_messages_exports, {
|
|
stream: () => stream3,
|
|
streamSimple: () => streamSimple2
|
|
});
|
|
function resolveCacheRetention2(cacheRetention, env) {
|
|
if (cacheRetention) {
|
|
return cacheRetention;
|
|
}
|
|
if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") {
|
|
return "long";
|
|
}
|
|
return "short";
|
|
}
|
|
function getCacheControl(model2, cacheRetention, env) {
|
|
const retention = resolveCacheRetention2(cacheRetention, env);
|
|
if (retention === "none") {
|
|
return { retention };
|
|
}
|
|
const ttl = retention === "long" && getAnthropicCompat(model2).supportsLongCacheRetention ? "1h" : void 0;
|
|
return {
|
|
retention,
|
|
cacheControl: { type: "ephemeral", ...ttl && { ttl } }
|
|
};
|
|
}
|
|
function convertImageBlock(image) {
|
|
return {
|
|
type: "image",
|
|
source: {
|
|
type: "base64",
|
|
media_type: image.mimeType,
|
|
data: image.data
|
|
}
|
|
};
|
|
}
|
|
function convertContentBlocks(content) {
|
|
const hasImages = content.some((c) => c.type === "image");
|
|
if (!hasImages) {
|
|
return sanitizeSurrogates(content.map((c) => c.text).join("\n"));
|
|
}
|
|
const blocks = content.map((block) => {
|
|
if (block.type === "text") {
|
|
return {
|
|
type: "text",
|
|
text: sanitizeSurrogates(block.text)
|
|
};
|
|
}
|
|
return convertImageBlock(block);
|
|
});
|
|
const hasText = blocks.some((b) => b.type === "text");
|
|
if (!hasText) {
|
|
blocks.unshift({
|
|
type: "text",
|
|
text: "(see attached image)"
|
|
});
|
|
}
|
|
return blocks;
|
|
}
|
|
function shouldUseServerSideFallbackBeta(model2) {
|
|
return (model2.compat?.allowedFallbackModels?.length ?? 0) > 0;
|
|
}
|
|
function getAnthropicCompat(model2) {
|
|
const isOpenRouter2 = model2.provider === "openrouter" || model2.baseUrl.includes("openrouter.ai");
|
|
return {
|
|
supportsEagerToolInputStreaming: model2.compat?.supportsEagerToolInputStreaming ?? true,
|
|
supportsLongCacheRetention: model2.compat?.supportsLongCacheRetention ?? true,
|
|
sendSessionAffinityHeaders: model2.compat?.sendSessionAffinityHeaders ?? isOpenRouter2,
|
|
sessionAffinityFormat: model2.compat?.sessionAffinityFormat ?? (isOpenRouter2 ? "openrouter" : void 0),
|
|
supportsCacheControlOnTools: model2.compat?.supportsCacheControlOnTools ?? true,
|
|
supportsTemperature: model2.compat?.supportsTemperature ?? true,
|
|
allowEmptySignature: model2.compat?.allowEmptySignature ?? false,
|
|
supportsStrictTools: model2.compat?.supportsStrictTools ?? false,
|
|
supportsMidConvoSystemMessages: model2.compat?.supportsMidConvoSystemMessages ?? false,
|
|
supportsMidConvoToolChanges: model2.compat?.supportsMidConvoToolChanges ?? false
|
|
};
|
|
}
|
|
function mergeHeaders2(...headerSources) {
|
|
const merged = {};
|
|
for (const headers of headerSources) {
|
|
if (headers) {
|
|
Object.assign(merged, headers);
|
|
}
|
|
}
|
|
return merged;
|
|
}
|
|
function hasHeader2(headers, name) {
|
|
if (!headers)
|
|
return false;
|
|
const expected = name.toLowerCase();
|
|
for (const [key, value] of Object.entries(headers)) {
|
|
if (key.toLowerCase() === expected && value !== null && value.trim().length > 0)
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function hasRequestAuth(apiKey, headers) {
|
|
return !!apiKey || hasHeader2(headers, "authorization") || hasHeader2(headers, "x-api-key") || hasHeader2(headers, "cf-aig-authorization");
|
|
}
|
|
function assertRequestAuth(provider2, apiKey, headers) {
|
|
if (!hasRequestAuth(apiKey, headers))
|
|
throw new Error(`No API key for provider: ${provider2}`);
|
|
}
|
|
function getAnthropicFederation(model2, apiKey, headers, env) {
|
|
if (model2.provider !== "anthropic" || hasRequestAuth(apiKey, headers))
|
|
return void 0;
|
|
const federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env);
|
|
const organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env);
|
|
const identityTokenFile = getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, env);
|
|
if (!federationRuleId || !organizationId || !identityTokenFile)
|
|
return void 0;
|
|
return {
|
|
organization_id: organizationId,
|
|
workspace_id: getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV, env),
|
|
authentication: {
|
|
type: "oidc_federation",
|
|
federation_rule_id: federationRuleId,
|
|
service_account_id: getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, env),
|
|
identity_token: { source: "file", path: identityTokenFile }
|
|
}
|
|
};
|
|
}
|
|
function flushSseEvent(state2) {
|
|
if (!state2.event && state2.data.length === 0) {
|
|
return null;
|
|
}
|
|
const event = {
|
|
event: state2.event,
|
|
data: state2.data.join("\n"),
|
|
raw: [...state2.raw]
|
|
};
|
|
state2.event = null;
|
|
state2.data = [];
|
|
state2.raw = [];
|
|
return event;
|
|
}
|
|
function decodeSseLine(line, state2) {
|
|
if (line === "") {
|
|
return flushSseEvent(state2);
|
|
}
|
|
state2.raw.push(line);
|
|
if (line.startsWith(":")) {
|
|
return null;
|
|
}
|
|
const delimiterIndex = line.indexOf(":");
|
|
const fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);
|
|
let value = delimiterIndex === -1 ? "" : line.slice(delimiterIndex + 1);
|
|
if (value.startsWith(" ")) {
|
|
value = value.slice(1);
|
|
}
|
|
if (fieldName === "event") {
|
|
state2.event = value;
|
|
} else if (fieldName === "data") {
|
|
state2.data.push(value);
|
|
}
|
|
return null;
|
|
}
|
|
function nextLineBreakIndex(text) {
|
|
const carriageReturnIndex = text.indexOf("\r");
|
|
const newlineIndex = text.indexOf("\n");
|
|
if (carriageReturnIndex === -1) {
|
|
return newlineIndex;
|
|
}
|
|
if (newlineIndex === -1) {
|
|
return carriageReturnIndex;
|
|
}
|
|
return Math.min(carriageReturnIndex, newlineIndex);
|
|
}
|
|
function consumeLine(text) {
|
|
const lineBreakIndex = nextLineBreakIndex(text);
|
|
if (lineBreakIndex === -1) {
|
|
return null;
|
|
}
|
|
let nextIndex = lineBreakIndex + 1;
|
|
if (text[lineBreakIndex] === "\r" && text[nextIndex] === "\n") {
|
|
nextIndex += 1;
|
|
}
|
|
return {
|
|
line: text.slice(0, lineBreakIndex),
|
|
rest: text.slice(nextIndex)
|
|
};
|
|
}
|
|
async function* iterateSseMessages(body, signal) {
|
|
const reader = body.getReader();
|
|
const decoder3 = new TextDecoder();
|
|
const state2 = { event: null, data: [], raw: [] };
|
|
let buffer = "";
|
|
try {
|
|
while (true) {
|
|
if (signal?.aborted) {
|
|
throw new Error("Request was aborted");
|
|
}
|
|
const { value, done } = await reader.read();
|
|
if (done) {
|
|
break;
|
|
}
|
|
buffer += decoder3.decode(value, { stream: true });
|
|
let consumed2 = consumeLine(buffer);
|
|
while (consumed2) {
|
|
buffer = consumed2.rest;
|
|
const event = decodeSseLine(consumed2.line, state2);
|
|
if (event) {
|
|
yield event;
|
|
}
|
|
consumed2 = consumeLine(buffer);
|
|
}
|
|
}
|
|
buffer += decoder3.decode();
|
|
let consumed = consumeLine(buffer);
|
|
while (consumed) {
|
|
buffer = consumed.rest;
|
|
const event = decodeSseLine(consumed.line, state2);
|
|
if (event) {
|
|
yield event;
|
|
}
|
|
consumed = consumeLine(buffer);
|
|
}
|
|
if (buffer.length > 0) {
|
|
const event = decodeSseLine(buffer, state2);
|
|
if (event) {
|
|
yield event;
|
|
}
|
|
}
|
|
const trailingEvent = flushSseEvent(state2);
|
|
if (trailingEvent) {
|
|
yield trailingEvent;
|
|
}
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
async function* iterateAnthropicEvents(response, signal) {
|
|
if (!response.body) {
|
|
throw new Error("Attempted to iterate over an Anthropic response with no body");
|
|
}
|
|
let sawMessageStart = false;
|
|
let sawMessageEnd = false;
|
|
for await (const sse of iterateSseMessages(response.body, signal)) {
|
|
if (sse.event === "error") {
|
|
throw new Error(sse.data);
|
|
}
|
|
if (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? "")) {
|
|
continue;
|
|
}
|
|
try {
|
|
const event = parseJsonWithRepair(sse.data);
|
|
if (event.type === "message_start") {
|
|
sawMessageStart = true;
|
|
} else if (event.type === "message_stop") {
|
|
sawMessageEnd = true;
|
|
}
|
|
yield event;
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`);
|
|
}
|
|
}
|
|
if (sawMessageStart && !sawMessageEnd) {
|
|
throw new Error("Anthropic stream ended before message_stop");
|
|
}
|
|
}
|
|
function mapThinkingLevelToEffort(model2, level) {
|
|
const mapped = level ? model2.thinkingLevelMap?.[level] : void 0;
|
|
if (typeof mapped === "string")
|
|
return mapped;
|
|
switch (level) {
|
|
case "minimal":
|
|
case "low":
|
|
return "low";
|
|
case "medium":
|
|
return "medium";
|
|
case "high":
|
|
return "high";
|
|
default:
|
|
return "high";
|
|
}
|
|
}
|
|
function isOAuthToken(apiKey) {
|
|
return apiKey.includes("sk-ant-oat");
|
|
}
|
|
function createClient2(model2, apiKey, optionsHeaders, fetch2, dynamicHeaders, sessionId, federation, identity) {
|
|
if (model2.provider === "github-copilot") {
|
|
const client2 = new PiAnthropic({
|
|
apiKey: null,
|
|
authToken: apiKey ?? null,
|
|
baseURL: model2.baseUrl,
|
|
dangerouslyAllowBrowser: true,
|
|
fetch: fetch2,
|
|
defaultHeaders: mergeHeaders2(getIdentityHeaders(model2, identity), {
|
|
accept: "application/json",
|
|
"anthropic-dangerous-direct-browser-access": "true"
|
|
}, model2.headers, dynamicHeaders, optionsHeaders)
|
|
});
|
|
return { client: client2, isOAuthToken: false };
|
|
}
|
|
if (apiKey && isOAuthToken(apiKey)) {
|
|
const client2 = new PiAnthropic({
|
|
apiKey: null,
|
|
authToken: apiKey,
|
|
baseURL: model2.baseUrl,
|
|
dangerouslyAllowBrowser: true,
|
|
fetch: fetch2,
|
|
defaultHeaders: mergeHeaders2({
|
|
accept: "application/json",
|
|
"anthropic-dangerous-direct-browser-access": "true",
|
|
"user-agent": `claude-cli/${claudeCodeVersion}`,
|
|
"x-app": "cli"
|
|
}, model2.headers, optionsHeaders)
|
|
});
|
|
return { client: client2, isOAuthToken: true };
|
|
}
|
|
const compat = getAnthropicCompat(model2);
|
|
const sessionAffinityHeaders = {};
|
|
if (sessionId && compat.sendSessionAffinityHeaders) {
|
|
const header = compat.sessionAffinityFormat === "openrouter" ? "x-session-id" : "x-session-affinity";
|
|
sessionAffinityHeaders[header] = sessionId;
|
|
}
|
|
const defaultHeaders = mergeHeaders2(getIdentityHeaders(model2, identity), {
|
|
accept: "application/json",
|
|
"anthropic-dangerous-direct-browser-access": "true"
|
|
}, sessionAffinityHeaders, model2.headers, optionsHeaders);
|
|
if (federation) {
|
|
const key = JSON.stringify([model2.baseUrl, federation]);
|
|
if (federationClient?.key !== key || federationClient.fetch !== fetch2) {
|
|
const client2 = new PiAnthropic({
|
|
apiKey: null,
|
|
authToken: null,
|
|
config: federation,
|
|
baseURL: model2.baseUrl,
|
|
dangerouslyAllowBrowser: true,
|
|
fetch: fetch2
|
|
});
|
|
federationClient = { key, fetch: fetch2, client: client2 };
|
|
}
|
|
return { client: federationClient.client.withOptions({ defaultHeaders }), isOAuthToken: false };
|
|
}
|
|
const client = new PiAnthropic({
|
|
apiKey: apiKey ?? null,
|
|
authToken: null,
|
|
baseURL: model2.baseUrl,
|
|
dangerouslyAllowBrowser: true,
|
|
fetch: fetch2,
|
|
defaultHeaders
|
|
});
|
|
return { client, isOAuthToken: false };
|
|
}
|
|
function getBetaFeatures(model2, context, isOAuthToken2, nativeToolChanges, options) {
|
|
let configuredFeatures;
|
|
for (const headers of [model2.headers, options?.headers]) {
|
|
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
if (name.toLowerCase() === "anthropic-beta")
|
|
configuredFeatures = value;
|
|
}
|
|
}
|
|
if (configuredFeatures === null)
|
|
return [];
|
|
if (configuredFeatures !== void 0) {
|
|
return [
|
|
...new Set(configuredFeatures.split(",").map((feature) => feature.trim()).filter((feature) => feature.length > 0))
|
|
];
|
|
}
|
|
const features = [];
|
|
if (isOAuthToken2)
|
|
features.push("claude-code-20250219", "oauth-2025-04-20");
|
|
if (shouldUseFineGrainedToolStreamingBeta(model2, context))
|
|
features.push(FINE_GRAINED_TOOL_STREAMING_BETA);
|
|
if (model2.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true) && model2.compat?.forceAdaptiveThinking !== true) {
|
|
features.push(INTERLEAVED_THINKING_BETA);
|
|
}
|
|
if (shouldUseServerSideFallbackBeta(model2))
|
|
features.push(SERVER_SIDE_FALLBACK_BETA);
|
|
if (model2.compat?.supportsMidConvoEffort === true) {
|
|
features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);
|
|
}
|
|
if (nativeToolChanges)
|
|
features.push(INLINE_TOOLS_BETA);
|
|
return [...new Set(features)];
|
|
}
|
|
function buildParams2(model2, context, isOAuthToken2, options, disablePreferredStrictTools = false) {
|
|
const { cacheControl } = getCacheControl(model2, options?.cacheRetention, options?.env);
|
|
const compat = getAnthropicCompat(model2);
|
|
const initialSystemMessage = getInitialSystemMessage(context.messages);
|
|
const initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : "";
|
|
const transformedMessages = transformMessages(context.messages, model2, normalizeToolCallId);
|
|
const conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages;
|
|
let hasPreferredStrictTools = false;
|
|
const convertToolDefinitions = (tools, toolCacheControl2) => {
|
|
const definitions = convertTools(tools, isOAuthToken2, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl2, disablePreferredStrictTools);
|
|
if (definitions.some((definition, index) => definition.strict === true && prefersJsonSchemaStrictSampling(tools[index]))) {
|
|
hasPreferredStrictTools = true;
|
|
}
|
|
return definitions;
|
|
};
|
|
const initialTools = initialSystemMessage?.toolsAdded ?? [];
|
|
const nativeToolChanges = compat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0;
|
|
const thinkingDisabled = model2.reasoning && options?.thinkingEnabled === false && model2.thinkingLevelMap?.off !== null;
|
|
const effortMessages = model2.compat?.supportsMidConvoEffort === true && !thinkingDisabled;
|
|
const converted = convertMessages(conversationMessages, isOAuthToken2, cacheControl, compat.allowEmptySignature, effortMessages ? model2.provider : void 0, nativeToolChanges ? convertToolDefinitions : void 0);
|
|
const activeEffort = options?.effort ?? "high";
|
|
const betaFeatures = getBetaFeatures(model2, context, isOAuthToken2, nativeToolChanges, options);
|
|
const params = {
|
|
model: model2.id,
|
|
messages: effortMessages ? insertThinkingLevelMessages(converted, activeEffort) : converted.messages,
|
|
max_tokens: options?.maxTokens ?? model2.maxTokens,
|
|
stream: true,
|
|
...betaFeatures.length > 0 ? { betas: betaFeatures } : {}
|
|
};
|
|
if (isOAuthToken2) {
|
|
params.system = [
|
|
{
|
|
type: "text",
|
|
text: "You are Claude Code, Anthropic's official CLI for Claude.",
|
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
}
|
|
];
|
|
if (initialSystemText) {
|
|
params.system.push({
|
|
type: "text",
|
|
text: sanitizeSurrogates(initialSystemText),
|
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
});
|
|
}
|
|
} else if (initialSystemText) {
|
|
params.system = [
|
|
{
|
|
type: "text",
|
|
text: sanitizeSurrogates(initialSystemText),
|
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
}
|
|
];
|
|
}
|
|
if (options?.temperature !== void 0 && !options?.thinkingEnabled && model2.compat?.supportsMidConvoEffort !== true && compat.supportsTemperature) {
|
|
params.temperature = options.temperature;
|
|
}
|
|
const toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : void 0;
|
|
if (nativeToolChanges) {
|
|
params.tools = [...convertToolDefinitions(initialTools, toolCacheControl), DEFERRED_TOOL_PLACEHOLDER];
|
|
} else {
|
|
const tools = getCurrentTools(context.messages);
|
|
if (tools.length > 0) {
|
|
params.tools = convertToolDefinitions(tools, toolCacheControl);
|
|
}
|
|
}
|
|
if (thinkingDisabled) {
|
|
params.thinking = { type: "disabled" };
|
|
} else if (effortMessages) {
|
|
params.thinking = {
|
|
type: "adaptive",
|
|
display: options?.thinkingDisplay ?? "summarized",
|
|
block_binding: { prefix_mismatch_behavior: "drop_block" }
|
|
};
|
|
params.output_config = { effort: "low" };
|
|
} else if (model2.reasoning && options?.thinkingEnabled) {
|
|
const display = options.thinkingDisplay ?? "summarized";
|
|
if (model2.compat?.forceAdaptiveThinking === true) {
|
|
params.thinking = { type: "adaptive", display };
|
|
if (options.effort) {
|
|
params.output_config = { effort: options.effort };
|
|
}
|
|
} else {
|
|
params.thinking = {
|
|
type: "enabled",
|
|
budget_tokens: options.thinkingBudgetTokens || 1024,
|
|
display
|
|
};
|
|
}
|
|
}
|
|
if (options?.metadata) {
|
|
const userId = options.metadata.user_id;
|
|
if (typeof userId === "string") {
|
|
params.metadata = { user_id: userId };
|
|
}
|
|
}
|
|
if (options?.toolChoice) {
|
|
if (typeof options.toolChoice === "string") {
|
|
params.tool_choice = { type: options.toolChoice };
|
|
} else {
|
|
params.tool_choice = options.toolChoice;
|
|
}
|
|
}
|
|
const allowedFallbackModels = model2.compat?.allowedFallbackModels;
|
|
if (allowedFallbackModels && allowedFallbackModels.length > 0) {
|
|
params.fallbacks = allowedFallbackModels.map((fallback2) => ({ model: fallback2.model }));
|
|
}
|
|
return { params, hasPreferredStrictTools, providerThinkingLevel: effortMessages ? activeEffort : void 0 };
|
|
}
|
|
function normalizeToolCallId(id) {
|
|
return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
|
|
}
|
|
function convertToolResult(msg, content = msg.content) {
|
|
return {
|
|
type: "tool_result",
|
|
tool_use_id: msg.toolCallId,
|
|
content: convertContentBlocks(content),
|
|
is_error: msg.isError
|
|
};
|
|
}
|
|
function convertMessages(transformedMessages, isOAuthToken2, cacheControl, allowEmptySignature = false, managedProvider, convertToolDefinitions) {
|
|
const params = [];
|
|
const assistantLevels = /* @__PURE__ */ new Map();
|
|
const pendingSystemMessages = [];
|
|
const flushPendingSystemMessages = () => {
|
|
params.push(...pendingSystemMessages);
|
|
pendingSystemMessages.length = 0;
|
|
};
|
|
for (let i = 0; i < transformedMessages.length; i++) {
|
|
const msg = transformedMessages[i];
|
|
if (msg.role === "system") {
|
|
const text = renderSystemMessageUpdate(msg);
|
|
const blocks = [];
|
|
if (text.length > 0)
|
|
blocks.push({ type: "text", text: sanitizeSurrogates(text) });
|
|
if (convertToolDefinitions) {
|
|
const added = msg.toolsAdded ?? [];
|
|
const redefined = new Set(added.map((tool) => tool.name));
|
|
for (const tool of msg.toolsRemoved ?? []) {
|
|
if (redefined.has(tool.name))
|
|
continue;
|
|
blocks.push({
|
|
type: "tool_removal",
|
|
tool: { type: "tool_reference", name: isOAuthToken2 ? toClaudeCodeName(tool.name) : tool.name }
|
|
});
|
|
}
|
|
for (const definition of convertToolDefinitions(added)) {
|
|
blocks.push({ type: "tool_addition", tool: { type: "tool_definition", definition } });
|
|
}
|
|
}
|
|
if (blocks.length > 0)
|
|
pendingSystemMessages.push({ role: "system", content: blocks });
|
|
} else if (msg.role === "user") {
|
|
if (typeof msg.content === "string") {
|
|
if (msg.content.trim().length > 0) {
|
|
params.push({
|
|
role: "user",
|
|
content: sanitizeSurrogates(msg.content)
|
|
});
|
|
}
|
|
} else {
|
|
const blocks = msg.content.map((item) => {
|
|
if (item.type === "text") {
|
|
return {
|
|
type: "text",
|
|
text: sanitizeSurrogates(item.text)
|
|
};
|
|
} else {
|
|
return convertImageBlock(item);
|
|
}
|
|
});
|
|
const filteredBlocks = blocks.filter((b) => {
|
|
if (b.type === "text") {
|
|
return b.text.trim().length > 0;
|
|
}
|
|
return true;
|
|
});
|
|
if (filteredBlocks.length === 0)
|
|
continue;
|
|
params.push({
|
|
role: "user",
|
|
content: filteredBlocks
|
|
});
|
|
}
|
|
} else if (msg.role === "assistant") {
|
|
const blocks = [];
|
|
for (const block of msg.content) {
|
|
if (block.type === "text") {
|
|
if (block.text.trim().length === 0)
|
|
continue;
|
|
blocks.push({
|
|
type: "text",
|
|
text: sanitizeSurrogates(block.text)
|
|
});
|
|
} else if (block.type === "thinking") {
|
|
if (block.redacted) {
|
|
blocks.push({
|
|
type: "redacted_thinking",
|
|
data: block.thinkingSignature
|
|
});
|
|
continue;
|
|
}
|
|
const thinkingSignature = block.thinkingSignature;
|
|
const hasThinkingSignature = !!thinkingSignature && thinkingSignature.trim().length > 0;
|
|
if (block.thinking.trim().length === 0 && !hasThinkingSignature)
|
|
continue;
|
|
if (!hasThinkingSignature) {
|
|
blocks.push(allowEmptySignature ? {
|
|
type: "thinking",
|
|
thinking: sanitizeSurrogates(block.thinking),
|
|
signature: ""
|
|
} : {
|
|
type: "text",
|
|
text: sanitizeSurrogates(block.thinking)
|
|
});
|
|
} else {
|
|
blocks.push({
|
|
type: "thinking",
|
|
thinking: sanitizeSurrogates(block.thinking),
|
|
signature: thinkingSignature
|
|
});
|
|
}
|
|
} else if (block.type === "toolCall") {
|
|
blocks.push({
|
|
type: "tool_use",
|
|
id: block.id,
|
|
name: isOAuthToken2 ? toClaudeCodeName(block.name) : block.name,
|
|
input: block.arguments ?? {}
|
|
});
|
|
}
|
|
}
|
|
if (blocks.length === 0)
|
|
continue;
|
|
flushPendingSystemMessages();
|
|
const messageIndex = params.length;
|
|
params.push({
|
|
role: "assistant",
|
|
content: blocks
|
|
});
|
|
if (managedProvider !== void 0 && msg.api === "anthropic-messages" && msg.provider === managedProvider && isAnthropicEffort(msg.providerThinkingLevel)) {
|
|
assistantLevels.set(messageIndex, msg.providerThinkingLevel);
|
|
}
|
|
} else if (msg.role === "toolResult") {
|
|
const toolResults = [];
|
|
const errorImages = [];
|
|
let j = i;
|
|
while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
|
|
const toolMsg = transformedMessages[j];
|
|
const split = splitErrorToolResultImages(toolMsg);
|
|
toolResults.push(convertToolResult(toolMsg, split?.content));
|
|
if (split) {
|
|
errorImages.push({ type: "text", text: split.caption }, ...split.images.map(convertImageBlock));
|
|
}
|
|
j++;
|
|
}
|
|
i = j - 1;
|
|
params.push({
|
|
role: "user",
|
|
content: [...toolResults, ...errorImages]
|
|
});
|
|
}
|
|
}
|
|
flushPendingSystemMessages();
|
|
if (cacheControl && params.length > 0) {
|
|
const lastMessage = params[params.length - 1];
|
|
if (lastMessage.role === "user" || lastMessage.role === "system") {
|
|
if (Array.isArray(lastMessage.content)) {
|
|
const lastBlock = lastMessage.content[lastMessage.content.length - 1];
|
|
if (lastBlock && (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result" || lastBlock.type === "tool_addition" || lastBlock.type === "tool_removal")) {
|
|
lastBlock.cache_control = cacheControl;
|
|
}
|
|
} else if (typeof lastMessage.content === "string") {
|
|
lastMessage.content = [
|
|
{
|
|
type: "text",
|
|
text: lastMessage.content,
|
|
cache_control: cacheControl
|
|
}
|
|
];
|
|
}
|
|
}
|
|
}
|
|
return { messages: params, assistantLevels };
|
|
}
|
|
function isAnthropicEffort(value) {
|
|
return value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max";
|
|
}
|
|
function insertThinkingLevelMessages(converted, activeEffort) {
|
|
const messages = [];
|
|
for (let index = 0; index < converted.messages.length; index++) {
|
|
const historicalEffort = converted.assistantLevels.get(index);
|
|
if (historicalEffort !== void 0) {
|
|
messages.push({ role: "system", content: [], output_config: { effort: historicalEffort } });
|
|
}
|
|
messages.push(converted.messages[index]);
|
|
}
|
|
messages.push({ role: "system", content: [], output_config: { effort: activeEffort } });
|
|
return messages;
|
|
}
|
|
function shouldUseFineGrainedToolStreamingBeta(model2, context) {
|
|
return getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model2).supportsEagerToolInputStreaming;
|
|
}
|
|
function convertTools(tools, isOAuthToken2, supportsEagerToolInputStreaming, supportsStrictTools, cacheControl, disablePreferredStrictTools = false) {
|
|
if (!tools)
|
|
return [];
|
|
return tools.map((tool, index) => {
|
|
const strict = disablePreferredStrictTools && prefersJsonSchemaStrictSampling(tool) ? void 0 : resolveJsonSchemaStrictSampling(tool, supportsStrictTools, isAnthropicStrictUnsupportedKeyword);
|
|
const parameters = getJsonSchemaToolParameters(tool, strict);
|
|
const schema4 = parameters;
|
|
const legacyInputSchema = {
|
|
type: "object",
|
|
properties: schema4.properties ?? {},
|
|
required: schema4.required ?? []
|
|
};
|
|
const inputSchema = strict === true ? {
|
|
...parameters,
|
|
...legacyInputSchema
|
|
} : legacyInputSchema;
|
|
return {
|
|
name: isOAuthToken2 ? toClaudeCodeName(tool.name) : tool.name,
|
|
description: tool.description,
|
|
...supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {},
|
|
...strict === true ? { strict: true } : {},
|
|
input_schema: inputSchema,
|
|
...cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}
|
|
};
|
|
});
|
|
}
|
|
function mapStopReason2(reason, stopDetails) {
|
|
switch (reason) {
|
|
case "end_turn":
|
|
return { stopReason: "stop" };
|
|
case "max_tokens":
|
|
return { stopReason: "length" };
|
|
case "tool_use":
|
|
return { stopReason: "toolUse" };
|
|
case "refusal":
|
|
return {
|
|
stopReason: "error",
|
|
errorMessage: stopDetails?.explanation || `The model refused to complete the request`
|
|
};
|
|
case "pause_turn":
|
|
return { stopReason: "stop" };
|
|
case "stop_sequence":
|
|
return { stopReason: "stop" };
|
|
// We don't supply stop sequences, so this should never happen
|
|
case "sensitive":
|
|
return { stopReason: "error", errorMessage: "Provider stopped with: sensitive" };
|
|
default:
|
|
throw new Error(`Unhandled stop reason: ${reason}`);
|
|
}
|
|
}
|
|
var claudeCodeVersion, claudeCodeTools, ccToolLookup, toClaudeCodeName, fromClaudeCodeName, FINE_GRAINED_TOOL_STREAMING_BETA, INTERLEAVED_THINKING_BETA, SERVER_SIDE_FALLBACK_BETA, MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA, INLINE_TOOLS_BETA, DEFERRED_TOOL_PLACEHOLDER, PiAnthropic, federationClient, ANTHROPIC_MESSAGE_EVENTS, stream3, streamSimple2, ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS, ANTHROPIC_STRICT_STRING_FORMATS, isAnthropicStrictUnsupportedKeyword;
|
|
var init_anthropic_messages = __esm({
|
|
"node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js"() {
|
|
init_sdk();
|
|
init_env_api_keys();
|
|
init_models();
|
|
init_diagnostics();
|
|
init_event_stream();
|
|
init_headers();
|
|
init_identity();
|
|
init_json_parse();
|
|
init_openrouter_cost();
|
|
init_provider_env();
|
|
init_provider_retry();
|
|
init_sanitize_unicode();
|
|
init_streaming_json();
|
|
init_text();
|
|
init_transcript();
|
|
init_constrained_sampling();
|
|
init_github_copilot_headers();
|
|
init_simple_options();
|
|
init_transform_messages();
|
|
claudeCodeVersion = "2.1.280";
|
|
claudeCodeTools = [
|
|
"Read",
|
|
"Write",
|
|
"Edit",
|
|
"Bash",
|
|
"Grep",
|
|
"Glob",
|
|
"AskUserQuestion",
|
|
"EnterPlanMode",
|
|
"ExitPlanMode",
|
|
"KillShell",
|
|
"NotebookEdit",
|
|
"Skill",
|
|
"Task",
|
|
"TaskOutput",
|
|
"TodoWrite",
|
|
"WebFetch",
|
|
"WebSearch"
|
|
];
|
|
ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
|
|
toClaudeCodeName = (name) => ccToolLookup.get(name.toLowerCase()) ?? name;
|
|
fromClaudeCodeName = (name, tools) => {
|
|
if (tools && tools.length > 0) {
|
|
const lowerName = name.toLowerCase();
|
|
const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
|
|
if (matchedTool)
|
|
return matchedTool.name;
|
|
}
|
|
return name;
|
|
};
|
|
FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";
|
|
INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
|
|
SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01";
|
|
MID_CONVERSATION_OUTPUT_CONFIG_BETA = "mid-conversation-output-config-2026-07-01";
|
|
THINKING_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
|
|
INLINE_TOOLS_BETA = "inline-tools-2026-09-15";
|
|
DEFERRED_TOOL_PLACEHOLDER = {
|
|
name: "__pi_deferred_placeholder__",
|
|
description: "Reserved placeholder. Never available. Never call this.",
|
|
input_schema: { type: "object", properties: {}, required: [] },
|
|
defer_loading: true
|
|
};
|
|
PiAnthropic = class extends Anthropic {
|
|
_shouldResolveDefaultCredentials() {
|
|
return false;
|
|
}
|
|
};
|
|
ANTHROPIC_MESSAGE_EVENTS = /* @__PURE__ */ new Set([
|
|
"message_start",
|
|
"message_delta",
|
|
"message_stop",
|
|
"content_block_start",
|
|
"content_block_delta",
|
|
"content_block_stop"
|
|
]);
|
|
stream3 = (model2, context, options) => {
|
|
const stream4 = new AssistantMessageEventStream();
|
|
const normalizedContext = resolveTranscript(context, getAnthropicCompat(model2).supportsMidConvoSystemMessages);
|
|
const currentTools = getCurrentTools(normalizedContext.messages);
|
|
(async () => {
|
|
const output = {
|
|
role: "assistant",
|
|
content: [],
|
|
api: model2.api,
|
|
provider: model2.provider,
|
|
model: model2.id,
|
|
usage: {
|
|
input: 0,
|
|
output: 0,
|
|
cacheRead: 0,
|
|
cacheWrite: 0,
|
|
totalTokens: 0,
|
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
|
|
},
|
|
stopReason: "pending",
|
|
timestamp: Date.now()
|
|
};
|
|
try {
|
|
let client;
|
|
let isOAuth;
|
|
let usageModel = model2;
|
|
let inputTransformations;
|
|
if (options?.client) {
|
|
client = options.client;
|
|
isOAuth = false;
|
|
} else {
|
|
const apiKey = options?.apiKey;
|
|
const federation = getAnthropicFederation(model2, apiKey, options?.headers, options?.env);
|
|
if (!federation)
|
|
assertRequestAuth(model2.provider, apiKey, options?.headers);
|
|
let copilotDynamicHeaders;
|
|
if (model2.provider === "github-copilot") {
|
|
const hasImages = hasCopilotVisionInput(normalizedContext.messages);
|
|
copilotDynamicHeaders = buildCopilotDynamicHeaders({
|
|
messages: normalizedContext.messages,
|
|
hasImages
|
|
});
|
|
}
|
|
const cacheRetention = resolveCacheRetention2(options?.cacheRetention, options?.env);
|
|
const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
|
|
const created = createClient2(model2, apiKey, options?.headers, options?.fetch, copilotDynamicHeaders, cacheSessionId, federation, options?.identity);
|
|
client = created.client;
|
|
isOAuth = created.isOAuthToken;
|
|
}
|
|
const requestOptions = {
|
|
...options?.signal ? { signal: options.signal } : {},
|
|
...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
|
|
maxRetries: 0
|
|
};
|
|
let disablePreferredStrictTools = false;
|
|
let response;
|
|
for (; ; ) {
|
|
options?.signal?.throwIfAborted();
|
|
const built = buildParams2(model2, normalizedContext, isOAuth, options, disablePreferredStrictTools);
|
|
if (built.providerThinkingLevel)
|
|
output.providerThinkingLevel = built.providerThinkingLevel;
|
|
let params = built.params;
|
|
const nextParams = await options?.onPayload?.(params, model2);
|
|
if (nextParams !== void 0) {
|
|
params = { ...nextParams, stream: true };
|
|
}
|
|
try {
|
|
response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {
|
|
maxRetries: options?.maxRetries,
|
|
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
signal: options?.signal
|
|
});
|
|
break;
|
|
} catch (error) {
|
|
if (options?.signal?.aborted || disablePreferredStrictTools || !built.hasPreferredStrictTools || !(error instanceof Anthropic.APIError) || error.status !== 400 || error.type !== "invalid_request_error" || !isStrictToolLimitErrorMessage(error.message)) {
|
|
throw error;
|
|
}
|
|
disablePreferredStrictTools = true;
|
|
appendAssistantMessageDiagnostic(output, {
|
|
type: "anthropic_strict_tools_fallback",
|
|
timestamp: Date.now(),
|
|
error: { message: error.message },
|
|
details: { reason: "strict_tool_limits_exceeded" }
|
|
});
|
|
}
|
|
}
|
|
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model2);
|
|
stream4.push({ type: "start", partial: output });
|
|
const openBlocks = /* @__PURE__ */ new Map();
|
|
const openBlock = (anthropicIndex) => {
|
|
const open = openBlocks.get(anthropicIndex);
|
|
return open === void 0 ? void 0 : { ...open, block: output.content[open.contentIndex] };
|
|
};
|
|
for await (const event of iterateAnthropicEvents(response, options?.signal)) {
|
|
await options?.onProviderStreamEvent?.(event, model2);
|
|
if (event.type === "message_start") {
|
|
output.responseId = event.message.id;
|
|
const transformations = event.message.input_transformations;
|
|
if (Array.isArray(transformations))
|
|
inputTransformations = transformations;
|
|
const responseModel = event.message.model;
|
|
if (responseModel !== model2.id)
|
|
output.responseModel = responseModel;
|
|
const fallbackCost = responseModel === model2.id ? void 0 : model2.compat?.allowedFallbackModels?.find((fallback2) => fallback2.provider === model2.provider && fallback2.model === responseModel)?.cost;
|
|
usageModel = fallbackCost ? { ...model2, id: responseModel, cost: fallbackCost } : model2;
|
|
output.usage.input = event.message.usage.input_tokens || 0;
|
|
output.usage.output = event.message.usage.output_tokens || 0;
|
|
output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
|
|
output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
|
|
output.usage.cacheWrite1h = event.message.usage.cache_creation?.ephemeral_1h_input_tokens || 0;
|
|
output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
|
|
calculateCost(usageModel, output.usage);
|
|
} else if (event.type === "content_block_start") {
|
|
if (event.content_block.type === "fallback") {
|
|
if (output.content.length > 0) {
|
|
throw new Error("Anthropic performed an unsupported mid-output model fallback");
|
|
}
|
|
continue;
|
|
}
|
|
if (event.content_block.type === "text") {
|
|
output.content.push({ type: "text", text: event.content_block.text ?? "" });
|
|
openBlocks.set(event.index, { contentIndex: output.content.length - 1 });
|
|
stream4.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
|
|
} else if (event.content_block.type === "thinking") {
|
|
output.content.push({
|
|
type: "thinking",
|
|
thinking: event.content_block.thinking ?? "",
|
|
thinkingSignature: event.content_block.signature ?? ""
|
|
});
|
|
openBlocks.set(event.index, { contentIndex: output.content.length - 1 });
|
|
stream4.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
|
|
} else if (event.content_block.type === "redacted_thinking") {
|
|
output.content.push({
|
|
type: "thinking",
|
|
thinking: "[Reasoning redacted]",
|
|
thinkingSignature: event.content_block.data,
|
|
redacted: true
|
|
});
|
|
openBlocks.set(event.index, { contentIndex: output.content.length - 1 });
|
|
stream4.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
|
|
} else if (event.content_block.type === "tool_use") {
|
|
output.content.push({
|
|
type: "toolCall",
|
|
id: event.content_block.id,
|
|
name: isOAuth ? fromClaudeCodeName(event.content_block.name, currentTools) : event.content_block.name,
|
|
arguments: event.content_block.input ?? {}
|
|
});
|
|
openBlocks.set(event.index, {
|
|
contentIndex: output.content.length - 1,
|
|
arguments: new ToolCallArgumentsStream()
|
|
});
|
|
stream4.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
|
|
}
|
|
} else if (event.type === "content_block_delta") {
|
|
const open = openBlock(event.index);
|
|
if (event.delta.type === "text_delta") {
|
|
if (open?.block.type === "text") {
|
|
open.block.text += event.delta.text;
|
|
stream4.push({
|
|
type: "text_delta",
|
|
contentIndex: open.contentIndex,
|
|
delta: event.delta.text,
|
|
partial: output
|
|
});
|
|
}
|
|
} else if (event.delta.type === "thinking_delta") {
|
|
if (open?.block.type === "thinking") {
|
|
open.block.thinking += event.delta.thinking;
|
|
stream4.push({
|
|
type: "thinking_delta",
|
|
contentIndex: open.contentIndex,
|
|
delta: event.delta.thinking,
|
|
partial: output
|
|
});
|
|
}
|
|
} else if (event.delta.type === "input_json_delta") {
|
|
if (open?.block.type === "toolCall" && open.arguments !== void 0) {
|
|
open.block.arguments = open.arguments.append(event.delta.partial_json);
|
|
stream4.push({
|
|
type: "toolcall_delta",
|
|
contentIndex: open.contentIndex,
|
|
delta: event.delta.partial_json,
|
|
partial: output
|
|
});
|
|
}
|
|
} else if (event.delta.type === "signature_delta") {
|
|
if (open?.block.type === "thinking") {
|
|
open.block.thinkingSignature = open.block.thinkingSignature || "";
|
|
open.block.thinkingSignature += event.delta.signature;
|
|
}
|
|
}
|
|
} else if (event.type === "content_block_stop") {
|
|
const open = openBlock(event.index);
|
|
openBlocks.delete(event.index);
|
|
if (open) {
|
|
const { block, contentIndex: index } = open;
|
|
if (block.type === "text") {
|
|
stream4.push({
|
|
type: "text_end",
|
|
contentIndex: index,
|
|
content: block.text,
|
|
partial: output
|
|
});
|
|
} else if (block.type === "thinking") {
|
|
stream4.push({
|
|
type: "thinking_end",
|
|
contentIndex: index,
|
|
content: block.thinking,
|
|
partial: output
|
|
});
|
|
} else if (block.type === "toolCall" && open.arguments !== void 0) {
|
|
Object.assign(block, open.arguments.finish());
|
|
stream4.push({
|
|
type: "toolcall_end",
|
|
contentIndex: index,
|
|
toolCall: block,
|
|
partial: output
|
|
});
|
|
}
|
|
}
|
|
} else if (event.type === "message_delta") {
|
|
const transformations = event.input_transformations;
|
|
if (Array.isArray(transformations))
|
|
inputTransformations = transformations;
|
|
if (event.delta.stop_reason) {
|
|
output.rawStopReason = event.delta.stop_reason;
|
|
const stopReasonResult = mapStopReason2(event.delta.stop_reason, event.delta.stop_details);
|
|
output.stopReason = stopReasonResult.stopReason;
|
|
if (stopReasonResult.errorMessage) {
|
|
output.errorMessage = stopReasonResult.errorMessage;
|
|
}
|
|
}
|
|
if (event.usage) {
|
|
if (event.usage.input_tokens != null) {
|
|
output.usage.input = event.usage.input_tokens;
|
|
}
|
|
if (event.usage.output_tokens != null) {
|
|
output.usage.output = event.usage.output_tokens;
|
|
}
|
|
if (event.usage.cache_read_input_tokens != null) {
|
|
output.usage.cacheRead = event.usage.cache_read_input_tokens;
|
|
}
|
|
if (event.usage.cache_creation_input_tokens != null) {
|
|
output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
|
|
}
|
|
const cacheCreation = event.usage.cache_creation;
|
|
if (cacheCreation?.ephemeral_1h_input_tokens != null) {
|
|
output.usage.cacheWrite1h = cacheCreation.ephemeral_1h_input_tokens;
|
|
}
|
|
const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;
|
|
if (thinkingTokens != null) {
|
|
output.usage.reasoning = thinkingTokens;
|
|
}
|
|
}
|
|
output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
|
|
calculateCost(usageModel, output.usage);
|
|
if (isOpenRouterModel(model2) && event.usage) {
|
|
applyOpenRouterReportedCost(output.usage, event.usage);
|
|
}
|
|
}
|
|
}
|
|
if (options?.signal?.aborted) {
|
|
throw new Error("Request was aborted");
|
|
}
|
|
if (output.stopReason === "pending") {
|
|
throw new Error("Anthropic stream ended without a stop reason");
|
|
}
|
|
if (output.stopReason === "aborted" || output.stopReason === "error") {
|
|
throw new Error(output.errorMessage || "An unknown error occurred");
|
|
}
|
|
if (inputTransformations && inputTransformations.length > 0) {
|
|
appendAssistantMessageDiagnostic(output, {
|
|
type: "anthropic_input_transformations",
|
|
timestamp: Date.now(),
|
|
details: {
|
|
transformations: inputTransformations.map((transformation) => ({
|
|
type: transformation.type ?? void 0,
|
|
path: transformation.path ?? void 0,
|
|
reason: transformation.reason ?? void 0
|
|
}))
|
|
}
|
|
});
|
|
}
|
|
stream4.push({ type: "done", reason: output.stopReason, message: output });
|
|
stream4.end();
|
|
} catch (error) {
|
|
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
|
|
stream4.push({ type: "error", reason: output.stopReason, error: output });
|
|
stream4.end();
|
|
}
|
|
})();
|
|
return stream4;
|
|
};
|
|
streamSimple2 = (model2, context, options) => {
|
|
if (!getAnthropicFederation(model2, options?.apiKey, options?.headers, options?.env)) {
|
|
assertRequestAuth(model2.provider, options?.apiKey, options?.headers);
|
|
}
|
|
const base = {
|
|
...buildBaseOptions(model2, context, options, options?.apiKey),
|
|
toolChoice: options?.toolChoice
|
|
};
|
|
if (!options?.reasoning) {
|
|
return stream3(model2, context, {
|
|
...base,
|
|
thinkingEnabled: false
|
|
});
|
|
}
|
|
if (model2.compat?.forceAdaptiveThinking === true) {
|
|
const effort = mapThinkingLevelToEffort(model2, options.reasoning);
|
|
return stream3(model2, context, {
|
|
...base,
|
|
thinkingEnabled: true,
|
|
effort
|
|
});
|
|
}
|
|
const adjusted = adjustMaxTokensForThinking(base.maxTokens, model2.maxTokens, options.reasoning, options.thinkingBudgets);
|
|
const maxTokens = clampMaxTokensToContext(model2, context, adjusted.maxTokens);
|
|
return stream3(model2, context, {
|
|
...base,
|
|
maxTokens,
|
|
thinkingEnabled: true,
|
|
thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
|
|
});
|
|
};
|
|
ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS = /* @__PURE__ */ new Set([
|
|
"minimum",
|
|
"maximum",
|
|
"exclusiveMinimum",
|
|
"exclusiveMaximum",
|
|
"multipleOf",
|
|
"maxItems",
|
|
"uniqueItems",
|
|
"minContains",
|
|
"maxContains",
|
|
"minProperties",
|
|
"maxProperties"
|
|
]);
|
|
ANTHROPIC_STRICT_STRING_FORMATS = /* @__PURE__ */ new Set([
|
|
"date-time",
|
|
"time",
|
|
"date",
|
|
"duration",
|
|
"email",
|
|
"hostname",
|
|
"uri",
|
|
"ipv4",
|
|
"ipv6",
|
|
"uuid"
|
|
]);
|
|
isAnthropicStrictUnsupportedKeyword = (key, value) => {
|
|
if (ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key))
|
|
return true;
|
|
if (key === "minItems")
|
|
return value !== 0 && value !== 1;
|
|
if (key === "format")
|
|
return typeof value !== "string" || !ANTHROPIC_STRICT_STRING_FORMATS.has(value);
|
|
return false;
|
|
};
|
|
}
|
|
});
|
|
|
|
// proxy-models.ts
|
|
init_models();
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/openai-decisions.lazy.js
|
|
var openAIDecisionsApi = () => ({
|
|
classify: async (model2, context, options) => (await Promise.resolve().then(() => (init_openai_decisions(), openai_decisions_exports))).classify(model2, context, options)
|
|
});
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
|
|
init_lazy();
|
|
var openAIResponsesApi = () => lazyApi(() => Promise.resolve().then(() => (init_openai_responses(), openai_responses_exports)));
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/auth/helpers.js
|
|
function envApiKeyAuth(name, envVars) {
|
|
return {
|
|
name,
|
|
login: async (interaction) => {
|
|
interaction.signal.throwIfAborted();
|
|
const key = await interaction.prompt({ type: "secret", message: `Enter ${name}` });
|
|
interaction.signal.throwIfAborted();
|
|
return { type: "api_key", key };
|
|
},
|
|
resolve: async ({ ctx, credential, signal }) => {
|
|
signal.throwIfAborted();
|
|
if (credential?.key) {
|
|
return { auth: { apiKey: credential.key }, env: credential.env, source: "stored credential" };
|
|
}
|
|
for (const envVar of envVars) {
|
|
const value = await ctx.env(envVar);
|
|
signal.throwIfAborted();
|
|
if (value)
|
|
return { auth: { apiKey: value }, source: envVar };
|
|
}
|
|
return void 0;
|
|
}
|
|
};
|
|
}
|
|
function lazyOAuth(input) {
|
|
let promise;
|
|
const loaded = () => {
|
|
promise ??= input.load();
|
|
return promise;
|
|
};
|
|
return {
|
|
name: input.name,
|
|
isSubscription: input.isSubscription,
|
|
loginLabel: input.loginLabel,
|
|
login: async (interaction, options) => (await loaded()).login(interaction, options),
|
|
refresh: async (credential, signal) => (await loaded()).refresh(credential, signal),
|
|
toAuth: async (credential) => (await loaded()).toAuth(credential)
|
|
};
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/auth/oauth/load.js
|
|
var __rewriteRelativeImportExtension2 = function(path4, preserveJsx) {
|
|
if (typeof path4 === "string" && /^\.\.?\//.test(path4)) {
|
|
return path4.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
|
|
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
|
|
});
|
|
}
|
|
return path4;
|
|
};
|
|
var importOAuthModule = (specifier) => {
|
|
const runtimeSpecifier = import.meta.url.endsWith(".js") ? specifier.replace(/\.ts$/, ".js") : specifier;
|
|
return import(__rewriteRelativeImportExtension2(runtimeSpecifier));
|
|
};
|
|
var bundledLoaders;
|
|
var loadAnthropicOAuth = async () => {
|
|
if (bundledLoaders)
|
|
return bundledLoaders.anthropic();
|
|
return (await importOAuthModule("./anthropic.ts")).anthropicOAuth;
|
|
};
|
|
var loadOpenAIChatGPTOAuth = async () => {
|
|
if (bundledLoaders)
|
|
return bundledLoaders.openaiChatGPT();
|
|
return (await importOAuthModule("./openai-chatgpt.ts")).openaiChatGPTOAuth;
|
|
};
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/openai.js
|
|
init_models();
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json
|
|
var openai_default = { "openai-decisions": { "classifier:gpt-6-luna": { type: "classifier", id: "gpt-6-luna", name: "GPT-6 Luna", api: "openai-decisions", provider: "openai", baseUrl: "https://api.openai.com/v1", input: ["text", "image"], cost: { input: 0.1, output: 0, cacheRead: 0, cacheWrite: 0, tiers: [{ inputTokensAbove: 272e3, input: 0.2, output: 0, cacheRead: 0, cacheWrite: 0 }] }, contextWindow: 922e3 } }, "openai-responses": { "chat:chat-latest": { id: "chat-latest", name: "Chat Latest", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4": { id: "gpt-4", name: "GPT-4", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text"], cost: { input: 30, output: 60, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 8192, compat: { supportsStrictMode: true }, type: "chat" }, "chat:gpt-4-turbo": { id: "gpt-4-turbo", name: "GPT-4 Turbo", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 10, output: 30, cacheRead: 0, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 4096, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4.1": { id: "gpt-4.1", name: "GPT-4.1", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 2, output: 8, cacheRead: 0.5, cacheWrite: 0 }, contextWindow: 1047576, maxTokens: 32768, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4.1-mini": { id: "gpt-4.1-mini", name: "GPT-4.1 mini", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 0.4, output: 1.6, cacheRead: 0.1, cacheWrite: 0 }, contextWindow: 1047576, maxTokens: 32768, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4.1-nano": { id: "gpt-4.1-nano", name: "GPT-4.1 nano", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 0.1, output: 0.4, cacheRead: 0.025, cacheWrite: 0 }, contextWindow: 1047576, maxTokens: 32768, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4o": { id: "gpt-4o", name: "GPT-4o", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 2.5, output: 10, cacheRead: 1.25, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 16384, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4o-2024-05-13": { id: "gpt-4o-2024-05-13", name: "GPT-4o (2024-05-13)", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 5, output: 15, cacheRead: 0, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 4096, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4o-2024-08-06": { id: "gpt-4o-2024-08-06", name: "GPT-4o (2024-08-06)", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 2.5, output: 10, cacheRead: 1.25, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 16384, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4o-2024-11-20": { id: "gpt-4o-2024-11-20", name: "GPT-4o (2024-11-20)", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 2.5, output: 10, cacheRead: 1.25, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 16384, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-4o-mini": { id: "gpt-4o-mini", name: "GPT-4o mini", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: false, input: ["text", "image"], cost: { input: 0.15, output: 0.6, cacheRead: 0.075, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 16384, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5": { id: "gpt-5", name: "GPT-5", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1.25, output: 10, cacheRead: 0.125, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5-chat-latest": { id: "gpt-5-chat-latest", name: "GPT-5 Chat Latest", api: "openai-responses", baseUrl: "https://api.openai.com/v1", provider: "openai", reasoning: false, input: ["text", "image"], cost: { input: 1.25, output: 10, cacheRead: 0.125, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 16384, thinkingLevelMap: { off: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5-mini": { id: "gpt-5-mini", name: "GPT-5 Mini", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 0.25, output: 2, cacheRead: 0.025, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5-nano": { id: "gpt-5-nano", name: "GPT-5 Nano", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 0.05, output: 0.4, cacheRead: 5e-3, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5-pro": { id: "gpt-5-pro", name: "GPT-5 Pro", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 15, output: 120, cacheRead: 0, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: null, medium: null, high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.1": { id: "gpt-5.1", name: "GPT-5.1", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1.25, output: 10, cacheRead: 0.125, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.2": { id: "gpt-5.2", name: "GPT-5.2", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.2-pro": { id: "gpt-5.2-pro", name: "GPT-5.2 Pro", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 21, output: 168, cacheRead: 0, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: null, medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.3-codex": { id: "gpt-5.3-codex", name: "GPT-5.3 Codex", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.3-codex-spark": { id: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1.75, output: 14, cacheRead: 0.175, cacheWrite: 0 }, contextWindow: 128e3, maxTokens: 32e3, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.4": { id: "gpt-5.4", name: "GPT-5.4", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 2.5, output: 15, cacheRead: 0.25, cacheWrite: 0, tiers: [{ inputTokensAbove: 272e3, input: 5, output: 22.5, cacheRead: 0.5, cacheWrite: 0 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsMidConvoSystemMessages: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.4-mini": { id: "gpt-5.4-mini", name: "GPT-5.4 mini", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 0.75, output: 4.5, cacheRead: 0.075, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsMidConvoSystemMessages: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.4-nano": { id: "gpt-5.4-nano", name: "GPT-5.4 nano", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 0.2, output: 1.25, cacheRead: 0.02, cacheWrite: 0 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.4-pro": { id: "gpt-5.4-pro", name: "GPT-5.4 Pro", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 30, output: 180, cacheRead: 0, cacheWrite: 0, tiers: [{ inputTokensAbove: 272e3, input: 60, output: 270, cacheRead: 0, cacheWrite: 0 }] }, contextWindow: 105e4, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: null, medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsMidConvoSystemMessages: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.5": { id: "gpt-5.5", name: "GPT-5.5", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 30, cacheRead: 0.5, cacheWrite: 0, tiers: [{ inputTokensAbove: 272e3, input: 10, output: 45, cacheRead: 1, cacheWrite: 0 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsMidConvoSystemMessages: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.5-pro": { id: "gpt-5.5-pro", name: "GPT-5.5 Pro", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 30, output: 180, cacheRead: 0, cacheWrite: 0, tiers: [{ inputTokensAbove: 272e3, input: 60, output: 270, cacheRead: 0, cacheWrite: 0 }] }, contextWindow: 105e4, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: null, medium: "medium", high: "high", xhigh: "xhigh", max: null }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.6-cyber": { id: "gpt-5.6-cyber", name: "GPT-5.6 Cyber", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 12.5, output: 75, cacheRead: 1.25, cacheWrite: 15.625 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsExplicitPromptCacheMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.6-luna": { id: "gpt-5.6-luna", name: "GPT-5.6 Luna", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 0.2, output: 1.2, cacheRead: 0.02, cacheWrite: 0.25, tiers: [{ inputTokensAbove: 272e3, input: 0.4, output: 1.8, cacheRead: 0.04, cacheWrite: 0.5 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.6-sol": { id: "gpt-5.6-sol", name: "GPT-5.6 Sol", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 4, output: 20, cacheRead: 0.4, cacheWrite: 5, tiers: [{ inputTokensAbove: 272e3, input: 8, output: 30, cacheRead: 0.8, cacheWrite: 10 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-5.6-terra": { id: "gpt-5.6-terra", name: "GPT-5.6 Terra", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 2, output: 12, cacheRead: 0.2, cacheWrite: 2.5, tiers: [{ inputTokensAbove: 272e3, input: 4, output: 18, cacheRead: 0.4, cacheWrite: 5 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-6-astra": { id: "gpt-6-astra", name: "GPT-6 Astra", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5, tiers: [{ inputTokensAbove: 272e3, input: 20, output: 75, cacheRead: 2, cacheWrite: 25 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true, supportsMidConvoEffort: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-6-luna": { id: "gpt-6-luna", name: "GPT-6 Luna", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125, tiers: [{ inputTokensAbove: 272e3, input: 0.2, output: 0.75, cacheRead: 0.02, cacheWrite: 0.25 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true, supportsMidConvoEffort: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-6-sol": { id: "gpt-6-sol", name: "GPT-6 Sol", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5, tiers: [{ inputTokensAbove: 272e3, input: 4, output: 15, cacheRead: 0.4, cacheWrite: 5 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true, supportsMidConvoEffort: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-6.1-sol": { id: "gpt-6.1-sol", name: "GPT-6.1 Sol", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2.5, tiers: [{ inputTokensAbove: 272e3, input: 4, output: 15, cacheRead: 0.2, cacheWrite: 5 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true, supportsMidConvoEffort: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-6.1-terra": { id: "gpt-6.1-terra", name: "GPT-6.1 Terra", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1, output: 5, cacheRead: 0.05, cacheWrite: 1.25, tiers: [{ inputTokensAbove: 272e3, input: 2, output: 7.5, cacheRead: 0.1, cacheWrite: 2.5 }] }, contextWindow: 272e3, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsOpenAIGrammarTools: true, supportsAdditionalTools: true, supportsToolSearch: true, supportsMidConvoSystemMessages: true, supportsExplicitPromptCacheMode: true, supportsMidConvoEffort: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-daybreak-blue-latest": { id: "gpt-daybreak-blue-latest", name: "Daybreak Blue", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 4, output: 20, cacheRead: 0.4, cacheWrite: 5, tiers: [{ inputTokensAbove: 272e3, input: 8, output: 30, cacheRead: 0.8, cacheWrite: 10 }] }, contextWindow: 105e4, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsExplicitPromptCacheMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:gpt-daybreak-red-latest": { id: "gpt-daybreak-red-latest", name: "Daybreak Red", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 12.5, output: 75, cacheRead: 1.25, cacheWrite: 15.625 }, contextWindow: 4e5, maxTokens: 128e3, thinkingLevelMap: { off: "none", minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { supportsStrictMode: true, supportsExplicitPromptCacheMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:o1": { id: "o1", name: "o1", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 15, output: 60, cacheRead: 7.5, cacheWrite: 0 }, contextWindow: 2e5, maxTokens: 1e5, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:o1-pro": { id: "o1-pro", name: "o1-pro", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 150, output: 600, cacheRead: 0, cacheWrite: 0 }, contextWindow: 2e5, maxTokens: 1e5, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:o3": { id: "o3", name: "o3", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 2, output: 8, cacheRead: 0.5, cacheWrite: 0 }, contextWindow: 2e5, maxTokens: 1e5, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:o3-mini": { id: "o3-mini", name: "o3-mini", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text"], cost: { input: 1.1, output: 4.4, cacheRead: 0.55, cacheWrite: 0 }, contextWindow: 2e5, maxTokens: 1e5, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true }, type: "chat" }, "chat:o3-pro": { id: "o3-pro", name: "o3-pro", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 20, output: 80, cacheRead: 0, cacheWrite: 0 }, contextWindow: 2e5, maxTokens: 1e5, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:o4-mini": { id: "o4-mini", name: "o4-mini", api: "openai-responses", provider: "openai", baseUrl: "https://api.openai.com/v1", reasoning: true, input: ["text", "image"], cost: { input: 1.1, output: 4.4, cacheRead: 0.275, cacheWrite: 0 }, contextWindow: 2e5, maxTokens: 1e5, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null }, compat: { supportsStrictMode: true }, inputLimits: { maxRequestBytes: 536870912, images: { maxPerRequest: 1500, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" } } };
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/model-catalog.js
|
|
function flattenModelCatalog(groups, type) {
|
|
return Object.fromEntries(Object.values(groups).flatMap((models2) => Object.values(models2)).filter((model2) => model2.type === type).map((model2) => [model2.id, model2]));
|
|
}
|
|
function flattenChatModelCatalog(_provider, groups) {
|
|
return flattenModelCatalog(groups, "chat");
|
|
}
|
|
function flattenImageModelCatalog(_provider, groups) {
|
|
return flattenModelCatalog(groups, "image");
|
|
}
|
|
function flattenClassifierModelCatalog(_provider, groups) {
|
|
return flattenModelCatalog(groups, "classifier");
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/openai.models.js
|
|
var OPENAI_MODELS = flattenChatModelCatalog("openai", openai_default);
|
|
var OPENAI_IMAGE_MODELS = flattenImageModelCatalog("openai", openai_default);
|
|
var OPENAI_CLASSIFIER_MODELS = flattenClassifierModelCatalog("openai", openai_default);
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/openai.js
|
|
function openaiProvider() {
|
|
return createProvider({
|
|
id: "openai",
|
|
name: "OpenAI",
|
|
baseUrl: "https://api.openai.com/v1",
|
|
auth: {
|
|
apiKey: envApiKeyAuth("OpenAI API key", ["OPENAI_API_KEY"]),
|
|
oauth: lazyOAuth({
|
|
name: "OpenAI (ChatGPT subscription)",
|
|
isSubscription: true,
|
|
loginLabel: "Sign in with ChatGPT",
|
|
load: loadOpenAIChatGPTOAuth
|
|
})
|
|
},
|
|
models: [
|
|
...Object.values(OPENAI_MODELS),
|
|
...Object.values(OPENAI_CLASSIFIER_MODELS)
|
|
],
|
|
// Sign in with ChatGPT tokens only reach the Responses API; the Decisions API rejects them.
|
|
filterAllModels: (models2, credential) => credential?.type === "oauth" ? models2.filter((model2) => !isModelType(model2, "classifier")) : models2,
|
|
api: openAIResponsesApi(),
|
|
classifiers: {
|
|
"openai-decisions": openAIDecisionsApi()
|
|
}
|
|
});
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
|
|
init_lazy();
|
|
var anthropicMessagesApi = () => lazyApi(() => Promise.resolve().then(() => (init_anthropic_messages(), anthropic_messages_exports)));
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/anthropic.js
|
|
init_env_api_keys();
|
|
init_models();
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json
|
|
var anthropic_default = { "anthropic-messages": { "chat:claude-fable-5": { id: "claude-fable-5", name: "Claude Fable 5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { off: null, xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true, allowedFallbackModels: [{ provider: "anthropic", model: "claude-opus-4-8", cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 } }, { provider: "anthropic", model: "claude-opus-5", cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 } }] }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-fable-5-1": { id: "claude-fable-5-1", name: "Claude Fable 5.1", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 10, output: 50, cacheRead: 0.25, cacheWrite: 12.5 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { off: null, xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsMidConvoEffort: true, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-haiku-4-5": { id: "claude-haiku-4-5", name: "Claude Haiku 4.5 (latest)", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 }, contextWindow: 2e5, maxTokens: 64e3, compat: { supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 100, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-haiku-4-5-20251001": { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 }, contextWindow: 2e5, maxTokens: 64e3, compat: { supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 100, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-haiku-5-5": { id: "claude-haiku-5-5", name: "Claude Haiku 5.5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 0.1, output: 0.5, cacheRead: 0.01, cacheWrite: 0.125, tiers: [{ inputTokensAbove: 1e5, input: 0.5, output: 2.5, cacheRead: 0.05, cacheWrite: 0.625 }] }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsTemperature: false, supportsMidConvoEffort: true, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-4-5": { id: "claude-opus-4-5", name: "Claude Opus 4.5 (latest)", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, contextWindow: 2e5, maxTokens: 64e3, compat: { supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 100, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-4-5-20251101": { id: "claude-opus-4-5-20251101", name: "Claude Opus 4.5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, contextWindow: 2e5, maxTokens: 64e3, compat: { supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 100, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-4-6": { id: "claude-opus-4-6", name: "Claude Opus 4.6", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { max: "max" }, compat: { forceAdaptiveThinking: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-4-7": { id: "claude-opus-4-7", name: "Claude Opus 4.7", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsTemperature: false, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-4-8": { id: "claude-opus-4-8", name: "Claude Opus 4.8", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsTemperature: false, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-5": { id: "claude-opus-5", name: "Claude Opus 5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsTemperature: false, supportsMidConvoEffort: true, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-opus-5-5": { id: "claude-opus-5-5", name: "Claude Opus 5.5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 5 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsTemperature: false, supportsMidConvoEffort: true, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-sonnet-4-5": { id: "claude-sonnet-4-5", name: "Claude Sonnet 4.5 (latest)", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, contextWindow: 2e5, maxTokens: 64e3, compat: { supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 100, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-sonnet-4-5-20250929": { id: "claude-sonnet-4-5-20250929", name: "Claude Sonnet 4.5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, contextWindow: 2e5, maxTokens: 64e3, compat: { supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 100, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-sonnet-4-6": { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { max: "max" }, compat: { forceAdaptiveThinking: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-sonnet-5": { id: "claude-sonnet-5", name: "Claude Sonnet 5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 2, output: 10, cacheRead: 0.2, cacheWrite: 2.5 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" }, "chat:claude-sonnet-5-5": { id: "claude-sonnet-5-5", name: "Claude Sonnet 5.5", api: "anthropic-messages", provider: "anthropic", baseUrl: "https://api.anthropic.com", reasoning: true, input: ["text", "image"], cost: { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 2.5 }, contextWindow: 1e6, maxTokens: 128e3, thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" }, compat: { forceAdaptiveThinking: true, supportsTemperature: false, supportsMidConvoEffort: true, supportsMidConvoSystemMessages: true, supportsMidConvoToolChanges: true, supportsStrictTools: true }, promptCache: { short: 300, long: 3600 }, inputLimits: { maxRequestBytes: 33554432, images: { maxPerRequest: 600, resize: { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4718592, jpegQuality: 80 } } }, type: "chat" } } };
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/anthropic.models.js
|
|
var ANTHROPIC_MODELS = flattenChatModelCatalog("anthropic", anthropic_default);
|
|
var ANTHROPIC_IMAGE_MODELS = flattenImageModelCatalog("anthropic", anthropic_default);
|
|
var ANTHROPIC_CLASSIFIER_MODELS = flattenClassifierModelCatalog("anthropic", anthropic_default);
|
|
|
|
// node_modules/@earendil-works/pi-ai/dist/providers/anthropic.js
|
|
function anthropicApiKeyAuth() {
|
|
return {
|
|
name: "Anthropic API key",
|
|
login: async (interaction) => {
|
|
interaction.signal.throwIfAborted();
|
|
const key = await interaction.prompt({ type: "secret", message: "Enter Anthropic API key" });
|
|
interaction.signal.throwIfAborted();
|
|
return { type: "api_key", key };
|
|
},
|
|
resolve: async ({ ctx, credential, signal }) => {
|
|
signal.throwIfAborted();
|
|
if (credential?.key) {
|
|
return { auth: { apiKey: credential.key }, env: credential.env, source: "stored credential" };
|
|
}
|
|
const authToken = await ctx.env(ANTHROPIC_AUTH_TOKEN_ENV);
|
|
signal.throwIfAborted();
|
|
if (authToken) {
|
|
return {
|
|
auth: { headers: { Authorization: `Bearer ${authToken}` } },
|
|
source: ANTHROPIC_AUTH_TOKEN_ENV
|
|
};
|
|
}
|
|
for (const envVar of [ANTHROPIC_OAUTH_TOKEN_ENV, ANTHROPIC_API_KEY_ENV]) {
|
|
const apiKey = await ctx.env(envVar);
|
|
signal.throwIfAborted();
|
|
if (apiKey)
|
|
return { auth: { apiKey }, source: envVar };
|
|
}
|
|
const federation = {};
|
|
for (const envVar of [
|
|
ANTHROPIC_FEDERATION_RULE_ID_ENV,
|
|
ANTHROPIC_ORGANIZATION_ID_ENV,
|
|
ANTHROPIC_IDENTITY_TOKEN_FILE_ENV
|
|
]) {
|
|
const value = await ctx.env(envVar);
|
|
signal.throwIfAborted();
|
|
if (!value)
|
|
return void 0;
|
|
federation[envVar] = value;
|
|
}
|
|
for (const envVar of [ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, ANTHROPIC_WORKSPACE_ID_ENV]) {
|
|
const value = await ctx.env(envVar);
|
|
signal.throwIfAborted();
|
|
if (value)
|
|
federation[envVar] = value;
|
|
}
|
|
return { auth: {}, env: federation, source: "workload identity federation" };
|
|
}
|
|
};
|
|
}
|
|
function anthropicProvider() {
|
|
return createProvider({
|
|
id: "anthropic",
|
|
name: "Anthropic",
|
|
baseUrl: "https://api.anthropic.com",
|
|
auth: {
|
|
apiKey: anthropicApiKeyAuth(),
|
|
oauth: lazyOAuth({
|
|
name: "Anthropic (Claude Pro/Max)",
|
|
isSubscription: true,
|
|
load: loadAnthropicOAuth
|
|
})
|
|
},
|
|
models: Object.values(ANTHROPIC_MODELS),
|
|
api: anthropicMessagesApi()
|
|
});
|
|
}
|
|
|
|
// proxy-models.ts
|
|
async function proxyModels(proxy, readProxy2 = async () => proxy) {
|
|
const models2 = createModels();
|
|
const base = proxy.base_url.replace(/\/$/, "");
|
|
let catalog = [];
|
|
try {
|
|
if (proxy.base_url && proxy.api_key) {
|
|
const response = await fetch(`${base}/v1/models`, {
|
|
headers: { Authorization: `Bearer ${proxy.api_key}` },
|
|
signal: AbortSignal.timeout(5e3)
|
|
});
|
|
if (response.ok) catalog = (await response.json()).data ?? [];
|
|
}
|
|
} catch {
|
|
}
|
|
for (const [provider2, api, path4, fallback2] of [
|
|
[openaiProvider(), "openai-responses", "/v1/responses", "gpt-6.1-sol"],
|
|
[anthropicProvider(), "anthropic-messages", "/apis/anthropic/v1/messages", "claude-opus-5-5"]
|
|
]) {
|
|
const rows = catalog.filter((row) => row.creator === provider2.id && row.endpoints?.some((endpoint) => endpoint.api === api));
|
|
const entries = (rows.length ? rows : [{ id: fallback2 }]).map((row) => {
|
|
const endpoint = row.endpoints?.find((endpoint2) => endpoint2.api === api)?.path ?? path4;
|
|
const suffix = api === "anthropic-messages" ? "/v1/messages" : "/responses";
|
|
const baseUrl = `${base}${endpoint.slice(0, -suffix.length)}`;
|
|
const price = row.providers?.[0]?.pricing;
|
|
const scale = price?.currency === "USD" ? 1e6 / price.unit_tokens : 0;
|
|
return {
|
|
id: row.id,
|
|
name: row.name ?? row.id,
|
|
provider: provider2.id,
|
|
api,
|
|
baseUrl,
|
|
reasoning: row.capabilities?.reasoning ?? true,
|
|
input: ["text"],
|
|
thinkingLevelMap: {
|
|
off: null,
|
|
minimal: null,
|
|
...Object.fromEntries((row.capabilities?.reasoning_options?.find((option) => option.type === "effort")?.values ?? []).map((level) => [level, level]))
|
|
},
|
|
compat: api === "anthropic-messages" ? { forceAdaptiveThinking: row.capabilities?.reasoning_options?.some((option) => option.type === "effort") ?? true } : void 0,
|
|
cost: {
|
|
input: (price?.input ?? 0) * scale,
|
|
output: (price?.output ?? 0) * scale,
|
|
cacheRead: (price?.cached_input ?? 0) * scale,
|
|
cacheWrite: (price?.cache_write ?? 0) * scale
|
|
},
|
|
contextWindow: row.limits?.context_window ?? 2e5,
|
|
maxTokens: 4096
|
|
};
|
|
});
|
|
models2.setProvider({
|
|
...provider2,
|
|
baseUrl: entries[0].baseUrl,
|
|
getModels: () => entries,
|
|
auth: { apiKey: { name: "Sausage proxy", resolve: async () => {
|
|
const current = await readProxy2();
|
|
if (!current.base_url || !current.api_key) throw new Error("Set proxy.base_url and proxy.api_key in /etc/sausage/config.yaml before a model request");
|
|
return { auth: {
|
|
apiKey: current.api_key,
|
|
baseUrl: current.base_url.replace(/\/$/, "") + entries[0].baseUrl.slice(base.length),
|
|
headers: { "Shopify-Usage-Tag": JSON.stringify(["pi", "sausage"]) }
|
|
}, source: "/etc/sausage/config.yaml" };
|
|
} } }
|
|
});
|
|
}
|
|
return models2;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-schema/dist/builders.js
|
|
function str(options = {}) {
|
|
return { type: "string", ...options };
|
|
}
|
|
function num(options = {}) {
|
|
return { type: "number", ...options };
|
|
}
|
|
function bool(options = {}) {
|
|
return { type: "boolean", ...options };
|
|
}
|
|
function lit(value, options = {}) {
|
|
return { const: value, ...options };
|
|
}
|
|
function union(schemas, options = {}) {
|
|
return { anyOf: schemas, ...options };
|
|
}
|
|
function arr(items, options = {}) {
|
|
return { type: "array", items, ...options };
|
|
}
|
|
var Optional = class {
|
|
schema;
|
|
constructor(schema4) {
|
|
this.schema = schema4;
|
|
}
|
|
};
|
|
function opt(schema4) {
|
|
return new Optional(schema4);
|
|
}
|
|
function obj(properties, options = {}) {
|
|
const { open, ...annotations } = options;
|
|
const props = {};
|
|
const required = [];
|
|
for (const [name, property] of Object.entries(properties)) {
|
|
if (property instanceof Optional)
|
|
props[name] = property.schema;
|
|
else {
|
|
props[name] = property;
|
|
required.push(name);
|
|
}
|
|
}
|
|
return {
|
|
type: "object",
|
|
properties: props,
|
|
...required.length > 0 ? { required } : {},
|
|
...open === true ? {} : { additionalProperties: false },
|
|
...annotations
|
|
};
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/documents.js
|
|
function defineDoc(definition) {
|
|
validateDefinition(definition);
|
|
return { definition };
|
|
}
|
|
function validateDefinition(definition) {
|
|
if (!Number.isSafeInteger(definition.version) || definition.version < 1) {
|
|
throw new TypeError(`Document ${definition.kind} version must be a positive integer`);
|
|
}
|
|
}
|
|
|
|
// node_modules/@earendil-works/chord/dist/output.js
|
|
var encoder = new TextEncoder();
|
|
var decoder = new TextDecoder("utf-8", { ignoreBOM: true });
|
|
function characterEnd(bytes2, index) {
|
|
let end = index;
|
|
while (end > 0 && ((bytes2[end] ?? 0) & 192) === 128)
|
|
end--;
|
|
return end;
|
|
}
|
|
var runtimeBuffer = globalThis.Buffer;
|
|
var nonAsciiPattern = /[^\x00-\x7f]/;
|
|
function utf8ByteLength(content) {
|
|
if (runtimeBuffer)
|
|
return runtimeBuffer.byteLength(content, "utf8");
|
|
const firstNonAscii = content.search(nonAsciiPattern);
|
|
if (firstNonAscii === -1)
|
|
return content.length;
|
|
let bytes2 = firstNonAscii;
|
|
for (let i = firstNonAscii; i < content.length; i++) {
|
|
const code = content.charCodeAt(i);
|
|
if (code <= 127)
|
|
bytes2 += 1;
|
|
else if (code <= 2047)
|
|
bytes2 += 2;
|
|
else if (code >= 55296 && code <= 56319 && i + 1 < content.length) {
|
|
const next = content.charCodeAt(i + 1);
|
|
if (next >= 56320 && next <= 57343) {
|
|
bytes2 += 4;
|
|
i++;
|
|
} else
|
|
bytes2 += 3;
|
|
} else
|
|
bytes2 += 3;
|
|
}
|
|
return bytes2;
|
|
}
|
|
var PROGRESS_BYTES_PER_SECOND = 100 * 1024;
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/truncate.js
|
|
var DEFAULT_MAX_LINES = 2e3;
|
|
var DEFAULT_MAX_BYTES = 50 * 1024;
|
|
function splitLinesForCounting(content) {
|
|
if (content.length === 0)
|
|
return [];
|
|
const lines = content.split("\n");
|
|
if (content.endsWith("\n"))
|
|
lines.pop();
|
|
return lines;
|
|
}
|
|
function formatSize(bytes2) {
|
|
if (bytes2 < 1024) {
|
|
return `${bytes2}B`;
|
|
} else if (bytes2 < 1024 * 1024) {
|
|
return `${(bytes2 / 1024).toFixed(1)}KB`;
|
|
} else {
|
|
return `${(bytes2 / (1024 * 1024)).toFixed(1)}MB`;
|
|
}
|
|
}
|
|
function truncateHeadOf(prefix, totals, options = {}) {
|
|
const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
|
|
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
const totalBytes = totals.bytes;
|
|
const lines = splitLinesForCounting(prefix);
|
|
const totalLines = totals.lines;
|
|
if (totalLines <= maxLines && totalBytes <= maxBytes) {
|
|
return {
|
|
content: prefix,
|
|
truncated: false,
|
|
truncatedBy: null,
|
|
totalLines,
|
|
totalBytes,
|
|
outputLines: totalLines,
|
|
outputBytes: totalBytes,
|
|
lastLinePartial: false,
|
|
firstLineExceedsLimit: false,
|
|
maxLines,
|
|
maxBytes
|
|
};
|
|
}
|
|
const firstLineBytes = utf8ByteLength(lines[0]);
|
|
if (firstLineBytes > maxBytes) {
|
|
return {
|
|
content: "",
|
|
truncated: true,
|
|
truncatedBy: "bytes",
|
|
totalLines,
|
|
totalBytes,
|
|
outputLines: 0,
|
|
outputBytes: 0,
|
|
lastLinePartial: false,
|
|
firstLineExceedsLimit: true,
|
|
maxLines,
|
|
maxBytes
|
|
};
|
|
}
|
|
const outputLinesArr = [];
|
|
let outputBytesCount = 0;
|
|
let truncatedBy = "lines";
|
|
for (let i = 0; i < lines.length && i < maxLines; i++) {
|
|
const line = lines[i];
|
|
const lineBytes = utf8ByteLength(line) + (i > 0 ? 1 : 0);
|
|
if (outputBytesCount + lineBytes > maxBytes) {
|
|
truncatedBy = "bytes";
|
|
break;
|
|
}
|
|
outputLinesArr.push(line);
|
|
outputBytesCount += lineBytes;
|
|
}
|
|
if (truncatedBy !== "bytes")
|
|
truncatedBy = outputLinesArr.length < totalLines ? "lines" : "bytes";
|
|
const outputContent = outputLinesArr.join("\n");
|
|
const finalOutputBytes = utf8ByteLength(outputContent);
|
|
return {
|
|
content: outputContent,
|
|
truncated: true,
|
|
truncatedBy,
|
|
totalLines,
|
|
totalBytes,
|
|
outputLines: outputLinesArr.length,
|
|
outputBytes: finalOutputBytes,
|
|
lastLinePartial: false,
|
|
firstLineExceedsLimit: false,
|
|
maxLines,
|
|
maxBytes
|
|
};
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/harness/define.js
|
|
function defineExtension(extension) {
|
|
return extension;
|
|
}
|
|
function defineTool(tool) {
|
|
return tool;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/identity.js
|
|
var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias");
|
|
var DOC = /* @__PURE__ */ Symbol.for("yaml.document");
|
|
var MAP = /* @__PURE__ */ Symbol.for("yaml.map");
|
|
var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair");
|
|
var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar");
|
|
var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq");
|
|
var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type");
|
|
var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS;
|
|
var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC;
|
|
var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP;
|
|
var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR;
|
|
var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR;
|
|
var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ;
|
|
function isCollection(node) {
|
|
if (node && typeof node === "object")
|
|
switch (node[NODE_TYPE]) {
|
|
case MAP:
|
|
case SEQ:
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
function isNode(node) {
|
|
if (node && typeof node === "object")
|
|
switch (node[NODE_TYPE]) {
|
|
case ALIAS:
|
|
case MAP:
|
|
case SCALAR:
|
|
case SEQ:
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;
|
|
|
|
// node_modules/yaml/browser/dist/visit.js
|
|
var BREAK = /* @__PURE__ */ Symbol("break visit");
|
|
var SKIP = /* @__PURE__ */ Symbol("skip children");
|
|
var REMOVE = /* @__PURE__ */ Symbol("remove node");
|
|
function visit(node, visitor) {
|
|
const visitor_ = initVisitor(visitor);
|
|
if (isDocument(node)) {
|
|
const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
|
|
if (cd === REMOVE)
|
|
node.contents = null;
|
|
} else
|
|
visit_(null, node, visitor_, Object.freeze([]));
|
|
}
|
|
visit.BREAK = BREAK;
|
|
visit.SKIP = SKIP;
|
|
visit.REMOVE = REMOVE;
|
|
function visit_(key, node, visitor, path4) {
|
|
const ctrl = callVisitor(key, node, visitor, path4);
|
|
if (isNode(ctrl) || isPair(ctrl)) {
|
|
replaceNode(key, path4, ctrl);
|
|
return visit_(key, ctrl, visitor, path4);
|
|
}
|
|
if (typeof ctrl !== "symbol") {
|
|
if (isCollection(node)) {
|
|
path4 = Object.freeze(path4.concat(node));
|
|
for (let i = 0; i < node.items.length; ++i) {
|
|
const ci = visit_(i, node.items[i], visitor, path4);
|
|
if (typeof ci === "number")
|
|
i = ci - 1;
|
|
else if (ci === BREAK)
|
|
return BREAK;
|
|
else if (ci === REMOVE) {
|
|
node.items.splice(i, 1);
|
|
i -= 1;
|
|
}
|
|
}
|
|
} else if (isPair(node)) {
|
|
path4 = Object.freeze(path4.concat(node));
|
|
const ck = visit_("key", node.key, visitor, path4);
|
|
if (ck === BREAK)
|
|
return BREAK;
|
|
else if (ck === REMOVE)
|
|
node.key = null;
|
|
const cv = visit_("value", node.value, visitor, path4);
|
|
if (cv === BREAK)
|
|
return BREAK;
|
|
else if (cv === REMOVE)
|
|
node.value = null;
|
|
}
|
|
}
|
|
return ctrl;
|
|
}
|
|
async function visitAsync(node, visitor) {
|
|
const visitor_ = initVisitor(visitor);
|
|
if (isDocument(node)) {
|
|
const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));
|
|
if (cd === REMOVE)
|
|
node.contents = null;
|
|
} else
|
|
await visitAsync_(null, node, visitor_, Object.freeze([]));
|
|
}
|
|
visitAsync.BREAK = BREAK;
|
|
visitAsync.SKIP = SKIP;
|
|
visitAsync.REMOVE = REMOVE;
|
|
async function visitAsync_(key, node, visitor, path4) {
|
|
const ctrl = await callVisitor(key, node, visitor, path4);
|
|
if (isNode(ctrl) || isPair(ctrl)) {
|
|
replaceNode(key, path4, ctrl);
|
|
return visitAsync_(key, ctrl, visitor, path4);
|
|
}
|
|
if (typeof ctrl !== "symbol") {
|
|
if (isCollection(node)) {
|
|
path4 = Object.freeze(path4.concat(node));
|
|
for (let i = 0; i < node.items.length; ++i) {
|
|
const ci = await visitAsync_(i, node.items[i], visitor, path4);
|
|
if (typeof ci === "number")
|
|
i = ci - 1;
|
|
else if (ci === BREAK)
|
|
return BREAK;
|
|
else if (ci === REMOVE) {
|
|
node.items.splice(i, 1);
|
|
i -= 1;
|
|
}
|
|
}
|
|
} else if (isPair(node)) {
|
|
path4 = Object.freeze(path4.concat(node));
|
|
const ck = await visitAsync_("key", node.key, visitor, path4);
|
|
if (ck === BREAK)
|
|
return BREAK;
|
|
else if (ck === REMOVE)
|
|
node.key = null;
|
|
const cv = await visitAsync_("value", node.value, visitor, path4);
|
|
if (cv === BREAK)
|
|
return BREAK;
|
|
else if (cv === REMOVE)
|
|
node.value = null;
|
|
}
|
|
}
|
|
return ctrl;
|
|
}
|
|
function initVisitor(visitor) {
|
|
if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) {
|
|
return Object.assign({
|
|
Alias: visitor.Node,
|
|
Map: visitor.Node,
|
|
Scalar: visitor.Node,
|
|
Seq: visitor.Node
|
|
}, visitor.Value && {
|
|
Map: visitor.Value,
|
|
Scalar: visitor.Value,
|
|
Seq: visitor.Value
|
|
}, visitor.Collection && {
|
|
Map: visitor.Collection,
|
|
Seq: visitor.Collection
|
|
}, visitor);
|
|
}
|
|
return visitor;
|
|
}
|
|
function callVisitor(key, node, visitor, path4) {
|
|
if (typeof visitor === "function")
|
|
return visitor(key, node, path4);
|
|
if (isMap(node))
|
|
return visitor.Map?.(key, node, path4);
|
|
if (isSeq(node))
|
|
return visitor.Seq?.(key, node, path4);
|
|
if (isPair(node))
|
|
return visitor.Pair?.(key, node, path4);
|
|
if (isScalar(node))
|
|
return visitor.Scalar?.(key, node, path4);
|
|
if (isAlias(node))
|
|
return visitor.Alias?.(key, node, path4);
|
|
return void 0;
|
|
}
|
|
function replaceNode(key, path4, node) {
|
|
const parent = path4[path4.length - 1];
|
|
if (isCollection(parent)) {
|
|
parent.items[key] = node;
|
|
} else if (isPair(parent)) {
|
|
if (key === "key")
|
|
parent.key = node;
|
|
else
|
|
parent.value = node;
|
|
} else if (isDocument(parent)) {
|
|
parent.contents = node;
|
|
} else {
|
|
const pt = isAlias(parent) ? "alias" : "scalar";
|
|
throw new Error(`Cannot replace node with ${pt} parent`);
|
|
}
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/doc/directives.js
|
|
var escapeChars = {
|
|
"!": "%21",
|
|
",": "%2C",
|
|
"[": "%5B",
|
|
"]": "%5D",
|
|
"{": "%7B",
|
|
"}": "%7D"
|
|
};
|
|
var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]);
|
|
var Directives = class _Directives {
|
|
constructor(yaml, tags) {
|
|
this.docStart = null;
|
|
this.docEnd = false;
|
|
this.yaml = Object.assign({}, _Directives.defaultYaml, yaml);
|
|
this.tags = Object.assign({}, _Directives.defaultTags, tags);
|
|
}
|
|
clone() {
|
|
const copy = new _Directives(this.yaml, this.tags);
|
|
copy.docStart = this.docStart;
|
|
return copy;
|
|
}
|
|
/**
|
|
* During parsing, get a Directives instance for the current document and
|
|
* update the stream state according to the current version's spec.
|
|
*/
|
|
atDocument() {
|
|
const res = new _Directives(this.yaml, this.tags);
|
|
switch (this.yaml.version) {
|
|
case "1.1":
|
|
this.atNextDocument = true;
|
|
break;
|
|
case "1.2":
|
|
this.atNextDocument = false;
|
|
this.yaml = {
|
|
explicit: _Directives.defaultYaml.explicit,
|
|
version: "1.2"
|
|
};
|
|
this.tags = Object.assign({}, _Directives.defaultTags);
|
|
break;
|
|
}
|
|
return res;
|
|
}
|
|
/**
|
|
* @param onError - May be called even if the action was successful
|
|
* @returns `true` on success
|
|
*/
|
|
add(line, onError) {
|
|
if (this.atNextDocument) {
|
|
this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" };
|
|
this.tags = Object.assign({}, _Directives.defaultTags);
|
|
this.atNextDocument = false;
|
|
}
|
|
const parts = line.trim().split(/[ \t]+/);
|
|
const name = parts.shift();
|
|
switch (name) {
|
|
case "%TAG": {
|
|
if (parts.length !== 2) {
|
|
onError(0, "%TAG directive should contain exactly two parts");
|
|
if (parts.length < 2)
|
|
return false;
|
|
}
|
|
const [handle, prefix] = parts;
|
|
this.tags[handle] = prefix;
|
|
return true;
|
|
}
|
|
case "%YAML": {
|
|
this.yaml.explicit = true;
|
|
if (parts.length !== 1) {
|
|
onError(0, "%YAML directive should contain exactly one part");
|
|
return false;
|
|
}
|
|
const [version] = parts;
|
|
if (version === "1.1" || version === "1.2") {
|
|
this.yaml.version = version;
|
|
return true;
|
|
} else {
|
|
const isValid = /^\d+\.\d+$/.test(version);
|
|
onError(6, `Unsupported YAML version ${version}`, isValid);
|
|
return false;
|
|
}
|
|
}
|
|
default:
|
|
onError(0, `Unknown directive ${name}`, true);
|
|
return false;
|
|
}
|
|
}
|
|
/**
|
|
* Resolves a tag, matching handles to those defined in %TAG directives.
|
|
*
|
|
* @returns Resolved tag, which may also be the non-specific tag `'!'` or a
|
|
* `'!local'` tag, or `null` if unresolvable.
|
|
*/
|
|
tagName(source, onError) {
|
|
if (source === "!")
|
|
return "!";
|
|
if (source[0] !== "!") {
|
|
onError(`Not a valid tag: ${source}`);
|
|
return null;
|
|
}
|
|
if (source[1] === "<") {
|
|
const verbatim = source.slice(2, -1);
|
|
if (verbatim === "!" || verbatim === "!!") {
|
|
onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
|
|
return null;
|
|
}
|
|
if (source[source.length - 1] !== ">")
|
|
onError("Verbatim tags must end with a >");
|
|
return verbatim;
|
|
}
|
|
const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
|
|
if (!suffix)
|
|
onError(`The ${source} tag has no suffix`);
|
|
const prefix = this.tags[handle];
|
|
if (prefix) {
|
|
try {
|
|
return prefix + decodeURIComponent(suffix);
|
|
} catch (error) {
|
|
onError(String(error));
|
|
return null;
|
|
}
|
|
}
|
|
if (handle === "!")
|
|
return source;
|
|
onError(`Could not resolve tag: ${source}`);
|
|
return null;
|
|
}
|
|
/**
|
|
* Given a fully resolved tag, returns its printable string form,
|
|
* taking into account current tag prefixes and defaults.
|
|
*/
|
|
tagString(tag) {
|
|
for (const [handle, prefix] of Object.entries(this.tags)) {
|
|
if (tag.startsWith(prefix))
|
|
return handle + escapeTagName(tag.substring(prefix.length));
|
|
}
|
|
return tag[0] === "!" ? tag : `!<${tag}>`;
|
|
}
|
|
toString(doc) {
|
|
const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : [];
|
|
const tagEntries = Object.entries(this.tags);
|
|
let tagNames;
|
|
if (doc && tagEntries.length > 0 && isNode(doc.contents)) {
|
|
const tags = {};
|
|
visit(doc.contents, (_key, node) => {
|
|
if (isNode(node) && node.tag)
|
|
tags[node.tag] = true;
|
|
});
|
|
tagNames = Object.keys(tags);
|
|
} else
|
|
tagNames = [];
|
|
for (const [handle, prefix] of tagEntries) {
|
|
if (handle === "!!" && prefix === "tag:yaml.org,2002:")
|
|
continue;
|
|
if (!doc || tagNames.some((tn) => tn.startsWith(prefix)))
|
|
lines.push(`%TAG ${handle} ${prefix}`);
|
|
}
|
|
return lines.join("\n");
|
|
}
|
|
};
|
|
Directives.defaultYaml = { explicit: false, version: "1.2" };
|
|
Directives.defaultTags = { "!!": "tag:yaml.org,2002:" };
|
|
|
|
// node_modules/yaml/browser/dist/doc/anchors.js
|
|
function anchorIsValid(anchor) {
|
|
if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
|
|
const sa = JSON.stringify(anchor);
|
|
const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
|
|
throw new Error(msg);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/doc/applyReviver.js
|
|
function applyReviver(reviver, obj2, key, val) {
|
|
if (val && typeof val === "object") {
|
|
if (Array.isArray(val)) {
|
|
for (let i = 0, len = val.length; i < len; ++i) {
|
|
const v0 = val[i];
|
|
const v1 = applyReviver(reviver, val, String(i), v0);
|
|
if (v1 === void 0)
|
|
delete val[i];
|
|
else if (v1 !== v0)
|
|
val[i] = v1;
|
|
}
|
|
} else if (val instanceof Map) {
|
|
for (const k of Array.from(val.keys())) {
|
|
const v0 = val.get(k);
|
|
const v1 = applyReviver(reviver, val, k, v0);
|
|
if (v1 === void 0)
|
|
val.delete(k);
|
|
else if (v1 !== v0)
|
|
val.set(k, v1);
|
|
}
|
|
} else if (val instanceof Set) {
|
|
for (const v0 of Array.from(val)) {
|
|
const v1 = applyReviver(reviver, val, v0, v0);
|
|
if (v1 === void 0)
|
|
val.delete(v0);
|
|
else if (v1 !== v0) {
|
|
val.delete(v0);
|
|
val.add(v1);
|
|
}
|
|
}
|
|
} else {
|
|
for (const [k, v0] of Object.entries(val)) {
|
|
const v1 = applyReviver(reviver, val, k, v0);
|
|
if (v1 === void 0)
|
|
delete val[k];
|
|
else if (v1 !== v0)
|
|
val[k] = v1;
|
|
}
|
|
}
|
|
}
|
|
return reviver.call(obj2, key, val);
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/toJS.js
|
|
function toJS(value, arg, ctx) {
|
|
if (Array.isArray(value))
|
|
return value.map((v, i) => toJS(v, String(i), ctx));
|
|
if (value && typeof value.toJSON === "function") {
|
|
if (!ctx || !hasAnchor(value))
|
|
return value.toJSON(arg, ctx);
|
|
const data = { aliasCount: 0, count: 1, res: void 0 };
|
|
ctx.anchors.set(value, data);
|
|
ctx.onCreate = (res2) => {
|
|
data.res = res2;
|
|
delete ctx.onCreate;
|
|
};
|
|
const res = value.toJSON(arg, ctx);
|
|
if (ctx.onCreate)
|
|
ctx.onCreate(res);
|
|
return res;
|
|
}
|
|
if (typeof value === "bigint" && !ctx?.keep)
|
|
return Number(value);
|
|
return value;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/Node.js
|
|
var NodeBase = class {
|
|
constructor(type) {
|
|
Object.defineProperty(this, NODE_TYPE, { value: type });
|
|
}
|
|
/** Create a copy of this node. */
|
|
clone() {
|
|
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
|
|
if (this.range)
|
|
copy.range = this.range.slice();
|
|
return copy;
|
|
}
|
|
/** A plain JavaScript representation of this node. */
|
|
toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
|
|
if (!isDocument(doc))
|
|
throw new TypeError("A document argument is required");
|
|
const ctx = {
|
|
anchors: /* @__PURE__ */ new Map(),
|
|
doc,
|
|
keep: true,
|
|
mapAsMap: mapAsMap === true,
|
|
mapKeyWarned: false,
|
|
maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100
|
|
};
|
|
const res = toJS(this, "", ctx);
|
|
if (typeof onAnchor === "function")
|
|
for (const { count, res: res2 } of ctx.anchors.values())
|
|
onAnchor(res2, count);
|
|
return typeof reviver === "function" ? applyReviver(reviver, { "": res }, "", res) : res;
|
|
}
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/nodes/Alias.js
|
|
var Alias = class extends NodeBase {
|
|
constructor(source) {
|
|
super(ALIAS);
|
|
this.source = source;
|
|
Object.defineProperty(this, "tag", {
|
|
set() {
|
|
throw new Error("Alias nodes cannot have tags");
|
|
}
|
|
});
|
|
}
|
|
/**
|
|
* Resolve the value of this alias within `doc`, finding the last
|
|
* instance of the `source` anchor before this node.
|
|
*/
|
|
resolve(doc, ctx) {
|
|
if (ctx?.maxAliasCount === 0)
|
|
throw new ReferenceError("Alias resolution is disabled");
|
|
let nodes;
|
|
if (ctx?.aliasResolveCache) {
|
|
nodes = ctx.aliasResolveCache;
|
|
} else {
|
|
nodes = [];
|
|
visit(doc, {
|
|
Node: (_key, node) => {
|
|
if (isAlias(node) || hasAnchor(node))
|
|
nodes.push(node);
|
|
}
|
|
});
|
|
if (ctx)
|
|
ctx.aliasResolveCache = nodes;
|
|
}
|
|
let found = void 0;
|
|
for (const node of nodes) {
|
|
if (node === this)
|
|
break;
|
|
if (node.anchor === this.source)
|
|
found = node;
|
|
}
|
|
if (found && ctx) {
|
|
const { anchors, doc: doc2, maxAliasCount } = ctx;
|
|
let data = anchors.get(found);
|
|
if (!data) {
|
|
toJS(found, null, ctx);
|
|
data = anchors.get(found);
|
|
}
|
|
if (data?.res === void 0) {
|
|
const msg = "This should not happen: Alias anchor was not resolved?";
|
|
throw new ReferenceError(msg);
|
|
}
|
|
if (maxAliasCount >= 0) {
|
|
data.count += 1;
|
|
if (data.aliasCount === 0)
|
|
data.aliasCount = getAliasCount(doc2, found, anchors);
|
|
if (data.count * data.aliasCount > maxAliasCount) {
|
|
const msg = "Excessive alias count indicates a resource exhaustion attack";
|
|
throw new ReferenceError(msg);
|
|
}
|
|
}
|
|
}
|
|
return found;
|
|
}
|
|
toJSON(_arg, ctx) {
|
|
if (!ctx)
|
|
return { source: this.source };
|
|
const source = this.resolve(ctx.doc, ctx);
|
|
if (!source) {
|
|
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
|
|
throw new ReferenceError(msg);
|
|
}
|
|
return ctx.anchors.get(source).res;
|
|
}
|
|
toString(ctx, _onComment, _onChompKeep) {
|
|
const src = `*${this.source}`;
|
|
if (ctx) {
|
|
anchorIsValid(this.source);
|
|
if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
|
|
const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
|
|
throw new Error(msg);
|
|
}
|
|
if (ctx.implicitKey)
|
|
return `${src} `;
|
|
}
|
|
return src;
|
|
}
|
|
};
|
|
function getAliasCount(doc, node, anchors) {
|
|
if (isAlias(node)) {
|
|
const source = node.resolve(doc);
|
|
const anchor = anchors && source && anchors.get(source);
|
|
return anchor ? anchor.count * anchor.aliasCount : 0;
|
|
} else if (isCollection(node)) {
|
|
let count = 0;
|
|
for (const item of node.items) {
|
|
const c = getAliasCount(doc, item, anchors);
|
|
if (c > count)
|
|
count = c;
|
|
}
|
|
return count;
|
|
} else if (isPair(node)) {
|
|
const kc = getAliasCount(doc, node.key, anchors);
|
|
const vc = getAliasCount(doc, node.value, anchors);
|
|
return Math.max(kc, vc);
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/Scalar.js
|
|
var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object";
|
|
var Scalar = class extends NodeBase {
|
|
constructor(value) {
|
|
super(SCALAR);
|
|
this.value = value;
|
|
}
|
|
toJSON(arg, ctx) {
|
|
return ctx?.keep ? this.value : toJS(this.value, arg, ctx);
|
|
}
|
|
toString() {
|
|
return String(this.value);
|
|
}
|
|
};
|
|
Scalar.BLOCK_FOLDED = "BLOCK_FOLDED";
|
|
Scalar.BLOCK_LITERAL = "BLOCK_LITERAL";
|
|
Scalar.PLAIN = "PLAIN";
|
|
Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE";
|
|
Scalar.QUOTE_SINGLE = "QUOTE_SINGLE";
|
|
|
|
// node_modules/yaml/browser/dist/doc/createNode.js
|
|
var defaultTagPrefix = "tag:yaml.org,2002:";
|
|
function findTagObject(value, tagName, tags) {
|
|
if (tagName) {
|
|
const match = tags.filter((t) => t.tag === tagName);
|
|
const tagObj = match.find((t) => !t.format) ?? match[0];
|
|
if (!tagObj)
|
|
throw new Error(`Tag ${tagName} not found`);
|
|
return tagObj;
|
|
}
|
|
return tags.find((t) => t.identify?.(value) && !t.format);
|
|
}
|
|
function createNode(value, tagName, ctx) {
|
|
if (isDocument(value))
|
|
value = value.contents;
|
|
if (isNode(value))
|
|
return value;
|
|
if (isPair(value)) {
|
|
const map3 = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
|
|
map3.items.push(value);
|
|
return map3;
|
|
}
|
|
if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) {
|
|
value = value.valueOf();
|
|
}
|
|
const { aliasDuplicateObjects, onAnchor, onTagObj, schema: schema4, sourceObjects } = ctx;
|
|
let ref = void 0;
|
|
if (aliasDuplicateObjects && value && typeof value === "object") {
|
|
ref = sourceObjects.get(value);
|
|
if (ref) {
|
|
ref.anchor ?? (ref.anchor = onAnchor(value));
|
|
return new Alias(ref.anchor);
|
|
} else {
|
|
ref = { anchor: null, node: null };
|
|
sourceObjects.set(value, ref);
|
|
}
|
|
}
|
|
if (tagName?.startsWith("!!"))
|
|
tagName = defaultTagPrefix + tagName.slice(2);
|
|
let tagObj = findTagObject(value, tagName, schema4.tags);
|
|
if (!tagObj) {
|
|
if (value && typeof value.toJSON === "function") {
|
|
value = value.toJSON();
|
|
}
|
|
if (!value || typeof value !== "object") {
|
|
const node2 = new Scalar(value);
|
|
if (ref)
|
|
ref.node = node2;
|
|
return node2;
|
|
}
|
|
tagObj = value instanceof Map ? schema4[MAP] : Symbol.iterator in Object(value) ? schema4[SEQ] : schema4[MAP];
|
|
}
|
|
if (onTagObj) {
|
|
onTagObj(tagObj);
|
|
delete ctx.onTagObj;
|
|
}
|
|
const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar(value);
|
|
if (tagName)
|
|
node.tag = tagName;
|
|
else if (!tagObj.default)
|
|
node.tag = tagObj.tag;
|
|
if (ref)
|
|
ref.node = node;
|
|
return node;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/Collection.js
|
|
function collectionFromPath(schema4, path4, value) {
|
|
let v = value;
|
|
for (let i = path4.length - 1; i >= 0; --i) {
|
|
const k = path4[i];
|
|
if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
|
|
const a = [];
|
|
a[k] = v;
|
|
v = a;
|
|
} else {
|
|
v = /* @__PURE__ */ new Map([[k, v]]);
|
|
}
|
|
}
|
|
return createNode(v, void 0, {
|
|
aliasDuplicateObjects: false,
|
|
keepUndefined: false,
|
|
onAnchor: () => {
|
|
throw new Error("This should not happen, please report a bug.");
|
|
},
|
|
schema: schema4,
|
|
sourceObjects: /* @__PURE__ */ new Map()
|
|
});
|
|
}
|
|
var isEmptyPath = (path4) => path4 == null || typeof path4 === "object" && !!path4[Symbol.iterator]().next().done;
|
|
var Collection = class extends NodeBase {
|
|
constructor(type, schema4) {
|
|
super(type);
|
|
Object.defineProperty(this, "schema", {
|
|
value: schema4,
|
|
configurable: true,
|
|
enumerable: false,
|
|
writable: true
|
|
});
|
|
}
|
|
/**
|
|
* Create a copy of this collection.
|
|
*
|
|
* @param schema - If defined, overwrites the original's schema
|
|
*/
|
|
clone(schema4) {
|
|
const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
|
|
if (schema4)
|
|
copy.schema = schema4;
|
|
copy.items = copy.items.map((it) => isNode(it) || isPair(it) ? it.clone(schema4) : it);
|
|
if (this.range)
|
|
copy.range = this.range.slice();
|
|
return copy;
|
|
}
|
|
/**
|
|
* Adds a value to the collection. For `!!map` and `!!omap` the value must
|
|
* be a Pair instance or a `{ key, value }` object, which may not have a key
|
|
* that already exists in the map.
|
|
*/
|
|
addIn(path4, value) {
|
|
if (isEmptyPath(path4))
|
|
this.add(value);
|
|
else {
|
|
const [key, ...rest] = path4;
|
|
const node = this.get(key, true);
|
|
if (isCollection(node))
|
|
node.addIn(rest, value);
|
|
else if (node === void 0 && this.schema)
|
|
this.set(key, collectionFromPath(this.schema, rest, value));
|
|
else
|
|
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
|
|
}
|
|
}
|
|
/**
|
|
* Removes a value from the collection.
|
|
* @returns `true` if the item was found and removed.
|
|
*/
|
|
deleteIn(path4) {
|
|
const [key, ...rest] = path4;
|
|
if (rest.length === 0)
|
|
return this.delete(key);
|
|
const node = this.get(key, true);
|
|
if (isCollection(node))
|
|
return node.deleteIn(rest);
|
|
else
|
|
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
|
|
}
|
|
/**
|
|
* Returns item at `key`, or `undefined` if not found. By default unwraps
|
|
* scalar values from their surrounding node; to disable set `keepScalar` to
|
|
* `true` (collections are always returned intact).
|
|
*/
|
|
getIn(path4, keepScalar) {
|
|
const [key, ...rest] = path4;
|
|
const node = this.get(key, true);
|
|
if (rest.length === 0)
|
|
return !keepScalar && isScalar(node) ? node.value : node;
|
|
else
|
|
return isCollection(node) ? node.getIn(rest, keepScalar) : void 0;
|
|
}
|
|
hasAllNullValues(allowScalar) {
|
|
return this.items.every((node) => {
|
|
if (!isPair(node))
|
|
return false;
|
|
const n = node.value;
|
|
return n == null || allowScalar && isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag;
|
|
});
|
|
}
|
|
/**
|
|
* Checks if the collection includes a value with the key `key`.
|
|
*/
|
|
hasIn(path4) {
|
|
const [key, ...rest] = path4;
|
|
if (rest.length === 0)
|
|
return this.has(key);
|
|
const node = this.get(key, true);
|
|
return isCollection(node) ? node.hasIn(rest) : false;
|
|
}
|
|
/**
|
|
* Sets a value in this collection. For `!!set`, `value` needs to be a
|
|
* boolean to add/remove the item from the set.
|
|
*/
|
|
setIn(path4, value) {
|
|
const [key, ...rest] = path4;
|
|
if (rest.length === 0) {
|
|
this.set(key, value);
|
|
} else {
|
|
const node = this.get(key, true);
|
|
if (isCollection(node))
|
|
node.setIn(rest, value);
|
|
else if (node === void 0 && this.schema)
|
|
this.set(key, collectionFromPath(this.schema, rest, value));
|
|
else
|
|
throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
|
|
}
|
|
}
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/stringify/stringifyComment.js
|
|
var stringifyComment = (str2) => str2.replace(/^(?!$)(?: $)?/gm, "#");
|
|
function indentComment(comment, indent) {
|
|
if (/^\n+$/.test(comment))
|
|
return comment.substring(1);
|
|
return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
|
|
}
|
|
var lineComment = (str2, indent, comment) => str2.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str2.endsWith(" ") ? "" : " ") + comment;
|
|
|
|
// node_modules/yaml/browser/dist/stringify/foldFlowLines.js
|
|
var FOLD_FLOW = "flow";
|
|
var FOLD_BLOCK = "block";
|
|
var FOLD_QUOTED = "quoted";
|
|
function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
|
|
if (!lineWidth || lineWidth < 0)
|
|
return text;
|
|
if (lineWidth < minContentWidth)
|
|
minContentWidth = 0;
|
|
const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
|
|
if (text.length <= endStep)
|
|
return text;
|
|
const folds = [];
|
|
const escapedFolds = {};
|
|
let end = lineWidth - indent.length;
|
|
if (typeof indentAtStart === "number") {
|
|
if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
|
|
folds.push(0);
|
|
else
|
|
end = lineWidth - indentAtStart;
|
|
}
|
|
let split = void 0;
|
|
let prev = void 0;
|
|
let overflow = false;
|
|
let i = -1;
|
|
let escStart = -1;
|
|
let escEnd = -1;
|
|
if (mode === FOLD_BLOCK) {
|
|
i = consumeMoreIndentedLines(text, i, indent.length);
|
|
if (i !== -1)
|
|
end = i + endStep;
|
|
}
|
|
for (let ch; ch = text[i += 1]; ) {
|
|
if (mode === FOLD_QUOTED && ch === "\\") {
|
|
escStart = i;
|
|
switch (text[i + 1]) {
|
|
case "x":
|
|
i += 3;
|
|
break;
|
|
case "u":
|
|
i += 5;
|
|
break;
|
|
case "U":
|
|
i += 9;
|
|
break;
|
|
default:
|
|
i += 1;
|
|
}
|
|
escEnd = i;
|
|
}
|
|
if (ch === "\n") {
|
|
if (mode === FOLD_BLOCK)
|
|
i = consumeMoreIndentedLines(text, i, indent.length);
|
|
end = i + indent.length + endStep;
|
|
split = void 0;
|
|
} else {
|
|
if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") {
|
|
const next = text[i + 1];
|
|
if (next && next !== " " && next !== "\n" && next !== " ")
|
|
split = i;
|
|
}
|
|
if (i >= end) {
|
|
if (split) {
|
|
folds.push(split);
|
|
end = split + endStep;
|
|
split = void 0;
|
|
} else if (mode === FOLD_QUOTED) {
|
|
while (prev === " " || prev === " ") {
|
|
prev = ch;
|
|
ch = text[i += 1];
|
|
overflow = true;
|
|
}
|
|
const j = i > escEnd + 1 ? i - 2 : escStart - 1;
|
|
if (escapedFolds[j])
|
|
return text;
|
|
folds.push(j);
|
|
escapedFolds[j] = true;
|
|
end = j + endStep;
|
|
split = void 0;
|
|
} else {
|
|
overflow = true;
|
|
}
|
|
}
|
|
}
|
|
prev = ch;
|
|
}
|
|
if (overflow && onOverflow)
|
|
onOverflow();
|
|
if (folds.length === 0)
|
|
return text;
|
|
if (onFold)
|
|
onFold();
|
|
let res = text.slice(0, folds[0]);
|
|
for (let i2 = 0; i2 < folds.length; ++i2) {
|
|
const fold = folds[i2];
|
|
const end2 = folds[i2 + 1] || text.length;
|
|
if (fold === 0)
|
|
res = `
|
|
${indent}${text.slice(0, end2)}`;
|
|
else {
|
|
if (mode === FOLD_QUOTED && escapedFolds[fold])
|
|
res += `${text[fold]}\\`;
|
|
res += `
|
|
${indent}${text.slice(fold + 1, end2)}`;
|
|
}
|
|
}
|
|
return res;
|
|
}
|
|
function consumeMoreIndentedLines(text, i, indent) {
|
|
let end = i;
|
|
let start = i + 1;
|
|
let ch = text[start];
|
|
while (ch === " " || ch === " ") {
|
|
if (i < start + indent) {
|
|
ch = text[++i];
|
|
} else {
|
|
do {
|
|
ch = text[++i];
|
|
} while (ch && ch !== "\n");
|
|
end = i;
|
|
start = i + 1;
|
|
ch = text[start];
|
|
}
|
|
}
|
|
return end;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/stringify/stringifyString.js
|
|
var getFoldOptions = (ctx, isBlock) => ({
|
|
indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
|
|
lineWidth: ctx.options.lineWidth,
|
|
minContentWidth: ctx.options.minContentWidth
|
|
});
|
|
var containsDocumentMarker = (str2) => /^(%|---|\.\.\.)/m.test(str2);
|
|
function lineLengthOverLimit(str2, lineWidth, indentLength) {
|
|
if (!lineWidth || lineWidth < 0)
|
|
return false;
|
|
const limit3 = lineWidth - indentLength;
|
|
const strLen = str2.length;
|
|
if (strLen <= limit3)
|
|
return false;
|
|
for (let i = 0, start = 0; i < strLen; ++i) {
|
|
if (str2[i] === "\n") {
|
|
if (i - start > limit3)
|
|
return true;
|
|
start = i + 1;
|
|
if (strLen - start <= limit3)
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
function doubleQuotedString(value, ctx) {
|
|
const json = JSON.stringify(value);
|
|
if (ctx.options.doubleQuotedAsJSON)
|
|
return json;
|
|
const { implicitKey } = ctx;
|
|
const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
|
|
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
|
|
let str2 = "";
|
|
let start = 0;
|
|
for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
|
|
if (ch === " " && json[i + 1] === "\\" && json[i + 2] === "n") {
|
|
str2 += json.slice(start, i) + "\\ ";
|
|
i += 1;
|
|
start = i;
|
|
ch = "\\";
|
|
}
|
|
if (ch === "\\")
|
|
switch (json[i + 1]) {
|
|
case "u":
|
|
{
|
|
str2 += json.slice(start, i);
|
|
const code = json.substr(i + 2, 4);
|
|
switch (code) {
|
|
case "0000":
|
|
str2 += "\\0";
|
|
break;
|
|
case "0007":
|
|
str2 += "\\a";
|
|
break;
|
|
case "000b":
|
|
str2 += "\\v";
|
|
break;
|
|
case "001b":
|
|
str2 += "\\e";
|
|
break;
|
|
case "0085":
|
|
str2 += "\\N";
|
|
break;
|
|
case "00a0":
|
|
str2 += "\\_";
|
|
break;
|
|
case "2028":
|
|
str2 += "\\L";
|
|
break;
|
|
case "2029":
|
|
str2 += "\\P";
|
|
break;
|
|
default:
|
|
if (code.substr(0, 2) === "00")
|
|
str2 += "\\x" + code.substr(2);
|
|
else
|
|
str2 += json.substr(i, 6);
|
|
}
|
|
i += 5;
|
|
start = i + 1;
|
|
}
|
|
break;
|
|
case "n":
|
|
if (implicitKey || json[i + 2] === '"' || json.length < minMultiLineLength) {
|
|
i += 1;
|
|
} else {
|
|
str2 += json.slice(start, i) + "\n\n";
|
|
while (json[i + 2] === "\\" && json[i + 3] === "n" && json[i + 4] !== '"') {
|
|
str2 += "\n";
|
|
i += 2;
|
|
}
|
|
str2 += indent;
|
|
if (json[i + 2] === " ")
|
|
str2 += "\\";
|
|
i += 1;
|
|
start = i + 1;
|
|
}
|
|
break;
|
|
default:
|
|
i += 1;
|
|
}
|
|
}
|
|
str2 = start ? str2 + json.slice(start) : json;
|
|
return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
|
|
}
|
|
function singleQuotedString(value, ctx) {
|
|
if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value))
|
|
return doubleQuotedString(value, ctx);
|
|
const indent = ctx.indent || (containsDocumentMarker(value) ? " " : "");
|
|
const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&
|
|
${indent}`) + "'";
|
|
return ctx.implicitKey ? res : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
|
|
}
|
|
function quotedString(value, ctx) {
|
|
const { singleQuote } = ctx.options;
|
|
let qs;
|
|
if (singleQuote === false)
|
|
qs = doubleQuotedString;
|
|
else {
|
|
const hasDouble = value.includes('"');
|
|
const hasSingle = value.includes("'");
|
|
if (hasDouble && !hasSingle)
|
|
qs = singleQuotedString;
|
|
else if (hasSingle && !hasDouble)
|
|
qs = doubleQuotedString;
|
|
else
|
|
qs = singleQuote ? singleQuotedString : doubleQuotedString;
|
|
}
|
|
return qs(value, ctx);
|
|
}
|
|
var blockEndNewlines;
|
|
try {
|
|
blockEndNewlines = new RegExp("(^|(?<!\n))\n+(?!\n|$)", "g");
|
|
} catch {
|
|
blockEndNewlines = /\n+(?!\n|$)/g;
|
|
}
|
|
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
|
|
const { blockQuote, commentString, lineWidth } = ctx.options;
|
|
if (!blockQuote || /\n[\t ]+$/.test(value)) {
|
|
return quotedString(value, ctx);
|
|
}
|
|
const indent = ctx.indent || (ctx.forceBlockIndent || containsDocumentMarker(value) ? " " : "");
|
|
const literal = blockQuote === "literal" ? true : blockQuote === "folded" || type === Scalar.BLOCK_FOLDED ? false : type === Scalar.BLOCK_LITERAL ? true : !lineLengthOverLimit(value, lineWidth, indent.length);
|
|
if (!value)
|
|
return literal ? "|\n" : ">\n";
|
|
let chomp;
|
|
let endStart;
|
|
for (endStart = value.length; endStart > 0; --endStart) {
|
|
const ch = value[endStart - 1];
|
|
if (ch !== "\n" && ch !== " " && ch !== " ")
|
|
break;
|
|
}
|
|
let end = value.substring(endStart);
|
|
const endNlPos = end.indexOf("\n");
|
|
if (endNlPos === -1) {
|
|
chomp = "-";
|
|
} else if (value === end || endNlPos !== end.length - 1) {
|
|
chomp = "+";
|
|
if (onChompKeep)
|
|
onChompKeep();
|
|
} else {
|
|
chomp = "";
|
|
}
|
|
if (end) {
|
|
value = value.slice(0, -end.length);
|
|
if (end[end.length - 1] === "\n")
|
|
end = end.slice(0, -1);
|
|
end = end.replace(blockEndNewlines, `$&${indent}`);
|
|
}
|
|
let startWithSpace = false;
|
|
let startEnd;
|
|
let startNlPos = -1;
|
|
for (startEnd = 0; startEnd < value.length; ++startEnd) {
|
|
const ch = value[startEnd];
|
|
if (ch === " ")
|
|
startWithSpace = true;
|
|
else if (ch === "\n")
|
|
startNlPos = startEnd;
|
|
else
|
|
break;
|
|
}
|
|
let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
|
|
if (start) {
|
|
value = value.substring(start.length);
|
|
start = start.replace(/\n+/g, `$&${indent}`);
|
|
}
|
|
const indentSize = indent ? "2" : "1";
|
|
let header = (startWithSpace ? indentSize : "") + chomp;
|
|
if (comment) {
|
|
header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " "));
|
|
if (onComment)
|
|
onComment();
|
|
}
|
|
if (!literal) {
|
|
const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`);
|
|
let literalFallback = false;
|
|
const foldOptions = getFoldOptions(ctx, true);
|
|
if (blockQuote !== "folded" && type !== Scalar.BLOCK_FOLDED) {
|
|
foldOptions.onOverflow = () => {
|
|
literalFallback = true;
|
|
};
|
|
}
|
|
const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);
|
|
if (!literalFallback)
|
|
return `>${header}
|
|
${indent}${body}`;
|
|
}
|
|
value = value.replace(/\n+/g, `$&${indent}`);
|
|
return `|${header}
|
|
${indent}${start}${value}${end}`;
|
|
}
|
|
function plainString(item, ctx, onComment, onChompKeep) {
|
|
const { type, value } = item;
|
|
const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
|
|
if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) {
|
|
return quotedString(value, ctx);
|
|
}
|
|
if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
|
|
return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep);
|
|
}
|
|
if (!implicitKey && !inFlow && type !== Scalar.PLAIN && value.includes("\n")) {
|
|
return blockString(item, ctx, onComment, onChompKeep);
|
|
}
|
|
if (containsDocumentMarker(value)) {
|
|
if (indent === "") {
|
|
ctx.forceBlockIndent = true;
|
|
return blockString(item, ctx, onComment, onChompKeep);
|
|
} else if (implicitKey && indent === indentStep) {
|
|
return quotedString(value, ctx);
|
|
}
|
|
}
|
|
const str2 = value.replace(/\n+/g, `$&
|
|
${indent}`);
|
|
if (actualString) {
|
|
const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str2);
|
|
const { compat, tags } = ctx.doc.schema;
|
|
if (tags.some(test) || compat?.some(test))
|
|
return quotedString(value, ctx);
|
|
}
|
|
return implicitKey ? str2 : foldFlowLines(str2, indent, FOLD_FLOW, getFoldOptions(ctx, false));
|
|
}
|
|
function stringifyString(item, ctx, onComment, onChompKeep) {
|
|
const { implicitKey, inFlow } = ctx;
|
|
const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) });
|
|
let { type } = item;
|
|
if (type !== Scalar.QUOTE_DOUBLE) {
|
|
if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
|
|
type = Scalar.QUOTE_DOUBLE;
|
|
}
|
|
const _stringify = (_type) => {
|
|
switch (_type) {
|
|
case Scalar.BLOCK_FOLDED:
|
|
case Scalar.BLOCK_LITERAL:
|
|
return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep);
|
|
case Scalar.QUOTE_DOUBLE:
|
|
return doubleQuotedString(ss.value, ctx);
|
|
case Scalar.QUOTE_SINGLE:
|
|
return singleQuotedString(ss.value, ctx);
|
|
case Scalar.PLAIN:
|
|
return plainString(ss, ctx, onComment, onChompKeep);
|
|
default:
|
|
return null;
|
|
}
|
|
};
|
|
let res = _stringify(type);
|
|
if (res === null) {
|
|
const { defaultKeyType, defaultStringType } = ctx.options;
|
|
const t = implicitKey && defaultKeyType || defaultStringType;
|
|
res = _stringify(t);
|
|
if (res === null)
|
|
throw new Error(`Unsupported default string type ${t}`);
|
|
}
|
|
return res;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/stringify/stringify.js
|
|
function createStringifyContext(doc, options) {
|
|
const opt2 = Object.assign({
|
|
blockQuote: true,
|
|
commentString: stringifyComment,
|
|
defaultKeyType: null,
|
|
defaultStringType: "PLAIN",
|
|
directives: null,
|
|
doubleQuotedAsJSON: false,
|
|
doubleQuotedMinMultiLineLength: 40,
|
|
falseStr: "false",
|
|
flowCollectionPadding: true,
|
|
indentSeq: true,
|
|
lineWidth: 80,
|
|
minContentWidth: 20,
|
|
nullStr: "null",
|
|
simpleKeys: false,
|
|
singleQuote: null,
|
|
trailingComma: false,
|
|
trueStr: "true",
|
|
verifyAliasOrder: true
|
|
}, doc.schema.toStringOptions, options);
|
|
let inFlow;
|
|
switch (opt2.collectionStyle) {
|
|
case "block":
|
|
inFlow = false;
|
|
break;
|
|
case "flow":
|
|
inFlow = true;
|
|
break;
|
|
default:
|
|
inFlow = null;
|
|
}
|
|
return {
|
|
anchors: /* @__PURE__ */ new Set(),
|
|
doc,
|
|
flowCollectionPadding: opt2.flowCollectionPadding ? " " : "",
|
|
indent: "",
|
|
indentStep: typeof opt2.indent === "number" ? " ".repeat(opt2.indent) : " ",
|
|
inFlow,
|
|
options: opt2
|
|
};
|
|
}
|
|
function getTagObject(tags, item) {
|
|
if (item.tag) {
|
|
const match = tags.filter((t) => t.tag === item.tag);
|
|
if (match.length > 0)
|
|
return match.find((t) => t.format === item.format) ?? match[0];
|
|
}
|
|
let tagObj = void 0;
|
|
let obj2;
|
|
if (isScalar(item)) {
|
|
obj2 = item.value;
|
|
let match = tags.filter((t) => t.identify?.(obj2));
|
|
if (match.length > 1) {
|
|
const testMatch = match.filter((t) => t.test);
|
|
if (testMatch.length > 0)
|
|
match = testMatch;
|
|
}
|
|
tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format);
|
|
} else {
|
|
obj2 = item;
|
|
tagObj = tags.find((t) => t.nodeClass && obj2 instanceof t.nodeClass);
|
|
}
|
|
if (!tagObj) {
|
|
const name = obj2?.constructor?.name ?? (obj2 === null ? "null" : typeof obj2);
|
|
throw new Error(`Tag not resolved for ${name} value`);
|
|
}
|
|
return tagObj;
|
|
}
|
|
function stringifyProps(node, tagObj, { anchors, doc }) {
|
|
if (!doc.directives)
|
|
return "";
|
|
const props = [];
|
|
const anchor = (isScalar(node) || isCollection(node)) && node.anchor;
|
|
if (anchor && anchorIsValid(anchor)) {
|
|
anchors.add(anchor);
|
|
props.push(`&${anchor}`);
|
|
}
|
|
const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);
|
|
if (tag)
|
|
props.push(doc.directives.tagString(tag));
|
|
return props.join(" ");
|
|
}
|
|
function stringify3(item, ctx, onComment, onChompKeep) {
|
|
if (isPair(item))
|
|
return item.toString(ctx, onComment, onChompKeep);
|
|
if (isAlias(item)) {
|
|
if (ctx.doc.directives)
|
|
return item.toString(ctx);
|
|
if (ctx.resolvedAliases?.has(item)) {
|
|
throw new TypeError(`Cannot stringify circular structure without alias nodes`);
|
|
} else {
|
|
if (ctx.resolvedAliases)
|
|
ctx.resolvedAliases.add(item);
|
|
else
|
|
ctx.resolvedAliases = /* @__PURE__ */ new Set([item]);
|
|
item = item.resolve(ctx.doc);
|
|
}
|
|
}
|
|
let tagObj = void 0;
|
|
const node = isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o });
|
|
tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));
|
|
const props = stringifyProps(node, tagObj, ctx);
|
|
if (props.length > 0)
|
|
ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
|
|
const str2 = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : isScalar(node) ? stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep);
|
|
if (!props)
|
|
return str2;
|
|
return isScalar(node) || str2[0] === "{" || str2[0] === "[" ? `${props} ${str2}` : `${props}
|
|
${ctx.indent}${str2}`;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/stringify/stringifyPair.js
|
|
function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
|
|
const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
|
|
let keyComment = isNode(key) && key.comment || null;
|
|
if (simpleKeys) {
|
|
if (keyComment) {
|
|
throw new Error("With simple keys, key nodes cannot have comments");
|
|
}
|
|
if (isCollection(key) || !isNode(key) && typeof key === "object") {
|
|
const msg = "With simple keys, collection cannot be used as a key value";
|
|
throw new Error(msg);
|
|
}
|
|
}
|
|
let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || isCollection(key) || (isScalar(key) ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL : typeof key === "object"));
|
|
ctx = Object.assign({}, ctx, {
|
|
allNullValues: false,
|
|
implicitKey: !explicitKey && (simpleKeys || !allNullValues),
|
|
indent: indent + indentStep
|
|
});
|
|
let keyCommentDone = false;
|
|
let chompKeep = false;
|
|
let str2 = stringify3(key, ctx, () => keyCommentDone = true, () => chompKeep = true);
|
|
if (!explicitKey && !ctx.inFlow && str2.length > 1024) {
|
|
if (simpleKeys)
|
|
throw new Error("With simple keys, single line scalar must not span more than 1024 characters");
|
|
explicitKey = true;
|
|
}
|
|
if (ctx.inFlow) {
|
|
if (allNullValues || value == null) {
|
|
if (keyCommentDone && onComment)
|
|
onComment();
|
|
return str2 === "" ? "?" : explicitKey ? `? ${str2}` : str2;
|
|
}
|
|
} else if (allNullValues && !simpleKeys || value == null && explicitKey) {
|
|
str2 = `? ${str2}`;
|
|
if (keyComment && !keyCommentDone) {
|
|
str2 += lineComment(str2, ctx.indent, commentString(keyComment));
|
|
} else if (chompKeep && onChompKeep)
|
|
onChompKeep();
|
|
return str2;
|
|
}
|
|
if (keyCommentDone)
|
|
keyComment = null;
|
|
if (explicitKey) {
|
|
if (keyComment)
|
|
str2 += lineComment(str2, ctx.indent, commentString(keyComment));
|
|
str2 = `? ${str2}
|
|
${indent}:`;
|
|
} else {
|
|
str2 = `${str2}:`;
|
|
if (keyComment)
|
|
str2 += lineComment(str2, ctx.indent, commentString(keyComment));
|
|
}
|
|
let vsb, vcb, valueComment;
|
|
if (isNode(value)) {
|
|
vsb = !!value.spaceBefore;
|
|
vcb = value.commentBefore;
|
|
valueComment = value.comment;
|
|
} else {
|
|
vsb = false;
|
|
vcb = null;
|
|
valueComment = null;
|
|
if (value && typeof value === "object")
|
|
value = doc.createNode(value);
|
|
}
|
|
ctx.implicitKey = false;
|
|
if (!explicitKey && !keyComment && isScalar(value))
|
|
ctx.indentAtStart = str2.length + 1;
|
|
chompKeep = false;
|
|
if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && isSeq(value) && !value.flow && !value.tag && !value.anchor) {
|
|
ctx.indent = ctx.indent.substring(2);
|
|
}
|
|
let valueCommentDone = false;
|
|
const valueStr = stringify3(value, ctx, () => valueCommentDone = true, () => chompKeep = true);
|
|
let ws = " ";
|
|
if (keyComment || vsb || vcb) {
|
|
ws = vsb ? "\n" : "";
|
|
if (vcb) {
|
|
const cs = commentString(vcb);
|
|
ws += `
|
|
${indentComment(cs, ctx.indent)}`;
|
|
}
|
|
if (valueStr === "" && !ctx.inFlow) {
|
|
if (ws === "\n" && valueComment)
|
|
ws = "\n\n";
|
|
} else {
|
|
ws += `
|
|
${ctx.indent}`;
|
|
}
|
|
} else if (!explicitKey && isCollection(value)) {
|
|
const vs0 = valueStr[0];
|
|
const nl0 = valueStr.indexOf("\n");
|
|
const hasNewline = nl0 !== -1;
|
|
const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
|
|
if (hasNewline || !flow) {
|
|
let hasPropsLine = false;
|
|
if (hasNewline && (vs0 === "&" || vs0 === "!")) {
|
|
let sp0 = valueStr.indexOf(" ");
|
|
if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") {
|
|
sp0 = valueStr.indexOf(" ", sp0 + 1);
|
|
}
|
|
if (sp0 === -1 || nl0 < sp0)
|
|
hasPropsLine = true;
|
|
}
|
|
if (!hasPropsLine)
|
|
ws = `
|
|
${ctx.indent}`;
|
|
}
|
|
} else if (valueStr === "" || valueStr[0] === "\n") {
|
|
ws = "";
|
|
}
|
|
str2 += ws + valueStr;
|
|
if (ctx.inFlow) {
|
|
if (valueCommentDone && onComment)
|
|
onComment();
|
|
} else if (valueComment && !valueCommentDone) {
|
|
str2 += lineComment(str2, ctx.indent, commentString(valueComment));
|
|
} else if (chompKeep && onChompKeep) {
|
|
onChompKeep();
|
|
}
|
|
return str2;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/log.js
|
|
function warn(logLevel, warning) {
|
|
if (logLevel === "debug" || logLevel === "warn") {
|
|
console.warn(warning);
|
|
}
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js
|
|
var MERGE_KEY = "<<";
|
|
var merge = {
|
|
identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY,
|
|
default: "key",
|
|
tag: "tag:yaml.org,2002:merge",
|
|
test: /^<<$/,
|
|
resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {
|
|
addToJSMap: addMergeToJSMap
|
|
}),
|
|
stringify: () => MERGE_KEY
|
|
};
|
|
var isMergeKey = (ctx, key) => (merge.identify(key) || isScalar(key) && (!key.type || key.type === Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default);
|
|
function addMergeToJSMap(ctx, map3, value) {
|
|
const source = resolveAliasValue(ctx, value);
|
|
if (isSeq(source))
|
|
for (const it of source.items)
|
|
mergeValue(ctx, map3, it);
|
|
else if (Array.isArray(source))
|
|
for (const it of source)
|
|
mergeValue(ctx, map3, it);
|
|
else
|
|
mergeValue(ctx, map3, source);
|
|
}
|
|
function mergeValue(ctx, map3, value) {
|
|
const source = resolveAliasValue(ctx, value);
|
|
if (!isMap(source))
|
|
throw new Error("Merge sources must be maps or map aliases");
|
|
const srcMap = source.toJSON(null, ctx, Map);
|
|
for (const [key, value2] of srcMap) {
|
|
if (map3 instanceof Map) {
|
|
if (!map3.has(key))
|
|
map3.set(key, value2);
|
|
} else if (map3 instanceof Set) {
|
|
map3.add(key);
|
|
} else if (!Object.prototype.hasOwnProperty.call(map3, key)) {
|
|
Object.defineProperty(map3, key, {
|
|
value: value2,
|
|
writable: true,
|
|
enumerable: true,
|
|
configurable: true
|
|
});
|
|
}
|
|
}
|
|
return map3;
|
|
}
|
|
function resolveAliasValue(ctx, value) {
|
|
return ctx && isAlias(value) ? value.resolve(ctx.doc, ctx) : value;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/addPairToJSMap.js
|
|
function addPairToJSMap(ctx, map3, { key, value }) {
|
|
if (isNode(key) && key.addToJSMap)
|
|
key.addToJSMap(ctx, map3, value);
|
|
else if (isMergeKey(ctx, key))
|
|
addMergeToJSMap(ctx, map3, value);
|
|
else {
|
|
const jsKey = toJS(key, "", ctx);
|
|
if (map3 instanceof Map) {
|
|
map3.set(jsKey, toJS(value, jsKey, ctx));
|
|
} else if (map3 instanceof Set) {
|
|
map3.add(jsKey);
|
|
} else {
|
|
const stringKey = stringifyKey(key, jsKey, ctx);
|
|
const jsValue = toJS(value, stringKey, ctx);
|
|
if (stringKey in map3)
|
|
Object.defineProperty(map3, stringKey, {
|
|
value: jsValue,
|
|
writable: true,
|
|
enumerable: true,
|
|
configurable: true
|
|
});
|
|
else
|
|
map3[stringKey] = jsValue;
|
|
}
|
|
}
|
|
return map3;
|
|
}
|
|
function stringifyKey(key, jsKey, ctx) {
|
|
if (jsKey === null)
|
|
return "";
|
|
if (typeof jsKey !== "object")
|
|
return String(jsKey);
|
|
if (isNode(key) && ctx?.doc) {
|
|
const strCtx = createStringifyContext(ctx.doc, {});
|
|
strCtx.anchors = /* @__PURE__ */ new Set();
|
|
for (const node of ctx.anchors.keys())
|
|
strCtx.anchors.add(node.anchor);
|
|
strCtx.inFlow = true;
|
|
strCtx.inStringifyKey = true;
|
|
const strKey = key.toString(strCtx);
|
|
if (!ctx.mapKeyWarned) {
|
|
let jsonStr = JSON.stringify(strKey);
|
|
if (jsonStr.length > 40)
|
|
jsonStr = jsonStr.substring(0, 36) + '..."';
|
|
warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
|
|
ctx.mapKeyWarned = true;
|
|
}
|
|
return strKey;
|
|
}
|
|
return JSON.stringify(jsKey);
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/Pair.js
|
|
function createPair(key, value, ctx) {
|
|
const k = createNode(key, void 0, ctx);
|
|
const v = createNode(value, void 0, ctx);
|
|
return new Pair(k, v);
|
|
}
|
|
var Pair = class _Pair {
|
|
constructor(key, value = null) {
|
|
Object.defineProperty(this, NODE_TYPE, { value: PAIR });
|
|
this.key = key;
|
|
this.value = value;
|
|
}
|
|
clone(schema4) {
|
|
let { key, value } = this;
|
|
if (isNode(key))
|
|
key = key.clone(schema4);
|
|
if (isNode(value))
|
|
value = value.clone(schema4);
|
|
return new _Pair(key, value);
|
|
}
|
|
toJSON(_, ctx) {
|
|
const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
|
|
return addPairToJSMap(ctx, pair, this);
|
|
}
|
|
toString(ctx, onComment, onChompKeep) {
|
|
return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this);
|
|
}
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/stringify/stringifyCollection.js
|
|
function stringifyCollection(collection, ctx, options) {
|
|
const flow = ctx.inFlow ?? collection.flow;
|
|
const stringify6 = flow ? stringifyFlowCollection : stringifyBlockCollection;
|
|
return stringify6(collection, ctx, options);
|
|
}
|
|
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
|
|
const { indent, options: { commentString } } = ctx;
|
|
const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
|
|
let chompKeep = false;
|
|
const lines = [];
|
|
for (let i = 0; i < items.length; ++i) {
|
|
const item = items[i];
|
|
let comment2 = null;
|
|
if (isNode(item)) {
|
|
if (!chompKeep && item.spaceBefore)
|
|
lines.push("");
|
|
addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
|
|
if (item.comment)
|
|
comment2 = item.comment;
|
|
} else if (isPair(item)) {
|
|
const ik = isNode(item.key) ? item.key : null;
|
|
if (ik) {
|
|
if (!chompKeep && ik.spaceBefore)
|
|
lines.push("");
|
|
addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
|
|
}
|
|
}
|
|
chompKeep = false;
|
|
let str3 = stringify3(item, itemCtx, () => comment2 = null, () => chompKeep = true);
|
|
if (comment2)
|
|
str3 += lineComment(str3, itemIndent, commentString(comment2));
|
|
if (chompKeep && comment2)
|
|
chompKeep = false;
|
|
lines.push(blockItemPrefix + str3);
|
|
}
|
|
let str2;
|
|
if (lines.length === 0) {
|
|
str2 = flowChars.start + flowChars.end;
|
|
} else {
|
|
str2 = lines[0];
|
|
for (let i = 1; i < lines.length; ++i) {
|
|
const line = lines[i];
|
|
str2 += line ? `
|
|
${indent}${line}` : "\n";
|
|
}
|
|
}
|
|
if (comment) {
|
|
str2 += "\n" + indentComment(commentString(comment), indent);
|
|
if (onComment)
|
|
onComment();
|
|
} else if (chompKeep && onChompKeep)
|
|
onChompKeep();
|
|
return str2;
|
|
}
|
|
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
|
|
const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
|
|
itemIndent += indentStep;
|
|
const itemCtx = Object.assign({}, ctx, {
|
|
indent: itemIndent,
|
|
inFlow: true,
|
|
type: null
|
|
});
|
|
let reqNewline = false;
|
|
let linesAtValue = 0;
|
|
const lines = [];
|
|
for (let i = 0; i < items.length; ++i) {
|
|
const item = items[i];
|
|
let comment = null;
|
|
if (isNode(item)) {
|
|
if (item.spaceBefore)
|
|
lines.push("");
|
|
addCommentBefore(ctx, lines, item.commentBefore, false);
|
|
if (item.comment)
|
|
comment = item.comment;
|
|
} else if (isPair(item)) {
|
|
const ik = isNode(item.key) ? item.key : null;
|
|
if (ik) {
|
|
if (ik.spaceBefore)
|
|
lines.push("");
|
|
addCommentBefore(ctx, lines, ik.commentBefore, false);
|
|
if (ik.comment)
|
|
reqNewline = true;
|
|
}
|
|
const iv = isNode(item.value) ? item.value : null;
|
|
if (iv) {
|
|
if (iv.comment)
|
|
comment = iv.comment;
|
|
if (iv.commentBefore)
|
|
reqNewline = true;
|
|
} else if (item.value == null && ik?.comment) {
|
|
comment = ik.comment;
|
|
}
|
|
}
|
|
if (comment)
|
|
reqNewline = true;
|
|
let str2 = stringify3(item, itemCtx, () => comment = null);
|
|
reqNewline || (reqNewline = lines.length > linesAtValue || str2.includes("\n"));
|
|
if (i < items.length - 1) {
|
|
str2 += ",";
|
|
} else if (ctx.options.trailingComma) {
|
|
if (ctx.options.lineWidth > 0) {
|
|
reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str2.length + 2) > ctx.options.lineWidth);
|
|
}
|
|
if (reqNewline) {
|
|
str2 += ",";
|
|
}
|
|
}
|
|
if (comment)
|
|
str2 += lineComment(str2, itemIndent, commentString(comment));
|
|
lines.push(str2);
|
|
linesAtValue = lines.length;
|
|
}
|
|
const { start, end } = flowChars;
|
|
if (lines.length === 0) {
|
|
return start + end;
|
|
} else {
|
|
if (!reqNewline) {
|
|
const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
|
|
reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
|
|
}
|
|
if (reqNewline) {
|
|
let str2 = start;
|
|
for (const line of lines)
|
|
str2 += line ? `
|
|
${indentStep}${indent}${line}` : "\n";
|
|
return `${str2}
|
|
${indent}${end}`;
|
|
} else {
|
|
return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`;
|
|
}
|
|
}
|
|
}
|
|
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
|
|
if (comment && chompKeep)
|
|
comment = comment.replace(/^\n+/, "");
|
|
if (comment) {
|
|
const ic = indentComment(commentString(comment), indent);
|
|
lines.push(ic.trimStart());
|
|
}
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/nodes/YAMLMap.js
|
|
function findPair(items, key) {
|
|
const k = isScalar(key) ? key.value : key;
|
|
for (const it of items) {
|
|
if (isPair(it)) {
|
|
if (it.key === key || it.key === k)
|
|
return it;
|
|
if (isScalar(it.key) && it.key.value === k)
|
|
return it;
|
|
}
|
|
}
|
|
return void 0;
|
|
}
|
|
var YAMLMap = class extends Collection {
|
|
static get tagName() {
|
|
return "tag:yaml.org,2002:map";
|
|
}
|
|
constructor(schema4) {
|
|
super(MAP, schema4);
|
|
this.items = [];
|
|
}
|
|
/**
|
|
* A generic collection parsing method that can be extended
|
|
* to other node classes that inherit from YAMLMap
|
|
*/
|
|
static from(schema4, obj2, ctx) {
|
|
const { keepUndefined, replacer } = ctx;
|
|
const map3 = new this(schema4);
|
|
const add = (key, value) => {
|
|
if (typeof replacer === "function")
|
|
value = replacer.call(obj2, key, value);
|
|
else if (Array.isArray(replacer) && !replacer.includes(key))
|
|
return;
|
|
if (value !== void 0 || keepUndefined)
|
|
map3.items.push(createPair(key, value, ctx));
|
|
};
|
|
if (obj2 instanceof Map) {
|
|
for (const [key, value] of obj2)
|
|
add(key, value);
|
|
} else if (obj2 && typeof obj2 === "object") {
|
|
for (const key of Object.keys(obj2))
|
|
add(key, obj2[key]);
|
|
}
|
|
if (typeof schema4.sortMapEntries === "function") {
|
|
map3.items.sort(schema4.sortMapEntries);
|
|
}
|
|
return map3;
|
|
}
|
|
/**
|
|
* Adds a value to the collection.
|
|
*
|
|
* @param overwrite - If not set `true`, using a key that is already in the
|
|
* collection will throw. Otherwise, overwrites the previous value.
|
|
*/
|
|
add(pair, overwrite) {
|
|
let _pair;
|
|
if (isPair(pair))
|
|
_pair = pair;
|
|
else if (!pair || typeof pair !== "object" || !("key" in pair)) {
|
|
_pair = new Pair(pair, pair?.value);
|
|
} else
|
|
_pair = new Pair(pair.key, pair.value);
|
|
const prev = findPair(this.items, _pair.key);
|
|
const sortEntries = this.schema?.sortMapEntries;
|
|
if (prev) {
|
|
if (!overwrite)
|
|
throw new Error(`Key ${_pair.key} already set`);
|
|
if (isScalar(prev.value) && isScalarValue(_pair.value))
|
|
prev.value.value = _pair.value;
|
|
else
|
|
prev.value = _pair.value;
|
|
} else if (sortEntries) {
|
|
const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0);
|
|
if (i === -1)
|
|
this.items.push(_pair);
|
|
else
|
|
this.items.splice(i, 0, _pair);
|
|
} else {
|
|
this.items.push(_pair);
|
|
}
|
|
}
|
|
delete(key) {
|
|
const it = findPair(this.items, key);
|
|
if (!it)
|
|
return false;
|
|
const del = this.items.splice(this.items.indexOf(it), 1);
|
|
return del.length > 0;
|
|
}
|
|
get(key, keepScalar) {
|
|
const it = findPair(this.items, key);
|
|
const node = it?.value;
|
|
return (!keepScalar && isScalar(node) ? node.value : node) ?? void 0;
|
|
}
|
|
has(key) {
|
|
return !!findPair(this.items, key);
|
|
}
|
|
set(key, value) {
|
|
this.add(new Pair(key, value), true);
|
|
}
|
|
/**
|
|
* @param ctx - Conversion context, originally set in Document#toJS()
|
|
* @param {Class} Type - If set, forces the returned collection type
|
|
* @returns Instance of Type, Map, or Object
|
|
*/
|
|
toJSON(_, ctx, Type) {
|
|
const map3 = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {};
|
|
if (ctx?.onCreate)
|
|
ctx.onCreate(map3);
|
|
for (const item of this.items)
|
|
addPairToJSMap(ctx, map3, item);
|
|
return map3;
|
|
}
|
|
toString(ctx, onComment, onChompKeep) {
|
|
if (!ctx)
|
|
return JSON.stringify(this);
|
|
for (const item of this.items) {
|
|
if (!isPair(item))
|
|
throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
|
|
}
|
|
if (!ctx.allNullValues && this.hasAllNullValues(false))
|
|
ctx = Object.assign({}, ctx, { allNullValues: true });
|
|
return stringifyCollection(this, ctx, {
|
|
blockItemPrefix: "",
|
|
flowChars: { start: "{", end: "}" },
|
|
itemIndent: ctx.indent || "",
|
|
onChompKeep,
|
|
onComment
|
|
});
|
|
}
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/schema/common/map.js
|
|
var map2 = {
|
|
collection: "map",
|
|
default: true,
|
|
nodeClass: YAMLMap,
|
|
tag: "tag:yaml.org,2002:map",
|
|
resolve(map3, onError) {
|
|
if (!isMap(map3))
|
|
onError("Expected a mapping for this tag");
|
|
return map3;
|
|
},
|
|
createNode: (schema4, obj2, ctx) => YAMLMap.from(schema4, obj2, ctx)
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/nodes/YAMLSeq.js
|
|
var YAMLSeq = class extends Collection {
|
|
static get tagName() {
|
|
return "tag:yaml.org,2002:seq";
|
|
}
|
|
constructor(schema4) {
|
|
super(SEQ, schema4);
|
|
this.items = [];
|
|
}
|
|
add(value) {
|
|
this.items.push(value);
|
|
}
|
|
/**
|
|
* Removes a value from the collection.
|
|
*
|
|
* `key` must contain a representation of an integer for this to succeed.
|
|
* It may be wrapped in a `Scalar`.
|
|
*
|
|
* @returns `true` if the item was found and removed.
|
|
*/
|
|
delete(key) {
|
|
const idx = asItemIndex(key);
|
|
if (typeof idx !== "number")
|
|
return false;
|
|
const del = this.items.splice(idx, 1);
|
|
return del.length > 0;
|
|
}
|
|
get(key, keepScalar) {
|
|
const idx = asItemIndex(key);
|
|
if (typeof idx !== "number")
|
|
return void 0;
|
|
const it = this.items[idx];
|
|
return !keepScalar && isScalar(it) ? it.value : it;
|
|
}
|
|
/**
|
|
* Checks if the collection includes a value with the key `key`.
|
|
*
|
|
* `key` must contain a representation of an integer for this to succeed.
|
|
* It may be wrapped in a `Scalar`.
|
|
*/
|
|
has(key) {
|
|
const idx = asItemIndex(key);
|
|
return typeof idx === "number" && idx < this.items.length;
|
|
}
|
|
/**
|
|
* Sets a value in this collection. For `!!set`, `value` needs to be a
|
|
* boolean to add/remove the item from the set.
|
|
*
|
|
* If `key` does not contain a representation of an integer, this will throw.
|
|
* It may be wrapped in a `Scalar`.
|
|
*/
|
|
set(key, value) {
|
|
const idx = asItemIndex(key);
|
|
if (typeof idx !== "number")
|
|
throw new Error(`Expected a valid index, not ${key}.`);
|
|
const prev = this.items[idx];
|
|
if (isScalar(prev) && isScalarValue(value))
|
|
prev.value = value;
|
|
else
|
|
this.items[idx] = value;
|
|
}
|
|
toJSON(_, ctx) {
|
|
const seq2 = [];
|
|
if (ctx?.onCreate)
|
|
ctx.onCreate(seq2);
|
|
let i = 0;
|
|
for (const item of this.items)
|
|
seq2.push(toJS(item, String(i++), ctx));
|
|
return seq2;
|
|
}
|
|
toString(ctx, onComment, onChompKeep) {
|
|
if (!ctx)
|
|
return JSON.stringify(this);
|
|
return stringifyCollection(this, ctx, {
|
|
blockItemPrefix: "- ",
|
|
flowChars: { start: "[", end: "]" },
|
|
itemIndent: (ctx.indent || "") + " ",
|
|
onChompKeep,
|
|
onComment
|
|
});
|
|
}
|
|
static from(schema4, obj2, ctx) {
|
|
const { replacer } = ctx;
|
|
const seq2 = new this(schema4);
|
|
if (obj2 && Symbol.iterator in Object(obj2)) {
|
|
let i = 0;
|
|
for (let it of obj2) {
|
|
if (typeof replacer === "function") {
|
|
const key = obj2 instanceof Set ? it : String(i++);
|
|
it = replacer.call(obj2, key, it);
|
|
}
|
|
seq2.items.push(createNode(it, void 0, ctx));
|
|
}
|
|
}
|
|
return seq2;
|
|
}
|
|
};
|
|
function asItemIndex(key) {
|
|
let idx = isScalar(key) ? key.value : key;
|
|
if (idx && typeof idx === "string")
|
|
idx = Number(idx);
|
|
return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/schema/common/seq.js
|
|
var seq = {
|
|
collection: "seq",
|
|
default: true,
|
|
nodeClass: YAMLSeq,
|
|
tag: "tag:yaml.org,2002:seq",
|
|
resolve(seq2, onError) {
|
|
if (!isSeq(seq2))
|
|
onError("Expected a sequence for this tag");
|
|
return seq2;
|
|
},
|
|
createNode: (schema4, obj2, ctx) => YAMLSeq.from(schema4, obj2, ctx)
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/schema/json/schema.js
|
|
function intIdentify(value) {
|
|
return typeof value === "bigint" || Number.isInteger(value);
|
|
}
|
|
var stringifyJSON = ({ value }) => JSON.stringify(value);
|
|
var jsonScalars = [
|
|
{
|
|
identify: (value) => typeof value === "string",
|
|
default: true,
|
|
tag: "tag:yaml.org,2002:str",
|
|
resolve: (str2) => str2,
|
|
stringify: stringifyJSON
|
|
},
|
|
{
|
|
identify: (value) => value == null,
|
|
createNode: () => new Scalar(null),
|
|
default: true,
|
|
tag: "tag:yaml.org,2002:null",
|
|
test: /^null$/,
|
|
resolve: () => null,
|
|
stringify: stringifyJSON
|
|
},
|
|
{
|
|
identify: (value) => typeof value === "boolean",
|
|
default: true,
|
|
tag: "tag:yaml.org,2002:bool",
|
|
test: /^true$|^false$/,
|
|
resolve: (str2) => str2 === "true",
|
|
stringify: stringifyJSON
|
|
},
|
|
{
|
|
identify: intIdentify,
|
|
default: true,
|
|
tag: "tag:yaml.org,2002:int",
|
|
test: /^-?(?:0|[1-9][0-9]*)$/,
|
|
resolve: (str2, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str2) : parseInt(str2, 10),
|
|
stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
|
|
},
|
|
{
|
|
identify: (value) => typeof value === "number",
|
|
default: true,
|
|
tag: "tag:yaml.org,2002:float",
|
|
test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
|
|
resolve: (str2) => parseFloat(str2),
|
|
stringify: stringifyJSON
|
|
}
|
|
];
|
|
var jsonError = {
|
|
default: true,
|
|
tag: "",
|
|
test: /^/,
|
|
resolve(str2, onError) {
|
|
onError(`Unresolved plain scalar ${JSON.stringify(str2)}`);
|
|
return str2;
|
|
}
|
|
};
|
|
var schema = [map2, seq].concat(jsonScalars, jsonError);
|
|
|
|
// node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js
|
|
function createPairs(schema4, iterable, ctx) {
|
|
const { replacer } = ctx;
|
|
const pairs2 = new YAMLSeq(schema4);
|
|
pairs2.tag = "tag:yaml.org,2002:pairs";
|
|
let i = 0;
|
|
if (iterable && Symbol.iterator in Object(iterable))
|
|
for (let it of iterable) {
|
|
if (typeof replacer === "function")
|
|
it = replacer.call(iterable, String(i++), it);
|
|
let key, value;
|
|
if (Array.isArray(it)) {
|
|
if (it.length === 2) {
|
|
key = it[0];
|
|
value = it[1];
|
|
} else
|
|
throw new TypeError(`Expected [key, value] tuple: ${it}`);
|
|
} else if (it && it instanceof Object) {
|
|
const keys = Object.keys(it);
|
|
if (keys.length === 1) {
|
|
key = keys[0];
|
|
value = it[key];
|
|
} else {
|
|
throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
|
|
}
|
|
} else {
|
|
key = it;
|
|
}
|
|
pairs2.items.push(createPair(key, value, ctx));
|
|
}
|
|
return pairs2;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js
|
|
var YAMLOMap = class _YAMLOMap extends YAMLSeq {
|
|
constructor() {
|
|
super();
|
|
this.add = YAMLMap.prototype.add.bind(this);
|
|
this.delete = YAMLMap.prototype.delete.bind(this);
|
|
this.get = YAMLMap.prototype.get.bind(this);
|
|
this.has = YAMLMap.prototype.has.bind(this);
|
|
this.set = YAMLMap.prototype.set.bind(this);
|
|
this.tag = _YAMLOMap.tag;
|
|
}
|
|
/**
|
|
* If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
|
|
* but TypeScript won't allow widening the signature of a child method.
|
|
*/
|
|
toJSON(_, ctx) {
|
|
if (!ctx)
|
|
return super.toJSON(_);
|
|
const map3 = /* @__PURE__ */ new Map();
|
|
if (ctx?.onCreate)
|
|
ctx.onCreate(map3);
|
|
for (const pair of this.items) {
|
|
let key, value;
|
|
if (isPair(pair)) {
|
|
key = toJS(pair.key, "", ctx);
|
|
value = toJS(pair.value, key, ctx);
|
|
} else {
|
|
key = toJS(pair, "", ctx);
|
|
}
|
|
if (map3.has(key))
|
|
throw new Error("Ordered maps must not include duplicate keys");
|
|
map3.set(key, value);
|
|
}
|
|
return map3;
|
|
}
|
|
static from(schema4, iterable, ctx) {
|
|
const pairs2 = createPairs(schema4, iterable, ctx);
|
|
const omap2 = new this();
|
|
omap2.items = pairs2.items;
|
|
return omap2;
|
|
}
|
|
};
|
|
YAMLOMap.tag = "tag:yaml.org,2002:omap";
|
|
|
|
// node_modules/yaml/browser/dist/schema/yaml-1.1/set.js
|
|
var YAMLSet = class _YAMLSet extends YAMLMap {
|
|
constructor(schema4) {
|
|
super(schema4);
|
|
this.tag = _YAMLSet.tag;
|
|
}
|
|
add(key) {
|
|
let pair;
|
|
if (isPair(key))
|
|
pair = key;
|
|
else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null)
|
|
pair = new Pair(key.key, null);
|
|
else
|
|
pair = new Pair(key, null);
|
|
const prev = findPair(this.items, pair.key);
|
|
if (!prev)
|
|
this.items.push(pair);
|
|
}
|
|
/**
|
|
* If `keepPair` is `true`, returns the Pair matching `key`.
|
|
* Otherwise, returns the value of that Pair's key.
|
|
*/
|
|
get(key, keepPair) {
|
|
const pair = findPair(this.items, key);
|
|
return !keepPair && isPair(pair) ? isScalar(pair.key) ? pair.key.value : pair.key : pair;
|
|
}
|
|
set(key, value) {
|
|
if (typeof value !== "boolean")
|
|
throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
|
|
const prev = findPair(this.items, key);
|
|
if (prev && !value) {
|
|
this.items.splice(this.items.indexOf(prev), 1);
|
|
} else if (!prev && value) {
|
|
this.items.push(new Pair(key));
|
|
}
|
|
}
|
|
toJSON(_, ctx) {
|
|
return super.toJSON(_, ctx, Set);
|
|
}
|
|
toString(ctx, onComment, onChompKeep) {
|
|
if (!ctx)
|
|
return JSON.stringify(this);
|
|
if (this.hasAllNullValues(true))
|
|
return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
|
|
else
|
|
throw new Error("Set items must all have null values");
|
|
}
|
|
static from(schema4, iterable, ctx) {
|
|
const { replacer } = ctx;
|
|
const set2 = new this(schema4);
|
|
if (iterable && Symbol.iterator in Object(iterable))
|
|
for (let value of iterable) {
|
|
if (typeof replacer === "function")
|
|
value = replacer.call(iterable, value, value);
|
|
set2.items.push(createPair(value, null, ctx));
|
|
}
|
|
return set2;
|
|
}
|
|
};
|
|
YAMLSet.tag = "tag:yaml.org,2002:set";
|
|
|
|
// node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js
|
|
function parseSexagesimal(str2, asBigInt) {
|
|
const sign = str2[0];
|
|
const parts = sign === "-" || sign === "+" ? str2.substring(1) : str2;
|
|
const num2 = (n) => asBigInt ? BigInt(n) : Number(n);
|
|
const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num2(60) + num2(p), num2(0));
|
|
return sign === "-" ? num2(-1) * res : res;
|
|
}
|
|
var timestamp = {
|
|
identify: (value) => value instanceof Date,
|
|
default: true,
|
|
tag: "tag:yaml.org,2002:timestamp",
|
|
// If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
|
|
// may be omitted altogether, resulting in a date format. In such a case, the time part is
|
|
// assumed to be 00:00:00Z (start of day, UTC).
|
|
test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),
|
|
resolve(str2) {
|
|
const match = str2.match(timestamp.test);
|
|
if (!match)
|
|
throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");
|
|
const [, year, month, day, hour, minute, second] = match.map(Number);
|
|
const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0;
|
|
let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
|
|
const tz = match[8];
|
|
if (tz && tz !== "Z") {
|
|
let d = parseSexagesimal(tz, false);
|
|
if (Math.abs(d) < 30)
|
|
d *= 60;
|
|
date -= 6e4 * d;
|
|
}
|
|
return new Date(date);
|
|
},
|
|
stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? ""
|
|
};
|
|
|
|
// node_modules/yaml/browser/dist/parse/cst-visit.js
|
|
var BREAK2 = /* @__PURE__ */ Symbol("break visit");
|
|
var SKIP2 = /* @__PURE__ */ Symbol("skip children");
|
|
var REMOVE2 = /* @__PURE__ */ Symbol("remove item");
|
|
function visit2(cst, visitor) {
|
|
if ("type" in cst && cst.type === "document")
|
|
cst = { start: cst.start, value: cst.value };
|
|
_visit(Object.freeze([]), cst, visitor);
|
|
}
|
|
visit2.BREAK = BREAK2;
|
|
visit2.SKIP = SKIP2;
|
|
visit2.REMOVE = REMOVE2;
|
|
visit2.itemAtPath = (cst, path4) => {
|
|
let item = cst;
|
|
for (const [field, index] of path4) {
|
|
const tok = item?.[field];
|
|
if (tok && "items" in tok) {
|
|
item = tok.items[index];
|
|
} else
|
|
return void 0;
|
|
}
|
|
return item;
|
|
};
|
|
visit2.parentCollection = (cst, path4) => {
|
|
const parent = visit2.itemAtPath(cst, path4.slice(0, -1));
|
|
const field = path4[path4.length - 1][0];
|
|
const coll = parent?.[field];
|
|
if (coll && "items" in coll)
|
|
return coll;
|
|
throw new Error("Parent collection not found");
|
|
};
|
|
function _visit(path4, item, visitor) {
|
|
let ctrl = visitor(item, path4);
|
|
if (typeof ctrl === "symbol")
|
|
return ctrl;
|
|
for (const field of ["key", "value"]) {
|
|
const token = item[field];
|
|
if (token && "items" in token) {
|
|
for (let i = 0; i < token.items.length; ++i) {
|
|
const ci = _visit(Object.freeze(path4.concat([[field, i]])), token.items[i], visitor);
|
|
if (typeof ci === "number")
|
|
i = ci - 1;
|
|
else if (ci === BREAK2)
|
|
return BREAK2;
|
|
else if (ci === REMOVE2) {
|
|
token.items.splice(i, 1);
|
|
i -= 1;
|
|
}
|
|
}
|
|
if (typeof ctrl === "function" && field === "key")
|
|
ctrl = ctrl(item, path4);
|
|
}
|
|
}
|
|
return typeof ctrl === "function" ? ctrl(item, path4) : ctrl;
|
|
}
|
|
|
|
// node_modules/yaml/browser/dist/parse/lexer.js
|
|
var hexDigits = new Set("0123456789ABCDEFabcdef");
|
|
var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
|
|
var flowIndicatorChars = new Set(",[]{}");
|
|
var invalidAnchorChars = new Set(" ,[]{}\n\r ");
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/env.js
|
|
function requireEnv(api) {
|
|
if (api.env === void 0)
|
|
throw new Error("No execution environment is configured");
|
|
return api.env;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/bash.js
|
|
var MAX_TIMEOUT_SECONDS = 2147483647 / 1e3;
|
|
var bashSchema = obj({
|
|
command: str({ description: "Bash command to execute" }),
|
|
timeout: opt(num({ description: "Timeout in seconds (optional, no default timeout)" }))
|
|
}, { open: true });
|
|
var powershellSchema = obj({
|
|
command: str({ description: "PowerShell command to execute" }),
|
|
timeout: opt(num({ description: "Timeout in seconds (optional, no default timeout)" }))
|
|
}, { open: true });
|
|
var shellStructuredOutputSchema = obj({
|
|
output: str({ description: "Combined stdout and stderr: the retained tail, as the model sees it" }),
|
|
truncated: bool({ description: "Whether earlier output was dropped" }),
|
|
fullOutputPath: opt(str({ description: "File with the complete output, when it was spilled" })),
|
|
exitCode: num()
|
|
}, { open: true });
|
|
function validateTimeout(timeout) {
|
|
if (timeout === void 0)
|
|
return;
|
|
if (!Number.isFinite(timeout) || timeout <= 0) {
|
|
throw new Error("Invalid timeout: must be a finite number of seconds");
|
|
}
|
|
if (timeout > MAX_TIMEOUT_SECONDS) {
|
|
throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);
|
|
}
|
|
}
|
|
async function prepareExecution(command, options, api, context) {
|
|
const execution = {
|
|
command: options?.commandPrefix ? `${options.commandPrefix}
|
|
${command}` : command,
|
|
cwd: requireEnv(api).cwd,
|
|
env: {},
|
|
inheritEnv: true
|
|
};
|
|
await options?.prepare?.(execution, api, context);
|
|
return execution;
|
|
}
|
|
async function runCommand(commands, execution, timeout, api, context) {
|
|
const env = requireEnv(api);
|
|
let result;
|
|
for (const command of commands) {
|
|
result = await env.exec(command, {
|
|
cwd: execution.cwd,
|
|
env: execution.env,
|
|
inheritEnv: execution.inheritEnv,
|
|
...timeout === void 0 ? {} : { timeout },
|
|
onOutput: (text, _context, info) => api.output(text, info.skipped),
|
|
spill: { afterBytes: DEFAULT_MAX_BYTES, afterLines: DEFAULT_MAX_LINES },
|
|
// An environment may then omit output outside the retained tail and report the omission.
|
|
...api.outputWindow === void 0 ? {} : { window: api.outputWindow }
|
|
}, context);
|
|
if (result.ok || result.error.code !== "spawn_error")
|
|
break;
|
|
}
|
|
if (result === void 0)
|
|
throw new Error("No command to run");
|
|
const spillPath = result.ok ? result.value.spillPath : result.error.spillPath;
|
|
if (spillPath !== void 0) {
|
|
api.diagnostic({ severity: "info", code: "full_output", message: `Full output: ${spillPath}` });
|
|
}
|
|
if (!result.ok) {
|
|
if (result.error.code === "aborted" && context.abortSignal?.aborted)
|
|
throw result.error;
|
|
if (result.error.code === "timeout")
|
|
throw new Error(`Command timed out after ${timeout} seconds`);
|
|
if (result.error.code === "aborted")
|
|
throw new Error("Command aborted");
|
|
throw result.error;
|
|
}
|
|
const exitCode = result.value.exitCode;
|
|
const retained = api.retainedOutput();
|
|
const structuredOutput = {
|
|
output: retained.text,
|
|
truncated: retained.truncated,
|
|
...spillPath === void 0 ? {} : { fullOutputPath: spillPath },
|
|
exitCode
|
|
};
|
|
if (exitCode === 0)
|
|
return { structuredOutput };
|
|
const exited = { severity: "error", code: "exit_code", message: `Command exited with code ${exitCode}` };
|
|
return { structuredOutput, isError: true, diagnostics: [exited] };
|
|
}
|
|
function createBashTool(options) {
|
|
return defineTool({
|
|
name: "bash",
|
|
description: `Execute a bash command in the current working directory. Returns combined stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
|
|
parameters: bashSchema,
|
|
structuredOutputSchema: shellStructuredOutputSchema,
|
|
outputLimits: { retain: "tail" },
|
|
async execute(args, api, context) {
|
|
validateTimeout(args.timeout);
|
|
const execution = await prepareExecution(args.command, options, api, context);
|
|
return runCommand([execution.command], execution, args.timeout, api, context);
|
|
}
|
|
});
|
|
}
|
|
|
|
// node_modules/diff/libesm/diff/base.js
|
|
var Diff = class {
|
|
diff(oldStr, newStr, options = {}) {
|
|
let callback;
|
|
if (typeof options === "function") {
|
|
callback = options;
|
|
options = {};
|
|
} else if ("callback" in options) {
|
|
callback = options.callback;
|
|
}
|
|
const oldString = this.castInput(oldStr, options);
|
|
const newString = this.castInput(newStr, options);
|
|
const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
|
|
const newTokens = this.removeEmpty(this.tokenize(newString, options));
|
|
return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
|
|
}
|
|
diffWithOptionsObj(oldTokens, newTokens, options, callback) {
|
|
var _a6;
|
|
const done = (value) => {
|
|
value = this.postProcess(value, options);
|
|
if (callback) {
|
|
setTimeout(function() {
|
|
callback(value);
|
|
}, 0);
|
|
return void 0;
|
|
} else {
|
|
return value;
|
|
}
|
|
};
|
|
const newLen = newTokens.length, oldLen = oldTokens.length;
|
|
let editLength = 1;
|
|
let maxEditLength = newLen + oldLen;
|
|
if (options.maxEditLength != null) {
|
|
maxEditLength = Math.min(maxEditLength, options.maxEditLength);
|
|
}
|
|
const maxExecutionTime = (_a6 = options.timeout) !== null && _a6 !== void 0 ? _a6 : Infinity;
|
|
const abortAfterTimestamp = Date.now() + maxExecutionTime;
|
|
const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
|
|
let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
|
|
if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
|
|
return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
|
|
}
|
|
let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
|
|
const execEditLength = () => {
|
|
for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
|
|
let basePath;
|
|
const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
|
|
if (removePath) {
|
|
bestPath[diagonalPath - 1] = void 0;
|
|
}
|
|
let canAdd = false;
|
|
if (addPath) {
|
|
const addPathNewPos = addPath.oldPos - diagonalPath;
|
|
canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
|
|
}
|
|
const canRemove = removePath && removePath.oldPos + 1 < oldLen;
|
|
if (!canAdd && !canRemove) {
|
|
bestPath[diagonalPath] = void 0;
|
|
continue;
|
|
}
|
|
if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
|
|
basePath = this.addToPath(addPath, true, false, 0, options);
|
|
} else {
|
|
basePath = this.addToPath(removePath, false, true, 1, options);
|
|
}
|
|
newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
|
|
if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
|
|
return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
|
|
} else {
|
|
bestPath[diagonalPath] = basePath;
|
|
if (basePath.oldPos + 1 >= oldLen) {
|
|
maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
|
|
}
|
|
if (newPos + 1 >= newLen) {
|
|
minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
|
|
}
|
|
}
|
|
}
|
|
editLength++;
|
|
};
|
|
if (callback) {
|
|
(function exec() {
|
|
setTimeout(function() {
|
|
if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
|
|
return callback(void 0);
|
|
}
|
|
if (!execEditLength()) {
|
|
exec();
|
|
}
|
|
}, 0);
|
|
})();
|
|
} else {
|
|
while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
|
|
const ret = execEditLength();
|
|
if (ret) {
|
|
return ret;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
addToPath(path4, added, removed, oldPosInc, options) {
|
|
const last = path4.lastComponent;
|
|
if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
|
|
return {
|
|
oldPos: path4.oldPos + oldPosInc,
|
|
lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
|
|
};
|
|
} else {
|
|
return {
|
|
oldPos: path4.oldPos + oldPosInc,
|
|
lastComponent: { count: 1, added, removed, previousComponent: last }
|
|
};
|
|
}
|
|
}
|
|
extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
|
|
const newLen = newTokens.length, oldLen = oldTokens.length;
|
|
let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
|
|
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
|
|
newPos++;
|
|
oldPos++;
|
|
commonCount++;
|
|
if (options.oneChangePerToken) {
|
|
basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
|
|
}
|
|
}
|
|
if (commonCount && !options.oneChangePerToken) {
|
|
basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
|
|
}
|
|
basePath.oldPos = oldPos;
|
|
return newPos;
|
|
}
|
|
equals(left, right, options) {
|
|
if (options.comparator) {
|
|
return options.comparator(left, right);
|
|
} else {
|
|
return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
|
|
}
|
|
}
|
|
removeEmpty(array) {
|
|
const ret = [];
|
|
for (let i = 0; i < array.length; i++) {
|
|
if (array[i]) {
|
|
ret.push(array[i]);
|
|
}
|
|
}
|
|
return ret;
|
|
}
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
castInput(value, options) {
|
|
return value;
|
|
}
|
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
tokenize(value, options) {
|
|
return Array.from(value);
|
|
}
|
|
join(chars) {
|
|
return chars.join("");
|
|
}
|
|
postProcess(changeObjects, options) {
|
|
return changeObjects;
|
|
}
|
|
get useLongestToken() {
|
|
return false;
|
|
}
|
|
buildValues(lastComponent, newTokens, oldTokens) {
|
|
const components = [];
|
|
let nextComponent;
|
|
while (lastComponent) {
|
|
components.push(lastComponent);
|
|
nextComponent = lastComponent.previousComponent;
|
|
delete lastComponent.previousComponent;
|
|
lastComponent = nextComponent;
|
|
}
|
|
components.reverse();
|
|
const componentLen = components.length;
|
|
let componentPos = 0, newPos = 0, oldPos = 0;
|
|
for (; componentPos < componentLen; componentPos++) {
|
|
const component = components[componentPos];
|
|
if (!component.removed) {
|
|
if (!component.added && this.useLongestToken) {
|
|
let value = newTokens.slice(newPos, newPos + component.count);
|
|
value = value.map(function(value2, i) {
|
|
const oldValue = oldTokens[oldPos + i];
|
|
return oldValue.length > value2.length ? oldValue : value2;
|
|
});
|
|
component.value = this.join(value);
|
|
} else {
|
|
component.value = this.join(newTokens.slice(newPos, newPos + component.count));
|
|
}
|
|
newPos += component.count;
|
|
if (!component.added) {
|
|
oldPos += component.count;
|
|
}
|
|
} else {
|
|
component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
|
|
oldPos += component.count;
|
|
}
|
|
}
|
|
return components;
|
|
}
|
|
};
|
|
|
|
// node_modules/diff/libesm/diff/line.js
|
|
var LineDiff = class extends Diff {
|
|
constructor() {
|
|
super(...arguments);
|
|
this.tokenize = tokenize2;
|
|
}
|
|
equals(left, right, options) {
|
|
if (options.ignoreWhitespace) {
|
|
if (!options.newlineIsToken || !left.includes("\n")) {
|
|
left = left.trim();
|
|
}
|
|
if (!options.newlineIsToken || !right.includes("\n")) {
|
|
right = right.trim();
|
|
}
|
|
} else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
|
|
if (left.endsWith("\n")) {
|
|
left = left.slice(0, -1);
|
|
}
|
|
if (right.endsWith("\n")) {
|
|
right = right.slice(0, -1);
|
|
}
|
|
}
|
|
return super.equals(left, right, options);
|
|
}
|
|
};
|
|
var lineDiff = new LineDiff();
|
|
function diffLines(oldStr, newStr, options) {
|
|
return lineDiff.diff(oldStr, newStr, options);
|
|
}
|
|
function tokenize2(value, options) {
|
|
if (options.stripTrailingCr) {
|
|
value = value.replace(/\r\n/g, "\n");
|
|
}
|
|
const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
|
|
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
|
|
linesAndNewlines.pop();
|
|
}
|
|
for (let i = 0; i < linesAndNewlines.length; i++) {
|
|
const line = linesAndNewlines[i];
|
|
if (i % 2 && !options.newlineIsToken) {
|
|
retLines[retLines.length - 1] += line;
|
|
} else {
|
|
retLines.push(line);
|
|
}
|
|
}
|
|
return retLines;
|
|
}
|
|
|
|
// node_modules/diff/libesm/patch/create.js
|
|
var INCLUDE_HEADERS = {
|
|
includeIndex: true,
|
|
includeUnderline: true,
|
|
includeFileHeaders: true
|
|
};
|
|
var FILE_HEADERS_ONLY = {
|
|
includeIndex: false,
|
|
includeUnderline: false,
|
|
includeFileHeaders: true
|
|
};
|
|
function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
|
|
let optionsObj;
|
|
if (!options) {
|
|
optionsObj = {};
|
|
} else if (typeof options === "function") {
|
|
optionsObj = { callback: options };
|
|
} else {
|
|
optionsObj = options;
|
|
}
|
|
if (typeof optionsObj.context === "undefined") {
|
|
optionsObj.context = 4;
|
|
}
|
|
const context = optionsObj.context;
|
|
if (optionsObj.newlineIsToken) {
|
|
throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");
|
|
}
|
|
if (!optionsObj.callback) {
|
|
return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj));
|
|
} else {
|
|
const { callback } = optionsObj;
|
|
diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => {
|
|
const patch = diffLinesResultToPatch(diff);
|
|
callback(patch);
|
|
} }));
|
|
}
|
|
function diffLinesResultToPatch(diff) {
|
|
if (!diff) {
|
|
return;
|
|
}
|
|
diff.push({ value: "", lines: [] });
|
|
function contextLines(lines) {
|
|
return lines.map(function(entry) {
|
|
return " " + entry;
|
|
});
|
|
}
|
|
const hunks = [];
|
|
let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1;
|
|
for (let i = 0; i < diff.length; i++) {
|
|
const current = diff[i], lines = current.lines || splitLines(current.value);
|
|
current.lines = lines;
|
|
if (current.added || current.removed) {
|
|
if (!oldRangeStart) {
|
|
const prev = diff[i - 1];
|
|
oldRangeStart = oldLine;
|
|
newRangeStart = newLine;
|
|
if (prev) {
|
|
curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : [];
|
|
oldRangeStart -= curRange.length;
|
|
newRangeStart -= curRange.length;
|
|
}
|
|
}
|
|
for (const line of lines) {
|
|
curRange.push((current.added ? "+" : "-") + line);
|
|
}
|
|
if (current.added) {
|
|
newLine += lines.length;
|
|
} else {
|
|
oldLine += lines.length;
|
|
}
|
|
} else {
|
|
if (oldRangeStart) {
|
|
if (lines.length <= context * 2 && i < diff.length - 2) {
|
|
for (const line of contextLines(lines)) {
|
|
curRange.push(line);
|
|
}
|
|
} else {
|
|
const contextSize = Math.min(lines.length, context);
|
|
for (const line of contextLines(lines.slice(0, contextSize))) {
|
|
curRange.push(line);
|
|
}
|
|
const hunk = {
|
|
oldStart: oldRangeStart,
|
|
oldLines: oldLine - oldRangeStart + contextSize,
|
|
newStart: newRangeStart,
|
|
newLines: newLine - newRangeStart + contextSize,
|
|
lines: curRange
|
|
};
|
|
hunks.push(hunk);
|
|
oldRangeStart = 0;
|
|
newRangeStart = 0;
|
|
curRange = [];
|
|
}
|
|
}
|
|
oldLine += lines.length;
|
|
newLine += lines.length;
|
|
}
|
|
}
|
|
for (const hunk of hunks) {
|
|
for (let i = 0; i < hunk.lines.length; i++) {
|
|
if (hunk.lines[i].endsWith("\n")) {
|
|
hunk.lines[i] = hunk.lines[i].slice(0, -1);
|
|
} else {
|
|
hunk.lines.splice(i + 1, 0, "\\ No newline at end of file");
|
|
i++;
|
|
}
|
|
}
|
|
}
|
|
return {
|
|
oldFileName,
|
|
newFileName,
|
|
oldHeader,
|
|
newHeader,
|
|
hunks
|
|
};
|
|
}
|
|
}
|
|
function formatPatch(patch, headerOptions) {
|
|
if (!headerOptions) {
|
|
headerOptions = INCLUDE_HEADERS;
|
|
}
|
|
if (Array.isArray(patch)) {
|
|
if (patch.length > 1 && !headerOptions.includeFileHeaders) {
|
|
throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");
|
|
}
|
|
return patch.map((p) => formatPatch(p, headerOptions)).join("\n");
|
|
}
|
|
const ret = [];
|
|
if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) {
|
|
ret.push("Index: " + patch.oldFileName);
|
|
}
|
|
if (headerOptions.includeUnderline) {
|
|
ret.push("===================================================================");
|
|
}
|
|
if (headerOptions.includeFileHeaders) {
|
|
ret.push("--- " + patch.oldFileName + (typeof patch.oldHeader === "undefined" ? "" : " " + patch.oldHeader));
|
|
ret.push("+++ " + patch.newFileName + (typeof patch.newHeader === "undefined" ? "" : " " + patch.newHeader));
|
|
}
|
|
for (let i = 0; i < patch.hunks.length; i++) {
|
|
const hunk = patch.hunks[i];
|
|
if (hunk.oldLines === 0) {
|
|
hunk.oldStart -= 1;
|
|
}
|
|
if (hunk.newLines === 0) {
|
|
hunk.newStart -= 1;
|
|
}
|
|
ret.push("@@ -" + hunk.oldStart + "," + hunk.oldLines + " +" + hunk.newStart + "," + hunk.newLines + " @@");
|
|
for (const line of hunk.lines) {
|
|
ret.push(line);
|
|
}
|
|
}
|
|
return ret.join("\n") + "\n";
|
|
}
|
|
function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
|
|
if (typeof options === "function") {
|
|
options = { callback: options };
|
|
}
|
|
if (!(options === null || options === void 0 ? void 0 : options.callback)) {
|
|
const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
|
|
if (!patchObj) {
|
|
return;
|
|
}
|
|
return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions);
|
|
} else {
|
|
const { callback } = options;
|
|
structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: (patchObj) => {
|
|
if (!patchObj) {
|
|
callback(void 0);
|
|
} else {
|
|
callback(formatPatch(patchObj, options.headerOptions));
|
|
}
|
|
} }));
|
|
}
|
|
}
|
|
function splitLines(text) {
|
|
const hasTrailingNl = text.endsWith("\n");
|
|
const result = text.split("\n").map((line) => line + "\n");
|
|
if (hasTrailingNl) {
|
|
result.pop();
|
|
} else {
|
|
result.push(result.pop().slice(0, -1));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/edit-diff.js
|
|
function detectLineEnding(content) {
|
|
const crlfIdx = content.indexOf("\r\n");
|
|
const lfIdx = content.indexOf("\n");
|
|
if (lfIdx === -1)
|
|
return "\n";
|
|
if (crlfIdx === -1)
|
|
return "\n";
|
|
return crlfIdx < lfIdx ? "\r\n" : "\n";
|
|
}
|
|
function normalizeToLF(text) {
|
|
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
}
|
|
function restoreLineEndings(text, ending) {
|
|
return ending === "\r\n" ? text.replace(/\n/g, "\r\n") : text;
|
|
}
|
|
function normalizeForFuzzyMatch(text) {
|
|
return text.normalize("NFKC").split("\n").map((line) => line.trimEnd()).join("\n").replace(/[\u2018\u2019\u201A\u201B]/g, "'").replace(/[\u201C\u201D\u201E\u201F]/g, '"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015\u2212]/g, "-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ");
|
|
}
|
|
function splitLinesWithEndings(content) {
|
|
return content.match(/[^\n]*\n|[^\n]+/g) ?? [];
|
|
}
|
|
function getLineSpans(content) {
|
|
let offset = 0;
|
|
return splitLinesWithEndings(content).map((line) => {
|
|
const span = { start: offset, end: offset + line.length };
|
|
offset = span.end;
|
|
return span;
|
|
});
|
|
}
|
|
function getReplacementLineRange(lines, replacement) {
|
|
const replacementStart = replacement.matchIndex;
|
|
const replacementEnd = replacement.matchIndex + replacement.matchLength;
|
|
let startLine = -1;
|
|
for (let i = 0; i < lines.length; i++) {
|
|
const line = lines[i];
|
|
if (replacementStart >= line.start && replacementStart < line.end) {
|
|
startLine = i;
|
|
break;
|
|
}
|
|
}
|
|
if (startLine === -1) {
|
|
throw new Error("Replacement range is outside the base content.");
|
|
}
|
|
let endLine = startLine;
|
|
while (endLine < lines.length && lines[endLine].end < replacementEnd) {
|
|
endLine++;
|
|
}
|
|
if (endLine >= lines.length) {
|
|
throw new Error("Replacement range is outside the base content.");
|
|
}
|
|
return { startLine, endLine: endLine + 1 };
|
|
}
|
|
function applyReplacements(content, replacements, offset = 0) {
|
|
let result = content;
|
|
for (let i = replacements.length - 1; i >= 0; i--) {
|
|
const replacement = replacements[i];
|
|
const matchIndex = replacement.matchIndex - offset;
|
|
result = result.substring(0, matchIndex) + replacement.newText + result.substring(matchIndex + replacement.matchLength);
|
|
}
|
|
return result;
|
|
}
|
|
function applyReplacementsPreservingUnchangedLines(originalContent, baseContent, replacements) {
|
|
const originalLines = splitLinesWithEndings(originalContent);
|
|
const baseLines = getLineSpans(baseContent);
|
|
if (originalLines.length !== baseLines.length) {
|
|
throw new Error("Cannot preserve unchanged lines because the base content has a different line count.");
|
|
}
|
|
const groups = [];
|
|
const sortedReplacements = [...replacements].sort((a, b) => a.matchIndex - b.matchIndex);
|
|
for (const replacement of sortedReplacements) {
|
|
const range = getReplacementLineRange(baseLines, replacement);
|
|
const current = groups[groups.length - 1];
|
|
if (current && range.startLine < current.endLine) {
|
|
current.endLine = Math.max(current.endLine, range.endLine);
|
|
current.replacements.push(replacement);
|
|
continue;
|
|
}
|
|
groups.push({ ...range, replacements: [replacement] });
|
|
}
|
|
let originalLineIndex = 0;
|
|
let result = "";
|
|
for (const group of groups) {
|
|
result += originalLines.slice(originalLineIndex, group.startLine).join("");
|
|
const groupStartOffset = baseLines[group.startLine].start;
|
|
const groupEndOffset = baseLines[group.endLine - 1].end;
|
|
result += applyReplacements(baseContent.slice(groupStartOffset, groupEndOffset), group.replacements, groupStartOffset);
|
|
originalLineIndex = group.endLine;
|
|
}
|
|
result += originalLines.slice(originalLineIndex).join("");
|
|
return result;
|
|
}
|
|
function fuzzyFindText(content, oldText) {
|
|
const exactIndex = content.indexOf(oldText);
|
|
if (exactIndex !== -1) {
|
|
return {
|
|
found: true,
|
|
index: exactIndex,
|
|
matchLength: oldText.length,
|
|
usedFuzzyMatch: false,
|
|
contentForReplacement: content
|
|
};
|
|
}
|
|
const fuzzyContent = normalizeForFuzzyMatch(content);
|
|
const fuzzyOldText = normalizeForFuzzyMatch(oldText);
|
|
const fuzzyIndex = fuzzyContent.indexOf(fuzzyOldText);
|
|
if (fuzzyIndex === -1) {
|
|
return {
|
|
found: false,
|
|
index: -1,
|
|
matchLength: 0,
|
|
usedFuzzyMatch: false,
|
|
contentForReplacement: content
|
|
};
|
|
}
|
|
return {
|
|
found: true,
|
|
index: fuzzyIndex,
|
|
matchLength: fuzzyOldText.length,
|
|
usedFuzzyMatch: true,
|
|
contentForReplacement: fuzzyContent
|
|
};
|
|
}
|
|
function stripBom(content) {
|
|
return content.startsWith("\uFEFF") ? { bom: "\uFEFF", text: content.slice(1) } : { bom: "", text: content };
|
|
}
|
|
function countOccurrences(content, oldText) {
|
|
const fuzzyContent = normalizeForFuzzyMatch(content);
|
|
const fuzzyOldText = normalizeForFuzzyMatch(oldText);
|
|
return fuzzyContent.split(fuzzyOldText).length - 1;
|
|
}
|
|
function getNotFoundError(path4, editIndex, totalEdits) {
|
|
if (totalEdits === 1) {
|
|
return new Error(`Could not find the exact text in ${path4}. The old text must match exactly including all whitespace and newlines.`);
|
|
}
|
|
return new Error(`Could not find edits[${editIndex}] in ${path4}. The oldText must match exactly including all whitespace and newlines.`);
|
|
}
|
|
function getDuplicateError(path4, editIndex, totalEdits, occurrences) {
|
|
if (totalEdits === 1) {
|
|
return new Error(`Found ${occurrences} occurrences of the text in ${path4}. The text must be unique. Please provide more context to make it unique.`);
|
|
}
|
|
return new Error(`Found ${occurrences} occurrences of edits[${editIndex}] in ${path4}. Each oldText must be unique. Please provide more context to make it unique.`);
|
|
}
|
|
function getEmptyOldTextError(path4, editIndex, totalEdits) {
|
|
if (totalEdits === 1) {
|
|
return new Error(`oldText must not be empty in ${path4}.`);
|
|
}
|
|
return new Error(`edits[${editIndex}].oldText must not be empty in ${path4}.`);
|
|
}
|
|
function getNoChangeError(path4, totalEdits) {
|
|
if (totalEdits === 1) {
|
|
return new Error(`No changes made to ${path4}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`);
|
|
}
|
|
return new Error(`No changes made to ${path4}. The replacements produced identical content.`);
|
|
}
|
|
function applyEditsToNormalizedContent(normalizedContent, edits, path4) {
|
|
const normalizedEdits = edits.map((edit) => ({
|
|
oldText: normalizeToLF(edit.oldText),
|
|
newText: normalizeToLF(edit.newText)
|
|
}));
|
|
for (let i = 0; i < normalizedEdits.length; i++) {
|
|
if (normalizedEdits[i].oldText.length === 0) {
|
|
throw getEmptyOldTextError(path4, i, normalizedEdits.length);
|
|
}
|
|
}
|
|
const initialMatches = normalizedEdits.map((edit) => fuzzyFindText(normalizedContent, edit.oldText));
|
|
const usedFuzzyMatch = initialMatches.some((match) => match.usedFuzzyMatch);
|
|
const replacementBaseContent = usedFuzzyMatch ? normalizeForFuzzyMatch(normalizedContent) : normalizedContent;
|
|
const matchedEdits = [];
|
|
for (let i = 0; i < normalizedEdits.length; i++) {
|
|
const edit = normalizedEdits[i];
|
|
const matchResult = fuzzyFindText(replacementBaseContent, edit.oldText);
|
|
if (!matchResult.found) {
|
|
throw getNotFoundError(path4, i, normalizedEdits.length);
|
|
}
|
|
const occurrences = countOccurrences(replacementBaseContent, edit.oldText);
|
|
if (occurrences > 1) {
|
|
throw getDuplicateError(path4, i, normalizedEdits.length, occurrences);
|
|
}
|
|
matchedEdits.push({
|
|
editIndex: i,
|
|
matchIndex: matchResult.index,
|
|
matchLength: matchResult.matchLength,
|
|
newText: edit.newText
|
|
});
|
|
}
|
|
matchedEdits.sort((a, b) => a.matchIndex - b.matchIndex);
|
|
for (let i = 1; i < matchedEdits.length; i++) {
|
|
const previous = matchedEdits[i - 1];
|
|
const current = matchedEdits[i];
|
|
if (previous.matchIndex + previous.matchLength > current.matchIndex) {
|
|
throw new Error(`edits[${previous.editIndex}] and edits[${current.editIndex}] overlap in ${path4}. Merge them into one edit or target disjoint regions.`);
|
|
}
|
|
}
|
|
const baseContent = normalizedContent;
|
|
const newContent = usedFuzzyMatch ? applyReplacementsPreservingUnchangedLines(normalizedContent, replacementBaseContent, matchedEdits) : applyReplacements(replacementBaseContent, matchedEdits);
|
|
if (baseContent === newContent) {
|
|
throw getNoChangeError(path4, normalizedEdits.length);
|
|
}
|
|
return { baseContent, newContent };
|
|
}
|
|
function generateUnifiedPatch(path4, oldContent, newContent, contextLines = 4) {
|
|
return createTwoFilesPatch(path4, path4, oldContent, newContent, void 0, void 0, {
|
|
context: contextLines,
|
|
headerOptions: FILE_HEADERS_ONLY
|
|
});
|
|
}
|
|
function generateDiffString(oldContent, newContent, contextLines = 4) {
|
|
const parts = diffLines(oldContent, newContent);
|
|
const output = [];
|
|
const oldLines = oldContent.split("\n");
|
|
const newLines = newContent.split("\n");
|
|
const maxLineNum = Math.max(oldLines.length, newLines.length);
|
|
const lineNumWidth = String(maxLineNum).length;
|
|
let oldLineNum = 1;
|
|
let newLineNum = 1;
|
|
let lastWasChange = false;
|
|
let firstChangedLine;
|
|
for (let i = 0; i < parts.length; i++) {
|
|
const part = parts[i];
|
|
const raw = part.value.split("\n");
|
|
if (raw[raw.length - 1] === "") {
|
|
raw.pop();
|
|
}
|
|
if (part.added || part.removed) {
|
|
if (firstChangedLine === void 0) {
|
|
firstChangedLine = newLineNum;
|
|
}
|
|
for (const line of raw) {
|
|
if (part.added) {
|
|
const lineNum = String(newLineNum).padStart(lineNumWidth, " ");
|
|
output.push(`+${lineNum} ${line}`);
|
|
newLineNum++;
|
|
} else {
|
|
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
output.push(`-${lineNum} ${line}`);
|
|
oldLineNum++;
|
|
}
|
|
}
|
|
lastWasChange = true;
|
|
} else {
|
|
const nextPartIsChange = i < parts.length - 1 && (parts[i + 1].added || parts[i + 1].removed);
|
|
const hasLeadingChange = lastWasChange;
|
|
const hasTrailingChange = nextPartIsChange;
|
|
if (hasLeadingChange && hasTrailingChange) {
|
|
if (raw.length <= contextLines * 2) {
|
|
for (const line of raw) {
|
|
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
output.push(` ${lineNum} ${line}`);
|
|
oldLineNum++;
|
|
newLineNum++;
|
|
}
|
|
} else {
|
|
const leadingLines = raw.slice(0, contextLines);
|
|
const trailingLines = raw.slice(raw.length - contextLines);
|
|
const skippedLines = raw.length - leadingLines.length - trailingLines.length;
|
|
for (const line of leadingLines) {
|
|
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
output.push(` ${lineNum} ${line}`);
|
|
oldLineNum++;
|
|
newLineNum++;
|
|
}
|
|
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
oldLineNum += skippedLines;
|
|
newLineNum += skippedLines;
|
|
for (const line of trailingLines) {
|
|
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
output.push(` ${lineNum} ${line}`);
|
|
oldLineNum++;
|
|
newLineNum++;
|
|
}
|
|
}
|
|
} else if (hasLeadingChange) {
|
|
const shownLines = raw.slice(0, contextLines);
|
|
const skippedLines = raw.length - shownLines.length;
|
|
for (const line of shownLines) {
|
|
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
output.push(` ${lineNum} ${line}`);
|
|
oldLineNum++;
|
|
newLineNum++;
|
|
}
|
|
if (skippedLines > 0) {
|
|
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
oldLineNum += skippedLines;
|
|
newLineNum += skippedLines;
|
|
}
|
|
} else if (hasTrailingChange) {
|
|
const skippedLines = Math.max(0, raw.length - contextLines);
|
|
if (skippedLines > 0) {
|
|
output.push(` ${"".padStart(lineNumWidth, " ")} ...`);
|
|
oldLineNum += skippedLines;
|
|
newLineNum += skippedLines;
|
|
}
|
|
for (const line of raw.slice(skippedLines)) {
|
|
const lineNum = String(oldLineNum).padStart(lineNumWidth, " ");
|
|
output.push(` ${lineNum} ${line}`);
|
|
oldLineNum++;
|
|
newLineNum++;
|
|
}
|
|
} else {
|
|
oldLineNum += raw.length;
|
|
newLineNum += raw.length;
|
|
}
|
|
lastWasChange = false;
|
|
}
|
|
}
|
|
return { diff: output.join("\n"), firstChangedLine };
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/env/decode.js
|
|
function rangeDecoder() {
|
|
return new TextDecoder("utf-8", { ignoreBOM: true });
|
|
}
|
|
function startsWithBom(firstBytes) {
|
|
return firstBytes[0] === 239 && firstBytes[1] === 187 && firstBytes[2] === 191;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/env/index.js
|
|
function getOrThrow(result) {
|
|
if (!result.ok)
|
|
throw result.error;
|
|
return result.value;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/file-mutation-queue.js
|
|
var queues = /* @__PURE__ */ new Map();
|
|
async function mutationKey(env, path4, context) {
|
|
const absolutePath = getOrThrow(await env.absolutePath(path4, context));
|
|
return `${env.id}\0${await canonical(env, absolutePath, context)}`;
|
|
}
|
|
async function canonical(env, absolutePath, context) {
|
|
const result = await env.canonicalPath(absolutePath, context);
|
|
if (result.ok)
|
|
return result.value;
|
|
if (result.error.code === "not_supported")
|
|
return absolutePath;
|
|
if (result.error.code !== "not_found")
|
|
throw result.error;
|
|
const parent = getOrThrow(await env.joinPath([absolutePath, ".."], context));
|
|
if (parent === absolutePath || !absolutePath.startsWith(parent))
|
|
return absolutePath;
|
|
const name = absolutePath.slice(parent.length + (/[/\\]$/.test(parent) ? 0 : 1));
|
|
return getOrThrow(await env.joinPath([await canonical(env, parent, context), name], context));
|
|
}
|
|
async function withFileMutationQueue(env, path4, fn, context) {
|
|
const key = await mutationKey(env, path4, context);
|
|
const previous = queues.get(key) ?? Promise.resolve();
|
|
let release = () => {
|
|
};
|
|
const done = new Promise((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const tail = previous.then(() => done);
|
|
queues.set(key, tail);
|
|
await previous;
|
|
try {
|
|
return await fn();
|
|
} finally {
|
|
release();
|
|
if (queues.get(key) === tail)
|
|
queues.delete(key);
|
|
}
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/path-utils.js
|
|
var UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
|
|
var NARROW_NO_BREAK_SPACE = "\u202F";
|
|
function normalizeToolPath(path4) {
|
|
const normalized = path4.replace(UNICODE_SPACES, " ");
|
|
return normalized.startsWith("@") ? normalized.slice(1) : normalized;
|
|
}
|
|
async function resolveToolPath(env, path4, context) {
|
|
return getOrThrow(await env.absolutePath(normalizeToolPath(path4), context));
|
|
}
|
|
async function resolveReadToolPath(env, path4, context) {
|
|
const resolved = await resolveToolPath(env, path4, context);
|
|
const variants = [
|
|
resolved,
|
|
resolved.replace(/ (AM|PM)\./gi, `${NARROW_NO_BREAK_SPACE}$1.`),
|
|
resolved.normalize("NFD"),
|
|
resolved.replace(/'/g, "\u2019"),
|
|
resolved.normalize("NFD").replace(/'/g, "\u2019")
|
|
];
|
|
for (const variant of new Set(variants)) {
|
|
if (getOrThrow(await env.exists(variant, context)))
|
|
return variant;
|
|
}
|
|
return resolved;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/edit.js
|
|
var replaceEditSchema = obj({
|
|
oldText: str({
|
|
description: "Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call."
|
|
}),
|
|
newText: str({ description: "Replacement text for this targeted edit." })
|
|
}, { open: true });
|
|
var editSchema = obj({
|
|
path: str({ description: "Path to the file to edit (relative or absolute)" }),
|
|
edits: arr(replaceEditSchema, {
|
|
description: "One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead."
|
|
})
|
|
}, { open: true });
|
|
function isSingleEditInput(value) {
|
|
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
return false;
|
|
const edit = value;
|
|
return typeof edit.oldText === "string" && typeof edit.newText === "string";
|
|
}
|
|
function prepareEditArguments(input) {
|
|
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
return input;
|
|
const args = { ...input };
|
|
if (typeof args.edits === "string") {
|
|
try {
|
|
const parsed = JSON.parse(args.edits);
|
|
if (Array.isArray(parsed)) {
|
|
args.edits = parsed;
|
|
} else if (isSingleEditInput(parsed)) {
|
|
args.edits = [parsed];
|
|
}
|
|
} catch {
|
|
}
|
|
} else if (isSingleEditInput(args.edits)) {
|
|
args.edits = [args.edits];
|
|
}
|
|
const legacy = args;
|
|
if (typeof legacy.oldText !== "string" || typeof legacy.newText !== "string")
|
|
return legacy;
|
|
const edits = Array.isArray(legacy.edits) ? [...legacy.edits] : [];
|
|
edits.push({ oldText: legacy.oldText, newText: legacy.newText });
|
|
const { oldText: _oldText, newText: _newText, ...rest } = legacy;
|
|
return { ...rest, edits };
|
|
}
|
|
function validateEditInput(input) {
|
|
if (!Array.isArray(input.edits) || input.edits.length === 0) {
|
|
throw new Error("Edit tool input is invalid. edits must contain at least one replacement.");
|
|
}
|
|
return { path: input.path, edits: input.edits };
|
|
}
|
|
function editAccessError(path4, error) {
|
|
return new Error(`Could not edit file: ${path4}. Error code: ${error.code}.`, { cause: error });
|
|
}
|
|
function createEditTool() {
|
|
return defineTool({
|
|
name: "edit",
|
|
description: "Edit a single file using exact text replacement. Every edits[].oldText must match a unique, non-overlapping region of the original file. If two changes affect the same block or nearby lines, merge them into one edit instead of emitting overlapping edits. Do not include large unchanged regions just to connect distant changes.",
|
|
parameters: editSchema,
|
|
prepareArguments: prepareEditArguments,
|
|
async execute(args, api, context) {
|
|
const { path: path4, edits } = validateEditInput(args);
|
|
const env = requireEnv(api);
|
|
const absolutePath = await resolveToolPath(env, path4, context);
|
|
return withFileMutationQueue(env, absolutePath, async () => {
|
|
if (context.abortSignal?.aborted)
|
|
throw new Error("Operation aborted");
|
|
const info = await env.fileInfo(absolutePath, context);
|
|
if (!info.ok)
|
|
throw editAccessError(path4, info.error);
|
|
if (info.value.kind !== "file" && info.value.kind !== "symlink") {
|
|
throw new Error(`Could not edit file: ${path4}. Path is not a file.`);
|
|
}
|
|
const readResult = await env.readTextFile(absolutePath, context);
|
|
if (!readResult.ok)
|
|
throw editAccessError(path4, readResult.error);
|
|
if (context.abortSignal?.aborted)
|
|
throw new Error("Operation aborted");
|
|
const { bom, text: content } = stripBom(readResult.value);
|
|
const originalEnding = detectLineEnding(content);
|
|
const normalizedContent = normalizeToLF(content);
|
|
const { baseContent, newContent } = applyEditsToNormalizedContent(normalizedContent, edits, path4);
|
|
if (context.abortSignal?.aborted)
|
|
throw new Error("Operation aborted");
|
|
const finalContent = bom + restoreLineEndings(newContent, originalEnding);
|
|
const writeResult = await env.writeFile(absolutePath, finalContent, context);
|
|
if (!writeResult.ok)
|
|
throw editAccessError(path4, writeResult.error);
|
|
if (context.abortSignal?.aborted)
|
|
throw new Error("Operation aborted");
|
|
const diffResult = generateDiffString(baseContent, newContent);
|
|
const details = {
|
|
diff: diffResult.diff,
|
|
patch: generateUnifiedPatch(path4, baseContent, newContent),
|
|
...diffResult.firstChangedLine === void 0 ? {} : { firstChangedLine: diffResult.firstChangedLine }
|
|
};
|
|
return {
|
|
output: [{ type: "text", text: `Successfully replaced ${edits.length} block(s) in ${path4}.` }],
|
|
details
|
|
};
|
|
}, context);
|
|
}
|
|
});
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/image.js
|
|
var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
var HEADER_BYTES = 32;
|
|
var BLOCK_BYTES = 64 * 1024;
|
|
async function detectSupportedImageMimeTypeOf(source) {
|
|
const header = await source.read(0, HEADER_BYTES);
|
|
if (!startsWith(header, PNG_SIGNATURE))
|
|
return detectSupportedImageMimeType(header);
|
|
return isPng(header) && !await isAnimatedPngOf(source) ? "image/png" : void 0;
|
|
}
|
|
async function isAnimatedPngOf(source) {
|
|
let block = new Uint8Array(0);
|
|
let blockStart = 0;
|
|
const bytesAt = async (offset2, length) => {
|
|
if (offset2 < blockStart || offset2 + length > blockStart + block.length) {
|
|
blockStart = offset2;
|
|
block = await source.read(offset2, BLOCK_BYTES);
|
|
}
|
|
return block.subarray(offset2 - blockStart, offset2 - blockStart + length);
|
|
};
|
|
let offset = PNG_SIGNATURE.length;
|
|
while (offset + 8 <= source.size) {
|
|
const chunkHeader = await bytesAt(offset, 8);
|
|
const chunkLength = readUint32BE(chunkHeader, 0);
|
|
if (startsWithAscii(chunkHeader, 4, "acTL"))
|
|
return true;
|
|
if (startsWithAscii(chunkHeader, 4, "IDAT"))
|
|
return false;
|
|
const nextOffset = offset + 8 + chunkLength + 4;
|
|
if (nextOffset <= offset || nextOffset > source.size)
|
|
return false;
|
|
offset = nextOffset;
|
|
}
|
|
return false;
|
|
}
|
|
function detectSupportedImageMimeType(buffer) {
|
|
if (startsWith(buffer, [255, 216, 255]))
|
|
return buffer[3] === 247 ? void 0 : "image/jpeg";
|
|
if (startsWith(buffer, PNG_SIGNATURE))
|
|
return isPng(buffer) && !isAnimatedPng(buffer) ? "image/png" : void 0;
|
|
if (startsWithAscii(buffer, 0, "GIF87a") || startsWithAscii(buffer, 0, "GIF89a"))
|
|
return "image/gif";
|
|
if (startsWithAscii(buffer, 0, "RIFF") && startsWithAscii(buffer, 8, "WEBP"))
|
|
return "image/webp";
|
|
if (startsWithAscii(buffer, 0, "BM") && isBmp(buffer))
|
|
return "image/bmp";
|
|
return void 0;
|
|
}
|
|
function isPng(buffer) {
|
|
return buffer.length >= 16 && readUint32BE(buffer, PNG_SIGNATURE.length) === 13 && startsWithAscii(buffer, 12, "IHDR");
|
|
}
|
|
function isAnimatedPng(buffer) {
|
|
let offset = PNG_SIGNATURE.length;
|
|
while (offset + 8 <= buffer.length) {
|
|
const chunkLength = readUint32BE(buffer, offset);
|
|
const chunkTypeOffset = offset + 4;
|
|
if (startsWithAscii(buffer, chunkTypeOffset, "acTL"))
|
|
return true;
|
|
if (startsWithAscii(buffer, chunkTypeOffset, "IDAT"))
|
|
return false;
|
|
const nextOffset = offset + 8 + chunkLength + 4;
|
|
if (nextOffset <= offset || nextOffset > buffer.length)
|
|
return false;
|
|
offset = nextOffset;
|
|
}
|
|
return false;
|
|
}
|
|
function imageDimensions(bytes2, mimeType) {
|
|
switch (mimeType) {
|
|
case "image/png":
|
|
return bytes2.length < 24 ? void 0 : { width: readUint32BE(bytes2, 16), height: readUint32BE(bytes2, 20) };
|
|
case "image/gif":
|
|
return bytes2.length < 10 ? void 0 : { width: readUint16LE(bytes2, 6), height: readUint16LE(bytes2, 8) };
|
|
case "image/webp":
|
|
if (bytes2.length < 30)
|
|
return void 0;
|
|
if (startsWithAscii(bytes2, 12, "VP8 "))
|
|
return { width: readUint16LE(bytes2, 26) & 16383, height: readUint16LE(bytes2, 28) & 16383 };
|
|
if (startsWithAscii(bytes2, 12, "VP8L")) {
|
|
const bits = readUint32LE(bytes2, 21);
|
|
return { width: (bits & 16383) + 1, height: (bits >>> 14 & 16383) + 1 };
|
|
}
|
|
if (startsWithAscii(bytes2, 12, "VP8X")) {
|
|
const uint24 = (offset) => readUint16LE(bytes2, offset) + ((bytes2[offset + 2] ?? 0) << 16);
|
|
return { width: uint24(24) + 1, height: uint24(27) + 1 };
|
|
}
|
|
return void 0;
|
|
case "image/jpeg":
|
|
for (let offset = 2; offset + 9 <= bytes2.length; ) {
|
|
if (bytes2[offset] !== 255)
|
|
return void 0;
|
|
const marker = bytes2[offset + 1];
|
|
if (marker === 255) {
|
|
offset++;
|
|
continue;
|
|
}
|
|
if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
|
|
return { width: readUint16BE(bytes2, offset + 7), height: readUint16BE(bytes2, offset + 5) };
|
|
}
|
|
offset += 2 + readUint16BE(bytes2, offset + 2);
|
|
}
|
|
return void 0;
|
|
default:
|
|
return void 0;
|
|
}
|
|
}
|
|
function isBmp(buffer) {
|
|
if (buffer.length < 26)
|
|
return false;
|
|
const declaredFileSize = readUint32LE(buffer, 2);
|
|
const pixelDataOffset = readUint32LE(buffer, 10);
|
|
const dibHeaderSize = readUint32LE(buffer, 14);
|
|
if (declaredFileSize !== 0 && declaredFileSize < 26)
|
|
return false;
|
|
if (pixelDataOffset < 14 + dibHeaderSize)
|
|
return false;
|
|
if (declaredFileSize !== 0 && pixelDataOffset >= declaredFileSize)
|
|
return false;
|
|
let colorPlanes;
|
|
let bitsPerPixel;
|
|
if (dibHeaderSize === 12) {
|
|
colorPlanes = readUint16LE(buffer, 22);
|
|
bitsPerPixel = readUint16LE(buffer, 24);
|
|
} else if (dibHeaderSize >= 40 && dibHeaderSize <= 124) {
|
|
if (buffer.length < 30)
|
|
return false;
|
|
colorPlanes = readUint16LE(buffer, 26);
|
|
bitsPerPixel = readUint16LE(buffer, 28);
|
|
} else {
|
|
return false;
|
|
}
|
|
return colorPlanes === 1 && [1, 4, 8, 16, 24, 32].includes(bitsPerPixel);
|
|
}
|
|
function readUint16LE(buffer, offset) {
|
|
return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8);
|
|
}
|
|
function readUint16BE(buffer, offset) {
|
|
return ((buffer[offset] ?? 0) << 8) + (buffer[offset + 1] ?? 0);
|
|
}
|
|
function readUint32BE(buffer, offset) {
|
|
return (buffer[offset] ?? 0) * 16777216 + ((buffer[offset + 1] ?? 0) << 16) + ((buffer[offset + 2] ?? 0) << 8) + (buffer[offset + 3] ?? 0);
|
|
}
|
|
function readUint32LE(buffer, offset) {
|
|
return (buffer[offset] ?? 0) + ((buffer[offset + 1] ?? 0) << 8) + ((buffer[offset + 2] ?? 0) << 16) + (buffer[offset + 3] ?? 0) * 16777216;
|
|
}
|
|
function startsWith(buffer, bytes2) {
|
|
if (buffer.length < bytes2.length)
|
|
return false;
|
|
return bytes2.every((byte, index) => buffer[index] === byte);
|
|
}
|
|
function startsWithAscii(buffer, offset, text) {
|
|
if (buffer.length < offset + text.length)
|
|
return false;
|
|
for (let index = 0; index < text.length; index++) {
|
|
if (buffer[offset + index] !== text.charCodeAt(index))
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/image-processor.js
|
|
var DEFAULT_IMAGE_LIMITS = { maxWidth: 2e3, maxHeight: 2e3, maxBytes: 4.5 * 1024 * 1024 };
|
|
var INLINE_IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
function toBase64(bytes2) {
|
|
const parts = [];
|
|
for (let i = 0; i < bytes2.length; i += 8192) {
|
|
parts.push(String.fromCharCode.apply(null, bytes2.subarray(i, i + 8192)));
|
|
}
|
|
return btoa(parts.join(""));
|
|
}
|
|
function base64Length(byteLength) {
|
|
return Math.ceil(byteLength / 3) * 4;
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/read.js
|
|
var readSchema = obj({
|
|
path: str({ description: "Path to the file to read (relative or absolute)" }),
|
|
offset: opt(num({ description: "Line number to start reading from (1-indexed)" })),
|
|
limit: opt(num({ description: "Maximum number of lines to read" }))
|
|
}, { open: true });
|
|
var readStructuredOutputSchema = union([
|
|
str(),
|
|
obj({ type: lit("image"), data: str(), mimeType: str() }, { open: true })
|
|
]);
|
|
var READ_CHUNK = 64 * 1024;
|
|
function sliceIndex(value) {
|
|
return Number.isNaN(value) ? 0 : Math.trunc(value);
|
|
}
|
|
async function readHead(reader, start, end, skipBom, context) {
|
|
const decoder3 = rangeDecoder();
|
|
let text = "";
|
|
let newlines = 0;
|
|
for (let position = skipBom && start === 0 ? 3 : start; position < end; ) {
|
|
const bytes2 = getOrThrow(await reader.read(position, Math.min(READ_CHUNK, end - position), context));
|
|
if (bytes2.length === 0)
|
|
break;
|
|
position += bytes2.length;
|
|
const decoded = decoder3.decode(bytes2, { stream: true });
|
|
text += decoded;
|
|
for (let index = decoded.indexOf("\n"); index !== -1; index = decoded.indexOf("\n", index + 1))
|
|
newlines++;
|
|
if (newlines >= DEFAULT_MAX_LINES || utf8ByteLength(text) > DEFAULT_MAX_BYTES + 1)
|
|
return text;
|
|
}
|
|
return text + decoder3.decode();
|
|
}
|
|
function createReadTool(options = {}) {
|
|
const formats = options.images === void 0 ? "jpg, png, gif, webp" : "jpg, png, gif, webp, bmp";
|
|
return defineTool({
|
|
name: "read",
|
|
description: `Read the contents of a file. Supports text files and images (${formats}). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files. When you need the full file, continue with offset until complete.`,
|
|
parameters: readSchema,
|
|
structuredOutputSchema: readStructuredOutputSchema,
|
|
async execute(args, api, context) {
|
|
const { path: path4, offset, limit: limit3 } = args;
|
|
const env = requireEnv(api);
|
|
const absolutePath = await resolveReadToolPath(env, path4, context);
|
|
const reader = getOrThrow(await env.openBinaryReader(absolutePath, void 0, context));
|
|
try {
|
|
for (let attempt = 0; ; attempt++) {
|
|
const before = getOrThrow(await reader.info(context));
|
|
const mimeType = await detectSupportedImageMimeTypeOf({
|
|
size: before.size,
|
|
read: async (position, length) => getOrThrow(await reader.read(position, length, context))
|
|
});
|
|
const result = mimeType === void 0 ? await readText(reader, path4, offset, limit3, context) : await readImage(reader, before, path4, mimeType, options.images, await imageModel(api, context), context);
|
|
const after = getOrThrow(await reader.info(context));
|
|
const unchanged = after.size === before.size && after.mtimeMs === before.mtimeMs;
|
|
if (unchanged || mimeType === void 0 && after.size > before.size)
|
|
return result;
|
|
if (attempt === 1)
|
|
throw new Error(`${path4} changed while it was read`);
|
|
}
|
|
} finally {
|
|
await reader.close(context);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
async function readImage(reader, info, path4, mimeType, processor, { vision, limits }, context) {
|
|
let image;
|
|
const notes = [];
|
|
if (processor !== void 0) {
|
|
const bytes2 = getOrThrow(await reader.read(0, info.size, context));
|
|
const prepared = await processor.prepare(bytes2, mimeType, limits);
|
|
if (prepared === void 0)
|
|
return imageError(`${path4} is an image (${mimeType}) that cannot be prepared for the model`);
|
|
image = prepared;
|
|
if (prepared.convertedFrom !== void 0)
|
|
notes.push(`Converted from ${prepared.convertedFrom} to ${prepared.mimeType}.`);
|
|
if (prepared.resized !== void 0) {
|
|
const { from, to } = prepared.resized;
|
|
const scale = (from.width / to.width).toFixed(2);
|
|
notes.push(`Resized from ${from.width}x${from.height} to ${to.width}x${to.height}. Multiply coordinates by ${scale} to map them to the original.`);
|
|
}
|
|
} else {
|
|
if (!INLINE_IMAGE_TYPES.has(mimeType)) {
|
|
return imageError(`${path4} is an image (${mimeType}) that needs converting, and no image processor is configured`);
|
|
}
|
|
const unshrinkable = "and no image processor is configured to shrink it";
|
|
if (base64Length(info.size) > limits.maxBytes) {
|
|
return imageError(`${path4} is an image (${mimeType}) of ${formatSize(info.size)}, too large to send, ${unshrinkable}`);
|
|
}
|
|
const bytes2 = getOrThrow(await reader.read(0, info.size, context));
|
|
const size = imageDimensions(bytes2, mimeType);
|
|
if (size === void 0)
|
|
return imageError(`${path4} is an image (${mimeType}) whose size cannot be read`);
|
|
if (size.width > limits.maxWidth || size.height > limits.maxHeight) {
|
|
return imageError(`${path4} is an image (${mimeType}) of ${size.width}x${size.height}, larger than ${limits.maxWidth}x${limits.maxHeight}, ${unshrinkable}`);
|
|
}
|
|
image = { data: toBase64(bytes2), mimeType };
|
|
}
|
|
if (!vision)
|
|
notes.push("The current model does not support images; it sees a placeholder instead.");
|
|
const diagnostics = [
|
|
{ severity: "info", code: "image", message: [`Read image file [${image.mimeType}].`, ...notes].join(" ") }
|
|
];
|
|
const block = { type: "image", data: image.data, mimeType: image.mimeType };
|
|
return { output: [block], structuredOutput: block, diagnostics };
|
|
}
|
|
async function imageModel(api, context) {
|
|
const ref = (await api.agent(context)).model;
|
|
const model2 = ref === void 0 ? void 0 : api.models.getModel(ref.provider, ref.modelId);
|
|
const resize = model2?.inputLimits?.images?.resize;
|
|
return {
|
|
vision: model2?.input.includes("image") ?? true,
|
|
limits: {
|
|
maxWidth: resize?.maxWidth ?? DEFAULT_IMAGE_LIMITS.maxWidth,
|
|
maxHeight: resize?.maxHeight ?? DEFAULT_IMAGE_LIMITS.maxHeight,
|
|
maxBytes: resize?.maxBytes ?? DEFAULT_IMAGE_LIMITS.maxBytes
|
|
}
|
|
};
|
|
}
|
|
function imageError(message) {
|
|
return { output: [], isError: true, diagnostics: [{ severity: "error", code: "unsupported_image", message }] };
|
|
}
|
|
async function readText(reader, path4, offset, limit3, context) {
|
|
const startLine = offset ? Math.max(0, offset - 1) : 0;
|
|
const startLineDisplay = startLine + 1;
|
|
const sliceStart = sliceIndex(startLine);
|
|
const scanStart = Number.isSafeInteger(sliceStart) ? sliceStart : 0;
|
|
const requestedEnd = limit3 === void 0 ? void 0 : Math.max(scanStart + 1, sliceIndex(startLine + limit3));
|
|
const scanEnd = requestedEnd !== void 0 && Number.isSafeInteger(requestedEnd) ? requestedEnd : void 0;
|
|
const scanOf = async (endLine) => getOrThrow(await reader.scanLines({ startLine: scanStart, ...endLine === void 0 ? {} : { endLine } }, context));
|
|
let scan = await scanOf(scanEnd);
|
|
const totalFileLines = scan.newlines + 1;
|
|
if (startLine >= totalFileLines) {
|
|
throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);
|
|
}
|
|
let userLimitedLines;
|
|
let selectedLineCount = totalFileLines - sliceStart;
|
|
if (limit3 !== void 0) {
|
|
const endLine = Math.min(startLine + limit3, totalFileLines);
|
|
userLimitedLines = endLine - startLine;
|
|
const relativeEnd = sliceIndex(endLine);
|
|
const sliceEnd = relativeEnd < 0 ? Math.max(totalFileLines + relativeEnd, 0) : relativeEnd;
|
|
selectedLineCount = Math.max(0, sliceEnd - sliceStart);
|
|
if (selectedLineCount > 0 && relativeEnd < 0)
|
|
scan = await scanOf(sliceEnd);
|
|
}
|
|
const empty2 = selectedLineCount === 0;
|
|
const endsWithNewline = !empty2 && scan.lastLineStart === scan.end && scan.lastLineStart > scan.start;
|
|
const totals = {
|
|
lines: empty2 || scan.selectedBytes === 0 ? 0 : selectedLineCount - (endsWithNewline ? 1 : 0),
|
|
bytes: empty2 ? 0 : scan.selectedBytes
|
|
};
|
|
const firstBytes = getOrThrow(await reader.read(0, 3, context));
|
|
const head = empty2 ? "" : await readHead(reader, scan.start, scan.end, startsWithBom(firstBytes), context);
|
|
const { content: headText, ...truncation } = truncateHeadOf(head, totals);
|
|
const diagnostics = [];
|
|
let outputText = headText;
|
|
let details;
|
|
if (truncation.firstLineExceedsLimit) {
|
|
const integral = Number.isInteger(startLine);
|
|
const lineBytes = new TextEncoder().encode(integral ? head.split("\n")[0] ?? "" : "");
|
|
const lineSize = integral ? scan.firstLineBytes : 0;
|
|
const end = characterEnd(lineBytes, DEFAULT_MAX_BYTES);
|
|
outputText = new TextDecoder().decode(lineBytes.subarray(0, end));
|
|
diagnostics.push({
|
|
severity: "warn",
|
|
code: "truncated",
|
|
message: `Line ${startLineDisplay} is ${formatSize(lineSize)}, exceeds the ${formatSize(DEFAULT_MAX_BYTES)} limit; showing its first ${formatSize(end)}. Use bash: sed -n '${startLineDisplay}p' ${path4} | tail -c +${end + 1}`
|
|
});
|
|
details = { truncation: { ...truncation, outputBytes: end, outputLines: 1 } };
|
|
} else if (truncation.truncated) {
|
|
const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
|
|
const nextOffset = endLineDisplay + 1;
|
|
const limitText = truncation.truncatedBy === "lines" ? "" : ` (${formatSize(DEFAULT_MAX_BYTES)} limit)`;
|
|
diagnostics.push({
|
|
severity: "info",
|
|
code: "truncated",
|
|
message: `Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}${limitText}. Use offset=${nextOffset} to continue.`
|
|
});
|
|
details = { truncation };
|
|
} else if (userLimitedLines !== void 0 && startLine + userLimitedLines < totalFileLines) {
|
|
const remaining = totalFileLines - (startLine + userLimitedLines);
|
|
const nextOffset = startLine + userLimitedLines + 1;
|
|
diagnostics.push({
|
|
severity: "info",
|
|
message: `${remaining} more lines in file. Use offset=${nextOffset} to continue.`
|
|
});
|
|
}
|
|
return {
|
|
output: outputText === "" ? [] : [{ type: "text", text: outputText }],
|
|
structuredOutput: outputText,
|
|
...details === void 0 ? {} : { details },
|
|
diagnostics
|
|
};
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/write.js
|
|
var writeSchema = obj({
|
|
path: str({ description: "Path to the file to write (relative or absolute)" }),
|
|
content: str({ description: "Content to write to the file" })
|
|
}, { open: true });
|
|
function createWriteTool() {
|
|
return defineTool({
|
|
name: "write",
|
|
description: "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories.",
|
|
parameters: writeSchema,
|
|
async execute(args, api, context) {
|
|
const { path: path4, content } = args;
|
|
const env = requireEnv(api);
|
|
const absolutePath = await resolveToolPath(env, path4, context);
|
|
return withFileMutationQueue(env, absolutePath, async () => {
|
|
if (context.abortSignal?.aborted)
|
|
throw new Error("Operation aborted");
|
|
getOrThrow(await env.writeFile(absolutePath, content, context));
|
|
if (context.abortSignal?.aborted)
|
|
throw new Error("Operation aborted");
|
|
return { output: [{ type: "text", text: `Successfully wrote to ${path4}` }] };
|
|
}, context);
|
|
}
|
|
});
|
|
}
|
|
|
|
// node_modules/@earendil-works/pi-durable/dist/tools/index.js
|
|
function createCodingTools(options = {}) {
|
|
return defineExtension({
|
|
name: "coding-tools",
|
|
tools: [createReadTool(options), createWriteTool(), createEditTool(), createBashTool()]
|
|
});
|
|
}
|
|
var CodingTools = createCodingTools();
|
|
|
|
// events.ts
|
|
function defineEvent(name, options = {}) {
|
|
const kind = `event.${name}`;
|
|
return { name, kind, version: options.version ?? 1, is: (event) => event?.kind === kind };
|
|
}
|
|
var NoticeEvent = defineEvent("sausage.notice");
|
|
var EVENT_FEED = "sausage.event-feed";
|
|
var EventLog = defineDoc({
|
|
kind: "sausage.events",
|
|
version: 1,
|
|
scope: "conversation",
|
|
history: "latest",
|
|
fork: "initial",
|
|
checkpointWhen: () => false,
|
|
initial: () => ({ cursors: {} })
|
|
});
|
|
var EventFeed = defineDoc({
|
|
kind: EVENT_FEED,
|
|
version: 1,
|
|
scope: "conversation",
|
|
history: "latest",
|
|
fork: "initial",
|
|
checkpointWhen: () => false,
|
|
initial: () => ({ events: [] })
|
|
});
|
|
|
|
// environment.ts
|
|
var CodingTools2 = { ...CodingTools, tools: CodingTools.tools.map((tool) => ({
|
|
...tool,
|
|
execute: (args, api, context) => tool.execute(args, { ...api, env: api.env.forTool(api.callId, tool.name) }, context)
|
|
})) };
|
|
var Started = defineDoc({
|
|
kind: "board.started",
|
|
version: 1,
|
|
checkpointWhen: () => false,
|
|
scope: "conversation",
|
|
history: "latest",
|
|
fork: "initial",
|
|
initial: () => ({})
|
|
});
|
|
var ops = Deno.core.ops;
|
|
|
|
// extensions.ts
|
|
var ops2 = Deno.core.ops;
|
|
var encoder2 = new TextEncoder();
|
|
var decoder2 = new TextDecoder();
|
|
var ExtensionState = defineDoc({ kind: "sausage.extensions", version: 1, scope: "session", checkpointWhen: () => false, initial: () => ({ good: null, current: null, error: null }) });
|
|
var Metadata = defineDoc({ kind: "sausage.metadata", version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ label: "", title: "" }), checkpointWhen: () => false });
|
|
async function file(kind, path4, bytes2 = []) {
|
|
const result = await ops2.op_file(kind, path4, bytes2);
|
|
if (!result.ok) throw Object.assign(new Error(result.error.message), result.error);
|
|
return result.value;
|
|
}
|
|
var fs2 = {
|
|
read: async (path4) => decoder2.decode(new Uint8Array(await file("read", path4))),
|
|
write: (path4, text) => file("write", path4, Array.from(encoder2.encode(text))),
|
|
append: (path4, text) => file("append", path4, Array.from(encoder2.encode(text))),
|
|
list: (path4) => file("list", path4),
|
|
stat: (path4) => file("stat", path4),
|
|
lstat: (path4) => file("lstat", path4),
|
|
mkdir: (path4) => file("mkdir", path4),
|
|
remove: (path4) => file("remove", path4),
|
|
rename: (from, to) => file("rename", from, Array.from(encoder2.encode(to)))
|
|
};
|
|
|
|
// proxy-models-test.ts
|
|
var readProxy = () => Deno.core.ops.op_model_proxy();
|
|
var models = await proxyModels(await readProxy(), readProxy);
|
|
for (const [provider2, id] of [["openai", "gpt-6.1-sol"], ["anthropic", "claude-opus-5-5"]]) {
|
|
const model2 = models.getModel(provider2, id);
|
|
if (model2.cost.input !== 2 || model2.cost.cacheWrite !== 3) throw new Error("catalog prices lost");
|
|
const result = await models.completeSimple(model2, { messages: [{ role: "user", content: "Say hello.", timestamp: Date.now() }] }, { reasoning: "low", maxTokens: 128 });
|
|
if (result.stopReason === "error" || !result.content.some((block) => block.type === "text" && block.text === "hello")) {
|
|
throw new Error(`${provider2}: ${result.errorMessage ?? JSON.stringify(result.content)}`);
|
|
}
|
|
if (!(result.usage.cost.total > 0)) throw new Error("turn cost missing");
|
|
}
|
|
var fallback = await proxyModels({ ...globalThis.testProxy, base_url: `${globalThis.testProxy.base_url}/offline` });
|
|
for (const [provider2, api] of [["openai", "openai-responses"], ["anthropic", "anthropic-messages"]]) {
|
|
const model2 = fallback.getModels(provider2)[0];
|
|
if (model2.api !== api || model2.cost.input !== 0) throw new Error("offline transport fallback failed");
|
|
}
|
|
await fs2.write("/etc/sausage/config.yaml", JSON.stringify({ proxy: { base_url: `${globalThis.testProxy.base_url}/edited`, api_key: "next-key" } }));
|
|
var auth = await models.getAuth(models.getModel("openai", "gpt-6.1-sol"));
|
|
if (auth.auth.apiKey !== "next-key" || auth.auth.baseUrl !== `${globalThis.testProxy.base_url}/edited/v1`) throw new Error("Proxy edits did not reach the next request");
|
|
await fs2.write("/etc/sausage/config.yaml", JSON.stringify({ proxy: { base_url: "", api_key: "" } }));
|
|
var empty = await proxyModels(await readProxy(), readProxy);
|
|
var failure = "";
|
|
try {
|
|
const result = await empty.completeSimple(empty.getModels("openai")[0], { messages: [{ role: "user", content: "Missing key", timestamp: Date.now() }] });
|
|
failure = result.errorMessage ?? "";
|
|
} catch (error) {
|
|
failure = String(error);
|
|
}
|
|
if (!failure.includes("/etc/sausage/config.yaml")) throw new Error(`Missing proxy settings must name the config file: ${failure}`);
|