UNPKG

simple-ai-provider

Version:

A simple and extensible AI provider package for easy integration of multiple AI services

1,414 lines (1,388 loc) 2.97 MB
var __create = Object.create; var __getProtoOf = Object.getPrototypeOf; var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __hasOwnProp = Object.prototype.hasOwnProperty; var __toESM = (mod, isNodeMode, target) => { target = mod != null ? __create(__getProtoOf(mod)) : {}; const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; for (let key of __getOwnPropNames(mod)) if (!__hasOwnProp.call(to, key)) __defProp(to, key, { get: () => mod[key], enumerable: true }); return to; }; var __moduleCache = /* @__PURE__ */ new WeakMap; var __toCommonJS = (from) => { var entry = __moduleCache.get(from), desc; if (entry) return entry; entry = __defProp({}, "__esModule", { value: true }); if (from && typeof from === "object" || typeof from === "function") __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })); __moduleCache.set(from, entry); return entry; }; var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, set: (newValue) => all[name] = () => newValue }); }; var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); // node_modules/@anthropic-ai/sdk/internal/tslib.mjs function __classPrivateFieldSet(receiver, state, 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 state === "function" ? receiver !== state || !f : !state.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 : state.set(receiver, value), value; } function __classPrivateFieldGet(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.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 : state.get(receiver); } var init_tslib = () => {}; // node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs var uuid4 = function() { const { crypto: crypto2 } = globalThis; if (crypto2?.randomUUID) { uuid4 = crypto2.randomUUID.bind(crypto2); return crypto2.randomUUID(); } const u8 = new Uint8Array(1); const randomByte = crypto2 ? () => crypto2.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/errors.mjs function isAbortError(err) { return typeof err === "object" && err !== null && (("name" in err) && err.name === "AbortError" || ("message" in err) && String(err.message).includes("FetchRequestCanceledException")); } var castToError = (err) => { if (err instanceof Error) return err; if (typeof err === "object" && err !== null) { try { if (Object.prototype.toString.call(err) === "[object Error]") { 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, APIError, APIUserAbortError, APIConnectionError, APIConnectionTimeoutError, BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError; var init_error = __esm(() => { AnthropicError = class AnthropicError extends Error { }; APIError = 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.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 APIConnectionError({ message, cause: castToError(errorResponse) }); } const error = errorResponse; const type = error?.["error"]?.["type"]; if (status === 400) { return new BadRequestError(status, error, message, headers, type); } if (status === 401) { return new AuthenticationError(status, error, message, headers, type); } if (status === 403) { return new PermissionDeniedError(status, error, message, headers, type); } if (status === 404) { return new NotFoundError(status, error, message, headers, type); } if (status === 409) { return new ConflictError(status, error, message, headers, type); } if (status === 422) { return new UnprocessableEntityError(status, error, message, headers, type); } if (status === 429) { return new RateLimitError(status, error, message, headers, type); } if (status >= 500) { return new InternalServerError(status, error, message, headers, type); } return new APIError(status, error, message, headers, type); } }; APIUserAbortError = class APIUserAbortError extends APIError { constructor({ message } = {}) { super(undefined, undefined, message || "Request was aborted.", undefined); } }; APIConnectionError = class APIConnectionError extends APIError { constructor({ message, cause }) { super(undefined, undefined, message || "Connection error.", undefined); if (cause) this.cause = cause; } }; APIConnectionTimeoutError = class APIConnectionTimeoutError extends APIConnectionError { constructor({ message } = {}) { super({ message: message ?? "Request timed out." }); } }; BadRequestError = class BadRequestError extends APIError { }; AuthenticationError = class AuthenticationError extends APIError { }; PermissionDeniedError = class PermissionDeniedError extends APIError { }; NotFoundError = class NotFoundError extends APIError { }; ConflictError = class ConflictError extends APIError { }; UnprocessableEntityError = class UnprocessableEntityError extends APIError { }; RateLimitError = class RateLimitError extends APIError { }; InternalServerError = class InternalServerError extends APIError { }; }); // node_modules/@anthropic-ai/sdk/internal/utils/values.mjs function maybeObj(x) { if (typeof x !== "object") { return {}; } return x ?? {}; } function isEmptyObj(obj) { if (!obj) return true; for (const _k in obj) return false; return true; } function hasOwn(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } var startsWithSchemeRegexp, isAbsoluteURL = (url) => { return startsWithSchemeRegexp.test(url); }, isArray = (val) => (isArray = Array.isArray, isArray(val)), isReadonlyArray, validatePositiveInteger = (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; }, safeJSON = (text) => { try { return JSON.parse(text); } catch (err) { return; } }; var init_values = __esm(() => { init_error(); startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; isReadonlyArray = isArray; }); // node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs var sleep = (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 VERSION = "0.97.1"; // node_modules/@anthropic-ai/sdk/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: /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 isRunningInBrowser = () => { return typeof window !== "undefined" && typeof window.document !== "undefined" && 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 }; } 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"; }, _platformHeaders, getPlatformHeaders = () => { return _platformHeaders ?? (_platformHeaders = getPlatformProperties()); }; var init_detect_platform = () => {}; // node_modules/@anthropic-ai/sdk/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 Anthropic({ 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(stream) { if (stream[Symbol.asyncIterator]) return stream; const reader = stream.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: undefined }; }, [Symbol.asyncIterator]() { return this; } }; } async function CancelReadableStream(stream) { if (stream === null || typeof stream !== "object") return; if (stream[Symbol.asyncIterator]) { await stream[Symbol.asyncIterator]().return?.(); return; } const reader = stream.getReader(); const cancelPromise = reader.cancel(); reader.releaseLock(); await cancelPromise; } // node_modules/@anthropic-ai/sdk/internal/request-options.mjs var FallbackEncoder = ({ headers, body }) => { return { bodyHeaders: { "content-type": "application/json" }, body: JSON.stringify(body) }; }; // node_modules/@anthropic-ai/sdk/internal/qs/formats.mjs var default_format = "RFC3986", default_formatter = (v) => String(v), formatters, RFC1738 = "RFC1738"; var init_formats = __esm(() => { formatters = { RFC1738: (v) => String(v).replace(/%20/g, "+"), RFC3986: default_formatter }; }); // node_modules/@anthropic-ai/sdk/internal/qs/utils.mjs function is_buffer(obj) { if (!obj || typeof obj !== "object") { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); } function maybe_map(val, fn) { if (isArray(val)) { const mapped = []; for (let i = 0;i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); } var has = (obj, key) => (has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty), has(obj, key)), hex_table, limit = 1024, encode = (str, _defaultEncoder, charset, _kind, format) => { if (str.length === 0) { return str; } let string = str; if (typeof str === "symbol") { string = Symbol.prototype.toString.call(str); } else if (typeof str !== "string") { string = String(str); } if (charset === "iso-8859-1") { return escape(string).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 < string.length; j += limit) { const segment = string.length >= limit ? string.slice(j, j + limit) : string; const arr = []; 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 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === RFC1738 && (c === 40 || c === 41)) { arr[arr.length] = segment.charAt(i); continue; } if (c < 128) { arr[arr.length] = hex_table[c]; continue; } if (c < 2048) { arr[arr.length] = hex_table[192 | c >> 6] + hex_table[128 | c & 63]; continue; } if (c < 55296 || c >= 57344) { arr[arr.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); arr[arr.length] = hex_table[240 | c >> 18] + hex_table[128 | c >> 12 & 63] + hex_table[128 | c >> 6 & 63] + hex_table[128 | c & 63]; } out += arr.join(""); } return out; }; var init_utils = __esm(() => { init_formats(); init_values(); hex_table = /* @__PURE__ */ (() => { const array = []; for (let i = 0;i < 256; ++i) { array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase()); } return array; })(); }); // node_modules/@anthropic-ai/sdk/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, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { let obj = object; let tmp_sc = sideChannel; let step = 0; let find_flag = false; while ((tmp_sc = tmp_sc.get(sentinel)) !== undefined && !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(sentinel) === "undefined") { step = 0; } } if (typeof filter === "function") { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate?.(obj); } else if (generateArrayPrefix === "comma" && isArray(obj)) { obj = maybe_map(obj, function(value) { if (value instanceof Date) { return serializeDate?.(value); } return value; }); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, "key", format) : prefix; } obj = ""; } if (is_non_nullish_primitive(obj) || is_buffer(obj)) { if (encoder) { const key_value = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, "key", format); return [ formatter?.(key_value) + "=" + formatter?.(encoder(obj, defaults.encoder, charset, "value", format)) ]; } return [formatter?.(prefix) + "=" + formatter?.(String(obj))]; } const values = []; if (typeof obj === "undefined") { return values; } let obj_keys; if (generateArrayPrefix === "comma" && isArray(obj)) { if (encodeValuesOnly && encoder) { obj = maybe_map(obj, encoder); } obj_keys = [{ value: obj.length > 0 ? obj.join(",") || null : undefined }]; } else if (isArray(filter)) { obj_keys = filter; } else { const keys = Object.keys(obj); obj_keys = sort ? keys.sort(sort) : keys; } const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix); const adjusted_prefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + "[]" : encoded_prefix; if (allowEmptyArrays && isArray(obj) && obj.length === 0) { return adjusted_prefix + "[]"; } for (let j = 0;j < obj_keys.length; ++j) { const key = obj_keys[j]; const value = typeof key === "object" && typeof key.value !== "undefined" ? key.value : obj[key]; if (skipNulls && value === null) { continue; } const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, "%2E") : key; const key_prefix = isArray(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjusted_prefix, encoded_key) : adjusted_prefix : adjusted_prefix + (allowDots ? "." + encoded_key : "[" + encoded_key + "]"); sideChannel.set(object, step); const valueSideChannel = new WeakMap; valueSideChannel.set(sentinel, sideChannel); push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, generateArrayPrefix === "comma" && encodeValuesOnly && isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); } return values; } function normalize_stringify_options(opts = defaults) { 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 || defaults.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_format; if (typeof opts.format !== "undefined") { 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"); } const allowDots = typeof opts.allowDots === "undefined" ? !!opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; return { addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults.addQueryPrefix, 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: typeof opts.delimiter === "undefined" ? 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, sort: typeof opts.sort === "function" ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults.strictNullHandling }; } function stringify(object, opts = {}) { let obj = object; const options = normalize_stringify_options(opts); let obj_keys; let filter; if (typeof options.filter === "function") { filter = options.filter; obj = filter("", obj); } else if (isArray(options.filter)) { filter = options.filter; obj_keys = filter; } const keys = []; if (typeof obj !== "object" || obj === null) { return ""; } const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; const commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip; if (!obj_keys) { obj_keys = Object.keys(obj); } if (options.sort) { obj_keys.sort(options.sort); } const sideChannel = new WeakMap; for (let i = 0;i < obj_keys.length; ++i) { const key = obj_keys[i]; if (options.skipNulls && obj[key] === null) { continue; } push_to_array(keys, inner_stringify(obj[key], key, 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_generators, push_to_array = function(arr, value_or_array) { Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]); }, toISOString, defaults, sentinel; var init_stringify = __esm(() => { 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); } }; 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, indices: false, serializeDate(date) { return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); }, skipNulls: false, strictNullHandling: false }; sentinel = {}; }); // node_modules/@anthropic-ai/sdk/internal/utils/query.mjs function stringifyQuery(query) { return stringify(query, { arrayFormat: "brackets" }); } var init_query = __esm(() => { init_stringify(); }); // 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(path, onWarn = (m) => console.warn(`anthropic-sdk: ${m}`)) { if (typeof process === "undefined" || process.platform === "win32") return; const fs = await import("node:fs"); let resolved = path; let st; try { resolved = await fs.promises.realpath(path); st = await fs.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 = await import("node:fs"); const path = await import("node:path"); const dir = path.dirname(targetPath); await fs.promises.mkdir(dir, { recursive: true, mode: 448 }); const tmpPath = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; try { const fh = await fs.promises.open(tmpPath, "w", 384); try { await fh.writeFile(JSON.stringify(data, null, 2)); await fh.sync(); } finally { await fh.close(); } await fs.promises.rename(tmpPath, targetPath); } catch (err) { await fs.promises.unlink(tmpPath).catch(() => {}); throw err; } try { const dirFh = await fs.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 = "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, MAX_ERROR_BODY_CHARS = 2000, SAFE_ERROR_KEYS, WorkloadIdentityError; var init_types = __esm(() => { init_error(); MAX_TOKEN_RESPONSE_BYTES = 1 << 20; SAFE_ERROR_KEYS = new Set(["error", "error_description", "error_uri"]); WorkloadIdentityError = class WorkloadIdentityError 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() / 1000); } // node_modules/@anthropic-ai/sdk/lib/credentials/token-cache.mjs class TokenCache { constructor(provider, onAdvisoryRefreshError) { this.cached = null; this.pendingRefresh = null; this.nextForce = false; this.lastAdvisoryError = 0; this.provider = provider; 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; } invalidate() { this.cached = null; this.nextForce = true; } refresh(force = false) { if (this.pendingRefresh && !force) { return this.pendingRefresh; } return this.doRefresh(force); } 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); }); } doRefresh(force = false) { this.pendingRefresh = this.provider(force ? { forceRefresh: true } : undefined).then((token) => { this.cached = token; this.pendingRefresh = null; return token; }, (err) => { this.pendingRefresh = null; throw err; }); return this.pendingRefresh; } } var init_token_cache = __esm(() => { init_types(); }); // node_modules/@anthropic-ai/sdk/internal/utils/env.mjs var readEnv = (env) => { if (typeof globalThis.process !== "undefined") { return globalThis.process.env?.[env]?.trim() || undefined; } if (typeof globalThis.Deno !== "undefined") { return globalThis.Deno.env?.get?.(env)?.trim() || undefined; } return; }; // 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 encodeUTF8(str) { let encoder; return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder, encodeUTF8_ = encoder.encode.bind(encoder)))(str); } function decodeUTF8(bytes) { let decoder; return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder, decodeUTF8_ = decoder.decode.bind(decoder)))(bytes); } var encodeUTF8_, decodeUTF8_; // node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs var init_base64 = __esm(() => { init_error(); }); // node_modules/@anthropic-ai/sdk/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; } var levelNumbers, parseLogLevel = (maybeLevel, sourceName, client) => { if (!maybeLevel) { return; } 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; }, noopLogger, cachedLoggers, formatRequestDetails = (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; }; var init_log = __esm(() => { init_values(); levelNumbers = { off: 0, error: 200, warn: 300, info: 400, debug: 500 }; noopLogger = { error: noop, warn: noop, info: noop, debug: noop }; cachedLoggers = /* @__PURE__ */ new WeakMap; }); // node_modules/@anthropic-ai/sdk/internal/utils.mjs var init_utils2 = __esm(() => { init_values(); init_base64(); init_log(); init_query(); }); // 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 = "1.0", PROFILE_NAME_PATTERN, loadConfigWithSource = async (profile) => { var _a, _b; const rootConfigPath = await getRootConfigPath(); if (rootConfigPath === null) { return null; } const profileName = profile ?? await getActiveProfileName(); if (profileName === null) { return null; } validateProfileName(profileName); const fs = await import("node:fs"); const path = await import("node:path"); const configPath = path.join(rootConfigPath, "configs", `${profileName}.json`); let configRaw; try { configRaw = await fs.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 = readEnv("ANTHROPIC_ORGANIZATION_ID"); const identityTokenFile = readEnv("ANTHROPIC_IDENTITY_TOKEN_FILE"); const federationRuleId = readEnv("ANTHROPIC_FEDERATION_RULE_ID"); if (federationRuleId && organizationId) { return { fromFile: false, config: { organization_id: organizationId, workspace_id: readEnv("ANTHROPIC_WORKSPACE_ID"), base_url: readEnv("ANTHROPIC_BASE_URL"), authentication: { type: "oidc_federation", federation_rule_id: federationRuleId, service_account_id: readEnv("ANTHROPIC_SERVICE_ACCOUNT_ID"), identity_token: identityTokenFile ? { source: "file", path: identityTokenFile } : undefined, scope: readEnv("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 = readEnv("ANTHROPIC_ORGANIZATION_ID")); config.workspace_id ?? (config.workspace_id = readEnv("ANTHROPIC_WORKSPACE_ID")); config.base_url ?? (config.base_url = readEnv("ANTHROPIC_BASE_URL")); (_a = config.authentication).scope ?? (_a.scope = readEnv("ANTHROPIC_SCOPE")); if (config.authentication.type === "oidc_federation") { if (!config.authentication.identity_token) { const identityTokenFile = readEnv("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 = readEnv("ANTHROPIC_FEDERATION_RULE_ID") ?? ""; } (_b = config.authentication).service_account_id ?? (_b.service_account_id = readEnv("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 = await import("node:path"); return path.join(rootConfigPath, "credentials", `${profileName}.json`); }, getRootConfigPath = async () => { if (!supportsLocalConfigFiles()) { return null; } const path = await import("node:path"); const configDir = readEnv("ANTHROPIC_CONFIG_DIR"); if (configDir) { return configDir; } const os = getPlatformHeaders()["X-Stainless-OS"]; if (os === "Windows") { const appData = readEnv("APPDATA"); if (appData) { return path.join(appData, "Anthropic"); } const userProfile = readEnv("USERPROFILE"); if (userProfile) { return path.join(userProfile, "AppData", "Roaming", "Anthropic"); } return null; } const xdgConfigHome = readEnv("XDG_CONFIG_HOME"); if (xdgConfigHome) { return path.join(xdgConfigHome, "anthropic"); } const home = readEnv("HOME"); if (home) { return path.join(home, ".config", "anthropic"); } return null; }, supportsLocalConfigFiles = () => { const runtime = getPlatformHeaders()["X-Stainless-Runtime"]; return runtime === "node" || runtime === "deno"; }, getActiveProfileName = async () => { const rootConfigPath = await getRootConfigPath(); if (!rootConfigPath) { return null; } const profileName = readEnv("ANTHROPIC_PROFILE"); if (profileName) { return profileName; } const fs = await import("node:fs"); const path = await import("node:path"); const filePath = path.join(rootConfigPath, "active_config"); try { return (await fs.promises.readFile(filePath, "utf-8")).trim() || "default"; } catch (err) { if (err?.code !== "ENOENT") { throw new Error(`failed to read ${filePath}: ${err}`); } return "default"; } }; var init_credentials = __esm(() => { init_detect_platform(); init_utils2(); PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/; }); // node_modules/@anthropic-ai/sdk/lib/credentials/identity-token.mjs function identityTokenFromFile(path) { if (!path) { throw new AnthropicError("Identity token file path is empty"); } return async () => { const fs = await import("node:fs"); let content; try { content = await fs.promises.readFile(path, "utf-8"); } catch (err) { throw new AnthropicError(`Failed to read identity token file at ${path}: ${err}`); } const token = content.trim(); if (!token) { throw new AnthropicError(`Identity token file at ${path} is empty`); } return token; }; } function identityTokenFromValue(token) { if (!token) { throw new AnthropicError("Identity token value is empty"); } return () => token; } var init_identity_token = __esm(() => { init_error(); }); // 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/${VERSION} 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(() => { init_types(); }); // node_modules/@anthropic-ai/sdk/lib/credentials/user-oauth.mjs function userOAuthProvider(config) { return async (opts) => { const fs = await import("node:fs"); await checkCredentialsFileSafety(config.credentialsPath, config.onSafetyWarning); let raw; try { raw = await fs.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 n