@supersolutions/super-chat-core 0.5.1 → 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 CHANGED
@@ -7,8 +7,8 @@ import {
7
7
  streamAnthropic,
8
8
  toAnthropicMessages,
9
9
  usageFromAnthropic
10
- } from "./chunk-KUB5GKAM.js";
11
- import "./chunk-7G4U4NTL.js";
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
- const msg = e instanceof Error ? e.message : String(e);
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
  }
@@ -134,7 +152,7 @@ async function errorFromResponse(res, provider) {
134
152
  message = messageOf(parsed) ?? message;
135
153
  } catch {
136
154
  detail = bodyText;
137
- message = bodyText.slice(0, 500);
155
+ if (!/^\s*</.test(bodyText)) message = bodyText.slice(0, 500);
138
156
  }
139
157
  }
140
158
  } catch {
@@ -508,4 +526,4 @@ export {
508
526
  normalizeToolName,
509
527
  repairToolArguments
510
528
  };
511
- //# sourceMappingURL=chunk-7G4U4NTL.js.map
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;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK;AACnB,SAAK,WAAW,KAAK;AACrB,SAAK,aAAa,KAAK;AACvB,SAAK,QAAQ,KAAK;AAClB,SAAK,SAAS,KAAK;AAAA,EACrB;AAAA,EAEA,IAAI,YAAqB;AACvB,WAAO,UAAU,IAAI,KAAK,IAAI;AAAA,EAChC;AAAA;AAAA,EAGA,SAAS;AACP,WAAO,EAAE,MAAM,KAAK,MAAM,SAAS,KAAK,SAAS,QAAQ,KAAK,QAAQ,UAAU,KAAK,SAAS;AAAA,EAChG;AACF;AAEO,SAAS,aAAa,GAA6B;AACxD,SAAO,aAAa;AACtB;AAOA,SAAS,aAAa,MAA0C;AAC9D,MAAI,mBAAmB,KAAK,IAAI,EAAG,QAAO;AAC1C,MAAI,yCAAyC,KAAK,IAAI,EAAG,QAAO;AAChE,MAAI,0DAA0D,KAAK,IAAI,EAAG,QAAO;AACjF,MAAI,sEAAsE,KAAK,IAAI,EAAG,QAAO;AAC7F,MAAI,iCAAiC,KAAK,IAAI,EAAG,QAAO;AACxD,MAAI,0CAA0C,KAAK,IAAI,EAAG,QAAO;AACjE,SAAO;AACT;AAEO,SAAS,aAAa,GAAY,UAA+B;AACtE,MAAI,aAAa,CAAC,EAAG,QAAO;AAE5B,MAAI,OAAO,MAAM,YAAY,MAAM,QAAQ,EAAE,aAAa,QAAQ;AAChE,UAAM,E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15
15
  withDefaultTimeout,
16
16
  withRetry
17
- } from "./chunk-7G4U4NTL.js";
17
+ } from "./chunk-CJ6WV4KB.js";
18
18
 
19
19
  // src/providers/openai/map-in.ts
20
20
  function dataUrl(mediaType, base64) {
@@ -1164,4 +1164,4 @@ export {
1164
1164
  reap,
1165
1165
  resumeJobs
1166
1166
  };
1167
- //# sourceMappingURL=chunk-WFU4HXUG.js.map
1167
+ //# sourceMappingURL=chunk-HKGDZQS6.js.map
@@ -13,7 +13,7 @@ import {
13
13
  toAgentError,
14
14
  withDefaultTimeout,
15
15
  withRetry
16
- } from "./chunk-7G4U4NTL.js";
16
+ } from "./chunk-CJ6WV4KB.js";
17
17
 
18
18
  // src/providers/anthropic/map-in.ts
19
19
  var DEFAULT_MAX_TOKENS = 4096;
@@ -313,7 +313,7 @@ async function* streamAnthropic(body) {
313
313
  return;
314
314
  }
315
315
  case "error":
316
- yield { type: "error", error: new Error(text(event.error?.message) ?? "Stream error") };
316
+ yield { type: "error", error: { message: text(event.error?.message) ?? "Stream error", code: text(event.error?.type) } };
317
317
  return;
318
318
  default:
319
319
  break;
@@ -468,4 +468,4 @@ export {
468
468
  streamAnthropic,
469
469
  createAnthropicProvider
470
470
  };
