@supersolutions/super-chat-core 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anthropic.js +2 -2
- package/dist/{chunk-32DPF33V.js → chunk-CJ6WV4KB.js} +82 -20
- package/dist/chunk-CJ6WV4KB.js.map +1 -0
- package/dist/{chunk-MHGENDQX.js → chunk-HKGDZQS6.js} +188 -101
- package/dist/chunk-HKGDZQS6.js.map +1 -0
- package/dist/{chunk-JMM3X3GB.js → chunk-ZMPT7BBM.js} +58 -41
- package/dist/chunk-ZMPT7BBM.js.map +1 -0
- package/dist/index.d.ts +72 -12
- package/dist/index.js +485 -201
- package/dist/index.js.map +1 -1
- package/dist/openai.d.ts +0 -5
- package/dist/openai.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-32DPF33V.js.map +0 -1
- package/dist/chunk-JMM3X3GB.js.map +0 -1
- package/dist/chunk-MHGENDQX.js.map +0 -1
package/dist/anthropic.js
CHANGED
|
@@ -7,8 +7,8 @@ import {
|
|
|
7
7
|
streamAnthropic,
|
|
8
8
|
toAnthropicMessages,
|
|
9
9
|
usageFromAnthropic
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import "./chunk-
|
|
10
|
+
} from "./chunk-ZMPT7BBM.js";
|
|
11
|
+
import "./chunk-CJ6WV4KB.js";
|
|
12
12
|
export {
|
|
13
13
|
buildAnthropicRequest,
|
|
14
14
|
createAnthropicProvider,
|
|
@@ -34,9 +34,27 @@ var AgentError = class extends Error {
|
|
|
34
34
|
function isAgentError(e) {
|
|
35
35
|
return e instanceof AgentError;
|
|
36
36
|
}
|
|
37
|
+
function kindFromCode(code) {
|
|
38
|
+
if (/context.?length/i.test(code)) return "context-length";
|
|
39
|
+
if (/rate.?limit|too.?many.?requests|quota/i.test(code)) return "rate-limit";
|
|
40
|
+
if (/overload|server.?error|api.?error|unavailable|internal/i.test(code)) return "overloaded";
|
|
41
|
+
if (/invalid.?api.?key|authentication|permission|unauthorized|forbidden/i.test(code)) return "auth";
|
|
42
|
+
if (/invalid.?request|bad.?request/i.test(code)) return "invalid-request";
|
|
43
|
+
if (/content.?filter|content.?policy|safety/i.test(code)) return "content-filter";
|
|
44
|
+
return void 0;
|
|
45
|
+
}
|
|
37
46
|
function toAgentError(e, provider) {
|
|
38
47
|
if (isAgentError(e)) return e;
|
|
39
|
-
|
|
48
|
+
if (typeof e === "object" && e !== null && !(e instanceof Error)) {
|
|
49
|
+
const { message, code, type } = e;
|
|
50
|
+
const text2 = typeof message === "string" && message.trim() ? message : void 0;
|
|
51
|
+
const label = typeof code === "string" && code ? code : typeof type === "string" ? type : "";
|
|
52
|
+
if (text2 || label) {
|
|
53
|
+
const kind = kindFromCode(label) ?? toAgentError(new Error(text2 ?? label), provider).kind;
|
|
54
|
+
return new AgentError(kind, text2 ?? "The model's stream reported an error.", { provider, detail: e });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const msg = e instanceof Error ? e.message : typeof e === "object" && e !== null ? "Unknown error." : String(e);
|
|
40
58
|
if (e instanceof Error && e.name === "AbortError") {
|
|
41
59
|
return new AgentError("cancelled", "Request was cancelled.", { provider, cause: e });
|
|
42
60
|
}
|
|
@@ -74,13 +92,16 @@ function backoffDelay(attempt, policy, retryAfterSec) {
|
|
|
74
92
|
function parseRetryAfter(headers) {
|
|
75
93
|
const raw = headers.get("retry-after");
|
|
76
94
|
if (!raw) return void 0;
|
|
77
|
-
const
|
|
78
|
-
if (
|
|
79
|
-
|
|
80
|
-
|
|
95
|
+
const trimmed = raw.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
96
|
+
if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.max(0, Number(trimmed));
|
|
97
|
+
if (/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(trimmed)) {
|
|
98
|
+
const date = Date.parse(trimmed);
|
|
99
|
+
if (Number.isFinite(date)) return Math.max(0, (date - Date.now()) / 1e3);
|
|
100
|
+
}
|
|
81
101
|
return void 0;
|
|
82
102
|
}
|
|
83
103
|
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
104
|
+
if (signal?.aborted) return reject(new AgentError("cancelled", "Request was cancelled."));
|
|
84
105
|
const onAbort = () => {
|
|
85
106
|
clearTimeout(t);
|
|
86
107
|
reject(new AgentError("cancelled", "Request was cancelled."));
|
|
@@ -102,6 +123,7 @@ async function withRetry(run, opts = {}) {
|
|
|
102
123
|
lastError = err;
|
|
103
124
|
const isLast = attempt === policy.maxAttempts - 1;
|
|
104
125
|
if (!err.retryable || isLast) throw err;
|
|
126
|
+
if (opts.signal?.aborted) throw new AgentError("cancelled", "Request was cancelled.");
|
|
105
127
|
const delay = backoffDelay(attempt, policy, err.retryAfter);
|
|
106
128
|
opts.onRetry?.(attempt, err, delay);
|
|
107
129
|
await sleep(delay, opts.signal);
|
|
@@ -109,6 +131,14 @@ async function withRetry(run, opts = {}) {
|
|
|
109
131
|
}
|
|
110
132
|
throw lastError ?? new AgentError("unknown", "Retry loop exited without a result.");
|
|
111
133
|
}
|
|
134
|
+
function messageOf(body) {
|
|
135
|
+
if (typeof body !== "object" || body === null) return void 0;
|
|
136
|
+
const b = body;
|
|
137
|
+
const error = b.error;
|
|
138
|
+
const candidates = [typeof error === "object" && error !== null ? error.message : error, b.message, b.detail];
|
|
139
|
+
for (const c of candidates) if (typeof c === "string" && c.trim()) return c;
|
|
140
|
+
return void 0;
|
|
141
|
+
}
|
|
112
142
|
async function errorFromResponse(res, provider) {
|
|
113
143
|
const retryAfter = parseRetryAfter(res.headers);
|
|
114
144
|
let detail;
|
|
@@ -119,10 +149,10 @@ async function errorFromResponse(res, provider) {
|
|
|
119
149
|
try {
|
|
120
150
|
const parsed = JSON.parse(bodyText);
|
|
121
151
|
detail = parsed;
|
|
122
|
-
|
|
152
|
+
message = messageOf(parsed) ?? message;
|
|
123
153
|
} catch {
|
|
124
154
|
detail = bodyText;
|
|
125
|
-
message = bodyText.slice(0, 500);
|
|
155
|
+
if (!/^\s*</.test(bodyText)) message = bodyText.slice(0, 500);
|
|
126
156
|
}
|
|
127
157
|
}
|
|
128
158
|
} catch {
|
|
@@ -136,11 +166,17 @@ async function errorFromResponse(res, provider) {
|
|
|
136
166
|
}
|
|
137
167
|
|
|
138
168
|
// src/transport/sse.ts
|
|
169
|
+
var MAX_SSE_EVENT_CHARS = 32e6;
|
|
139
170
|
var SSEDecoder = class {
|
|
140
171
|
event = "";
|
|
141
172
|
data = [];
|
|
142
173
|
id;
|
|
143
174
|
retry;
|
|
175
|
+
chars = 0;
|
|
176
|
+
/** Characters held for the event being built (its data lines, not yet dispatched). */
|
|
177
|
+
get size() {
|
|
178
|
+
return this.chars;
|
|
179
|
+
}
|
|
144
180
|
/** Feed one line (terminator already removed). Returns an event when dispatched. */
|
|
145
181
|
push(line) {
|
|
146
182
|
if (line === "") return this.flush();
|
|
@@ -155,13 +191,13 @@ var SSEDecoder = class {
|
|
|
155
191
|
break;
|
|
156
192
|
case "data":
|
|
157
193
|
this.data.push(value);
|
|
194
|
+
this.chars += value.length + 1;
|
|
158
195
|
break;
|
|
159
196
|
case "id":
|
|
160
197
|
if (!value.includes("\0")) this.id = value;
|
|
161
198
|
break;
|
|
162
199
|
case "retry": {
|
|
163
|
-
|
|
164
|
-
if (Number.isInteger(n)) this.retry = n;
|
|
200
|
+
if (/^[0-9]+$/.test(value)) this.retry = Number(value);
|
|
165
201
|
break;
|
|
166
202
|
}
|
|
167
203
|
default:
|
|
@@ -180,6 +216,7 @@ var SSEDecoder = class {
|
|
|
180
216
|
};
|
|
181
217
|
this.event = "";
|
|
182
218
|
this.data = [];
|
|
219
|
+
this.chars = 0;
|
|
183
220
|
this.id = void 0;
|
|
184
221
|
this.retry = void 0;
|
|
185
222
|
return msg;
|
|
@@ -196,7 +233,8 @@ function findLineEnd(buf, from = 0) {
|
|
|
196
233
|
}
|
|
197
234
|
return null;
|
|
198
235
|
}
|
|
199
|
-
async function* parseSSE(stream) {
|
|
236
|
+
async function* parseSSE(stream, opts = {}) {
|
|
237
|
+
const maxEventChars = opts.maxEventChars ?? MAX_SSE_EVENT_CHARS;
|
|
200
238
|
const reader = stream.getReader();
|
|
201
239
|
const decoder = new TextDecoder("utf-8");
|
|
202
240
|
const sse = new SSEDecoder();
|
|
@@ -206,9 +244,9 @@ async function* parseSSE(stream) {
|
|
|
206
244
|
while (true) {
|
|
207
245
|
const { done, value } = await reader.read();
|
|
208
246
|
if (done) break;
|
|
209
|
-
const
|
|
210
|
-
buffer +=
|
|
211
|
-
const scan = cr ? "\r" +
|
|
247
|
+
const text2 = decoder.decode(value, { stream: true });
|
|
248
|
+
buffer += text2;
|
|
249
|
+
const scan = cr ? "\r" + text2 : text2;
|
|
212
250
|
const shift = buffer.length - scan.length;
|
|
213
251
|
let offset = 0;
|
|
214
252
|
let end = findLineEnd(scan);
|
|
@@ -221,6 +259,9 @@ async function* parseSSE(stream) {
|
|
|
221
259
|
}
|
|
222
260
|
if (offset > 0) buffer = buffer.slice(offset);
|
|
223
261
|
cr = scan.endsWith("\r");
|
|
262
|
+
if (sse.size + buffer.length > maxEventChars) {
|
|
263
|
+
throw new AgentError("invalid-request", `The stream sent an event larger than ${maxEventChars} characters; refusing to buffer more.`);
|
|
264
|
+
}
|
|
224
265
|
}
|
|
225
266
|
buffer += decoder.decode();
|
|
226
267
|
for (const line of buffer.split(/\r\n|\n|\r/)) {
|
|
@@ -394,13 +435,13 @@ function repairToolArguments(raw) {
|
|
|
394
435
|
return { value: {}, repaired: true, error: `Could not parse tool arguments: ${trimmed.slice(0, 200)}` };
|
|
395
436
|
}
|
|
396
437
|
var isJsonSpace = (ch) => ch === " " || ch === " " || ch === "\n" || ch === "\r";
|
|
397
|
-
function bracketed(
|
|
438
|
+
function bracketed(text2) {
|
|
398
439
|
let start = 0;
|
|
399
|
-
let end =
|
|
400
|
-
while (isJsonSpace(
|
|
401
|
-
while (end > start && isJsonSpace(
|
|
402
|
-
const open =
|
|
403
|
-
const close =
|
|
440
|
+
let end = text2.length - 1;
|
|
441
|
+
while (isJsonSpace(text2[start])) start += 1;
|
|
442
|
+
while (end > start && isJsonSpace(text2[end])) end -= 1;
|
|
443
|
+
const open = text2[start];
|
|
444
|
+
const close = text2[end];
|
|
404
445
|
return end > start && (open === "{" && close === "}" || open === "[" && close === "]");
|
|
405
446
|
}
|
|
406
447
|
|
|
@@ -441,6 +482,24 @@ function withDefaultTimeout(signal, ms = DEFAULT_TIMEOUT_MS) {
|
|
|
441
482
|
else timeoutSignal.addEventListener("abort", relay(timeoutSignal), { once: true });
|
|
442
483
|
return controller.signal;
|
|
443
484
|
}
|
|
485
|
+
function text(value) {
|
|
486
|
+
return typeof value === "string" ? value : void 0;
|
|
487
|
+
}
|
|
488
|
+
function count(value) {
|
|
489
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
490
|
+
}
|
|
491
|
+
async function readObject(res, provider) {
|
|
492
|
+
let body;
|
|
493
|
+
try {
|
|
494
|
+
body = await res.json();
|
|
495
|
+
} catch {
|
|
496
|
+
throw new AgentError("unknown", `Provider "${provider}" sent a reply that is not JSON.`, { provider });
|
|
497
|
+
}
|
|
498
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
499
|
+
throw new AgentError("unknown", `Provider "${provider}" sent a reply that is not a JSON object.`, { provider });
|
|
500
|
+
}
|
|
501
|
+
return body;
|
|
502
|
+
}
|
|
444
503
|
|
|
445
504
|
export {
|
|
446
505
|
AgentError,
|
|
@@ -461,7 +520,10 @@ export {
|
|
|
461
520
|
foreignFileText,
|
|
462
521
|
filterNativeTools,
|
|
463
522
|
withDefaultTimeout,
|
|
523
|
+
text,
|
|
524
|
+
count,
|
|
525
|
+
readObject,
|
|
464
526
|
normalizeToolName,
|
|
465
527
|
repairToolArguments
|
|
466
528
|
};
|
|
467
|
-
//# sourceMappingURL=chunk-
|
|
529
|
+
//# sourceMappingURL=chunk-CJ6WV4KB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/transport/types.ts","../src/transport/retry.ts","../src/transport/sse.ts","../src/tools/repair.ts","../src/providers/shared.ts"],"sourcesContent":["// One error type with a discriminating `kind`. The reason this matters: the\n// runtime's retry policy, the UI's message, and the host's alerting all key off\n// \"is this transient\" and \"is this the user's fault\" — and a raw `Error` from\n// `fetch` answers neither.\n\nexport type AgentErrorKind =\n | \"auth\" // bad/missing key — never retry\n | \"rate-limit\" // retry with backoff, honour Retry-After\n | \"overloaded\" // provider 5xx/529 — retry\n | \"timeout\" // retry\n | \"network\" // retry\n | \"invalid-request\" // our bug or the caller's — never retry\n | \"content-filter\" // provider refused — never retry\n | \"context-length\" // compact and retry once\n | \"not-supported\" // capability the adapter/model lacks\n | \"cancelled\"\n | \"tool-error\"\n | \"unknown\";\n\nconst RETRYABLE: ReadonlySet<AgentErrorKind> = new Set([\n \"rate-limit\",\n \"overloaded\",\n \"timeout\",\n \"network\",\n]);\n\nexport class AgentError extends Error {\n readonly kind: AgentErrorKind;\n readonly status?: number;\n readonly provider?: string;\n /** Seconds to wait before retrying, from a Retry-After header when present. */\n readonly retryAfter?: number;\n override readonly cause?: unknown;\n readonly detail?: unknown;\n\n constructor(\n kind: AgentErrorKind,\n message: string,\n opts: { status?: number; provider?: string; retryAfter?: number; cause?: unknown; detail?: unknown } = {},\n ) {\n super(message);\n this.name = \"AgentError\";\n this.kind = kind;\n this.status = opts.status;\n this.provider = opts.provider;\n this.retryAfter = opts.retryAfter;\n this.cause = opts.cause;\n this.detail = opts.detail;\n }\n\n get retryable(): boolean {\n return RETRYABLE.has(this.kind);\n }\n\n /** Compact shape for logs and for handing an error back to the model as data. */\n toJSON() {\n return { kind: this.kind, message: this.message, status: this.status, provider: this.provider };\n }\n}\n\nexport function isAgentError(e: unknown): e is AgentError {\n return e instanceof AgentError;\n}\n\n/**\n * Classify anything thrown. Used for errors that never went through an adapter\n * (a DNS failure, an aborted signal) and as the fallback in adapter mapping.\n */\n/** A provider's own error code (OpenAI `server_error`, Anthropic `overloaded_error`) → kind. Unknown codes give `undefined`. */\nfunction kindFromCode(code: string): AgentErrorKind | undefined {\n if (/context.?length/i.test(code)) return \"context-length\";\n if (/rate.?limit|too.?many.?requests|quota/i.test(code)) return \"rate-limit\";\n if (/overload|server.?error|api.?error|unavailable|internal/i.test(code)) return \"overloaded\";\n if (/invalid.?api.?key|authentication|permission|unauthorized|forbidden/i.test(code)) return \"auth\";\n if (/invalid.?request|bad.?request/i.test(code)) return \"invalid-request\";\n if (/content.?filter|content.?policy|safety/i.test(code)) return \"content-filter\";\n return undefined;\n}\n\nexport function toAgentError(e: unknown, provider?: string): AgentError {\n if (isAgentError(e)) return e;\n // A stream's own error event is a plain `{ message, code }`, not an `Error`: String() of it is \"[object Object]\".\n if (typeof e === \"object\" && e !== null && !(e instanceof Error)) {\n const { message, code, type } = e as { message?: unknown; code?: unknown; type?: unknown };\n const text = typeof message === \"string\" && message.trim() ? message : undefined;\n const label = typeof code === \"string\" && code ? code : typeof type === \"string\" ? type : \"\";\n if (text || label) {\n const kind = kindFromCode(label) ?? toAgentError(new Error(text ?? label), provider).kind;\n return new AgentError(kind, text ?? \"The model's stream reported an error.\", { provider, detail: e });\n }\n }\n const msg = e instanceof Error ? e.message : typeof e === \"object\" && e !== null ? \"Unknown error.\" : String(e);\n if (e instanceof Error && e.name === \"AbortError\") {\n return new AgentError(\"cancelled\", \"Request was cancelled.\", { provider, cause: e });\n }\n if (/timeout|etimedout|timed out/i.test(msg)) {\n return new AgentError(\"timeout\", msg, { provider, cause: e });\n }\n if (/fetch failed|econnreset|enotfound|econnrefused|network|socket hang up/i.test(msg)) {\n return new AgentError(\"network\", msg, { provider, cause: e });\n }\n return new AgentError(\"unknown\", msg, { provider, cause: e });\n}\n\n/** HTTP status → kind. Shared by every adapter so classification can't drift. */\nexport function kindFromStatus(status: number): AgentErrorKind {\n if (status === 401 || status === 403) return \"auth\";\n if (status === 429) return \"rate-limit\";\n if (status === 408) return \"timeout\";\n if (status === 400 || status === 404 || status === 422) return \"invalid-request\";\n if (status >= 500) return \"overloaded\";\n return \"unknown\";\n}\n","// The transport is the ONLY thing that knows where a request physically goes and\n// who holds the credential. Adapters build a `TransportRequest` describing the\n// provider-relative call (\"POST /responses with this body\") and hand it over.\n//\n// That split is what lets the same OpenAI adapter run:\n// • in the browser against a BFF that injects the key server-side (default), and\n// • in the browser straight at api.openai.com with a user-supplied key (BYOK), and\n// • on a server with the key in env,\n// without a single conditional inside the adapter.\n\nexport type TransportRequest = {\n /** Provider id (\"openai\"). The proxy transport uses it to route. */\n provider: string;\n /** Provider-relative path, always leading-slash (\"/responses\", \"/responses/{id}\"). */\n path: string;\n method: \"GET\" | \"POST\" | \"DELETE\";\n body?: unknown;\n headers?: Record<string, string>;\n /** Hint that the response is SSE. Transports must not buffer these. */\n stream?: boolean;\n signal?: AbortSignal;\n /** Extra query params, appended after any already present in `path`. */\n query?: Record<string, string | number | boolean | undefined>;\n};\n\n/**\n * A multipart/form-data body (file uploads). `TransportRequest.body` stays\n * `unknown`, so this is a convention, not a breaking change: adapters that\n * upload build this shape, and each transport recognizes it with\n * `isMultipartBody` and encodes it for its own wire — a real FormData on a\n * direct connection, base64 inside the JSON envelope through the proxy.\n *\n * Bytes are `Uint8Array` everywhere in core. Only the wire encodes.\n */\nexport type MultipartBody = {\n kind: \"multipart\";\n /** Plain string form fields (\"purpose\"). */\n fields: Record<string, string>;\n /** Binary parts. Raw bytes in memory; the proxy base64-encodes on the wire. */\n files: { field: string; filename: string; mediaType?: string; data: Uint8Array }[];\n};\n\nexport function isMultipartBody(b: unknown): b is MultipartBody {\n return (\n typeof b === \"object\" &&\n b !== null &&\n (b as { kind?: unknown }).kind === \"multipart\" &&\n Array.isArray((b as { files?: unknown }).files)\n );\n}\n\nexport type Transport = {\n readonly kind: \"direct\" | \"proxy\" | \"custom\";\n /**\n * Perform the call and return the raw `Response`. Returning `Response` rather\n * than parsed JSON is deliberate: streaming adapters need the body stream, and\n * error mapping needs status + headers (Retry-After).\n */\n fetch(req: TransportRequest): Promise<Response>;\n /**\n * Whether this transport can be trusted with a secret. `false` for\n * DirectTransport in a browser — the runtime surfaces this so a host can warn\n * rather than silently shipping a key to the client.\n */\n readonly credentialSafe: boolean;\n};\n\nexport type RetryPolicy = {\n maxAttempts: number;\n /** First backoff in ms; doubled each attempt with full jitter. */\n baseDelayMs: number;\n maxDelayMs: number;\n};\n\nexport const DEFAULT_RETRY: RetryPolicy = { maxAttempts: 3, baseDelayMs: 400, maxDelayMs: 8_000 };\n","import { AgentError, kindFromStatus, toAgentError } from \"../errors.js\";\nimport { DEFAULT_RETRY, type RetryPolicy } from \"./types.js\";\n\n/** Full-jitter exponential backoff. Full jitter (not equal) because synchronized\n * clients retrying a rate limit in lockstep is how a 429 becomes a 429 storm. */\nexport function backoffDelay(attempt: number, policy: RetryPolicy, retryAfterSec?: number): number {\n if (retryAfterSec != null && Number.isFinite(retryAfterSec)) {\n return Math.min(retryAfterSec * 1000, policy.maxDelayMs);\n }\n const ceiling = Math.min(policy.baseDelayMs * 2 ** attempt, policy.maxDelayMs);\n return Math.random() * ceiling;\n}\n\nexport function parseRetryAfter(headers: Headers): number | undefined {\n const raw = headers.get(\"retry-after\");\n if (!raw) return undefined;\n // Delta-seconds is digits (a fraction is tolerated), nothing else around it but spaces and tabs: `Number()` alone also reads\n // \"0x10\" as 16, \"1e3\" as 1000 and a blank as 0.\n const trimmed = raw.replace(/^[ \\t]+|[ \\t]+$/g, \"\");\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) return Math.max(0, Number(trimmed));\n // HTTP-date form, in the one format the header allows. `Date.parse` alone accepts \"foo 1\" as a date in 2001, which reads as\n // \"retry now\".\n if (/^[A-Za-z]{3}, \\d{2} [A-Za-z]{3} \\d{4} \\d{2}:\\d{2}:\\d{2} GMT$/.test(trimmed)) {\n const date = Date.parse(trimmed);\n if (Number.isFinite(date)) return Math.max(0, (date - Date.now()) / 1000);\n }\n return undefined;\n}\n\nconst sleep = (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n // An abort that already happened never fires again: waiting for it would sleep the whole delay.\n if (signal?.aborted) return reject(new AgentError(\"cancelled\", \"Request was cancelled.\"));\n const onAbort = () => {\n clearTimeout(t);\n reject(new AgentError(\"cancelled\", \"Request was cancelled.\"));\n };\n // `{once:true}` only detaches the listener once \"abort\" actually FIRES —\n // when the timer wins the race instead, it stays attached to the signal\n // for as long as the signal lives. A retry loop's signal is long-lived\n // (one AbortController for the whole call), so that leak accumulates one\n // stale listener per retry. Detach it explicitly on the timer-wins path too.\n const t = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n\n/**\n * Retry `run` while it fails transiently. Non-retryable failures (auth, bad\n * request, content filter) throw on the first attempt — retrying them just\n * burns quota and delays the real error reaching the user.\n */\nexport async function withRetry<T>(\n run: (attempt: number) => Promise<T>,\n opts: { policy?: RetryPolicy; signal?: AbortSignal; provider?: string; onRetry?: (attempt: number, err: AgentError, delayMs: number) => void } = {},\n): Promise<T> {\n const policy = opts.policy ?? DEFAULT_RETRY;\n let lastError: AgentError | undefined;\n\n for (let attempt = 0; attempt < policy.maxAttempts; attempt += 1) {\n try {\n return await run(attempt);\n } catch (raw) {\n const err = toAgentError(raw, opts.provider);\n lastError = err;\n const isLast = attempt === policy.maxAttempts - 1;\n if (!err.retryable || isLast) throw err;\n // Cancelled while it failed (a stream cut by the abort looks like a network error): do not try again.\n if (opts.signal?.aborted) throw new AgentError(\"cancelled\", \"Request was cancelled.\");\n const delay = backoffDelay(attempt, policy, err.retryAfter);\n opts.onRetry?.(attempt, err, delay);\n await sleep(delay, opts.signal);\n }\n }\n throw lastError ?? new AgentError(\"unknown\", \"Retry loop exited without a result.\");\n}\n\n/**\n * Turn a non-OK `Response` into a typed `AgentError`, pulling the provider's own\n * message out of the body so the user sees \"model X does not exist\" rather than\n * \"HTTP 404\".\n */\n/**\n * The provider's own sentence from an error body. OpenAI and Anthropic send `{ error: { message } }`; compatible servers send\n * `{ error: \"text\" }`, `{ message }` or `{ detail }` (FastAPI). Only text counts: an object there would print as \"[object Object]\".\n */\nfunction messageOf(body: unknown): string | undefined {\n if (typeof body !== \"object\" || body === null) return undefined;\n const b = body as { error?: unknown; message?: unknown; detail?: unknown };\n const error = b.error;\n const candidates = [typeof error === \"object\" && error !== null ? (error as { message?: unknown }).message : error, b.message, b.detail];\n for (const c of candidates) if (typeof c === \"string\" && c.trim()) return c;\n return undefined;\n}\n\nexport async function errorFromResponse(res: Response, provider: string): Promise<AgentError> {\n const retryAfter = parseRetryAfter(res.headers);\n let detail: unknown;\n let message = `${provider} request failed with ${res.status} ${res.statusText}`.trim();\n try {\n const bodyText = await res.text();\n if (bodyText) {\n try {\n const parsed = JSON.parse(bodyText) as unknown;\n detail = parsed;\n message = messageOf(parsed) ?? message;\n } catch {\n detail = bodyText;\n // A gateway's error page (Cloudflare 502, nginx 500) is HTML: the status line says it better than markup in the chat.\n if (!/^\\s*</.test(bodyText)) message = bodyText.slice(0, 500);\n }\n }\n } catch {\n /* body already consumed or unreadable — status alone is enough */\n }\n\n let kind = kindFromStatus(res.status);\n // Refine: a 400 whose body names the context window is recoverable by\n // compacting, which is a very different action from \"your request is invalid\".\n if (kind === \"invalid-request\" && /context.?length|maximum context|too many tokens|reduce the length/i.test(message)) {\n kind = \"context-length\";\n }\n if (/content.?filter|content_policy|safety/i.test(message)) kind = \"content-filter\";\n\n return new AgentError(kind, message, { status: res.status, provider, retryAfter, detail });\n}\n","// Server-Sent Events parser, per the WHATWG spec's event-stream algorithm.\n//\n// Hand-rolled rather than using EventSource because EventSource cannot POST and\n// cannot set an Authorization header — both of which every LLM streaming API\n// requires. The subtleties that a naive `split(\"\\n\\n\")` gets wrong and this\n// does not:\n// • chunk boundaries can land mid-line, mid-event, or mid-UTF-8-codepoint;\n// • line terminators may be \\n, \\r\\n or a bare \\r;\n// • a leading space after \"field:\" is stripped, but only one;\n// • multiple `data:` lines in one event join with \\n;\n// • comment lines (\":heartbeat\") keep the connection warm and must be ignored.\n\nimport { AgentError } from \"../errors.js\";\n\n/**\n * The most one event may hold, in characters (its unfinished line included). Far above any real event (a base64 image\n * in one `data:` field is a few MB), far below what a runaway or hostile upstream that never sends a blank line would\n * need to exhaust memory.\n */\nexport const MAX_SSE_EVENT_CHARS = 32_000_000;\n\nexport type SSEMessage = {\n event: string;\n data: string;\n id?: string;\n retry?: number;\n};\n\n/**\n * Incremental line-oriented decoder. State is per-instance, not module-level —\n * a background job poll and a foreground stream can run concurrently, and\n * shared accumulator state would interleave their events into garbage.\n */\nexport class SSEDecoder {\n private event = \"\";\n private data: string[] = [];\n private id: string | undefined;\n private retry: number | undefined;\n private chars = 0;\n\n /** Characters held for the event being built (its data lines, not yet dispatched). */\n get size(): number {\n return this.chars;\n }\n\n /** Feed one line (terminator already removed). Returns an event when dispatched. */\n push(line: string): SSEMessage | null {\n if (line === \"\") return this.flush(); // blank line dispatches\n if (line.startsWith(\":\")) return null; // comment / heartbeat\n\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1); // exactly one leading space\n\n switch (field) {\n case \"event\":\n this.event = value;\n break;\n case \"data\":\n this.data.push(value);\n this.chars += value.length + 1;\n break;\n case \"id\":\n if (!value.includes(\"\\0\")) this.id = value;\n break;\n case \"retry\": {\n // ASCII digits only, as the spec has it: Number() also reads \"\", \"0x10\", \"1e3\" and \"-5\".\n if (/^[0-9]+$/.test(value)) this.retry = Number(value);\n break;\n }\n default:\n break; // unknown fields ignored per spec\n }\n return null;\n }\n\n /** Dispatch whatever has accumulated. Called on a blank line and at stream end. */\n flush(): SSEMessage | null {\n if (this.data.length === 0 && !this.event) return null;\n const msg: SSEMessage = {\n event: this.event || \"message\",\n data: this.data.join(\"\\n\"),\n ...(this.id !== undefined ? { id: this.id } : {}),\n ...(this.retry !== undefined ? { retry: this.retry } : {}),\n };\n this.event = \"\";\n this.data = [];\n this.chars = 0;\n this.id = undefined;\n this.retry = undefined;\n return msg;\n }\n}\n\n/** Locate the next line terminator at or after `from`, or null if the buffer may still be mid-terminator. */\nfunction findLineEnd(buf: string, from = 0): { index: number; length: number } | null {\n for (let i = from; i < buf.length; i += 1) {\n const ch = buf[i];\n if (ch === \"\\n\") return { index: i, length: 1 };\n if (ch === \"\\r\") {\n // A trailing \\r could be the first half of \\r\\n — wait for more bytes.\n if (i === buf.length - 1) return null;\n return buf[i + 1] === \"\\n\" ? { index: i, length: 2 } : { index: i, length: 1 };\n }\n }\n return null;\n}\n\n/**\n * Decode a byte stream into SSE messages. `TextDecoder({stream:true})` is what\n * makes multi-byte characters split across chunks safe — decoding each chunk\n * independently corrupts any emoji or CJK text that straddles a boundary.\n */\nexport async function* parseSSE(\n stream: ReadableStream<Uint8Array>,\n opts: { maxEventChars?: number } = {},\n): AsyncGenerator<SSEMessage> {\n const maxEventChars = opts.maxEventChars ?? MAX_SSE_EVENT_CHARS;\n const reader = stream.getReader();\n const decoder = new TextDecoder(\"utf-8\");\n const sse = new SSEDecoder();\n let buffer = \"\";\n // Whether `buffer` ends in a \"\\r\" held back as a possible half of \"\\r\\n\".\n let cr = false;\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n const text = decoder.decode(value, { stream: true });\n // Appending links the two strings (engines build a rope) and copies\n // nothing until a character is read. So only the new text is scanned,\n // plus a held \"\\r\" so that a \"\\r\\n\" split across chunks still reads as one\n // terminator, and an unterminated line is copied once, when its terminator\n // shows up. Scanning `buffer` from the start read, and so copied, the\n // whole line again with every chunk: quadratic for a long line (a base64\n // image in one `data:` field).\n buffer += text;\n const scan: string = cr ? \"\\r\" + text : text;\n const shift = buffer.length - scan.length; // where `scan` starts in `buffer`\n\n // Track a read offset instead of slicing the buffer after every line —\n // a chunk with many short lines would otherwise re-copy the (shrinking)\n // remainder once per line. Slice once, after every complete line in\n // this chunk has been extracted.\n let offset = 0;\n let end = findLineEnd(scan);\n while (end) {\n const line = buffer.slice(offset, shift + end.index);\n offset = shift + end.index + end.length;\n const msg = sse.push(line);\n if (msg) yield msg;\n end = findLineEnd(scan, offset - shift);\n }\n if (offset > 0) buffer = buffer.slice(offset);\n cr = scan.endsWith(\"\\r\");\n if (sse.size + buffer.length > maxEventChars) {\n throw new AgentError(\"invalid-request\", `The stream sent an event larger than ${maxEventChars} characters; refusing to buffer more.`);\n }\n }\n\n // Flush a trailing event that arrived without its final blank line — some\n // proxies close the connection right after the last data line.\n buffer += decoder.decode();\n for (const line of buffer.split(/\\r\\n|\\n|\\r/)) {\n const msg = sse.push(line);\n if (msg) yield msg;\n }\n const tail = sse.flush();\n if (tail) yield tail;\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * SSE messages whose `data` is JSON, skipping the `[DONE]` sentinel that\n * OpenAI's Chat Completions stream terminates with.\n */\nexport async function* parseSSEJson<T = unknown>(\n stream: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: T }> {\n for await (const msg of parseSSE(stream)) {\n if (msg.data === \"[DONE]\") return;\n if (!msg.data) continue;\n try {\n yield { event: msg.event, data: JSON.parse(msg.data) as T };\n } catch {\n // A malformed frame is not worth killing a live stream over; the finish\n // event still arrives and the turn completes with what it got.\n }\n }\n}\n","// Tool-call repair.\n//\n// Models emit malformed tool arguments often enough that treating it as an\n// exception is the wrong design — a turn that dies on a stray newline inside a\n// JSON string is worse than a turn that fixes it and continues. Every fix here\n// is *syntactic and lossless*: we never invent argument values, so a repair can\n// change whether the call parses but not what it means.\n//\n// Observed failure modes, in the order we handle them:\n// 1. empty string / \"null\" for a no-argument tool → {}\n// 2. markdown fences around the JSON (```json … ```) → strip\n// 3. double-encoded JSON (\"\\\"{\\\\\\\"a\\\\\\\":1}\\\"\") → parse twice\n// 4. raw control characters inside string literals → escape them\n// 5. trailing commas before } or ] → drop\n// 6. Python literals (True/False/None) from local models → JSON literals\n// 7. single-quoted keys/values → double quotes\n// 8. prose wrapped around a JSON object → extract the object\n\nexport type RepairResult = { value: unknown; repaired: boolean; error?: string };\n\n/** Provider prefixes some routers prepend to tool names. Stripped before dispatch. */\nconst NAME_PREFIXES = [/^functions\\./, /^mcp_/, /^default_api[:.]/, /^tool[:.]/];\n\n/**\n * Normalize a tool name. Some OpenAI-compatible routers namespace tool names on\n * the way out but not on the way in, so the model calls `functions.getPrice`\n * for a tool we registered as `getPrice`.\n */\nexport function normalizeToolName(name: string): string {\n let out = name.trim();\n for (const re of NAME_PREFIXES) out = out.replace(re, \"\");\n return out;\n}\n\nconst CONTROL_ESCAPES: Record<string, string> = { \"\\n\": \"\\\\n\", \"\\r\": \"\\\\r\", \"\\t\": \"\\\\t\", \"\\b\": \"\\\\b\", \"\\f\": \"\\\\f\" };\nconst BACKSLASH = 0x5c;\nconst QUOTE = 0x22;\nconst COMMA = 0x2c;\nconst OPEN_BRACE = 0x7b;\nconst CLOSE_BRACE = 0x7d;\n\n// The scans below read character codes rather than one-character strings, and\n// the two that rewrite copy the untouched stretches between their fixes with one\n// slice each rather than building the output a character at a time, handing\n// back the input itself when there was nothing to fix. On a megabyte of\n// arguments the per-character version was most of a repair's cost.\n\n/** Escape control characters that appear *inside* JSON string literals. */\nfunction escapeControlCharsInStrings(input: string): string {\n const parts: string[] = [];\n let from = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = 0; i < input.length; i += 1) {\n const code = input.charCodeAt(i);\n if (escaped) {\n escaped = false;\n continue;\n }\n if (code === BACKSLASH) {\n escaped = true;\n continue;\n }\n if (code === QUOTE) {\n inString = !inString;\n continue;\n }\n if (inString && code < 0x20) {\n parts.push(input.slice(from, i), CONTROL_ESCAPES[input[i]!] ?? `\\\\u${code.toString(16).padStart(4, \"0\")}`);\n from = i + 1;\n }\n }\n if (!parts.length) return input;\n parts.push(input.slice(from));\n return parts.join(\"\");\n}\n\n/** The first character that is not whitespace, as `\\s` counts it. */\nconst NON_SPACE = /\\S/g;\n\n/** Remove trailing commas before a closing brace/bracket, outside of strings. */\nfunction dropTrailingCommas(input: string): string {\n const parts: string[] = [];\n let from = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = 0; i < input.length; i += 1) {\n const code = input.charCodeAt(i);\n if (escaped) {\n escaped = false;\n continue;\n }\n if (code === BACKSLASH) {\n escaped = true;\n continue;\n }\n if (code === QUOTE) inString = !inString;\n if (!inString && code === COMMA) {\n NON_SPACE.lastIndex = i + 1;\n const nextNonSpace = NON_SPACE.exec(input)?.[0];\n if (nextNonSpace === \"}\" || nextNonSpace === \"]\") {\n parts.push(input.slice(from, i)); // drop it\n from = i + 1;\n }\n }\n }\n if (!parts.length) return input;\n parts.push(input.slice(from));\n return parts.join(\"\");\n}\n\n/** Extract the outermost balanced {...} from prose, respecting string literals. */\nfunction extractJsonObject(input: string): string | null {\n const start = input.indexOf(\"{\");\n if (start === -1) return null;\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = start; i < input.length; i += 1) {\n const code = input.charCodeAt(i);\n if (escaped) {\n escaped = false;\n continue;\n }\n if (code === BACKSLASH) {\n escaped = true;\n continue;\n }\n if (code === QUOTE) {\n inString = !inString;\n continue;\n }\n if (inString) continue;\n if (code === OPEN_BRACE) depth += 1;\n else if (code === CLOSE_BRACE) {\n depth -= 1;\n if (depth === 0) return input.slice(start, i + 1);\n }\n }\n return null;\n}\n\n/**\n * Parse tool arguments, repairing what can be repaired losslessly.\n * Returns `{}` rather than throwing when nothing is salvageable — an empty\n * argument object lets the tool's own validation produce a message the model can\n * act on, which beats a parse error the model never sees.\n */\nexport function repairToolArguments(raw: unknown): RepairResult {\n if (raw == null) return { value: {}, repaired: false };\n if (typeof raw === \"object\") return { value: raw, repaired: false };\n if (typeof raw !== \"string\") return { value: {}, repaired: true, error: `Unexpected argument type ${typeof raw}` };\n\n const trimmed = raw.trim();\n if (trimmed === \"\" || trimmed === \"null\" || trimmed === \"{}\") {\n return { value: {}, repaired: trimmed !== \"{}\" };\n }\n\n // Fast path: already valid.\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n // Double-encoded: valid JSON that yields a string which is itself JSON.\n if (typeof parsed === \"string\") {\n try {\n return { value: JSON.parse(parsed) as unknown, repaired: true };\n } catch {\n return { value: { value: parsed }, repaired: true };\n }\n }\n return { value: parsed, repaired: false };\n } catch {\n /* fall through to repairs */\n }\n\n const unfenced = trimmed.replace(/^```(?:json)?\\s*/i, \"\");\n // The closing fence is cut by hand, and the whitespace before it goes with the\n // trim. As a regex, /\\s*```$/ restarts at every offset of a whitespace run and\n // rescans the rest of it, which is quadratic: 40,000 spaces took 0.6 s.\n const defenced = (unfenced.endsWith(\"```\") ? unfenced.slice(0, -3) : unfenced).trim();\n // Each candidate is built only once every one before it has failed to parse,\n // so a fenced object never pays for the scans and a trailing comma never pays\n // for the regex passes. Every candidate after this one builds on the same\n // `defenced` input, so the shared passes run once.\n function* candidates(): Generator<string> {\n yield defenced;\n const controlCharsEscaped = escapeControlCharsInStrings(defenced);\n yield controlCharsEscaped;\n const noTrailingCommas = dropTrailingCommas(controlCharsEscaped);\n yield noTrailingCommas;\n yield noTrailingCommas\n // Python literals, only as standalone tokens so \"None of the above\" survives.\n .replace(/\\bTrue\\b/g, \"true\")\n .replace(/\\bFalse\\b/g, \"false\")\n .replace(/\\bNone\\b/g, \"null\");\n // Single quotes last: it is the most destructive fix (an apostrophe inside a\n // value becomes a quote), so it only runs when everything else has failed.\n yield noTrailingCommas.replace(/'([^'\\\\]*)'(\\s*[:,}\\]])/g, '\"$1\"$2');\n const extracted = extractJsonObject(defenced);\n if (extracted) {\n yield extracted;\n // An object that is the whole input has been through these passes already.\n yield extracted === defenced ? noTrailingCommas : dropTrailingCommas(escapeControlCharsInStrings(extracted));\n }\n }\n\n // Most fixes change nothing on most inputs, and text that already failed will\n // fail again, so a candidate identical to one tried before — `trimmed`\n // included — is not parsed twice. Nor is one that cannot be an object or an\n // array because it does not start and end like one.\n const tried = [trimmed];\n for (const candidate of candidates()) {\n if (!bracketed(candidate) || tried.includes(candidate)) continue;\n tried.push(candidate);\n try {\n const parsed = JSON.parse(candidate) as unknown;\n if (parsed && typeof parsed === \"object\") return { value: parsed, repaired: true };\n } catch {\n continue;\n }\n }\n\n return { value: {}, repaired: true, error: `Could not parse tool arguments: ${trimmed.slice(0, 200)}` };\n}\n\nconst isJsonSpace = (ch: string | undefined) => ch === \" \" || ch === \"\\t\" || ch === \"\\n\" || ch === \"\\r\";\n\n/**\n * Whether `text` opens and closes like a JSON object or array, ignoring the\n * whitespace JSON allows around a value. JSON.parse can return an object only\n * when it does, so when it does not, a parse is known to be wasted.\n */\nfunction bracketed(text: string): boolean {\n let start = 0;\n let end = text.length - 1;\n while (isJsonSpace(text[start])) start += 1;\n while (end > start && isJsonSpace(text[end])) end -= 1;\n const open = text[start];\n const close = text[end];\n return end > start && ((open === \"{\" && close === \"}\") || (open === \"[\" && close === \"]\"));\n}\n","// Logic shared by more than one adapter. Anything that is genuinely one\n// provider's wire quirk belongs in that provider's own map-in.ts — this file\n// is only for the pieces that are identical in shape across adapters, where\n// duplicating them risks the copies drifting apart.\n\nimport { AgentError } from \"../errors.js\";\n\n/**\n * Collect the ids of \"answer\" markers from a flat list, via a callback that\n * returns the id when an item IS an answer, or undefined otherwise.\n *\n * Every wire format's orphan-call prune (OpenAI Responses' function_call /\n * function_call_output, Chat's tool_calls / role:\"tool\", Anthropic's\n * tool_use / tool_result) starts by building this same Set; only the\n * extractor differs; see `dropUnanswered` for the other half.\n */\nexport function collectAnsweredIds<T>(items: readonly T[], answerId: (item: T) => string | undefined): Set<string> {\n const ids = new Set<string>();\n for (const item of items) {\n const id = answerId(item);\n if (id !== undefined) ids.add(id);\n }\n return ids;\n}\n\n/**\n * Drop items whose call id is not in `answered`. `callId` returns undefined\n * for items that are not gated on an answer at all, which always pass.\n *\n * Used directly on the top-level list for a flat wire shape (Responses'\n * input items), and on the nested list inside a container for a wire shape\n * that groups calls under a message (Chat's tool_calls[], Anthropic's\n * content[]).\n */\nexport function dropUnanswered<T>(\n items: readonly T[],\n answered: ReadonlySet<string>,\n callId: (item: T) => string | undefined,\n): T[] {\n return items.filter((item) => {\n const id = callId(item);\n return id === undefined || answered.has(id);\n });\n}\n\n/**\n * A foreign file ref DEGRADES to text instead of throwing. Throwing would be\n * correct for the turn that attached it — but the ref lives in persisted\n * history, so a throw poisons every subsequent turn of the thread (the exact\n * failure mode the orphan-call prune exists to prevent for tool calls). The\n * model reading \"[attachment unavailable]\" can say so; a permanently 400ing\n * thread can't say anything.\n */\nexport function foreignFileText(\n kind: \"image\" | \"file\",\n filename: string | undefined,\n source: { id: string; provider: string },\n): string {\n return `[${kind} \"${filename ?? source.id}\" unavailable — it was uploaded to \"${source.provider}\" and cannot be read here. Ask the user to re-attach it.]`;\n}\n\n/**\n * Provider-hosted tool declarations ride the wire verbatim — we don't own\n * their shape, and the vendor versions it on their own cadence — but an\n * entry that isn't even an object with a `type` string would still get\n * spread into the request as-is, producing a wire object the provider\n * rejects with an error far from where the bad entry came from. This is\n * deliberately not a schema validator; it only catches \"not tool-shaped\".\n */\nexport function isNativeToolShape(value: unknown): value is Record<string, unknown> & { type: string } {\n return typeof value === \"object\" && value !== null && typeof (value as { type?: unknown }).type === \"string\";\n}\n\n/** `providerTools[id]`, narrowed to entries that at least look like a tool declaration. */\nexport function filterNativeTools(value: unknown): (Record<string, unknown> & { type: string })[] {\n return Array.isArray(value) ? value.filter(isNativeToolShape) : [];\n}\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\n\n/**\n * Combine a caller's signal with a default timeout, so a stalled connection\n * cannot hang forever when the caller never passes (or never aborts) its own\n * signal. Whichever fires first wins — a caller's shorter deadline is never\n * overridden by the default.\n */\nexport function withDefaultTimeout(signal: AbortSignal | undefined, ms: number = DEFAULT_TIMEOUT_MS): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(ms);\n if (!signal) return timeoutSignal;\n if (typeof AbortSignal.any === \"function\") return AbortSignal.any([signal, timeoutSignal]);\n\n // Manual combine for a runtime without AbortSignal.any.\n const controller = new AbortController();\n const relay = (from: AbortSignal) => () => controller.abort(from.reason);\n if (signal.aborted) controller.abort(signal.reason);\n else signal.addEventListener(\"abort\", relay(signal), { once: true });\n if (timeoutSignal.aborted) controller.abort(timeoutSignal.reason);\n else timeoutSignal.addEventListener(\"abort\", relay(timeoutSignal), { once: true });\n return controller.signal;\n}\n\n/** A string, or undefined: what a provider's frame holds where this library needs text (never \"undefined\", never a number). */\nexport function text(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** A token count: a non-negative safe integer, or undefined. A provider's `-1`, `1.5` or `\"7\"` is not a count, and a budget or a bill must not be built on it. */\nexport function count(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;\n}\n\n/**\n * A reply body read as a JSON object, or an AgentError. A server that answers `200` with `null`, a list, a number or\n * text that is not JSON is not an OpenAI/Anthropic server; the caller then gets a reason it can show, never a\n * `TypeError` from a field read or a bare `SyntaxError`.\n */\nexport async function readObject(res: Response, provider: string): Promise<Record<string, unknown>> {\n let body: unknown;\n try {\n body = await res.json();\n } catch {\n throw new AgentError(\"unknown\", `Provider \"${provider}\" sent a reply that is not JSON.`, { provider });\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n throw new AgentError(\"unknown\", `Provider \"${provider}\" sent a reply that is not a JSON object.`, { provider });\n }\n return body as Record<string, unknown>;\n}\n"],"mappings":";AAmBA,IAAM,YAAyC,oBAAI,IAAI;AAAA,EACrD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACS;AAAA,EACT;AAAA,EAET,YACE,MACA,SACA,OAAuG,CAAC,GACxG;AACA,UAAM,OAAO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