471
- //# sourceMappingURL=chunk-KUB5GKAM.js.map
471
+ //# sourceMappingURL=chunk-ZMPT7BBM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/providers/anthropic/map-in.ts","../src/providers/anthropic/map-out.ts","../src/providers/anthropic/stream.ts","../src/providers/anthropic/adapter.ts"],"sourcesContent":["// Normalized request → Anthropic Messages wire.\n//\n// Structural differences from the OpenAI builders that matter here:\n// • Tool CALLS are `tool_use` blocks inside the assistant message; tool\n// RESULTS are `tool_result` blocks inside the FOLLOWING USER message.\n// • Thinking replays as a `thinking` block with its `signature` — and only\n// with one; a reasoning part without a signature is display-only.\n// • `max_tokens` is required and caps thinking + text together.\n\nimport type { ContentPart, Message } from \"../../content/types.js\";\nimport type { NormalizedRequest, ToolSpec } from \"../types.js\";\nimport { collectAnsweredIds, dropUnanswered, filterNativeTools, foreignFileText } from \"../shared.js\";\nimport type {\n AnthropicContentBlock,\n AnthropicMessage,\n AnthropicRequest,\n AnthropicTool,\n AnthropicToolChoice,\n} from \"./wire.js\";\n\nexport type AnthropicBuildOptions = {\n stream?: boolean;\n providerId?: string;\n parallelToolCalls?: boolean;\n /** Applied when the request carries no maxOutputTokens (`max_tokens` is required). */\n defaultMaxTokens?: number;\n};\n\nconst DEFAULT_MAX_TOKENS = 4096;\n\nfunction toBlocks(part: ContentPart, providerId: string): AnthropicContentBlock | null {\n switch (part.type) {\n case \"text\":\n return part.text ? { type: \"text\", text: part.text } : null;\n case \"reasoning\":\n // Replayable only with its signature; redacted blocks round-trip via the\n // signature field where the opaque payload was stashed on the way out.\n if (part.redacted && part.signature) return { type: \"redacted_thinking\", data: part.signature };\n if (part.signature) return { type: \"thinking\", thinking: part.text, signature: part.signature };\n return null;\n case \"image\": {\n const s = part.source;\n if (s.kind === \"url\") return { type: \"image\", source: { type: \"url\", url: s.url } };\n if (s.kind === \"base64\") {\n return { type: \"image\", source: { type: \"base64\", media_type: part.mediaType ?? \"image/png\", data: s.data } };\n }\n if (s.provider !== providerId) return { type: \"text\", text: foreignFileText(\"image\", undefined, s) };\n return { type: \"image\", source: { type: \"file\", file_id: s.id } };\n }\n case \"file\": {\n const s = part.source;\n if (s.kind === \"url\") return { type: \"document\", source: { type: \"url\", url: s.url }, ...(part.filename ? { title: part.filename } : {}) };\n if (s.kind === \"base64\") {\n return {\n type: \"document\",\n source: { type: \"base64\", media_type: part.mediaType, data: s.data },\n ...(part.filename ? { title: part.filename } : {}),\n };\n }\n if (s.provider !== providerId) return { type: \"text\", text: foreignFileText(\"file\", part.filename, s) };\n return { type: \"document\", source: { type: \"file\", file_id: s.id }, ...(part.filename ? { title: part.filename } : {}) };\n }\n case \"audio\":\n // No audio input on the Messages API; surface the transcript.\n return part.transcript ? { type: \"text\", text: part.transcript } : null;\n case \"tool-call\":\n return {\n type: \"tool_use\",\n id: part.callId,\n name: part.name,\n input: typeof part.input === \"string\" ? tryParse(part.input) : (part.input ?? {}),\n };\n case \"tool-result\":\n return {\n type: \"tool_result\",\n tool_use_id: part.callId,\n content: typeof part.output === \"string\" ? part.output : JSON.stringify(part.output ?? null),\n ...(part.failure ? { is_error: true } : {}),\n };\n default:\n return null; // artifact parts are UI-only\n }\n}\n\nconst tryParse = (s: string): unknown => {\n try {\n return JSON.parse(s);\n } catch {\n return {};\n }\n};\n\n/**\n * Fold normalized messages into Anthropic's user/assistant alternation.\n * System messages are hoisted by the caller; `tool` role messages become USER\n * messages carrying tool_result blocks (the wire has no tool role). Adjacent\n * same-role messages merge — cheap, and robust to strict-alternation servers.\n */\nexport function toAnthropicMessages(messages: readonly Message[], providerId = \"anthropic\"): AnthropicMessage[] {\n const out: AnthropicMessage[] = [];\n\n for (const m of messages) {\n if (m.role === \"system\") continue;\n const role: \"user\" | \"assistant\" = m.role === \"assistant\" ? \"assistant\" : \"user\";\n const blocks = m.parts.map((p) => toBlocks(p, providerId)).filter((b): b is AnthropicContentBlock => b !== null);\n if (!blocks.length) continue;\n\n const last = out[out.length - 1];\n if (last && last.role === role) last.content.push(...blocks);\n else out.push({ role, content: blocks });\n }\n\n return dropOrphanToolUses(out);\n}\n\n/**\n * Same orphan rule as OpenAI: a `tool_use` with no `tool_result` in the next\n * user message 400s the whole request. A cancelled turn leaves exactly that in\n * persisted history, so prune rather than letting one lost step poison the\n * thread forever.\n */\nexport function dropOrphanToolUses(messages: AnthropicMessage[]): AnthropicMessage[] {\n const answered = collectAnsweredIds(\n messages.flatMap((m) => m.content),\n (b) => (b.type === \"tool_result\" ? b.tool_use_id : undefined),\n );\n return messages\n .map((m) => ({\n ...m,\n content: dropUnanswered(m.content, answered, (b) => (b.type === \"tool_use\" ? b.id : undefined)),\n }))\n .filter((m) => m.content.length > 0);\n}\n\nfunction toAnthropicTools(tools: readonly ToolSpec[]): AnthropicTool[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Record<string, unknown>,\n ...(t.strict ? { strict: true } : {}),\n }));\n}\n\nfunction toToolChoice(req: NormalizedRequest, parallel: boolean): AnthropicToolChoice | undefined {\n const noParallel = parallel ? {} : { disable_parallel_tool_use: true };\n // `activeTools` narrows like the OpenAI builder: a single active tool forces it.\n if (req.activeTools?.length === 1 && req.tools && req.tools.length > 1) {\n return { type: \"tool\", name: req.activeTools[0]!, ...noParallel };\n }\n if (req.activeTools?.length === 0) return { type: \"none\" };\n switch (req.toolChoice?.type) {\n case \"none\":\n return { type: \"none\" };\n case \"required\":\n return { type: \"any\", ...noParallel };\n case \"tool\":\n return { type: \"tool\", name: req.toolChoice.name, ...noParallel };\n default:\n return parallel ? { type: \"auto\" } : { type: \"auto\", disable_parallel_tool_use: true };\n }\n}\n\nconst EFFORT: Record<string, NonNullable<AnthropicRequest[\"output_config\"]>[\"effort\"]> = {\n minimal: \"low\",\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n};\n\nexport function buildAnthropicRequest(req: NormalizedRequest, opts: AnthropicBuildOptions = {}): AnthropicRequest {\n const providerId = opts.providerId ?? \"anthropic\";\n\n const systemFromMessages = req.messages\n .filter((m) => m.role === \"system\")\n .flatMap((m) => m.parts.filter((p) => p.type === \"text\").map((p) => (p as { text: string }).text))\n .join(\"\\n\\n\");\n const system = [req.system, systemFromMessages].filter(Boolean).join(\"\\n\\n\") || undefined;\n\n const out: AnthropicRequest = {\n model: req.model,\n max_tokens: req.maxOutputTokens ?? opts.defaultMaxTokens ?? DEFAULT_MAX_TOKENS,\n messages: toAnthropicMessages(req.messages, providerId),\n };\n if (system) out.system = system;\n\n // Provider-hosted tools (web search, code execution) share the tools array\n // with function tools and are appended verbatim — the vendor owns the shape.\n const nativeTools = filterNativeTools(req.providerTools?.[providerId]);\n if (req.tools?.length || nativeTools.length) {\n out.tools = [...(req.tools?.length ? toAnthropicTools(req.tools) : []), ...nativeTools] as AnthropicTool[];\n if (req.tools?.length) {\n const choice = toToolChoice(req, opts.parallelToolCalls !== false);\n if (choice) out.tool_choice = choice;\n }\n }\n\n if (req.reasoning) {\n // Current models: adaptive thinking + effort — never budget_tokens (400s\n // on Opus 4.7+). `summary` opt-in maps to display: \"summarized\" so hosts\n // that render reasoning actually receive text.\n out.thinking = {\n type: \"adaptive\",\n ...(req.reasoning.summary && req.reasoning.summary !== \"none\" ? { display: \"summarized\" as const } : {}),\n };\n const effort = req.reasoning.effort ? EFFORT[req.reasoning.effort] : undefined;\n if (effort) out.output_config = { ...(out.output_config ?? {}), effort };\n }\n\n if (req.responseFormat?.type === \"json_schema\") {\n out.output_config = {\n ...(out.output_config ?? {}),\n format: { type: \"json_schema\", schema: req.responseFormat.schema as Record<string, unknown> },\n };\n }\n\n // Sampling params are caller-set pass-throughs. NOTE: models from Opus 4.7\n // on REJECT them — leave unset unless the target model accepts them.\n if (req.temperature != null) out.temperature = req.temperature;\n if (req.topP != null) out.top_p = req.topP;\n if (req.stopSequences?.length) out.stop_sequences = req.stopSequences;\n if (opts.stream) out.stream = true;\n\n const extra = req.providerOptions?.[providerId];\n if (extra) Object.assign(out, extra);\n return out;\n}\n\n/** Whether any message references a providerFile minted by THIS provider (needs the Files beta header). */\nexport function usesOwnFiles(req: NormalizedRequest, providerId: string): boolean {\n return req.messages.some((m) =>\n m.parts.some(\n (p) =>\n (p.type === \"file\" || p.type === \"image\") &&\n p.source.kind === \"providerFile\" &&\n p.source.provider === providerId,\n ),\n );\n}\n","// Anthropic wire → normalized parts.\n\nimport { AgentError } from \"../../errors.js\";\nimport { count, text } from \"../shared.js\";\nimport type { ContentPart, FinishReason, Usage } from \"../../content/types.js\";\nimport type { AnthropicResponse, AnthropicStopReason, AnthropicUsage } from \"./wire.js\";\n\nexport function partsFromAnthropic(response: AnthropicResponse): ContentPart[] {\n const parts: ContentPart[] = [];\n for (const block of Array.isArray(response?.content) ? response.content : []) {\n if (block === null || typeof block !== \"object\") continue;\n switch (block.type) {\n case \"text\": {\n const t = text(block.text);\n if (t !== undefined) parts.push({ type: \"text\", text: t });\n break;\n }\n case \"thinking\":\n // The signature is the replay token — without it the block can never\n // be echoed back, so keep it on the part.\n parts.push({ type: \"reasoning\", text: text(block.thinking) ?? \"\", ...(text(block.signature) ? { signature: text(block.signature)! } : {}) });\n break;\n case \"redacted_thinking\":\n // Opaque payload rides in `signature` so map-in can round-trip it.\n parts.push({ type: \"reasoning\", text: \"\", signature: text(block.data) ?? \"\", redacted: true });\n break;\n case \"tool_use\": {\n const callId = text(block.id);\n const name = text(block.name);\n // A call nobody can name or answer is not worth running: end the turn with the reason.\n if (!callId || !name) throw new AgentError(\"unknown\", \"The model sent a tool call without an id or a name.\", { provider: \"anthropic\" });\n parts.push({ type: \"tool-call\", callId, name, input: block.input, status: \"pending\" });\n break;\n }\n default: {\n // `tool_result` never appears in an assistant response, so anything\n // else here is a PROVIDER-HOSTED tool record (server_tool_use,\n // web_search_tool_result, …): work done provider-side with no call for\n // us to execute. Surface it as a UI-only artifact so the transcript\n // shows the search happened; it is stripped before the next request.\n const record = block as { type: string; id?: string };\n if (record.type === \"tool_result\") break;\n parts.push({\n type: \"artifact\",\n id: text(record.id) ?? `${record.type}_${parts.length}`,\n kind: `provider-tool:${record.type}`,\n data: record,\n });\n break;\n }\n }\n }\n return parts;\n}\n\nexport function finishFromAnthropic(reason: AnthropicStopReason | null | undefined): FinishReason {\n switch (reason) {\n case \"end_turn\":\n case \"stop_sequence\":\n case \"pause_turn\":\n return \"stop\";\n case \"max_tokens\":\n case \"model_context_window_exceeded\":\n return \"length\";\n case \"tool_use\":\n return \"tool-calls\";\n case \"refusal\":\n return \"content-filter\";\n default:\n return \"unknown\";\n }\n}\n\nexport function usageFromAnthropic(usage: AnthropicUsage | undefined): Usage {\n if (!usage || typeof usage !== \"object\") return {};\n const input = count(usage.input_tokens) ?? 0;\n const output = count(usage.output_tokens) ?? 0;\n const cached = count(usage.cache_read_input_tokens);\n return {\n inputTokens: input,\n outputTokens: output,\n totalTokens: input + output,\n ...(cached !== undefined ? { cachedInputTokens: cached } : {}),\n };\n}\n","// Anthropic SSE dialect → normalized StreamEvents.\n//\n// Shape of the stream: message_start, then per content block a\n// content_block_start / *_delta / *_stop trio (indexed), then message_delta\n// (stop_reason + output usage) and message_stop. Deltas are typed:\n// text_delta, thinking_delta, signature_delta (the thinking replay token,\n// arriving at the END of a thinking block), input_json_delta (tool args).\n\nimport { parseSSEJson } from \"../../transport/sse.js\";\nimport { AgentError } from \"../../errors.js\";\nimport { repairToolArguments } from \"../../tools/repair.js\";\nimport { text } from \"../shared.js\";\nimport type { StreamEvent } from \"../types.js\";\nimport { finishFromAnthropic, usageFromAnthropic } from \"./map-out.js\";\nimport type { AnthropicStreamEvent, AnthropicUsage } from \"./wire.js\";\n\nexport async function* streamAnthropic(body: ReadableStream<Uint8Array>): AsyncGenerator<StreamEvent> {\n type PendingTool = { callId: string; name: string; args: string };\n const toolsByIndex = new Map<number, PendingTool>();\n let inputUsage: AnthropicUsage | undefined;\n let outputUsage: AnthropicUsage | undefined;\n let stopReason: Parameters<typeof finishFromAnthropic>[0] = null;\n\n for await (const frame of parseSSEJson<AnthropicStreamEvent>(body)) {\n const event = frame.data;\n // A compatible server may send a frame that is not an event at all (`data: null`, a bare number) or leave out\n // the part an event is about: skip it rather than end the turn with \"Cannot read properties of undefined\".\n if (event === null || typeof event !== \"object\") continue;\n switch (event.type) {\n case \"message_start\":\n inputUsage = event.message?.usage;\n yield { type: \"start\", responseId: text(event.message?.id), modelId: text(event.message?.model) ?? \"\" };\n break;\n\n case \"content_block_start\": {\n if (event.content_block?.type === \"tool_use\") {\n const callId = text(event.content_block.id);\n const name = text(event.content_block.name);\n if (!callId || !name) {\n yield { type: \"error\", error: { message: \"The model sent a tool call without an id or a name.\", code: \"invalid_upstream_event\" } };\n return;\n }\n const pending: PendingTool = {\n callId,\n name,\n // `input` on the start block is {} — args stream via input_json_delta.\n args: \"\",\n };\n toolsByIndex.set(event.index, pending);\n yield { type: \"tool-call-start\", callId: pending.callId, name: pending.name };\n }\n break;\n }\n\n case \"content_block_delta\": {\n const delta = event.delta;\n if (!delta) break;\n if (delta.type === \"text_delta\") {\n const t = text(delta.text);\n if (t) yield { type: \"text-delta\", delta: t };\n } else if (delta.type === \"thinking_delta\") {\n const t = text(delta.thinking);\n if (t) yield { type: \"reasoning-delta\", delta: t };\n } else if (delta.type === \"signature_delta\") {\n // The replay token arrives at the end of the thinking block. Emit an\n // empty reasoning delta carrying it — the collector stamps it onto\n // the accumulated reasoning part.\n const signature = text(delta.signature);\n if (signature) yield { type: \"reasoning-delta\", delta: \"\", signature };\n } else if (delta.type === \"input_json_delta\") {\n const pending = toolsByIndex.get(event.index);\n const partial = text(delta.partial_json);\n if (pending && partial) {\n pending.args += partial;\n yield { type: \"tool-call-delta\", callId: pending.callId, argsDelta: partial };\n }\n }\n break;\n }\n\n case \"content_block_stop\": {\n const pending = toolsByIndex.get(event.index);\n if (pending) {\n const { value, repaired } = repairToolArguments(pending.args || \"{}\");\n yield { type: \"tool-call-end\", callId: pending.callId, name: pending.name, input: value, repaired };\n toolsByIndex.delete(event.index);\n }\n break;\n }\n\n case \"message_delta\":\n if (event.delta?.stop_reason) stopReason = event.delta.stop_reason;\n if (event.usage) outputUsage = event.usage;\n break;\n\n case \"message_stop\": {\n // Input tokens arrive on message_start, output tokens on message_delta —\n // merge before reporting, or every streamed turn meters as zero input.\n const usage = usageFromAnthropic({ ...(inputUsage ?? {}), ...(outputUsage ?? {}) });\n yield { type: \"usage\", usage };\n yield { type: \"finish\", finishReason: finishFromAnthropic(stopReason), usage };\n return;\n }\n\n case \"error\":\n yield { type: \"error\", error: { message: text(event.error?.message) ?? \"Stream error\", code: text(event.error?.type) } };\n return;\n\n default:\n break; // ping and future event types\n }\n }\n\n // Stream ended without message_stop (dropped connection, proxy timeout). Finishing quietly would show the user a\n // truncated answer as a finished one, so report it; what already streamed stays in the transcript.\n throw new AgentError(\"network\", \"The model's stream ended before it finished.\", { provider: \"anthropic\" });\n}\n","// The Anthropic provider — the second adapter, and the real test of whether\n// the normalized content model holds up (HANDOFF said it would be).\n//\n// Everything speaks POST /messages. There is no background mode, no\n// server-side history, no /files upload here (the Files API is beta and out of\n// scope) — the capabilities object says so instead of the adapter pretending.\n//\n// Auth note: Anthropic wants `x-api-key` (not `Authorization: Bearer`) plus an\n// `anthropic-version` header on every call. The version header is attached\n// per-request below; the key belongs to the transport — use\n// `authStyle: \"x-api-key\"` on a direct transport or proxy provider entry.\n\nimport { AgentError, toAgentError } from \"../../errors.js\";\nimport { errorFromResponse, withRetry } from \"../../transport/retry.js\";\nimport type { RetryPolicy, Transport } from \"../../transport/types.js\";\nimport { readObject, text, withDefaultTimeout } from \"../shared.js\";\nimport type {\n CallOptions,\n GenerateResult,\n ModelInfo,\n NormalizedRequest,\n Provider,\n ProviderCapabilities,\n StreamEvent,\n} from \"../types.js\";\nimport { buildAnthropicRequest } from \"./map-in.js\";\nimport { finishFromAnthropic, partsFromAnthropic, usageFromAnthropic } from \"./map-out.js\";\nimport { streamAnthropic } from \"./stream.js\";\nimport type { AnthropicResponse } from \"./wire.js\";\n\nexport type AnthropicProviderConfig = {\n transport: Transport;\n /** Provider id, so several instances can coexist. Defaults to \"anthropic\". */\n id?: string;\n label?: string;\n retry?: RetryPolicy;\n capabilities?: Partial<ProviderCapabilities>;\n models?: ModelInfo[];\n /** `anthropic-version` header value. */\n version?: string;\n /** `max_tokens` is REQUIRED on this wire; applied when the request has none. */\n defaultMaxTokens?: number;\n};\n\nconst ANTHROPIC_CAPS: ProviderCapabilities = {\n streaming: true,\n backgroundJobs: false,\n resumableStreams: false,\n tools: true,\n parallelToolCalls: true,\n images: true,\n files: true, // document blocks (PDF etc.)\n audio: false,\n reasoning: true,\n strictJsonSchema: true,\n serverSideHistory: false,\n fileUpload: false, // Files API is beta; not implemented here\n};\n\nconst ANTHROPIC_MODELS: ModelInfo[] = [\n { id: \"claude-opus-5\", label: \"Claude Opus 5\", contextWindow: 1_000_000, maxOutputTokens: 128_000 },\n { id: \"claude-sonnet-5\", label: \"Claude Sonnet 5\", contextWindow: 1_000_000, maxOutputTokens: 128_000 },\n { id: \"claude-haiku-4-5\", label: \"Claude Haiku 4.5\", contextWindow: 200_000, maxOutputTokens: 64_000 },\n];\n\nexport function createAnthropicProvider(config: AnthropicProviderConfig): Provider {\n const id = config.id ?? \"anthropic\";\n const version = config.version ?? \"2023-06-01\";\n const capabilities: ProviderCapabilities = { ...ANTHROPIC_CAPS, ...config.capabilities };\n\n async function call(\n body: unknown,\n opts: CallOptions | undefined,\n extra: { stream?: boolean; betas?: string[] } = {},\n ): Promise<Response> {\n // A caller that never passes (or triggers) its own signal must not hang\n // forever on a stalled connection — the default timeout is a floor, not a\n // ceiling: whichever of the two signals fires first wins.\n const signal = withDefaultTimeout(opts?.signal);\n return withRetry(\n async () => {\n const res = await config.transport.fetch({\n provider: id,\n path: \"/messages\",\n method: \"POST\",\n body,\n stream: extra.stream,\n headers: {\n \"anthropic-version\": version,\n ...(extra.betas?.length ? { \"anthropic-beta\": extra.betas.join(\",\") } : {}),\n ...opts?.headers,\n },\n signal,\n });\n if (!res.ok) throw await errorFromResponse(res, id);\n return res;\n },\n { policy: config.retry, signal, provider: id },\n );\n }\n\n /** Everything `guardRequest` and `betasFor` need, computed in one pass over every part. */\n type MediaScan = { hasImage: boolean; hasSilentAudio: boolean; usesOwnFiles: boolean };\n\n /**\n * `guardRequest`'s per-type capability checks and `betasFor`'s \"does this\n * request reference a file this provider instance minted\" check used to\n * each rescan the whole message list independently — up to three full\n * walks of the same parts per call. One pass computes all of it together.\n */\n function scanRequest(req: NormalizedRequest): MediaScan {\n let hasImage = false;\n let hasSilentAudio = false;\n let usesOwnFiles = false;\n for (const m of req.messages) {\n for (const p of m.parts) {\n if (p.type === \"image\") {\n hasImage = true;\n if (p.source.kind === \"providerFile\" && p.source.provider === id) usesOwnFiles = true;\n } else if (p.type === \"file\") {\n if (p.source.kind === \"providerFile\" && p.source.provider === id) usesOwnFiles = true;\n } else if (p.type === \"audio\" && !p.transcript) {\n hasSilentAudio = true;\n }\n }\n }\n return { hasImage, hasSilentAudio, usesOwnFiles };\n }\n\n function guardRequest(req: NormalizedRequest, scan: MediaScan) {\n if (req.background) {\n throw new AgentError(\"not-supported\", `Provider \"${id}\" has no background mode. Use streaming or sync.`, {\n provider: id,\n });\n }\n if (req.responseFormat && req.responseFormat.type === \"json\") {\n throw new AgentError(\n \"not-supported\",\n `Provider \"${id}\" supports responseFormat \"json_schema\", not bare \"json\". Provide a schema.`,\n { provider: id },\n );\n }\n if (!capabilities.images && scan.hasImage) {\n throw new AgentError(\"not-supported\", `Provider \"${id}\" does not accept image parts.`, { provider: id });\n }\n // Audio degrades to transcript text in the builder; only refuse when\n // there is a part with nothing to degrade to.\n if (!capabilities.audio && scan.hasSilentAudio) {\n throw new AgentError(\"not-supported\", `Provider \"${id}\" does not accept audio parts.`, { provider: id });\n }\n }\n\n const buildOpts = (stream?: boolean) => ({\n ...(stream ? { stream: true } : {}),\n providerId: id,\n parallelToolCalls: capabilities.parallelToolCalls,\n defaultMaxTokens: config.defaultMaxTokens,\n });\n\n const applyCapabilities = (req: NormalizedRequest): NormalizedRequest =>\n capabilities.strictJsonSchema || !req.tools?.some((t) => t.strict)\n ? req\n : { ...req, tools: req.tools!.map(({ strict: _strict, ...t }) => t) };\n\n const betasFor = (scan: MediaScan): string[] => (scan.usesOwnFiles ? [\"files-api-2025-04-14\"] : []);\n\n return {\n id,\n label: config.label ?? \"Anthropic\",\n capabilities,\n transport: config.transport,\n\n async generate(rawReq, opts): Promise<GenerateResult> {\n const scan = scanRequest(rawReq);\n guardRequest(rawReq, scan);\n const req = applyCapabilities(rawReq);\n const res = await call(buildAnthropicRequest(req, buildOpts()), opts, { betas: betasFor(scan) });\n const json = (await readObject(res, id)) as AnthropicResponse;\n return {\n parts: partsFromAnthropic(json),\n finishReason: finishFromAnthropic(text(json.stop_reason)),\n usage: usageFromAnthropic(json.usage),\n responseId: text(json.id),\n modelId: text(json.model) ?? req.model,\n raw: json,\n };\n },\n\n async *stream(rawReq, opts): AsyncIterable<StreamEvent> {\n const scan = scanRequest(rawReq);\n guardRequest(rawReq, scan);\n const req = applyCapabilities(rawReq);\n try {\n const res = await call(buildAnthropicRequest(req, buildOpts(true)), opts, {\n stream: true,\n betas: betasFor(scan),\n });\n if (!res.body) throw new AgentError(\"network\", \"Response had no body to stream.\", { provider: id });\n yield* streamAnthropic(res.body);\n } catch (e) {\n yield { type: \"error\", error: toAgentError(e, id) };\n }\n },\n\n async listModels(): Promise<ModelInfo[]> {\n // /models exists but adds an allowlist entry for little gain; a static\n // list mirrors the OpenAI adapter's offline fallback behavior.\n return config.models ?? ANTHROPIC_MODELS;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,IAAM,qBAAqB;AAE3B,SAAS,SAAS,MAAmB,YAAkD;AACrF,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,KAAK,OAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,KAAK,IAAI;AAAA,IACzD,KAAK;AAGH,UAAI,KAAK,YAAY,KAAK,UAAW,QAAO,EAAE,MAAM,qBAAqB,MAAM,KAAK,UAAU;AAC9F,UAAI,KAAK,UAAW,QAAO,EAAE,MAAM,YAAY,UAAU,KAAK,MAAM,WAAW,KAAK,UAAU;AAC9F,aAAO;AAAA,IACT,KAAK,SAAS;AACZ,YAAM,IAAI,KAAK;AACf,UAAI,EAAE,SAAS,MAAO,QAAO,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,OAAO,KAAK,EAAE,IAAI,EAAE;AAClF,UAAI,EAAE,SAAS,UAAU;AACvB,eAAO,EAAE,MAAM,SAAS,QAAQ,EAAE,MAAM,UAAU,YAAY,KAAK,aAAa,aAAa,MAAM,EAAE,KAAK,EAAE;AAAA,MAC9G;AACA,UAAI,EAAE,aAAa,WAAY,QAAO,EAAE,MAAM,QAAQ,MAAM,gBA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IAElB,MAAM,SAAS,QAAQ,MAA+B;AACpD,YAAM,OAAO,YAAY,MAAM;AAC/B,mBAAa,QAAQ,IAAI;AACzB,YAAM,MAAM,kBAAkB,MAAM;AACpC,YAAM,MAAM,MAAM,KAAK,sBAAsB,KAAK,UAAU,CAAC,GAAG,MAAM,EAAE,OAAO,SAAS,IAAI,EAAE,CAAC;AAC/F,YAAM,OAAQ,MAAM,WAAW,KAAK,EAAE;AACtC,aAAO;AAAA,QACL,OAAO,mBAAmB,IAAI;AAAA,QAC9B,cAAc,oBAAoB,KAAK,KAAK,WAAW,CAAC;AAAA,QACxD,OAAO,mBAAmB,KAAK,KAAK;AAAA,QACpC,YAAY,KAAK,KAAK,EAAE;AAAA,QACxB,SAAS,KAAK,KAAK,KAAK,KAAK,IAAI;AAAA,QACjC,KAAK;AAAA,MACP;AAAA,IACF;AAAA,IAEA,OAAO,OAAO,QAAQ,MAAkC;AACtD,YAAM,OAAO,YAAY,MAAM;AAC/B,mBAAa,QAAQ,IAAI;AACzB,YAAM,MAAM,kBAAkB,MAAM;AACpC,UAAI;AACF,cAAM,MAAM,MAAM,KAAK,sBAAsB,KAAK,UAAU,IAAI,CAAC,GAAG,MAAM;AAAA,UACxE,QAAQ;AAAA,UACR,OAAO,SAAS,IAAI;AAAA,QACtB,CAAC;AACD,YAAI,CAAC,IAAI,KAAM,OAAM,IAAI,WAAW,WAAW,mCAAmC,EAAE,UAAU,GAAG,CAAC;AAClG,eAAO,gBAAgB,IAAI,IAAI;AAAA,MACjC,SAAS,GAAG;AACV,cAAM,EAAE,MAAM,SAAS,OAAO,aAAa,GAAG,EAAE,EAAE;AAAA,MACpD;AAAA,IACF;AAAA,IAEA,MAAM,aAAmC;AAGvC,aAAO,OAAO,UAAU;AAAA,IAC1B;AAAA,EACF;AACF;","names":[]}
package/dist/index.d.ts CHANGED
@@ -771,6 +771,64 @@ declare function withQuotes(text: string, quotes: readonly DocumentQuoteRef[]):
771
771
  /** Read quotes back off a message, for re-rendering the chips in history. */
772
772
  declare function quotesOf(metadata: Record<string, unknown> | undefined): DocumentQuoteRef[];
773
773
 
774
+ /** Words the user selected in the conversation and added to the next message. */
775
+ type ExcerptClip = {
776
+ kind: "excerpt";
777
+ /** Stable within a composer, so the same selection added twice is one chip. */
778
+ id: string;
779
+ text: string;
780
+ /** Whose message the words were in, and which one when the host knows. */
781
+ from?: {
782
+ role: "user" | "assistant";
783
+ messageId?: string;
784
+ };
785
+ };
786
+ /** One comment pinned on a document. */
787
+ type AnnotationMark = {
788
+ id: string;
789
+ /** The comment, in the author's own words. */
790
+ note: string;
791
+ /** The words of the document it is pinned to; absent for a comment on a whole block. */
792
+ quote?: string;
793
+ blockId?: string;
794
+ author?: string;
795
+ /** Replies in the thread, oldest first. */
796
+ replies?: {
797
+ author?: string;
798
+ text: string;
799
+ }[];
800
+ };
801
+ /** The comments pinned on one document, ready to ride with the next message. */
802
+ type AnnotationClip = {
803
+ kind: "annotations";
804
+ /** Stable per document, so a second batch for the same document replaces the first. */
805
+ id: string;
806
+ docId: string;
807
+ title: string;
808
+ /** The document's revision when the comments were gathered, when the editor says. */
809
+ revision?: number;
810
+ marks: AnnotationMark[];
811
+ };
812
+ type ContextClip = ExcerptClip | AnnotationClip;
813
+ /** Key under `Message.metadata` where clips are stored for re-rendering. */
814
+ declare const CLIPS_METADATA_KEY = "contextClips";
815
+ /** A clip's text is cut here when it is flattened: one selection is context, not a whole document. */
816
+ declare const MAX_CLIP_CHARS = 8000;
817
+ /** Render clips as the prefix of the user's message. */
818
+ declare function formatClips(clips: readonly ContextClip[]): string;
819
+ /** Prefix `text` with the clips, keeping a blank line between them. */
820
+ declare function withClips(text: string, clips: readonly ContextClip[]): string;
821
+ /**
822
+ * The user's own words, with the clips' prefix taken off: what a message bubble shows beside the
823
+ * chips. A text that does not start with exactly what `withClips` would have written (an edited
824
+ * message, a thread from before clips) comes back unchanged.
825
+ */
826
+ declare function stripClips(text: string, clips: readonly ContextClip[]): string;
827
+ /** Read clips back off a message, for re-rendering the chips in history. */
828
+ declare function clipsOf(metadata: Record<string, unknown> | undefined): ContextClip[];
829
+ /** The words a chip shows for a clip. Plain text, one line, cut to `limit` characters. */
830
+ declare function clipPreview(clip: ContextClip, limit?: number): string;
831
+
774
832
  type AgentErrorKind = "auth" | "rate-limit" | "overloaded" | "timeout" | "network" | "invalid-request" | "content-filter" | "context-length" | "not-supported" | "cancelled" | "tool-error" | "unknown";
775
833
  declare class AgentError extends Error {
776
834
  readonly kind: AgentErrorKind;
@@ -797,10 +855,6 @@ declare class AgentError extends Error {
797
855
  };
798
856
  }
799
857
  declare function isAgentError(e: unknown): e is AgentError;
800
- /**
801
- * Classify anything thrown. Used for errors that never went through an adapter
802
- * (a DNS failure, an aborted signal) and as the fallback in adapter mapping.
803
- */
804
858
  declare function toAgentError(e: unknown, provider?: string): AgentError;
805
859
  /** HTTP status → kind. Shared by every adapter so classification can't drift. */
806
860
  declare function kindFromStatus(status: number): AgentErrorKind;
@@ -3196,4 +3250,4 @@ declare function createMcpSkill(serverName: string, defs: readonly ToolDefinitio
3196
3250
  */
3197
3251
  declare function elicitViaCard(requestCard: (spec: CardSpec) => Promise<unknown>): McpElicitHandler;
3198
3252
 
3199
- export { A2UI_VERSION, type A2uiMessage, ANTHROPIC_OFFICIAL_PROFILE, AgentError, type AgentErrorKind, type AppAction, type AppStateBinding, type AppStateSourceOptions, type AppliedEdit, BUILTIN_CARDS, type BindingScope, type BudgetShares, type BuiltContext, type BuiltinCard, type BuiltinCardKind, CARD_COMPONENT, CARD_ENTRY_PREFIX, CARD_KEY, CARD_PLACEMENTS, CARD_REF_LIMITS, CARD_REF_SCHEME, CallOptions, type CalloutCard, type Card, type CardAction, type CardCarrier, type CardKindDefinition, type CardPlacement, type CardRef, type CardRefEvent, type CardRefHost, type CardRefParse, type CardRefResult, CardRegistry, type CardSpec, type CardTone, type CardValidation, type CardValueFormat, type ChartAnnotation, type ChartCard, type ChartSeries, type ChecklistCard, type ChoiceCard, type CitationsCard, type CodeCard, type CompactionResult, type ComparisonCard, type ConfirmCard, ContentPart, ContextBuilder, type ContextBuilderOptions, type ContextLayer, type ContextSource, type ContextSourceInput, type ContextSourceResult, type ContextTrace, DEFAULT_PRESETS, DEFAULT_STOP_CONDITIONS, type DiffCard, type DirectTransportConfig, type DocumentCard, type DocumentEdit, type DocumentOutlineEntry, type DocumentQuoteRef, type DocumentSnapshot, type DocumentStore, type DocumentToolsOptions, type EditHunk, type EditRejection, type EditResult, type EditReviewCard, type EmailCard, type ExecuteToolOptions, type FileStore, FinishReason, type FormCard, type FormField, type FunnelCard, type GaugeCard, type GenerateImageToolOptions, GenerateResult, type GeneratedMedia, type GeneratedMediaKind, type ImageGenerationRequest, JSONSchema, JobHandle, JobStatus, type KeyValueCard, type LayerId, MAILTO_SAFE_LENGTH, MESSAGE_OVERHEAD_TOKENS, type MailtoLink, type MarkdownBlock, type MarkdownBlockKind, type MarkdownCard, type McpCallResult, McpClient, type McpClientConfig, type McpContent, type McpElicitHandler, type McpElicitRequest, type McpElicitResult, type McpImportOptions, McpRpcError, type McpServerInfo, type McpTool, type MediaCard, type MediaJobHandle, type MediaJobSnapshot, type MediaProvider, type MediaProviderCapabilities, MediaSource, type MemoryEntry, type MemorySourceOptions, type MemoryStore, Message, MessageRole, type MeterSink, type MeteringError, type MeteringRecord, type MeteringSource, type MeteringStatus, ModelInfo, NormalizedRequest, OPENAI_OFFICIAL_PROFILE, type OpenAIImageProviderConfig, PartialJsonParser, type PartialToolCall, type PresetName, type ProfileDirectTransportConfig, type ProgressCard, type ProgressStep, Provider, ProviderCapabilities, ProviderFileRef, type ProviderProfile, type ProviderProtocol, type ProxyEnvelope, type ProxyTransportConfig, QUOTES_METADATA_KEY, type QuoteDrift, type RepairResult, type ResolvedSkill, type RestThreadStoreConfig, type RetrievalDoc, type RetrievalSourceOptions, type RetrievedChunk, type Retriever, RetryPolicy, type RunConfig, type RunEvent, type RunMeteringRecord, type RunMode, type RunState, SSEDecoder, type SSEMessage, SURFACE_A2UI_CATALOG_ID, SURFACE_ARTIFACT_KIND, SURFACE_CARD_KIND, SURFACE_EVENT_METADATA_KEY, SURFACE_FORMAT_VERSION, SURFACE_GUIDE, SURFACE_LIMITS, SURFACE_PRIMITIVES, SURFACE_SKILL_ID, SURFACE_TOOL_NAMES, type SchemaCheckOptions, type SchemaProblem, type SerializedMultipartBody, type Skill, type SkillContext, type SkillMatch, type SkillMatcher, type SkillMode, SkillRegistry, type SkillRegistryOptions, type SkillSection, type SpeechGenerationRequest, type StatItem, type StatsCard, type StepMeteringRecord, type StopCondition, type StopContext, type StoredFile, type StoredThread, type Summarizer, type SurfaceAction, type SurfaceActivity, type SurfaceActivityState, type SurfaceAggregateOp, type SurfaceBinding, type SurfaceBuildContext, type SurfaceBuildResult, type SurfaceCardAnswer, SurfaceCatalogue, type SurfaceCatalogueOptions, type SurfaceComponent, type SurfaceComponentCategory, type SurfaceComponentDefinition, type SurfaceCondition, type SurfaceConditionOp, type SurfaceEventRecord, type SurfaceIssue, type SurfaceIssueCode, type SurfaceItemBinding, SurfaceLedger, type SurfaceOperation, type SurfacePathBinding, type SurfacePendingPart, type SurfaceQuery, type SurfaceQueryBinding, type SurfaceSpec, type SurfaceTemplateBinding, type SurfaceToolAuthorization, type SurfaceToolRunConfig, type SurfaceToolsOptions, type SurfaceValidationContext, type SurfaceWhere, type SurfaceWhereOp, THREAD_SCHEMA_VERSION, type TableCard, type TableColumn, type ThreadMeta, type ThreadStore, type TimelineCard, type TokenBudget, type TokenCounter, type ToolApproval, type ToolCallOutcome, type ToolCallRequest, ToolCallStatus, type ToolDefinition, type ToolDisplay, type ToolExecutionContext, ToolFailureKind, type ToolLoading, type ToolLoadingHint, ToolRegistry, type ToolResolution, type ToolResult, type ToolResultExtras, type ToolSide, ToolSpec, type TraceEntry, type Transcript, type TranscriptionRequest, Transport, TransportRequest, type TreeCard, type TreeNode, type TurnLayoutOptions, type TurnSegment, USER_DECLINED, type UnsafeFinding, Usage, type VideoGenerationRequest, type VisualizePlacement, type VisualizeToolOptions, afterTool, appendReasoning, appendText, applyEdits, applySurfaceOperations, approvalCard, assistantMessage, authorizeSurfaceTool, backoffDelay, base64ToBytes, bindingProblems, buildEml, buildMailto, buildSummaryPrompt, buildSurface, buildUrl, bytesToBase64, calloutCard, chartCard, check, checkQuoteDrift, checkSchema, checklistCard, childrenOf, choiceCard, citationsCard, codeCard, combineMeteringSources, compactError, compactHistory, comparisonCard, confirmCard, consecutiveFailures, countMessageTokens, countMessagesTokens, createAppActionTools, createAppStateSource, createBudget, createBuiltinTools, createDirectTransport, createDirectTransportForProfile, createDocumentTools, createEmailDraftTool, createGenerateImageTool, createHttpTransport, createKeywordRetriever, createLoadSkillTool, createLocalDocumentStore, createLocalFileStore, createLocalMemoryStore, createLocalThreadStore, createMcpSkill, createMemoryDocumentStore, createMemoryFileStore, createMemoryMemoryStore, createMemorySource, createMemoryThreadStore, createOpenAICompatibleProfile, createOpenAIImageProvider, createProviderFromProfile, createProxyTransport, createRememberTool, createRestThreadStore, createRetrievalSource, createSurfaceContextSource, createSurfaceSkill, createSurfaceTools, createUpdateCardTool, createVisualizeTool, deliverMetering, diffCard, documentCard, editReviewCard, elicitViaCard, emailCard, emlFilename, errorFromResponse, estimateJsonTokens, estimateTokens, evaluateSurfaceCondition, executeToolCall, executeToolCalls, file, findUnsafe, foldSurfaces, formCard, formatQuotes, formatTemplate, funnelCard, gaugeCard, generatedMediaUrl, getAt, hasTurnOrder, humanizeFieldName, hunksOf, image, importMcpTools, initialRunState, isAgentError, isCardCarrier, isCardPlacement, isScriptUrl, isSurfaceBinding, isSurfaceId, isSurfaceSpec, isTextPart, isToolCallPart, isToolResultPart, isUserDecline, keyValueCard, kindFromStatus, lastUserText, latestLeaf, layoutTurn, linkLinear, makeCard, mapMcpResult, markdownCard, matchSkills, mediaCard, message, messageText, nextId, noToolCalls, normalizeProviderProfile, normalizeToolName, outlineOf, packByPriority, parseCardRef, parsePartialJson, parsePointer, parseRetryAfter, parseSSE, parseSSEJson, pathTo, previewSurface, progressCard, quoteDrift, quotesOf, reduceRunEvent, removeAt, renderSkill, repairToolArguments, resolvePartialCard, resolveSurfaceAction, resolveSurfaceValue, resolveToolLoading, runAgent, runSurfaceQuery, runSurfaceToolAction, safeCutIndex, safeSurfaceUrl, sanitizeSurfaceSpec, scoreSkill, searchBlocks, setAt, shouldStop, siblingsOf, spanOf, splitBlocks, statsCard, stepCountIs, stripCardPayload, stripUiOnlyParts, surfaceActionTools, surfaceCardId, tableCard, text, threadSnapshot, timelineCard, toA2uiMessages, toAgentError, tokenBudgetExceeded, tokenize, toolCall, toolCallsIn, toolResult, totalAllocated, treeCard, trimHistory, usageSource, userDeclined, userMessage, usesBinding, validateSurfaceAction, validateSurfaceComponent, validateSurfaceComponents, validateSurfaceGraph, withCard, withQuotes, withRetry };
3253
+ export { A2UI_VERSION, type A2uiMessage, ANTHROPIC_OFFICIAL_PROFILE, AgentError, type AgentErrorKind, type AnnotationClip, type AnnotationMark, type AppAction, type AppStateBinding, type AppStateSourceOptions, type AppliedEdit, BUILTIN_CARDS, type BindingScope, type BudgetShares, type BuiltContext, type BuiltinCard, type BuiltinCardKind, CARD_COMPONENT, CARD_ENTRY_PREFIX, CARD_KEY, CARD_PLACEMENTS, CARD_REF_LIMITS, CARD_REF_SCHEME, CLIPS_METADATA_KEY, CallOptions, type CalloutCard, type Card, type CardAction, type CardCarrier, type CardKindDefinition, type CardPlacement, type CardRef, type CardRefEvent, type CardRefHost, type CardRefParse, type CardRefResult, CardRegistry, type CardSpec, type CardTone, type CardValidation, type CardValueFormat, type ChartAnnotation, type ChartCard, type ChartSeries, type ChecklistCard, type ChoiceCard, type CitationsCard, type CodeCard, type CompactionResult, type ComparisonCard, type ConfirmCard, ContentPart, ContextBuilder, type ContextBuilderOptions, type ContextClip, type ContextLayer, type ContextSource, type ContextSourceInput, type ContextSourceResult, type ContextTrace, DEFAULT_PRESETS, DEFAULT_STOP_CONDITIONS, type DiffCard, type DirectTransportConfig, type DocumentCard, type DocumentEdit, type DocumentOutlineEntry, type DocumentQuoteRef, type DocumentSnapshot, type DocumentStore, type DocumentToolsOptions, type EditHunk, type EditRejection, type EditResult, type EditReviewCard, type EmailCard, type ExcerptClip, type ExecuteToolOptions, type FileStore, FinishReason, type FormCard, type FormField, type FunnelCard, type GaugeCard, type GenerateImageToolOptions, GenerateResult, type GeneratedMedia, type GeneratedMediaKind, type ImageGenerationRequest, JSONSchema, JobHandle, JobStatus, type KeyValueCard, type LayerId, MAILTO_SAFE_LENGTH, MAX_CLIP_CHARS, MESSAGE_OVERHEAD_TOKENS, type MailtoLink, type MarkdownBlock, type MarkdownBlockKind, type MarkdownCard, type McpCallResult, McpClient, type McpClientConfig, type McpContent, type McpElicitHandler, type McpElicitRequest, type McpElicitResult, type McpImportOptions, McpRpcError, type McpServerInfo, type McpTool, type MediaCard, type MediaJobHandle, type MediaJobSnapshot, type MediaProvider, type MediaProviderCapabilities, MediaSource, type MemoryEntry, type MemorySourceOptions, type MemoryStore, Message, MessageRole, type MeterSink, type MeteringError, type MeteringRecord, type MeteringSource, type MeteringStatus, ModelInfo, NormalizedRequest, OPENAI_OFFICIAL_PROFILE, type OpenAIImageProviderConfig, PartialJsonParser, type PartialToolCall, type PresetName, type ProfileDirectTransportConfig, type ProgressCard, type ProgressStep, Provider, ProviderCapabilities, ProviderFileRef, type ProviderProfile, type ProviderProtocol, type ProxyEnvelope, type ProxyTransportConfig, QUOTES_METADATA_KEY, type QuoteDrift, type RepairResult, type ResolvedSkill, type RestThreadStoreConfig, type RetrievalDoc, type RetrievalSourceOptions, type RetrievedChunk, type Retriever, RetryPolicy, type RunConfig, type RunEvent, type RunMeteringRecord, type RunMode, type RunState, SSEDecoder, type SSEMessage, SURFACE_A2UI_CATALOG_ID, SURFACE_ARTIFACT_KIND, SURFACE_CARD_KIND, SURFACE_EVENT_METADATA_KEY, SURFACE_FORMAT_VERSION, SURFACE_GUIDE, SURFACE_LIMITS, SURFACE_PRIMITIVES, SURFACE_SKILL_ID, SURFACE_TOOL_NAMES, type SchemaCheckOptions, type SchemaProblem, type SerializedMultipartBody, type Skill, type SkillContext, type SkillMatch, type SkillMatcher, type SkillMode, SkillRegistry, type SkillRegistryOptions, type SkillSection, type SpeechGenerationRequest, type StatItem, type StatsCard, type StepMeteringRecord, type StopCondition, type StopContext, type StoredFile, type StoredThread, type Summarizer, type SurfaceAction, type SurfaceActivity, type SurfaceActivityState, type SurfaceAggregateOp, type SurfaceBinding, type SurfaceBuildContext, type SurfaceBuildResult, type SurfaceCardAnswer, SurfaceCatalogue, type SurfaceCatalogueOptions, type SurfaceComponent, type SurfaceComponentCategory, type SurfaceComponentDefinition, type SurfaceCondition, type SurfaceConditionOp, type SurfaceEventRecord, type SurfaceIssue, type SurfaceIssueCode, type SurfaceItemBinding, SurfaceLedger, type SurfaceOperation, type SurfacePathBinding, type SurfacePendingPart, type SurfaceQuery, type SurfaceQueryBinding, type SurfaceSpec, type SurfaceTemplateBinding, type SurfaceToolAuthorization, type SurfaceToolRunConfig, type SurfaceToolsOptions, type SurfaceValidationContext, type SurfaceWhere, type SurfaceWhereOp, THREAD_SCHEMA_VERSION, type TableCard, type TableColumn, type ThreadMeta, type ThreadStore, type TimelineCard, type TokenBudget, type TokenCounter, type ToolApproval, type ToolCallOutcome, type ToolCallRequest, ToolCallStatus, type ToolDefinition, type ToolDisplay, type ToolExecutionContext, ToolFailureKind, type ToolLoading, type ToolLoadingHint, ToolRegistry, type ToolResolution, type ToolResult, type ToolResultExtras, type ToolSide, ToolSpec, type TraceEntry, type Transcript, type TranscriptionRequest, Transport, TransportRequest, type TreeCard, type TreeNode, type TurnLayoutOptions, type TurnSegment, USER_DECLINED, type UnsafeFinding, Usage, type VideoGenerationRequest, type VisualizePlacement, type VisualizeToolOptions, afterTool, appendReasoning, appendText, applyEdits, applySurfaceOperations, approvalCard, assistantMessage, authorizeSurfaceTool, backoffDelay, base64ToBytes, bindingProblems, buildEml, buildMailto, buildSummaryPrompt, buildSurface, buildUrl, bytesToBase64, calloutCard, chartCard, check, checkQuoteDrift, checkSchema, checklistCard, childrenOf, choiceCard, citationsCard, clipPreview, clipsOf, codeCard, combineMeteringSources, compactError, compactHistory, comparisonCard, confirmCard, consecutiveFailures, countMessageTokens, countMessagesTokens, createAppActionTools, createAppStateSource, createBudget, createBuiltinTools, createDirectTransport, createDirectTransportForProfile, createDocumentTools, createEmailDraftTool, createGenerateImageTool, createHttpTransport, createKeywordRetriever, createLoadSkillTool, createLocalDocumentStore, createLocalFileStore, createLocalMemoryStore, createLocalThreadStore, createMcpSkill, createMemoryDocumentStore, createMemoryFileStore, createMemoryMemoryStore, createMemorySource, createMemoryThreadStore, createOpenAICompatibleProfile, createOpenAIImageProvider, createProviderFromProfile, createProxyTransport, createRememberTool, createRestThreadStore, createRetrievalSource, createSurfaceContextSource, createSurfaceSkill, createSurfaceTools, createUpdateCardTool, createVisualizeTool, deliverMetering, diffCard, documentCard, editReviewCard, elicitViaCard, emailCard, emlFilename, errorFromResponse, estimateJsonTokens, estimateTokens, evaluateSurfaceCondition, executeToolCall, executeToolCalls, file, findUnsafe, foldSurfaces, formCard, formatClips, formatQuotes, formatTemplate, funnelCard, gaugeCard, generatedMediaUrl, getAt, hasTurnOrder, humanizeFieldName, hunksOf, image, importMcpTools, initialRunState, isAgentError, isCardCarrier, isCardPlacement, isScriptUrl, isSurfaceBinding, isSurfaceId, isSurfaceSpec, isTextPart, isToolCallPart, isToolResultPart, isUserDecline, keyValueCard, kindFromStatus, lastUserText, latestLeaf, layoutTurn, linkLinear, makeCard, mapMcpResult, markdownCard, matchSkills, mediaCard, message, messageText, nextId, noToolCalls, normalizeProviderProfile, normalizeToolName, outlineOf, packByPriority, parseCardRef, parsePartialJson, parsePointer, parseRetryAfter, parseSSE, parseSSEJson, pathTo, previewSurface, progressCard, quoteDrift, quotesOf, reduceRunEvent, removeAt, renderSkill, repairToolArguments, resolvePartialCard, resolveSurfaceAction, resolveSurfaceValue, resolveToolLoading, runAgent, runSurfaceQuery, runSurfaceToolAction, safeCutIndex, safeSurfaceUrl, sanitizeSurfaceSpec, scoreSkill, searchBlocks, setAt, shouldStop, siblingsOf, spanOf, splitBlocks, statsCard, stepCountIs, stripCardPayload, stripClips, stripUiOnlyParts, surfaceActionTools, surfaceCardId, tableCard, text, threadSnapshot, timelineCard, toA2uiMessages, toAgentError, tokenBudgetExceeded, tokenize, toolCall, toolCallsIn, toolResult, totalAllocated, treeCard, trimHistory, usageSource, userDeclined, userMessage, usesBinding, validateSurfaceAction, validateSurfaceComponent, validateSurfaceComponents, validateSurfaceGraph, withCard, withClips, withQuotes, withRetry };
package/dist/index.js CHANGED
@@ -8,11 +8,11 @@ import {
8
8
  isTerminal,
9
9
  reap,
10
10
  resumeJobs
11
- } from "./chunk-WFU4HXUG.js";
11
+ } from "./chunk-HKGDZQS6.js";
12
12
  import {
13
13
  buildAnthropicRequest,
14
14
  createAnthropicProvider
15
- } from "./chunk-KUB5GKAM.js";
15
+ } from "./chunk-ZMPT7BBM.js";
16
16
  import {
17
17
  AgentError,
18
18
  DEFAULT_RETRY,
@@ -31,7 +31,7 @@ import {
31
31
  text,
32
32
  toAgentError,
33
33
  withRetry
34
- } from "./chunk-7G4U4NTL.js";
34
+ } from "./chunk-CJ6WV4KB.js";
35
35
 
36
36
  // src/content/parts.ts
37
37
  var counter = 0;
@@ -338,6 +338,73 @@ function quotesOf(metadata) {
338
338
  return Array.isArray(raw) ? raw : [];
339
339
  }
340
340
 
341
+ // src/content/clips.ts
342
+ var CLIPS_METADATA_KEY = "contextClips";
343
+ var MAX_CLIP_CHARS = 8e3;
344
+ var fence2 = (text4) => {
345
+ const longest = [...text4.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);
346
+ return "`".repeat(longest + 1);
347
+ };
348
+ var clipped = (text4) => text4.length > MAX_CLIP_CHARS ? `${text4.slice(0, MAX_CLIP_CHARS)}
349
+ [cut: the selection is longer than ${MAX_CLIP_CHARS} characters]` : text4;
350
+ var oneLine = (text4) => text4.trim().replace(/\s+/g, " ");
351
+ function formatExcerpt(clip3) {
352
+ const source = clip3.from?.role === "user" ? "the user's own earlier message" : "an earlier answer in this conversation";
353
+ const body = clipped(clip3.text);
354
+ const f = fence2(body);
355
+ return `Excerpt the user selected from ${source}:
356
+ ${f}text
357
+ ${body}
358
+ ${f}`;
359
+ }
360
+ function formatAnnotations(clip3) {
361
+ const count = clip3.marks.length;
362
+ const where = `${JSON.stringify(clip3.title)} (${clip3.docId}${clip3.revision === void 0 ? "" : ` v${clip3.revision}`})`;
363
+ const lines = clip3.marks.map((mark, i) => {
364
+ const on = mark.quote ? `On "${oneLine(clipped(mark.quote))}"` : mark.blockId ? `On block ${mark.blockId}` : "On the document";
365
+ const block = mark.quote && mark.blockId ? ` (block ${mark.blockId})` : "";
366
+ const who = mark.author ? ` \u2014 ${mark.author}` : "";
367
+ const replies = (mark.replies ?? []).map((r) => `
368
+ Reply${r.author ? ` from ${r.author}` : ""}: ${oneLine(r.text)}`).join("");
369
+ return `${i + 1}. ${on}${block}: ${oneLine(clipped(mark.note))}${who}${replies}`;
370
+ });
371
+ return `The user pinned ${count === 1 ? "1 annotation" : `${count} annotations`} on the document ${where}. They are comments about places in the document, not part of its text:
372
+ ${lines.join("\n")}`;
373
+ }
374
+ function formatClips(clips) {
375
+ return clips.filter((c) => c.kind === "excerpt" ? c.text.trim() : c.marks.length > 0).map((c) => c.kind === "excerpt" ? formatExcerpt(c) : formatAnnotations(c)).join("\n\n");
376
+ }
377
+ function withClips(text4, clips) {
378
+ const prefix = formatClips(clips);
379
+ if (!prefix) return text4;
380
+ return text4.trim() ? `${prefix}
381
+
382
+ ${text4}` : prefix;
383
+ }
384
+ function stripClips(text4, clips) {
385
+ const prefix = formatClips(clips);
386
+ if (!prefix || !text4.startsWith(prefix)) return text4;
387
+ return text4.slice(prefix.length).replace(/^\n+/, "");
388
+ }
389
+ function clipsOf(metadata) {
390
+ const raw = metadata?.[CLIPS_METADATA_KEY];
391
+ if (!Array.isArray(raw)) return [];
392
+ return raw.filter((c) => {
393
+ if (!c || typeof c !== "object") return false;
394
+ const clip3 = c;
395
+ if (clip3.kind === "excerpt") return typeof clip3.id === "string" && typeof clip3.text === "string";
396
+ if (clip3.kind === "annotations") {
397
+ return typeof clip3.id === "string" && typeof clip3.docId === "string" && typeof clip3.title === "string" && Array.isArray(clip3.marks);
398
+ }
399
+ return false;
400
+ });
401
+ }
402
+ function clipPreview(clip3, limit = 90) {
403
+ const text4 = clip3.kind === "excerpt" ? clip3.text : clip3.marks.map((m) => m.note).filter(Boolean).join(" \xB7 ");
404
+ const flat = oneLine(text4);
405
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}\u2026` : flat;
406
+ }
407
+
341
408
  // src/transport/binary.ts
342
409
  var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
343
410
  var REVERSE = /* @__PURE__ */ (() => {
@@ -6022,6 +6089,9 @@ async function* runAgent(messages, config) {
6022
6089
  const meteringSources = [];
6023
6090
  const reportedModels = /* @__PURE__ */ new Set();
6024
6091
  try {
6092
+ if (!Number.isFinite(maxSteps) || maxSteps < 1) {
6093
+ throw new AgentError("invalid-request", `maxSteps must be a number of at least 1, not ${String(config.maxSteps)}.`, { provider: config.provider.id });
6094
+ }
6025
6095
  const baseTools = config.tools.resolve(config.toolResolution);
6026
6096
  const context = await config.contextBuilder.build({
6027
6097
  messages: history,
@@ -6803,7 +6873,7 @@ function createLocalMemoryStore(storageKey = "superchat:memory", opts = {}) {
6803
6873
  }
6804
6874
  };
6805
6875
  }
6806
- var oneLine = (text4) => String(text4).replace(/\s*[\r\n]+\s*/g, " ");
6876
+ var oneLine2 = (text4) => String(text4).replace(/\s*[\r\n]+\s*/g, " ");
6807
6877
  var clip2 = (text4) => {
6808
6878
  const value = String(text4);
6809
6879
  return value.length > MAX_VALUE_CHARS2 ? `${value.slice(0, MAX_VALUE_CHARS2)}\u2026` : value;
@@ -6816,7 +6886,7 @@ function createMemorySource(store, opts = {}) {
6816
6886
  if (!entries.length) return {};
6817
6887
  const text4 = [
6818
6888
  "Things you remember about this user, from earlier conversations:",
6819
- ...entries.map((e) => `- ${oneLine(e.key)}: ${oneLine(clip2(e.value))}`),
6889
+ ...entries.map((e) => `- ${oneLine2(e.key)}: ${oneLine2(clip2(e.value))}`),
6820
6890
  "Apply them without re-asking. Update them with the `remember` tool when they change."
6821
6891
  ].join("\n");
6822
6892
  return {
@@ -7412,12 +7482,14 @@ export {
7412
7482
  CARD_PLACEMENTS,
7413
7483
  CARD_REF_LIMITS,
7414
7484
  CARD_REF_SCHEME,
7485
+ CLIPS_METADATA_KEY,
7415
7486
  CardRegistry,
7416
7487
  ContextBuilder,
7417
7488
  DEFAULT_PRESETS,
7418
7489
  DEFAULT_RETRY,
7419
7490
  DEFAULT_STOP_CONDITIONS,
7420
7491
  MAILTO_SAFE_LENGTH,
7492
+ MAX_CLIP_CHARS,
7421
7493
  MESSAGE_OVERHEAD_TOKENS,
7422
7494
  McpClient,
7423
7495
  McpRpcError,
@@ -7471,6 +7543,8 @@ export {
7471
7543
  childrenOf,
7472
7544
  choiceCard,
7473
7545
  citationsCard,
7546
+ clipPreview,
7547
+ clipsOf,
7474
7548
  codeCard,
7475
7549
  combineMeteringSources,
7476
7550
  compactError,
@@ -7535,6 +7609,7 @@ export {
7535
7609
  findUnsafe,
7536
7610
  foldSurfaces,
7537
7611
  formCard,
7612
+ formatClips,
7538
7613
  formatQuotes,
7539
7614
  formatTemplate,
7540
7615
  funnelCard,
@@ -7616,6 +7691,7 @@ export {
7616
7691
  statsCard,
7617
7692
  stepCountIs,
7618
7693
  stripCardPayload,
7694
+ stripClips,
7619
7695
  stripUiOnlyParts,
7620
7696
  surfaceActionTools,
7621
7697
  surfaceCardId,
@@ -7642,6 +7718,7 @@ export {
7642
7718
  validateSurfaceComponents,
7643
7719
  validateSurfaceGraph,
7644
7720
  withCard,
7721
+ withClips,
7645
7722
  withQuotes,
7646
7723
  withRetry
7647
7724
  };