@supersolutions/super-chat-core 0.4.3 → 0.4.4
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/index.d.ts +31 -3
- package/dist/index.js +15 -6
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/content/parts.ts","../src/content/branching.ts","../src/content/blocks.ts","../src/content/turn-layout.ts","../src/content/quotes.ts","../src/transport/binary.ts","../src/transport/direct.ts","../src/transport/proxy.ts","../src/providers/profile.ts","../src/media/types.ts","../src/media/openai.ts","../src/media/tools.ts","../src/tokens/estimate.ts","../src/tokens/budget.ts","../src/skills/match.ts","../src/skills/registry.ts","../src/cards/types.ts","../src/context/compaction.ts","../src/context/builder.ts","../src/documents/edit.ts","../src/documents/store.ts","../src/documents/tools.ts","../src/documents/email.ts","../src/cards/registry.ts","../src/cards/card-ref.ts","../src/cards/builtin.ts","../src/surfaces/types.ts","../src/surfaces/pointer.ts","../src/surfaces/safety.ts","../src/surfaces/schema-check.ts","../src/surfaces/bindings.ts","../src/surfaces/primitives.ts","../src/surfaces/catalogue.ts","../src/surfaces/validate.ts","../src/surfaces/operations.ts","../src/surfaces/ledger.ts","../src/surfaces/tools.ts","../src/surfaces/disclosure.ts","../src/runtime/channel.ts","../src/tools/approval.ts","../src/runtime/execute-tools.ts","../src/runtime/metering.ts","../src/surfaces/action-run.ts","../src/surfaces/a2ui.ts","../src/tools/types.ts","../src/tools/registry.ts","../src/tools/partial-json.ts","../src/tools/builtin.ts","../src/runtime/events.ts","../src/runtime/stop.ts","../src/runtime/run.ts","../src/runtime/files.ts","../src/runtime/threads.ts","../src/memory/memory.ts","../src/retrieval/retrieval.ts","../src/app-state/app-state.ts","../src/mcp/client.ts","../src/mcp/import.ts"],"sourcesContent":["// Constructors, guards and small readers for the content model. Kept dependency\n// free so both the browser bundle and a server route can use them.\n\nimport type {\n ContentPart,\n MediaSource,\n Message,\n MessageRole,\n ToolCallStatus,\n ToolFailureKind,\n} from \"./types.js\";\n\nlet counter = 0;\n/**\n * Monotonic id. Deliberately not `crypto.randomUUID()` — ids show up in test\n * snapshots and in `previous_response_id` correlation logs, and a stable,\n * readable prefix is worth more here than global uniqueness. Callers that need\n * cross-device uniqueness pass their own id.\n */\nexport function nextId(prefix = \"msg\"): string {\n counter += 1;\n return `${prefix}_${Date.now().toString(36)}${counter.toString(36)}`;\n}\n\nexport const text = (value: string): ContentPart => ({ type: \"text\", text: value });\n\nexport const image = (\n source: MediaSource,\n opts: { mediaType?: string; detail?: \"auto\" | \"low\" | \"high\" } = {},\n): ContentPart => ({ type: \"image\", source, ...opts });\n\nexport const file = (source: MediaSource, mediaType: string, filename?: string): ContentPart => ({\n type: \"file\",\n source,\n mediaType,\n ...(filename ? { filename } : {}),\n});\n\nexport const toolCall = (\n callId: string,\n name: string,\n input: unknown,\n opts: { status?: ToolCallStatus; repaired?: boolean } = {},\n): ContentPart => ({ type: \"tool-call\", callId, name, input, status: opts.status ?? \"pending\", ...opts });\n\nexport const toolResult = (\n callId: string,\n name: string,\n output: unknown,\n opts: { failure?: ToolFailureKind; render?: string } = {},\n): ContentPart => ({ type: \"tool-result\", callId, name, output, ...opts });\n\nexport function message(role: MessageRole, parts: ContentPart[] | string, id?: string): Message {\n return {\n id: id ?? nextId(role === \"assistant\" ? \"asst\" : role),\n role,\n parts: typeof parts === \"string\" ? [text(parts)] : parts,\n createdAt: Date.now(),\n };\n}\n\nexport const userMessage = (parts: ContentPart[] | string, id?: string) => message(\"user\", parts, id);\nexport const assistantMessage = (parts: ContentPart[] | string, id?: string) => message(\"assistant\", parts, id);\n\nexport const isTextPart = (p: ContentPart): p is Extract<ContentPart, { type: \"text\" }> => p.type === \"text\";\nexport const isToolCallPart = (p: ContentPart): p is Extract<ContentPart, { type: \"tool-call\" }> =>\n p.type === \"tool-call\";\nexport const isToolResultPart = (p: ContentPart): p is Extract<ContentPart, { type: \"tool-result\" }> =>\n p.type === \"tool-result\";\n\n/** Concatenated text of a message — the \"what did it actually say\" reader. */\nexport function messageText(m: Message): string {\n return m.parts.filter(isTextPart).map((p) => p.text).join(\"\");\n}\n\n/** Last user-authored text in a thread. Drives skill matching and intent checks. */\nexport function lastUserText(messages: readonly Message[]): string {\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i];\n if (m && m.role === \"user\") return messageText(m).trim();\n }\n return \"\";\n}\n\nexport function toolCallsIn(messages: readonly Message[]): Extract<ContentPart, { type: \"tool-call\" }>[] {\n return messages.flatMap((m) => m.parts.filter(isToolCallPart));\n}\n\n/**\n * Merge streamed text deltas into the trailing text part instead of appending a\n * new part per token — otherwise a 2k-token reply becomes 2k parts and every\n * React render walks all of them.\n */\nexport function appendText(parts: ContentPart[], delta: string): ContentPart[] {\n const last = parts[parts.length - 1];\n if (last && last.type === \"text\") {\n return [...parts.slice(0, -1), { type: \"text\", text: last.text + delta }];\n }\n return [...parts, { type: \"text\", text: delta }];\n}\n\n/** Same merge, for reasoning streams (which arrive interleaved with text). */\nexport function appendReasoning(parts: ContentPart[], delta: string, signature?: string): ContentPart[] {\n const last = parts[parts.length - 1];\n if (last && last.type === \"reasoning\") {\n return [\n ...parts.slice(0, -1),\n { ...last, text: last.text + delta, ...(signature ? { signature } : {}) },\n ];\n }\n return [...parts, { type: \"reasoning\", text: delta, ...(signature ? { signature } : {}) }];\n}\n\n/**\n * Strip parts that exist only for the UI. Artifacts are host-rendered and have\n * no provider representation; sending them would either 400 or waste tokens on\n * a JSON blob the model can't act on.\n */\nexport function stripUiOnlyParts(m: Message): Message {\n const parts = m.parts.filter((p) => p.type !== \"artifact\");\n return parts.length === m.parts.length ? m : { ...m, parts };\n}\n","// Branching over a flat message list.\n//\n// The tree is stored FLAT — an array of messages with `parentId` pointers —\n// because that is what serializes, diffs and persists cleanly. These helpers\n// derive everything else: the active path (what the UI renders and the run\n// consumes), siblings (the \"< 2/3 >\" switcher), and leaves (where a switched\n// branch resumes). A thread with no branching is the degenerate case: every\n// message's parent is the previous one and the path IS the array.\n\nimport type { Message } from \"./types.js\";\n\n/** Root-first path from the root to `headId`. Unknown/missing head → []. */\nexport function pathTo(tree: readonly Message[], headId: string | null | undefined): Message[] {\n if (!headId) return [];\n const byId = new Map(tree.map((m) => [m.id, m]));\n const path: Message[] = [];\n let cursor = byId.get(headId);\n const seen = new Set<string>(); // cycle guard — corrupted data must not hang the UI\n while (cursor && !seen.has(cursor.id)) {\n seen.add(cursor.id);\n path.push(cursor);\n cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;\n }\n return path.reverse();\n}\n\n/** parentId → children, in tree insertion order. Built once per call site that needs repeated lookups. */\nfunction indexByParent(tree: readonly Message[]): Map<string | null, Message[]> {\n const index = new Map<string | null, Message[]>();\n for (const m of tree) {\n const parentId = m.parentId ?? null;\n const kids = index.get(parentId);\n if (kids) kids.push(m);\n else index.set(parentId, [m]);\n }\n return index;\n}\n\n/** Direct children of `parentId` (null = roots), in tree insertion order. */\nexport function childrenOf(tree: readonly Message[], parentId: string | null): Message[] {\n return indexByParent(tree).get(parentId) ?? [];\n}\n\n/** The message plus its siblings (shared parent), in insertion order. */\nexport function siblingsOf(tree: readonly Message[], id: string): Message[] {\n const self = tree.find((m) => m.id === id);\n if (!self) return [];\n return indexByParent(tree).get(self.parentId ?? null) ?? [];\n}\n\n/**\n * Deepest descendant of `fromId`, following the LATEST child at each level —\n * switching to a branch resumes at where that branch last left off.\n */\nexport function latestLeaf(tree: readonly Message[], fromId: string): string {\n // Built once here rather than via repeated `childrenOf` scans — one O(n)\n // pass instead of one per level of depth.\n const index = indexByParent(tree);\n let cursor = fromId;\n const seen = new Set<string>();\n for (;;) {\n if (seen.has(cursor)) return cursor;\n seen.add(cursor);\n const kids = index.get(cursor) ?? [];\n if (!kids.length) return cursor;\n cursor = kids[kids.length - 1]!.id;\n }\n}\n\n/**\n * Give a linear (pre-branching) message list its parent pointers. Used to\n * migrate v1 stored threads and to accept plain arrays as `initialMessages`.\n * Messages that already carry a parentId are left untouched.\n */\nexport function linkLinear(messages: readonly Message[]): Message[] {\n if (messages.some((m) => m.parentId !== undefined)) return [...messages];\n return messages.map((m, i) => ({ ...m, parentId: i === 0 ? null : messages[i - 1]!.id }));\n}\n","// Block structure of a Markdown source, addressed by offsets.\n//\n// This lives in core rather than beside the renderer because two very different\n// consumers have to agree on it exactly: the previewer, which turns a DOM\n// selection into a block index, and the edit protocol, which resolves that same\n// index back to text it is allowed to rewrite. Two implementations would drift,\n// and the drift would be silent — a quote pointing at block 4 and an edit\n// landing in block 5 both look fine until someone reads the result.\n//\n// Which is exactly why the first version's shortcuts had to go. It matched a\n// fence with `startsWith(\"```\")` and nothing else, so a four-backtick block\n// containing a three-backtick one closed on the inner fence and shattered into\n// four blocks with the code stranded in the middle as prose — and a `~~~` fence\n// was not a fence at all, which left the NEXT ``` in the document opening one\n// that ran to the end. Both produce anchors that point at the wrong text while\n// the page still renders plausibly, which is the failure mode this file exists\n// to prevent.\n\nexport type MarkdownBlockKind =\n /** A fenced code block, ``` or ~~~. Verbatim: no inline transforms. */\n | \"fence\"\n /** An indented (four-space or tab) code block. Also verbatim. */\n | \"code\"\n /** Everything else: a paragraph, heading, list, quote or table. */\n | \"text\";\n\n/** A top-level block, addressed by its half-open span in the SOURCE string. */\nexport type MarkdownBlock = {\n start: number;\n end: number;\n kind: MarkdownBlockKind;\n};\n\ntype Line = { text: string; start: number; end: number };\n\nfunction scanLines(src: string): Line[] {\n const out: Line[] = [];\n let start = 0;\n for (let i = 0; i <= src.length; i += 1) {\n if (i === src.length || src[i] === \"\\n\") {\n out.push({ text: src.slice(start, i), start, end: i });\n start = i + 1;\n }\n }\n return out;\n}\n\nconst isBlank = (text: string) => text.trim() === \"\";\n\n/** Up to three leading spaces still counts as the left margin, per CommonMark. */\nconst FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/;\nconst INDENTED = /^(?: {4}|\\t)/;\nconst LIST_ITEM = /^ {0,3}(?:[-*+]|\\d{1,9}[.)])(?:\\s|$)/;\nconst QUOTE = /^ {0,3}>/;\n\ntype Fence = { marker: string; char: string };\n\n/**\n * A fence opener, or null.\n *\n * The info string is rejected when it contains a backtick: ``` `a` ``` on one\n * line is an inline code span, not the start of a code block, and treating it\n * as one swallows the rest of the paragraph.\n */\nfunction fenceOpen(text: string): Fence | null {\n const m = FENCE_OPEN.exec(text);\n if (!m) return null;\n const marker = m[1]!;\n const char = marker[0]!;\n if (char === \"`\" && m[2]!.includes(\"`\")) return null;\n return { marker, char };\n}\n\n/**\n * Does this line close `open`?\n *\n * Same character, at least as long, and nothing but whitespace after it. The\n * length rule is the whole point: a ``` inside a ```` block is content, and\n * closing on it is what split a code sample into four bogus blocks.\n */\nfunction closesFence(text: string, open: Fence): boolean {\n const m = /^ {0,3}(`{3,}|~{3,})\\s*$/.exec(text);\n if (!m) return false;\n const marker = m[1]!;\n return marker[0] === open.char && marker.length >= open.marker.length;\n}\n\n/**\n * Whether a blank line inside `construct` is an interior gap rather than a\n * boundary.\n *\n * A loose list — items separated by blank lines — is one list, and splitting it\n * per item is not merely cosmetic: the previewer would render three `<ul>`s\n * where the document has one, and the outline would report three entries the\n * user reads as one thing. A quote continues the same way, but only through a\n * line that is still quoted; lazy continuation after a blank is not a thing.\n */\nfunction continues(construct: \"list\" | \"quote\" | \"other\", text: string): boolean {\n if (construct === \"list\") return LIST_ITEM.test(text) || INDENTED.test(text);\n if (construct === \"quote\") return QUOTE.test(text);\n return false;\n}\n\nconst constructOf = (text: string): \"list\" | \"quote\" | \"other\" =>\n QUOTE.test(text) ? \"quote\" : LIST_ITEM.test(text) ? \"list\" : \"other\";\n\n/**\n * Top-level blocks in source order, with their spans.\n *\n * Blank lines that separate blocks belong to none of them, so a span always\n * slices back to exactly the block's own text. Blank lines *inside* a block —\n * within a fence, between the items of a loose list — are part of it.\n */\nexport function splitBlocks(src: string): MarkdownBlock[] {\n const lines = scanLines(src);\n const blocks: MarkdownBlock[] = [];\n let i = 0;\n\n while (i < lines.length) {\n const line = lines[i]!;\n if (isBlank(line.text)) {\n i += 1;\n continue;\n }\n\n const open = fenceOpen(line.text);\n if (open) {\n let j = i + 1;\n while (j < lines.length && !closesFence(lines[j]!.text, open)) j += 1;\n // An unterminated fence runs to the end of the source rather than\n // swallowing the rest as prose — a half-streamed code block is a normal\n // state to render, not a malformed document.\n const closing = j < lines.length ? lines[j]! : lines[lines.length - 1]!;\n blocks.push({ start: line.start, end: closing.end, kind: \"fence\" });\n i = j + 1;\n continue;\n }\n\n if (INDENTED.test(line.text)) {\n // Indented code, with its interior blank lines kept and its trailing ones\n // returned to the separator. Only reachable at a block boundary: inside a\n // list the same indentation is item content, and the list branch below\n // consumes it first.\n let j = i;\n let last = i;\n while (j < lines.length && (isBlank(lines[j]!.text) || INDENTED.test(lines[j]!.text))) {\n if (!isBlank(lines[j]!.text)) last = j;\n j += 1;\n }\n blocks.push({ start: line.start, end: lines[last]!.end, kind: \"code\" });\n i = last + 1;\n continue;\n }\n\n const construct = constructOf(line.text);\n let j = i;\n let last = i;\n for (;;) {\n // Run to the next blank line or fence opener.\n while (j < lines.length && !isBlank(lines[j]!.text) && !fenceOpen(lines[j]!.text)) {\n last = j;\n j += 1;\n }\n // Then decide whether the gap is interior. Look past the blanks: if what\n // follows still belongs to this list or quote, absorb them and keep going.\n let k = j;\n while (k < lines.length && isBlank(lines[k]!.text)) k += 1;\n if (k > j && k < lines.length && continues(construct, lines[k]!.text)) {\n j = k;\n continue;\n }\n break;\n }\n blocks.push({ start: line.start, end: lines[last]!.end, kind: \"text\" });\n i = last + 1;\n }\n\n return blocks;\n}\n","// The order a turn actually happened in.\n//\n// A turn is text, then a tool's output, then more text. Rendering all cards above\n// all text loses that: the model writes \"here is the breakdown\" and \"so the second\n// row matters\" around a chart, and both land below it. Live and finished turns share\n// this one function so a turn does not rearrange itself the moment it commits.\n\nimport type { Card } from \"../cards/types.js\";\nimport type { ContentPart } from \"./types.js\";\n\nexport type TurnSegment =\n | { type: \"text\"; key: string; text: string }\n /** The output slot of one tool call. Stable from first preview to final card. */\n | { type: \"output\"; key: string; callId: string; cards: Card[] }\n /** A card no call in this turn accounts for. */\n | { type: \"card\"; key: string; card: Card };\n\nexport type TurnLayoutOptions = {\n /** Keep a slot for a call with no card yet. A live turn needs it for previews and skeletons. */\n keepEmptyOutputs?: boolean;\n};\n\n/**\n * True when a stored turn recorded where its cards belong. Turns saved before this\n * existed carry no `callId` on their artifacts and keep the layout they had.\n */\nexport function hasTurnOrder(parts: readonly ContentPart[]): boolean {\n return parts.some((p) => p.type === \"artifact\" && p.kind.startsWith(\"card:\") && typeof p.callId === \"string\");\n}\n\nexport function layoutTurn(parts: readonly ContentPart[], cards: readonly Card[], options: TurnLayoutOptions = {}): TurnSegment[] {\n const byCall = new Map<string, Card[]>();\n for (const card of cards) {\n if (!card.callId) continue;\n const list = byCall.get(card.callId);\n if (list) list.push(card);\n else byCall.set(card.callId, [card]);\n }\n\n const segments: TurnSegment[] = [];\n const placed = new Set<string>();\n let textCount = 0;\n // A call that drew nothing should not split a paragraph into two blocks, but\n // the words either side of it were still written apart.\n let crossedCall = false;\n\n for (const part of parts) {\n if (part.type === \"text\") {\n if (!part.text) continue;\n const last = segments[segments.length - 1];\n if (last?.type === \"text\") {\n last.text += (crossedCall ? \"\\n\\n\" : \"\") + part.text;\n } else {\n segments.push({ type: \"text\", key: `text:${textCount}`, text: part.text });\n textCount += 1;\n }\n crossedCall = false;\n } else if (part.type === \"tool-call\") {\n const owned = byCall.get(part.callId) ?? [];\n for (const card of owned) placed.add(card.id);\n if (owned.length || options.keepEmptyOutputs) {\n segments.push({ type: \"output\", key: `call:${part.callId}`, callId: part.callId, cards: owned });\n crossedCall = false;\n } else {\n crossedCall = true;\n }\n }\n }\n\n for (const card of cards) {\n if (!placed.has(card.id)) segments.push({ type: \"card\", key: `card:${card.id}`, card });\n }\n return segments;\n}\n","// Quoted document spans — what the user pointed at, carried into one request.\n//\n// The load-bearing decision is where a quote LIVES, and the obvious answer is\n// wrong. A selection looks like screen state, so app-state seems to be its\n// home. It is not:\n//\n// - app-state answers \"what is the user looking at now\" and is re-read every\n// turn. A quote is pinned to ONE request; the turn after, the user has not\n// selected anything and it must be gone.\n// - It would go stale in history. Select A, send, select B — and the first\n// message, re-read later, would show B, because app-state has no memory of\n// what it said three turns ago.\n// - It is droppable. app-state losing its slot to budget pressure costs some\n// environment detail. A span the user deliberately highlighted losing its\n// slot loses part of what the user SAID — a correctness bug wearing a\n// budget optimisation's clothes.\n//\n// So a quote is part of the user's message: flattened into a text part for the\n// model, and kept structurally on `Message.metadata`, which is documented as\n// never reaching a provider. Nothing in the adapters changes.\n//\n// Drift follows the same rule. Whether the document has moved past the quoted\n// revision is checked once, when the message is sent, and recorded on the\n// quote — not re-derived on every turn, which would make an old message\n// describe the document's present rather than what was true when the user\n// spoke.\n\nimport type { DocumentSnapshot, DocumentStore } from \"../documents/types.js\";\n\n/** A span of a document artifact, resolved to source offsets. */\nexport type DocumentQuoteRef = {\n docId: string;\n title: string;\n /** Revision the span was taken from — compared at send time; see `drift`. */\n revision: number;\n /** Inclusive block index range. */\n blocks: [number, number];\n start: number;\n end: number;\n /** SOURCE markdown, not rendered text. */\n text: string;\n /**\n * How the document had moved past `revision` when the message was sent.\n * Absent when it had not, or when nothing checked — see `checkQuoteDrift`.\n */\n drift?: QuoteDrift;\n};\n\n/**\n * What a quote's document did between the quoted revision and the send.\n *\n * The quoted revision can be old the moment it is taken — a document card\n * further up the thread still shows the body it was created with — and the\n * model cannot tell from the text alone. Told, it re-reads; not told, it\n * proposes an edit against text that may no longer be there, or answers about\n * a paragraph the user has since rewritten.\n */\nexport type QuoteDrift =\n /** Past the quoted revision. `intact`: the quoted text still appears verbatim. */\n | { status: \"moved\"; revision: number; intact: boolean }\n /** The document no longer exists. */\n | { status: \"removed\" };\n\n/**\n * Compare a quote against the document as it is now. `undefined` when the\n * quote is current.\n *\n * Any revision other than the quoted one counts — a lower one means the id now\n * names a different document, which is drift too.\n */\nexport function quoteDrift(\n quote: DocumentQuoteRef,\n current: Pick<DocumentSnapshot, \"revision\" | \"markdown\"> | undefined,\n): QuoteDrift | undefined {\n if (!current) return { status: \"removed\" };\n if (current.revision === quote.revision) return undefined;\n return { status: \"moved\", revision: current.revision, intact: current.markdown.includes(quote.text) };\n}\n\n/**\n * Stamp each quote with its drift against the store, ready to send.\n *\n * A lookup that throws leaves that quote unstamped rather than failing the\n * send: the user's message matters more than the annotation, the quote still\n * names its revision, and an edit made from it is still checked against the\n * current one.\n */\nexport async function checkQuoteDrift(\n quotes: readonly DocumentQuoteRef[],\n documents: Pick<DocumentStore, \"get\">,\n): Promise<DocumentQuoteRef[]> {\n const lookups = new Map<string, Promise<DocumentSnapshot | undefined | null>>();\n return Promise.all(\n quotes.map(async (quote) => {\n let lookup = lookups.get(quote.docId);\n if (!lookup) {\n lookup = documents.get(quote.docId).catch(() => null);\n lookups.set(quote.docId, lookup);\n }\n const current = await lookup;\n const { drift: _unchecked, ...rest } = quote;\n if (current === null) return rest;\n const drift = quoteDrift(quote, current);\n return drift ? { ...rest, drift } : rest;\n }),\n );\n}\n\nconst driftNote = (drift: QuoteDrift | undefined): string => {\n if (!drift) return \"\";\n if (drift.status === \"removed\") return \"Note: this document no longer exists.\\n\";\n return drift.intact\n ? `Note: the document is now at v${drift.revision}. This text is still in it, but its block numbers may have shifted — re-read before editing.\\n`\n : `Note: the document is now at v${drift.revision}, and this text is no longer in it. Re-read before acting on the quote.\\n`;\n};\n\n/** Key under `Message.metadata` where quotes are stored for re-rendering. */\nexport const QUOTES_METADATA_KEY = \"documentQuotes\";\n\nconst fence = (text: string) => {\n // A quote can itself contain a ``` fence, so the wrapper grows past the\n // longest run inside it rather than truncating or escaping the content.\n const longest = [...text.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);\n return \"`\".repeat(longest + 1);\n};\n\n/**\n * Render quotes as the prefix of the user's message.\n *\n * Fenced rather than indented, and labelled with the document and block range,\n * so the model can tell quoted material from the user's own words — and can\n * name what it is about to change when the edit tools arrive. A stamped drift\n * becomes a note between the label and the text.\n */\nexport function formatQuotes(quotes: readonly DocumentQuoteRef[]): string {\n if (!quotes.length) return \"\";\n return quotes\n .map((q) => {\n const [from, to] = q.blocks;\n const where = from === to ? `block ${from}` : `blocks ${from}–${to}`;\n const f = fence(q.text);\n return `Quoted from \"${q.title}\" (${q.docId} v${q.revision}, ${where}):\\n${driftNote(q.drift)}${f}markdown\\n${q.text}\\n${f}`;\n })\n .join(\"\\n\\n\");\n}\n\n/** Prefix `text` with the quotes, keeping a blank line between them. */\nexport function withQuotes(text: string, quotes: readonly DocumentQuoteRef[]): string {\n const prefix = formatQuotes(quotes);\n if (!prefix) return text;\n return text.trim() ? `${prefix}\\n\\n${text}` : prefix;\n}\n\n/** Read quotes back off a message, for re-rendering the chips in history. */\nexport function quotesOf(metadata: Record<string, unknown> | undefined): DocumentQuoteRef[] {\n const raw = metadata?.[QUOTES_METADATA_KEY];\n return Array.isArray(raw) ? (raw as DocumentQuoteRef[]) : [];\n}\n","// Base64 for the proxy envelope, where a 20 MB upload is the sizing case.\n// `Buffer` is Node-only (core is isomorphic), so each direction takes the\n// fastest codec the runtime has: `Uint8Array.prototype.toBase64` /\n// `Uint8Array.fromBase64` where they exist, else `btoa` / `atob` over a binary\n// string built in bounded chunks (`String.fromCharCode(...bytes)` in one call\n// blows the call stack on anything bigger than a small image), and the\n// hand-rolled table below only for a runtime with neither, or for input that\n// is not a Uint8Array.\n\nconst ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nconst REVERSE: Int16Array = (() => {\n const table = new Int16Array(128).fill(-1);\n for (let i = 0; i < ALPHABET.length; i += 1) table[ALPHABET.charCodeAt(i)] = i;\n return table;\n})();\n\n// Bytes per `String.fromCharCode.apply` call, far below every engine's argument limit.\nconst APPLY_CHUNK = 0x2000;\n\ntype NativeBase64 = {\n toBase64?: (this: Uint8Array) => string;\n fromBase64?: (s: string) => Uint8Array;\n};\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n // An untyped caller's array or other typed array keeps the old answer: the\n // platform encoders reject it or read it differently.\n if (!(bytes instanceof Uint8Array)) return encodeWithTable(bytes);\n // Also keeps a detached buffer at \"\" — the native encoder throws on one.\n if (bytes.length === 0) return \"\";\n const { toBase64 } = Uint8Array.prototype as NativeBase64;\n if (typeof toBase64 === \"function\") return toBase64.call(bytes);\n if (typeof btoa === \"function\") {\n const binary: string[] = [];\n for (let i = 0; i < bytes.length; i += APPLY_CHUNK) {\n binary.push(String.fromCharCode.apply(null, bytes.subarray(i, i + APPLY_CHUNK) as unknown as number[]));\n }\n return btoa(binary.join(\"\"));\n }\n return encodeWithTable(bytes);\n}\n\nfunction encodeWithTable(bytes: Uint8Array): string {\n const chunks: string[] = [];\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i]!;\n const b1 = i + 1 < bytes.length ? bytes[i + 1]! : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2]! : 0;\n out +=\n ALPHABET[b0 >> 2]! +\n ALPHABET[((b0 & 0x03) << 4) | (b1 >> 4)]! +\n (i + 1 < bytes.length ? ALPHABET[((b1 & 0x0f) << 2) | (b2 >> 6)]! : \"=\") +\n (i + 2 < bytes.length ? ALPHABET[b2 & 0x3f]! : \"=\");\n // Flush periodically so the accumulator never becomes one enormous rope.\n if (out.length >= 0x8000) {\n chunks.push(out);\n out = \"\";\n }\n }\n chunks.push(out);\n return chunks.join(\"\");\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n // Tolerate whitespace/newlines (some serializers wrap long values).\n const clean = s.replace(/[\\s=]+/g, \"\");\n // The platform decoders reject a lone trailing character, which the table\n // silently drops; leave that input to the table so the answer stays the same.\n if (clean.length % 4 !== 1) {\n try {\n const native = Uint8Array as NativeBase64;\n if (typeof native.fromBase64 === \"function\") return native.fromBase64(clean);\n if (typeof atob === \"function\") {\n const binary = atob(clean);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);\n return out;\n }\n } catch {\n // A character outside the alphabet. Find the first one, to report which\n // and where exactly as the table does, without decoding the input again.\n for (let i = 0; i < clean.length; i += 1) {\n const code = clean.charCodeAt(i);\n if (code >= 128 || REVERSE[code]! < 0) {\n throw new Error(`Invalid base64 character \"${clean[i]}\" at position ${i}.`);\n }\n }\n }\n }\n return decodeWithTable(clean);\n}\n\nfunction decodeWithTable(clean: string): Uint8Array {\n const out = new Uint8Array(Math.floor((clean.length * 3) / 4));\n let outPos = 0;\n let buffer = 0;\n let bits = 0;\n for (let i = 0; i < clean.length; i += 1) {\n const code = clean.charCodeAt(i);\n const value = code < 128 ? REVERSE[code]! : -1;\n if (value < 0) throw new Error(`Invalid base64 character \"${clean[i]}\" at position ${i}.`);\n buffer = (buffer << 6) | value;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n out[outPos] = (buffer >> bits) & 0xff;\n outPos += 1;\n }\n }\n return out.subarray(0, outPos);\n}\n","// DirectTransport — browser (or server) talks straight to the provider with a\n// key you supply.\n//\n// In a browser this puts the key in client memory and in the network tab. That\n// is fine for a local playground or a desktop app with the user's own key, and\n// wrong for anything multi-tenant. `credentialSafe` is false so the runtime can\n// warn, and `assertBrowserUseAcknowledged` makes the footgun explicit rather\n// than silent.\n\nimport { isMultipartBody, type Transport, type TransportRequest } from \"./types.js\";\n\nexport type DirectTransportConfig = {\n /** Provider API root, no trailing slash. e.g. \"https://api.openai.com/v1\". */\n baseUrl: string;\n /** Static key, or a getter for keys that rotate / come from a keychain. */\n apiKey: string | (() => string | Promise<string>);\n /**\n * How the key rides on the wire. \"bearer\" (default) sends\n * `Authorization: Bearer <key>`; \"x-api-key\" sends the `x-api-key` header —\n * what Anthropic's Messages API expects.\n */\n authStyle?: \"bearer\" | \"x-api-key\";\n /** Sent on every request; merged under per-request headers. */\n headers?: Record<string, string>;\n /**\n * Required to use this transport in a browser. Naming it forces the caller to\n * state the risk out loud instead of discovering it in production.\n */\n dangerouslyAllowBrowser?: boolean;\n fetchImpl?: typeof fetch;\n};\n\nconst isBrowser = () => typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\nexport function buildUrl(baseUrl: string, path: string, query?: TransportRequest[\"query\"]): string {\n const url = new URL(`${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? path : `/${path}`}`);\n for (const [k, v] of Object.entries(query ?? {})) {\n if (v !== undefined && v !== null) url.searchParams.set(k, String(v));\n }\n return url.toString();\n}\n\nexport function createDirectTransport(config: DirectTransportConfig): Transport {\n if (isBrowser() && !config.dangerouslyAllowBrowser) {\n throw new Error(\n \"DirectTransport sends your API key from the browser. Pass `dangerouslyAllowBrowser: true` to accept that, \" +\n \"or use createProxyTransport() so the key stays on your server.\",\n );\n }\n const doFetch = config.fetchImpl ?? globalThis.fetch;\n\n return {\n kind: \"direct\",\n credentialSafe: !isBrowser(),\n async fetch(req: TransportRequest): Promise<Response> {\n const apiKey = typeof config.apiKey === \"function\" ? await config.apiKey() : config.apiKey;\n const headers: Record<string, string> = {\n ...(config.authStyle === \"x-api-key\" ? { \"x-api-key\": apiKey } : { authorization: `Bearer ${apiKey}` }),\n ...config.headers,\n ...req.headers,\n };\n if (req.stream) headers[\"accept\"] = \"text/event-stream\";\n\n let body: BodyInit | undefined;\n if (isMultipartBody(req.body)) {\n // No content-type here — fetch sets multipart/form-data with the boundary.\n const form = new FormData();\n for (const [k, v] of Object.entries(req.body.fields)) form.set(k, v);\n for (const f of req.body.files) {\n form.set(f.field, new Blob([f.data as BlobPart], f.mediaType ? { type: f.mediaType } : {}), f.filename);\n }\n body = form;\n } else if (req.body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n body = JSON.stringify(req.body);\n }\n\n return doFetch(buildUrl(config.baseUrl, req.path, req.query), {\n method: req.method,\n headers,\n body,\n signal: req.signal,\n });\n },\n };\n}\n","// ProxyTransport — the browser calls your own backend, which injects the key and\n// forwards to the provider. This is the default, and the only shape that is\n// honest in a multi-user app.\n//\n// The wire format between client and BFF is intentionally trivial: the client\n// declares which provider, path, method and body it wants; the server decides\n// whether to allow it. `createProxyHandler` (@supersolutions/super-chat-server) is the matching half,\n// and it allowlists paths — a proxy that forwards any path is an open relay for\n// your API key.\n\nimport { bytesToBase64 } from \"./binary.js\";\nimport { isMultipartBody, type Transport, type TransportRequest } from \"./types.js\";\n\nexport type ProxyTransportConfig = {\n /** Base path of your proxy route, e.g. \"/api/agent\". */\n url: string;\n /** Extra headers (session cookie is automatic; use this for CSRF tokens). */\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);\n credentials?: RequestCredentials;\n fetchImpl?: typeof fetch;\n};\n\n/** The envelope a ProxyTransport POSTs to the BFF. Exported so the server half can type it. */\nexport type ProxyEnvelope = {\n provider: string;\n path: string;\n method: \"GET\" | \"POST\" | \"DELETE\";\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n stream?: boolean;\n /**\n * Per-request headers for the UPSTREAM call (org ids, beta flags, an MCP\n * session id). The server half forwards them after stripping credential\n * headers and then applies its own key on top — a client can request\n * headers, never substitute the credential.\n */\n headers?: Record<string, string>;\n};\n\n/**\n * A `MultipartBody` as it travels inside the JSON envelope: bytes become\n * base64 strings so the client→BFF wire stays one method, one body shape.\n * Base64 costs +33%, so treat ~20 MB per upload as the practical ceiling —\n * beyond that, use a direct transport or your own upload route.\n */\nexport type SerializedMultipartBody = {\n kind: \"multipart\";\n fields: Record<string, string>;\n files: { field: string; filename: string; mediaType?: string; data: string }[];\n};\n\nexport function createProxyTransport(config: ProxyTransportConfig): Transport {\n const doFetch = config.fetchImpl ?? globalThis.fetch;\n\n return {\n kind: \"proxy\",\n credentialSafe: true,\n async fetch(req: TransportRequest): Promise<Response> {\n const extra = typeof config.headers === \"function\" ? await config.headers() : config.headers;\n const body: unknown = isMultipartBody(req.body)\n ? ({\n kind: \"multipart\",\n fields: req.body.fields,\n files: req.body.files.map((f) => ({\n field: f.field,\n filename: f.filename,\n ...(f.mediaType ? { mediaType: f.mediaType } : {}),\n data: bytesToBase64(f.data),\n })),\n } satisfies SerializedMultipartBody)\n : req.body;\n\n const envelope: ProxyEnvelope = {\n provider: req.provider,\n path: req.path,\n method: req.method,\n body,\n query: req.query,\n stream: req.stream,\n // Inside the envelope, not on the outer request — the BFF builds the\n // upstream headers itself, and anything on the outer request is\n // between the browser and the BFF (cookies, CSRF), not for upstream.\n ...(req.headers ? { headers: req.headers } : {}),\n };\n\n // Always POST the envelope, even for provider-side GETs (job polling):\n // one method and one body shape keeps the server handler and any CSRF\n // middleware simple, and provider GETs carry no cacheable semantics for us.\n return doFetch(config.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(req.stream ? { accept: \"text/event-stream\" } : {}),\n ...extra,\n },\n body: JSON.stringify(envelope),\n credentials: config.credentials ?? \"same-origin\",\n signal: req.signal,\n });\n },\n };\n}\n","// Public provider profiles describe an endpoint without carrying its secret.\n// A profile is safe to render in a picker or persist in localStorage; the API\n// key stays in a Transport (direct/BYOK) or in createProxyHandler (server).\n\nimport { createDirectTransport, type DirectTransportConfig } from \"../transport/direct.js\";\nimport type { Transport } from \"../transport/types.js\";\nimport { createAnthropicProvider } from \"./anthropic/adapter.js\";\nimport { createOpenAIProvider } from \"./openai/adapter.js\";\nimport type { ModelInfo, Provider, ProviderCapabilities } from \"./types.js\";\n\nexport type ProviderProtocol = \"openai-responses\" | \"openai-chat\" | \"anthropic-messages\";\n\nexport type ProviderProfile = {\n /** Stable routing id. It must match the proxy provider key in proxy mode. */\n id: string;\n label: string;\n protocol: ProviderProtocol;\n /** Provider API root including its version prefix, without a trailing slash. */\n baseUrl: string;\n models?: ModelInfo[];\n capabilities?: Partial<ProviderCapabilities>;\n};\n\nexport const OPENAI_OFFICIAL_PROFILE: ProviderProfile = {\n id: \"openai\",\n label: \"OpenAI\",\n protocol: \"openai-responses\",\n baseUrl: \"https://api.openai.com/v1\",\n};\n\nexport const ANTHROPIC_OFFICIAL_PROFILE: ProviderProfile = {\n id: \"anthropic\",\n label: \"Anthropic\",\n protocol: \"anthropic-messages\",\n baseUrl: \"https://api.anthropic.com/v1\",\n};\n\nexport function createOpenAICompatibleProfile(\n profile: Omit<ProviderProfile, \"protocol\"> & { protocol?: \"openai-chat\" },\n): ProviderProfile {\n return normalizeProviderProfile({ ...profile, protocol: \"openai-chat\" });\n}\n\n/** Normalize user-authored profile fields and reject unsafe/ambiguous roots. */\nexport function normalizeProviderProfile(profile: ProviderProfile): ProviderProfile {\n const id = profile.id.trim();\n const label = profile.label.trim();\n if (!id || !/^[a-z0-9][a-z0-9._-]*$/i.test(id)) {\n throw new Error(\"Provider profile id must use letters, numbers, dots, underscores, or hyphens.\");\n }\n if (!label) throw new Error(\"Provider profile label is required.\");\n\n let url: URL;\n try {\n url = new URL(profile.baseUrl);\n } catch {\n throw new Error(\"Provider profile baseUrl must be an absolute URL.\");\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new Error(\"Provider profile baseUrl must use http or https.\");\n }\n if (url.username || url.password) {\n throw new Error(\"Provider profile baseUrl cannot contain credentials.\");\n }\n if (url.search || url.hash) {\n throw new Error(\"Provider profile baseUrl cannot include a query or fragment.\");\n }\n\n return {\n ...profile,\n id,\n label,\n baseUrl: url.toString().replace(/\\/$/, \"\"),\n };\n}\n\n/** Build the wire adapter for a profile. Credentials remain in the transport. */\nexport function createProviderFromProfile(profileInput: ProviderProfile, transport: Transport): Provider {\n const profile = normalizeProviderProfile(profileInput);\n const common = {\n transport,\n id: profile.id,\n label: profile.label,\n ...(profile.models ? { models: profile.models } : {}),\n ...(profile.capabilities ? { capabilities: profile.capabilities } : {}),\n };\n\n if (profile.protocol === \"anthropic-messages\") return createAnthropicProvider(common);\n return createOpenAIProvider({\n ...common,\n dialect: profile.protocol === \"openai-chat\" ? \"chat\" : \"responses\",\n });\n}\n\nexport type ProfileDirectTransportConfig = Omit<DirectTransportConfig, \"baseUrl\" | \"authStyle\">;\n\n/** Build a BYOK/server-direct transport with the profile's URL and auth style. */\nexport function createDirectTransportForProfile(\n profileInput: ProviderProfile,\n config: ProfileDirectTransportConfig,\n): Transport {\n const profile = normalizeProviderProfile(profileInput);\n return createDirectTransport({\n ...config,\n baseUrl: profile.baseUrl,\n ...(profile.protocol === \"anthropic-messages\" ? { authStyle: \"x-api-key\" as const } : {}),\n });\n}\n","import type { MediaSource } from \"../content/types.js\";\nimport type { CallOptions } from \"../providers/types.js\";\n\nexport type GeneratedMediaKind = \"image\" | \"audio\" | \"video\";\n\nexport type GeneratedMedia = {\n id: string;\n kind: GeneratedMediaKind;\n source: MediaSource;\n mediaType: string;\n provider: string;\n model?: string;\n revisedPrompt?: string;\n width?: number;\n height?: number;\n durationMs?: number;\n createdAt: number;\n};\n\nexport type MediaProviderCapabilities = {\n imageGeneration: boolean;\n speechGeneration: boolean;\n transcription: boolean;\n videoGeneration: boolean;\n asyncJobs: boolean;\n};\n\nexport type ImageGenerationRequest = {\n prompt: string;\n model?: string;\n n?: number;\n size?: string;\n quality?: string;\n style?: string;\n /** OpenAI-compatible response representation. Defaults to provider behavior. */\n responseFormat?: \"url\" | \"b64_json\";\n /** Escape hatch for endpoint-specific fields; normalized fields above win. */\n providerOptions?: Record<string, unknown>;\n};\n\nexport type SpeechGenerationRequest = {\n input: string;\n model?: string;\n voice?: string;\n format?: string;\n providerOptions?: Record<string, unknown>;\n};\n\nexport type TranscriptionRequest = {\n data: Blob | ArrayBuffer | Uint8Array;\n filename: string;\n mediaType?: string;\n model?: string;\n providerOptions?: Record<string, unknown>;\n};\n\nexport type Transcript = { text: string; language?: string; durationMs?: number; raw?: unknown };\n\nexport type VideoGenerationRequest = {\n prompt: string;\n model?: string;\n image?: MediaSource;\n durationSeconds?: number;\n providerOptions?: Record<string, unknown>;\n};\n\nexport type MediaJobHandle = { provider: string; id: string; kind: GeneratedMediaKind; createdAt: number };\nexport type MediaJobSnapshot = {\n handle: MediaJobHandle;\n status: \"queued\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n result?: GeneratedMedia[];\n error?: { message: string; code?: string };\n};\n\nexport type MediaProvider = {\n readonly id: string;\n readonly label: string;\n readonly capabilities: MediaProviderCapabilities;\n generateImage?(req: ImageGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia[]>;\n generateSpeech?(req: SpeechGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia>;\n transcribe?(req: TranscriptionRequest, opts?: CallOptions): Promise<Transcript>;\n startVideoJob?(req: VideoGenerationRequest, opts?: CallOptions): Promise<MediaJobHandle>;\n pollMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;\n cancelMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;\n};\n\n/** Resolve an asset for HTML renderers without losing its MIME type. */\nexport function generatedMediaUrl(asset: GeneratedMedia): string | null {\n if (asset.source.kind === \"url\") return asset.source.url;\n if (asset.source.kind === \"base64\") return `data:${asset.mediaType};base64,${asset.source.data}`;\n return null;\n}\n","// OpenAI-compatible image generation. This deliberately uses Transport, so the\n// same implementation works against official OpenAI, oneAPI, or a server proxy.\n\nimport { nextId } from \"../content/parts.js\";\nimport { errorFromResponse } from \"../transport/retry.js\";\nimport type { Transport } from \"../transport/types.js\";\nimport type { GeneratedMedia, ImageGenerationRequest, MediaProvider } from \"./types.js\";\n\ntype ImageGenerationResponse = {\n created?: number;\n data?: { url?: string; b64_json?: string; revised_prompt?: string }[];\n};\n\nconst dimensionsFromSize = (size?: string): { width: number; height: number } | undefined => {\n const match = /^(\\d+)x(\\d+)$/i.exec(size?.trim() ?? \"\");\n if (!match) return undefined;\n const width = Number(match[1]);\n const height = Number(match[2]);\n return width > 0 && height > 0 ? { width, height } : undefined;\n};\n\nexport type OpenAIImageProviderConfig = {\n transport: Transport;\n /** Must match the provider key registered by createProxyHandler. */\n id?: string;\n label?: string;\n defaultModel?: string;\n};\n\nexport function createOpenAIImageProvider(config: OpenAIImageProviderConfig): MediaProvider {\n const id = config.id ?? \"openai\";\n return {\n id,\n label: config.label ?? \"OpenAI Images\",\n capabilities: {\n imageGeneration: true,\n speechGeneration: false,\n transcription: false,\n videoGeneration: false,\n asyncJobs: false,\n },\n async generateImage(req: ImageGenerationRequest, opts): Promise<GeneratedMedia[]> {\n const prompt = req.prompt.trim();\n if (!prompt) throw new Error(\"Image generation prompt is required.\");\n const body = {\n ...req.providerOptions,\n prompt,\n ...(req.model ?? config.defaultModel ? { model: req.model ?? config.defaultModel } : {}),\n ...(req.n != null ? { n: req.n } : {}),\n ...(req.size ? { size: req.size } : {}),\n ...(req.quality ? { quality: req.quality } : {}),\n ...(req.style ? { style: req.style } : {}),\n ...(req.responseFormat ? { response_format: req.responseFormat } : {}),\n };\n const res = await config.transport.fetch({\n provider: id,\n path: \"/images/generations\",\n method: \"POST\",\n body,\n headers: opts?.headers,\n signal: opts?.signal,\n });\n if (!res.ok) throw await errorFromResponse(res, id);\n const json = (await res.json()) as ImageGenerationResponse;\n if (!json.data?.length) throw new Error(`Provider \"${id}\" returned no generated images.`);\n const createdAt = (json.created ?? Math.floor(Date.now() / 1000)) * 1000;\n const dimensions = dimensionsFromSize(req.size);\n return json.data.map((item) => {\n if (!item.url && !item.b64_json) throw new Error(`Provider \"${id}\" returned an image without url or b64_json.`);\n return {\n id: nextId(\"media\"),\n kind: \"image\" as const,\n source: item.url ? { kind: \"url\" as const, url: item.url } : { kind: \"base64\" as const, data: item.b64_json! },\n mediaType: \"image/png\",\n provider: id,\n ...(req.model ?? config.defaultModel ? { model: req.model ?? config.defaultModel } : {}),\n ...(item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}),\n ...(dimensions ?? {}),\n createdAt,\n };\n });\n },\n };\n}\n","import type { MediaCard } from \"../cards/types.js\";\nimport type { ToolDefinition } from \"../tools/types.js\";\nimport { generatedMediaUrl, type ImageGenerationRequest, type MediaProvider } from \"./types.js\";\n\nexport type GenerateImageToolOptions = {\n name?: string;\n /** Used when the model does not explicitly select one. */\n defaultModel?: string;\n};\n\n/**\n * Expose a MediaProvider to an agent without teaching the chat Provider any\n * image-generation wire format. The compact output goes back to the model;\n * the binary/URL payload stays in a media card for the user.\n */\nexport function createGenerateImageTool(provider: MediaProvider, options: GenerateImageToolOptions = {}): ToolDefinition {\n return {\n name: options.name ?? \"generateImage\",\n side: \"write\",\n strict: true,\n description: \"Generate one or more images from a prompt and show them to the user.\",\n loading: (input) => {\n const request = (input ?? {}) as Partial<ImageGenerationRequest>;\n const count = Math.max(1, Math.min(10, Number.isFinite(request.n) ? Math.round(request.n!) : 1));\n const size = /^(\\d+)x(\\d+)$/i.exec(request.size?.trim() ?? \"\");\n return {\n kind: \"media\",\n label: count === 1 ? \"Generating image\" : `Generating ${count} images`,\n count,\n ...(size ? { aspectRatio: `${Number(size[1])} / ${Number(size[2])}` } : {}),\n };\n },\n inputSchema: {\n type: \"object\",\n required: [\"prompt\"],\n properties: {\n prompt: { type: \"string\", description: \"A concrete visual description of the image to generate.\" },\n model: { type: \"string\" },\n n: { type: \"integer\", minimum: 1, maximum: 10 },\n size: { type: \"string\", description: \"Provider-supported size, for example 1024x1024.\" },\n quality: { type: \"string\" },\n style: { type: \"string\" },\n },\n additionalProperties: false,\n },\n async execute(input, ctx) {\n if (!provider.generateImage || !provider.capabilities.imageGeneration) {\n return { output: { ok: false, error: `Provider \"${provider.id}\" cannot generate images.` }, failure: \"execution-error\" as const };\n }\n const request = (input ?? {}) as ImageGenerationRequest;\n if (!request.prompt?.trim()) {\n return { output: { ok: false, error: \"`prompt` is required.\" }, failure: \"invalid-input\" as const };\n }\n const assets = await provider.generateImage(\n { ...request, ...(request.model || !options.defaultModel ? {} : { model: options.defaultModel }) },\n { signal: ctx.signal },\n );\n const items = assets.flatMap((asset) => {\n const url = generatedMediaUrl(asset);\n return url\n ? [{\n url,\n mediaType: asset.mediaType,\n alt: asset.revisedPrompt ?? request.prompt,\n caption: asset.revisedPrompt,\n ...(asset.width ? { width: asset.width } : {}),\n ...(asset.height ? { height: asset.height } : {}),\n ...(asset.durationMs ? { durationMs: asset.durationMs } : {}),\n }]\n : [];\n });\n const card: MediaCard | undefined = items.length\n ? { kind: \"media\", title: assets.length === 1 ? \"Generated image\" : \"Generated images\", layout: assets.length === 1 ? \"single\" : \"grid\", items }\n : undefined;\n return {\n output: {\n ok: true,\n provider: provider.id,\n count: assets.length,\n assets: assets.map((asset) => ({\n id: asset.id,\n kind: asset.kind,\n mediaType: asset.mediaType,\n ...(asset.model ? { model: asset.model } : {}),\n ...(asset.revisedPrompt ? { revisedPrompt: asset.revisedPrompt } : {}),\n })),\n },\n ...(card ? { card } : {}),\n };\n },\n };\n}\n","// Token estimation without a tokenizer.\n//\n// Shipping tiktoken to the browser costs ~1MB of WASM plus a rank table, to\n// answer a question we only need approximately: \"will this fit in the budget\".\n// A byte-aware heuristic gets within roughly ±15% on ordinary prose and is\n// deliberately biased to OVER-estimate, because the failure mode of\n// over-estimating is dropping one extra history turn, while the failure mode of\n// under-estimating is a 400 from the provider mid-conversation.\n//\n// Hosts that need exactness inject their own counter through `TokenCounter`.\n\nexport type TokenCounter = (text: string) => number;\n\nconst LATIN_CHARS_PER_TOKEN = 3.7; // GPT-family BPE on English prose\nconst CJK_CHARS_PER_TOKEN = 1.1; // CJK is close to one token per character\n\n/**\n * Estimate tokens for a string. Splits CJK from Latin because a single ratio is\n * wrong by 3x on Chinese/Japanese text — which matters here, since this\n * framework is being built by someone who writes prompts in both.\n */\nexport function estimateTokens(text: string): number {\n if (!text) return 0;\n\n let cjk = 0;\n let other = 0;\n for (const ch of text) {\n const code = ch.codePointAt(0)!;\n const isCjk =\n (code >= 0x3040 && code <= 0x30ff) || // kana\n (code >= 0x3400 && code <= 0x4dbf) || // CJK ext A\n (code >= 0x4e00 && code <= 0x9fff) || // CJK unified\n (code >= 0xac00 && code <= 0xd7af) || // hangul\n (code >= 0xf900 && code <= 0xfaff);\n if (isCjk) cjk += 1;\n else other += 1;\n }\n\n const base = cjk / CJK_CHARS_PER_TOKEN + other / LATIN_CHARS_PER_TOKEN;\n // Structural overhead: JSON punctuation and whitespace tokenize poorly and\n // are common in tool payloads, so add a small margin rather than under-count.\n return Math.ceil(base * 1.05);\n}\n\n/** JSON payloads (tool args/results) tokenize worse than prose — count the serialized form. */\nexport function estimateJsonTokens(value: unknown): number {\n if (value == null) return 1;\n if (typeof value === \"string\") return estimateTokens(value);\n try {\n return estimateTokens(JSON.stringify(value));\n } catch {\n return estimateTokens(String(value));\n }\n}\n\n/** Fixed per-message overhead the provider adds for role markers and separators. */\nexport const MESSAGE_OVERHEAD_TOKENS = 4;\n","// Token budgeting.\n//\n// The context window is a fixed resource contended for by five claimants:\n// instructions, skills, memory, history, and the model's own output. Without an\n// explicit allocator whichever one grows fastest (history) silently starves the\n// rest, and the first symptom is the model \"forgetting\" its rules on long\n// threads — which reads like a prompt problem and isn't.\n\nimport { estimateTokens, MESSAGE_OVERHEAD_TOKENS, type TokenCounter } from \"./estimate.js\";\nimport type { Message } from \"../content/types.js\";\n\nexport type BudgetShares = {\n /** Reserved for the model's reply. Never lent out. */\n output: number;\n system: number;\n skills: number;\n memory: number;\n history: number;\n tools: number;\n};\n\nexport type TokenBudget = {\n contextWindow: number;\n shares: BudgetShares;\n /** Safety margin, since estimation is approximate. */\n reservePct: number;\n};\n\nexport function createBudget(contextWindow: number, opts: Partial<BudgetShares> & { reservePct?: number; maxOutputTokens?: number } = {}): TokenBudget {\n const output = opts.output ?? opts.maxOutputTokens ?? Math.min(8_000, Math.floor(contextWindow * 0.15));\n const reservePct = opts.reservePct ?? 0.05;\n const usable = Math.floor(contextWindow * (1 - reservePct)) - output;\n\n // Defaults chosen so that on a 128k window the fixed layers get generous room\n // and history still takes the majority — history is where the actual\n // conversation lives, and starving it to preserve skills is the wrong trade.\n return {\n contextWindow,\n reservePct,\n shares: {\n output,\n system: opts.system ?? Math.floor(usable * 0.08),\n skills: opts.skills ?? Math.floor(usable * 0.2),\n memory: opts.memory ?? Math.floor(usable * 0.07),\n tools: opts.tools ?? Math.floor(usable * 0.15),\n history: opts.history ?? Math.floor(usable * 0.5),\n },\n };\n}\n\nexport const totalAllocated = (b: TokenBudget): number =>\n b.shares.system + b.shares.skills + b.shares.memory + b.shares.tools + b.shares.history;\n\n/**\n * Fill a budget with prioritized items, greedily, highest first.\n *\n * Greedy rather than optimal (knapsack) because the ordering is meaningful:\n * skill priority encodes the author's intent about what must survive, and an\n * optimal packer would happily drop a critical high-priority skill to fit two\n * cheap ones.\n */\nexport function packByPriority<T>(\n items: readonly T[],\n limit: number,\n sizeOf: (item: T) => number,\n): { included: T[]; dropped: { item: T; size: number }[]; used: number } {\n const included: T[] = [];\n const dropped: { item: T; size: number }[] = [];\n let used = 0;\n\n for (const item of items) {\n const size = sizeOf(item);\n if (used + size <= limit) {\n included.push(item);\n used += size;\n } else {\n dropped.push({ item, size });\n }\n }\n return { included, dropped, used };\n}\n\n// Per-message token counts, cached by message object identity. Persisted\n// messages are never mutated in place (a new object is built for every\n// change — see runtime/run.ts), so a cached count never goes stale, and a\n// context build that re-walks the same history on every step (budget checks,\n// compaction, the builder's own summation) does not re-count every character\n// of every message it already counted last time.\n//\n// Keyed by object identity rather than `message.id`: compaction mints\n// synthetic summary messages with a formulaic, non-unique id\n// (`summary_${cut}`), so two DIFFERENT messages can share an id — an id-keyed\n// cache would risk serving one message's count for another's. The counter is\n// also part of the key: a caller-supplied counter and the default estimator\n// must not share a cache entry.\nconst messageTokenCache = new WeakMap<Message, WeakMap<TokenCounter, number>>();\n\nexport function countMessageTokens(m: Message, counter: TokenCounter = estimateTokens): number {\n const cached = messageTokenCache.get(m)?.get(counter);\n if (cached !== undefined) return cached;\n\n let total = MESSAGE_OVERHEAD_TOKENS;\n for (const part of m.parts) {\n switch (part.type) {\n case \"text\":\n case \"reasoning\":\n total += counter(part.text);\n break;\n case \"tool-call\":\n total += counter(part.name) + counter(typeof part.input === \"string\" ? part.input : JSON.stringify(part.input ?? {})) + 8;\n break;\n case \"tool-result\":\n total += counter(typeof part.output === \"string\" ? part.output : JSON.stringify(part.output ?? null)) + 8;\n break;\n case \"image\":\n // Images bill by tiles, not characters. 1105 is the low-detail flat cost\n // for a 512px tile; high detail scales with dimensions we don't know\n // here, so assume a common 2-tile image rather than guessing zero.\n total += part.detail === \"low\" ? 85 : 1_105;\n break;\n case \"file\":\n total += 2_000; // a parsed PDF page is roughly this; deliberately pessimistic\n break;\n case \"audio\":\n total += part.transcript ? counter(part.transcript) : 500;\n break;\n case \"artifact\":\n break; // stripped before send — costs nothing\n }\n }\n\n let byCounter = messageTokenCache.get(m);\n if (!byCounter) {\n byCounter = new WeakMap();\n messageTokenCache.set(m, byCounter);\n }\n byCounter.set(counter, total);\n return total;\n}\n\nexport const countMessagesTokens = (messages: readonly Message[], counter: TokenCounter = estimateTokens): number =>\n messages.reduce((sum, m) => sum + countMessageTokens(m, counter), 0);\n","// Skill matching. Deliberately lexical — no embeddings, no network call.\n//\n// Retrieval that requires an API round-trip before the *first* token of the real\n// request is a latency tax on every turn, and for a curated skill set (tens, not\n// millions) alias scoring is both faster and more predictable. A host that wants\n// semantic retrieval implements `SkillRegistry`'s matcher hook instead; this is\n// the default, not the only option.\n\nimport type { Skill, SkillMatch, SkillSection } from \"./types.js\";\n\nconst STOPWORDS = new Set([\n \"a\", \"an\", \"the\", \"and\", \"or\", \"but\", \"if\", \"then\", \"to\", \"of\", \"in\", \"on\", \"for\", \"with\", \"at\", \"by\",\n \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"do\", \"does\", \"did\", \"can\", \"could\", \"would\", \"should\",\n \"i\", \"me\", \"my\", \"you\", \"your\", \"it\", \"its\", \"this\", \"that\", \"what\", \"how\", \"please\", \"help\",\n]);\n\nexport function tokenize(input: string): string[] {\n return input\n .toLowerCase()\n // Keep CJK runs as single tokens; they carry meaning without spaces.\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t));\n}\n\n// Aliases/tags/names are registered once and matched against on every query\n// thereafter, so their tokenization is cached rather than redone per call.\n// Unbounded by design: the keys are the distinct alias/tag/name strings a\n// process ever sees, which for a curated skill set is tens, not millions.\nconst aliasTokenCache = new Map<string, string[]>();\nfunction tokenizeAlias(a: string): string[] {\n let tokens = aliasTokenCache.get(a);\n if (!tokens) {\n tokens = tokenize(a);\n aliasTokenCache.set(a, tokens);\n }\n return tokens;\n}\n\n/**\n * Score one alias against the query.\n *\n * Both containment directions are checked on purpose: a query \"add liquidity to\n * the SUI pool\" should hit the alias \"add liquidity\" (alias ⊂ query), and a\n * query \"clmm\" should hit the alias \"clmm liquidity\" (query ⊂ alias). Only one\n * direction and half the natural phrasings miss.\n */\nfunction scoreAlias(alias: string, query: string, queryTokens: Set<string>): number {\n const a = alias.toLowerCase().trim();\n if (!a) return 0;\n if (a === query) return 6;\n if (queryTokens.has(a)) return 4;\n if (query.includes(a)) return 3;\n if (a.includes(query) && query.length >= 3) return 2;\n // Partial token overlap for multi-word aliases: \"provide liquidity\" vs \"liquidity\".\n const aliasTokens = tokenizeAlias(a);\n if (aliasTokens.length > 1) {\n const hits = aliasTokens.filter((t) => queryTokens.has(t)).length;\n if (hits) return 1.5 * (hits / aliasTokens.length);\n }\n return 0;\n}\n\nexport function scoreSkill(skill: Skill, query: string): { score: number; reason: string; sections: SkillSection[] } {\n const q = query.toLowerCase().trim();\n if (!q) return { score: 0, reason: \"empty query\", sections: [] };\n const queryTokens = new Set(tokenize(q));\n\n let score = 0;\n const reasons: string[] = [];\n\n const nameScore = scoreAlias(skill.name, q, queryTokens);\n if (nameScore) {\n score += nameScore * 1.2;\n reasons.push(`name:${nameScore.toFixed(1)}`);\n }\n if (scoreAlias(skill.id, q, queryTokens)) {\n score += 4;\n reasons.push(\"id\");\n }\n\n let bestAlias = 0;\n for (const alias of skill.aliases ?? []) bestAlias = Math.max(bestAlias, scoreAlias(alias, q, queryTokens));\n if (bestAlias) {\n score += bestAlias;\n reasons.push(`alias:${bestAlias.toFixed(1)}`);\n }\n\n let tagHits = 0;\n for (const tag of skill.tags ?? []) if (scoreAlias(tag, q, queryTokens)) tagHits += 1;\n if (tagHits) {\n score += Math.min(tagHits, 3) * 1.2;\n reasons.push(`tags:${tagHits}`);\n }\n\n // Sections matched independently so a long skill can contribute just the\n // relevant part rather than its whole body.\n const sections: SkillSection[] = [];\n for (const section of skill.sections ?? []) {\n const secScore = Math.max(\n scoreAlias(section.id, q, queryTokens),\n scoreAlias(section.name, q, queryTokens),\n ...(section.aliases ?? []).map((a) => scoreAlias(a, q, queryTokens)),\n );\n if (secScore >= 1.5) {\n sections.push(section);\n score += secScore * 0.6;\n }\n }\n if (sections.length) reasons.push(`sections:${sections.length}`);\n\n score += skill.priority ?? 0;\n\n return { score, reason: reasons.join(\" \") || \"no match\", sections };\n}\n\n/** Rank skills by relevance. `threshold` filters noise; sorting is stable by id for determinism. */\nexport function matchSkills(skills: readonly Skill[], query: string, threshold = 1.5): SkillMatch[] {\n return skills\n .map((skill) => {\n const { score, reason, sections } = scoreSkill(skill, query);\n return { skill, score, reason, sections };\n })\n .filter((m) => m.score >= threshold)\n .sort((a, b) => b.score - a.score || a.skill.id.localeCompare(b.skill.id));\n}\n","// The skill registry: one store, three delivery modes, plus the tool surface\n// that makes `manual` skills reachable by the model.\n\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport { matchSkills } from \"./match.js\";\nimport type { ResolvedSkill, Skill, SkillContext, SkillMatch, SkillSection } from \"./types.js\";\n\nexport type SkillMatcher = (skills: readonly Skill[], query: string) => SkillMatch[];\n\nexport type SkillRegistryOptions = {\n /** Swap in embeddings/BM25 without touching the rest of the pipeline. */\n matcher?: SkillMatcher;\n /** Max `matched`-mode skills injected per turn. Guards against a query that hits everything. */\n maxMatched?: number;\n threshold?: number;\n};\n\n/** Render a skill (or just its matched sections) to the text that goes in context. */\nexport async function renderSkill(\n skill: Skill,\n ctx: SkillContext,\n sections?: SkillSection[],\n): Promise<string> {\n const body = typeof skill.body === \"function\" ? await skill.body(ctx) : skill.body;\n const chosen = sections?.length ? sections : skill.sections ?? [];\n\n const parts = [`## ${skill.name}`, body.trim()];\n for (const section of chosen) {\n parts.push(`### ${section.name}`, section.body.trim());\n }\n if (skill.resources?.length) {\n parts.push(\n \"Resources:\",\n skill.resources.map((r) => `- ${r.name}${r.description ? ` — ${r.description}` : \"\"}: ${r.uri}`).join(\"\\n\"),\n );\n }\n return parts.filter(Boolean).join(\"\\n\\n\");\n}\n\nexport class SkillRegistry {\n private skills = new Map<string, Skill>();\n private readonly matcher: SkillMatcher;\n private readonly maxMatched: number;\n private readonly threshold: number;\n /** Cached `manualIndex()` render; invalidated by `register`/`unregister`. */\n private manualIndexCache: string | undefined;\n\n constructor(skills: readonly Skill[] = [], options: SkillRegistryOptions = {}) {\n this.threshold = options.threshold ?? 1.5;\n this.matcher = options.matcher ?? ((s, q) => matchSkills(s, q, this.threshold));\n this.maxMatched = options.maxMatched ?? 3;\n for (const s of skills) this.register(s);\n }\n\n register(skill: Skill): this {\n this.skills.set(skill.id, skill);\n this.manualIndexCache = undefined;\n return this;\n }\n\n unregister(id: string): this {\n this.skills.delete(id);\n this.manualIndexCache = undefined;\n return this;\n }\n\n get(id: string): Skill | undefined {\n return this.skills.get(id);\n }\n\n list(): Skill[] {\n return [...this.skills.values()];\n }\n\n match(query: string): SkillMatch[] {\n return this.matcher(this.list(), query);\n }\n\n /**\n * The skills that should be *pushed* into this turn's context: every `always`\n * skill, plus the top-scoring `matched` ones.\n *\n * `manual` skills are excluded by design — they are pulled by the model via\n * `loadSkill`, and pushing them would defeat the point of having the mode.\n */\n async resolveForTurn(ctx: SkillContext, opts: { forceIds?: string[] } = {}): Promise<ResolvedSkill[]> {\n const forced = new Set(opts.forceIds ?? []);\n // Computed once and fed to the matcher directly (rather than through\n // `this.match`, which would call `this.list()` again) — one array\n // allocation per turn instead of two.\n const list = this.list();\n const always = list.filter((s) => s.mode === \"always\" || forced.has(s.id));\n const matched = this.matcher(list, ctx.query)\n .filter((m) => m.skill.mode === \"matched\" && !forced.has(m.skill.id))\n .slice(0, this.maxMatched);\n\n const out: ResolvedSkill[] = [];\n for (const skill of always) {\n const text = await renderSkill(skill, ctx);\n out.push({\n id: skill.id,\n name: skill.name,\n text,\n tokens: estimateTokens(text),\n // Sort key: `always` outranks any matched score so it survives packing.\n score: 1_000 + (skill.priority ?? 0),\n mode: skill.mode,\n tools: skill.tools ?? [],\n });\n }\n for (const m of matched) {\n const text = await renderSkill(m.skill, ctx, m.sections);\n out.push({\n id: m.skill.id,\n name: m.skill.name,\n text,\n tokens: estimateTokens(text),\n score: m.score,\n mode: m.skill.mode,\n tools: m.skill.tools ?? [],\n });\n }\n return out.sort((a, b) => b.score - a.score);\n }\n\n /**\n * One-line index of the skills the model may load on demand. Cheap enough to\n * include every turn — this is the \"menu\" half of progressive disclosure.\n */\n manualIndex(): string {\n if (this.manualIndexCache !== undefined) return this.manualIndexCache;\n const manual = this.list().filter((s) => s.mode === \"manual\");\n const lines = manual.map((s) => `- ${s.id}: ${s.description}`);\n const index = !manual.length\n ? \"\"\n : [\"Loadable skills — call `loadSkill` with an id before acting in these areas:\", ...lines].join(\"\\n\");\n this.manualIndexCache = index;\n return index;\n }\n\n /** Everything a `loadSkill` call should return for `id`. */\n async load(id: string, ctx: SkillContext): Promise<{ found: boolean; text: string; tools: string[] }> {\n const skill = this.skills.get(id);\n if (!skill) {\n const near = this.list()\n .map((s) => s.id)\n .filter((sid) => sid.includes(id) || id.includes(sid));\n return {\n found: false,\n // Return a suggestion, not just a failure: a model that gets \"unknown\n // id\" retries the same id, while one that gets alternatives recovers.\n text: near.length\n ? `No skill \"${id}\". Did you mean: ${near.join(\", \")}?`\n : `No skill \"${id}\". Available: ${this.list().map((s) => s.id).join(\", \") || \"(none)\"}`,\n tools: [],\n };\n }\n return { found: true, text: await renderSkill(skill, ctx), tools: skill.tools ?? [] };\n }\n}\n","// Agent cards — the agent's visual vocabulary.\n//\n// A card is a structured tool output that the host renders as UI instead of as\n// JSON. Two ways one gets produced:\n// • a DOMAIN tool attaches a card to its result (\"here are the pools I found\"), or\n// • the agent calls the generic `visualize` tool and CHOOSES a presentation.\n// The second is what makes the agent visually flexible rather than limited to\n// whatever cards someone hard-coded.\n//\n// Three design rules, each learned from a real failure mode:\n//\n// 1. Validator and renderer are registered TOGETHER (registry.ts). In a\n// hand-maintained dispatch chain, adding a payload parser and forgetting the\n// render branch degrades the card to a bare \"ran ✓\" chip — silently, in\n// production, and only for that one card.\n//\n// 2. Interactive cards are never collapsible. A card that asks for a decision\n// (confirm, pick, fill) is part of the conversation's control flow; hiding\n// it inside a \"3 steps completed\" accordion makes it unreachable, which\n// reads to the user as the agent hanging.\n//\n// 3. Cards carry their own `expired` state. Card payloads are large and often\n// trimmed out of persisted history; a reloaded thread must say \"this result\n// expired, ask again\" rather than rendering an empty shell.\n\nexport type CardTone = \"neutral\" | \"positive\" | \"negative\" | \"warning\" | \"info\";\n\nexport type CardValueFormat = \"text\" | \"number\" | \"currency\" | \"percent\" | \"bytes\" | \"duration\" | \"datetime\" | \"code\";\n\n// ── Built-in card specs ─────────────────────────────────────────────────────\n\nexport type TableColumn = {\n key: string;\n label: string;\n format?: CardValueFormat;\n align?: \"left\" | \"right\" | \"center\";\n /** Render this column's cell as an emphasis/status pill. */\n pill?: boolean;\n};\n\nexport type TableCard = {\n kind: \"table\";\n title?: string;\n caption?: string;\n columns: TableColumn[];\n rows: Record<string, unknown>[];\n /** Column key to sort by on first render. */\n sortBy?: string;\n sortDir?: \"asc\" | \"desc\";\n};\n\nexport type StatItem = {\n label: string;\n value: string | number;\n format?: CardValueFormat;\n /** Signed change vs a prior period; drives colour and arrow. */\n delta?: number;\n deltaFormat?: CardValueFormat;\n hint?: string;\n tone?: CardTone;\n};\n\nexport type StatsCard = {\n kind: \"stats\";\n title?: string;\n items: StatItem[];\n};\n\nexport type ChartSeries = {\n name: string;\n /** `[x, y]` pairs; x is a number, a timestamp, or a category label. */\n points: [string | number, number][];\n type?: \"line\" | \"area\" | \"bar\" | \"scatter\";\n color?: string;\n /** Plot against a secondary axis — volume under price, for instance. */\n axis?: \"left\" | \"right\";\n};\n\nexport type ChartAnnotation = {\n type: \"hline\" | \"vline\" | \"band\" | \"marker\";\n value: string | number;\n /** Second bound, for `band`. */\n to?: string | number;\n label?: string;\n tone?: CardTone;\n};\n\nexport type ChartCard = {\n kind: \"chart\";\n title?: string;\n /** OHLC candles are their own shape; series charts use `series`. */\n variant?: \"series\" | \"candlestick\";\n xLabel?: string;\n yLabel?: string;\n xType?: \"time\" | \"number\" | \"category\";\n series?: ChartSeries[];\n candles?: { t: string | number; o: number; h: number; l: number; c: number; v?: number }[];\n annotations?: ChartAnnotation[];\n stacked?: boolean;\n};\n\nexport type TimelineCard = {\n kind: \"timeline\";\n title?: string;\n events: {\n at: string | number;\n label: string;\n detail?: string;\n tone?: CardTone;\n }[];\n};\n\nexport type KeyValueCard = {\n kind: \"keyvalue\";\n title?: string;\n items: { label: string; value: string | number; format?: CardValueFormat; tone?: CardTone; mono?: boolean }[];\n};\n\nexport type ProgressStep = {\n label: string;\n status: \"pending\" | \"active\" | \"done\" | \"failed\" | \"skipped\";\n detail?: string;\n};\n\nexport type ProgressCard = {\n kind: \"progress\";\n title?: string;\n steps: ProgressStep[];\n /** 0–1. Omit for indeterminate. */\n fraction?: number;\n};\n\nexport type MediaCard = {\n kind: \"media\";\n title?: string;\n items: {\n url: string;\n alt?: string;\n caption?: string;\n mediaType?: string;\n /** Known intrinsic geometry keeps generated media from shifting on decode. */\n width?: number;\n height?: number;\n durationMs?: number;\n }[];\n layout?: \"grid\" | \"single\";\n};\n\nexport type MarkdownCard = { kind: \"markdown\"; title?: string; body: string };\n\n/**\n * A document artifact — long-form Markdown the agent authored and the user\n * reads in a previewer rather than inline in the transcript.\n *\n * `docId` is the stable handle every later turn addresses: the body here is for\n * display only, and stripCardPayload removes it from what the model sees after\n * the turn that produced it. A model that wants to re-read the document calls\n * the read tool with this id — which is the point, because a document large\n * enough to deserve a previewer is too large to re-send every turn.\n *\n * `revision` is the optimistic-concurrency token. An edit carrying a stale one\n * is refused rather than applied to text that has since moved.\n */\nexport type DocumentCard = {\n kind: \"document\";\n docId: string;\n title: string;\n markdown: string;\n revision: number;\n};\n\n/**\n * A matrix of options against criteria.\n *\n * The most domain-portable card there is: legal clause-vs-clause, vendor\n * selection, pricing tiers, candidate evaluation, feature comparison. Boolean\n * values render as ✓/✗, so \"does it have X\" tables need no encoding by the model.\n */\nexport type ComparisonCard = {\n kind: \"comparison\";\n title?: string;\n /** The things being compared — these become columns. */\n options: { id: string; label: string; note?: string; highlight?: boolean }[];\n /** The dimensions they are compared on — these become rows. */\n criteria: {\n label: string;\n /** Keyed by option id. `true`/`false` render as ✓/✗; `null` renders as “—”. */\n values: Record<string, string | number | boolean | null>;\n detail?: string;\n weight?: \"low\" | \"normal\" | \"high\";\n }[];\n};\n\n/** Items with a state. Compliance reviews, launch readiness, QA passes, audits. */\nexport type ChecklistCard = {\n kind: \"checklist\";\n title?: string;\n items: {\n label: string;\n status: \"done\" | \"todo\" | \"blocked\" | \"na\";\n detail?: string;\n /** Optional heading to group consecutive items under. */\n group?: string;\n }[];\n};\n\n/** A single highlighted note. Disclaimers, caveats, prerequisites, warnings. */\nexport type CalloutCard = {\n kind: \"callout\";\n tone: \"info\" | \"warning\" | \"danger\" | \"success\" | \"note\";\n title?: string;\n body: string;\n};\n\n/**\n * Sources behind a claim.\n *\n * Domain-agnostic and unusually important for agents specifically: it is the\n * card that lets a reader check the work rather than trust the summary.\n */\nexport type CitationsCard = {\n kind: \"citations\";\n title?: string;\n items: {\n title: string;\n /** Publication, court, statute, dataset, site — whatever the source is. */\n source?: string;\n url?: string;\n date?: string | number;\n /** The specific passage relied on. */\n snippet?: string;\n locator?: string;\n relevance?: \"high\" | \"medium\" | \"low\";\n }[];\n};\n\n/** Staged drop-off. Conversion funnels, hiring pipelines, case attrition, intake flows. */\nexport type FunnelCard = {\n kind: \"funnel\";\n title?: string;\n stages: { label: string; value: number; note?: string }[];\n format?: CardValueFormat;\n};\n\n/** One value against a scale, with optional named bands. Scores, risk levels, sentiment. */\nexport type GaugeCard = {\n kind: \"gauge\";\n title?: string;\n value: number;\n min?: number;\n max?: number;\n label?: string;\n bands?: { from: number; to: number; label: string; tone?: CardTone }[];\n format?: CardValueFormat;\n};\n\nexport type TreeNode = {\n label: string;\n detail?: string;\n tone?: CardTone;\n children?: TreeNode[];\n};\n\n/** Nested structure. Document outlines, org charts, taxonomies, decision trees. */\nexport type TreeCard = {\n kind: \"tree\";\n title?: string;\n nodes: TreeNode[];\n};\n\nexport type CodeCard = { kind: \"code\"; title?: string; language?: string; code: string; filename?: string };\n\nexport type DiffCard = {\n kind: \"diff\";\n title?: string;\n before: string;\n after: string;\n language?: string;\n};\n\n// ── Interactive card specs ──────────────────────────────────────────────────\n// These produce a CardAction when the user responds, which the runtime feeds\n// back as the tool's result — that is the human-in-the-loop seam.\n\nexport type ChoiceCard = {\n kind: \"choice\";\n title?: string;\n prompt?: string;\n multiple?: boolean;\n options: {\n id: string;\n label: string;\n description?: string;\n /** Small facts shown on the option row: APR, TVL, price. */\n meta?: { label: string; value: string | number; format?: CardValueFormat }[];\n imageUrl?: string;\n disabled?: boolean;\n disabledReason?: string;\n }[];\n};\n\nexport type FormField =\n | { name: string; label: string; type: \"text\" | \"textarea\"; placeholder?: string; required?: boolean; value?: string }\n | { name: string; label: string; type: \"number\"; min?: number; max?: number; step?: number; required?: boolean; value?: number; suffix?: string }\n | { name: string; label: string; type: \"select\"; options: { value: string; label: string }[]; required?: boolean; value?: string }\n | { name: string; label: string; type: \"boolean\"; value?: boolean };\n\nexport type FormCard = {\n kind: \"form\";\n title?: string;\n description?: string;\n fields: FormField[];\n submitLabel?: string;\n};\n\nexport type ConfirmCard = {\n kind: \"confirm\";\n /** The one question the buttons answer, such as \"Rename the report?\". Shown last, above the buttons. */\n title: string;\n /** The consequential details — amounts, targets, anything irreversible. May be empty when `description` already says all of it. */\n summary: { label: string; value: string | number; tone?: CardTone; mono?: boolean }[];\n /** What will happen, in a sentence or two. Shown first. */\n description?: string;\n confirmLabel?: string;\n cancelLabel?: string;\n /** Renders the confirm control as destructive. */\n danger?: boolean;\n};\n\nexport type BuiltinCard =\n | TableCard\n | StatsCard\n | ChartCard\n | TimelineCard\n | KeyValueCard\n | ProgressCard\n | MediaCard\n | MarkdownCard\n | DocumentCard\n | EditReviewCard\n | EmailCard\n | CodeCard\n | DiffCard\n | ComparisonCard\n | ChecklistCard\n | CalloutCard\n | CitationsCard\n | FunnelCard\n | GaugeCard\n | TreeCard\n | ChoiceCard\n | FormCard\n | ConfirmCard;\n\nexport type BuiltinCardKind = BuiltinCard[\"kind\"];\n\n/**\n * The approval surface for a proposed document edit.\n *\n * Interactive, because in in-chat editing the diff IS the approval: there is no\n * other moment at which the user gets to see what is about to happen. Hunks are\n * accepted individually rather than all-or-nothing — partial acceptance is what\n * makes the exchange read as collaboration instead of take-it-or-leave-it, and\n * an edit is already the smallest independently applicable unit because it\n * carries its own anchor.\n */\nexport type EditReviewCard = {\n kind: \"editreview\";\n docId: string;\n title: string;\n /** Revision the edits were computed against; a stale one is refused. */\n revision: number;\n /** One line on why, in the model's words. */\n summary?: string;\n hunks: {\n index: number;\n block: number;\n removed: string[];\n added: string[];\n }[];\n};\n\n/**\n * A drafted email, before it is anyone's outbox.\n *\n * Always a draft the user completes — which is exactly the `draft` preset tier\n * (\"produces something the USER must approve/sign. No side effects\"). The\n * framework never holds a mail credential, for the same reason a Transport\n * never holds an API key.\n *\n * Editable but not interactive: nothing waits on it. The run does not suspend,\n * because the model asked no question — it produced a thing.\n */\nexport type EmailCard = {\n kind: \"email\";\n to: string[];\n cc?: string[];\n bcc?: string[];\n subject: string;\n /** Plain text. Markdown here would be a lie: mailto cannot carry it. */\n body: string;\n};\n\n/** A host-registered card is any `{kind}` object; built-ins are the typed subset. */\nexport type CardSpec = BuiltinCard | ({ kind: string } & Record<string, unknown>);\n\n/** Envelope attached to a tool result, or returned by `visualize`. */\n/**\n * Where a host shows a card: in the conversation (`inline`, the default), in its side panel\n * (`panel`), or inside a document block (`document`). The same renderer draws it in every place.\n * Structurally the same as super-protocol's `CardPlacement`; core has no dependencies, so it is\n * repeated here. An interactive card is only ever inline.\n */\nexport type CardPlacement = \"inline\" | \"panel\" | \"document\";\n\nexport const CARD_PLACEMENTS: readonly CardPlacement[] = [\"inline\", \"panel\", \"document\"];\n\nexport const isCardPlacement = (value: unknown): value is CardPlacement => CARD_PLACEMENTS.includes(value as CardPlacement);\n\nexport type Card = {\n id: string;\n spec: CardSpec;\n /**\n * Where the agent or tool asked for the card to be shown. Absent means `inline`. A host with no\n * side panel shows a `panel` card inline; it never drops it.\n */\n placement?: CardPlacement;\n /** Set when the payload was dropped from persisted history. */\n expired?: boolean;\n /** Tool call this card belongs to, for correlating an action back. */\n callId?: string;\n /**\n * What the user answered, once they have.\n *\n * Lives on the card rather than in the renderer's local state because the card\n * is re-mounted from history when the turn commits — state does not survive\n * that, and a renderer left guessing shows the wrong answer.\n */\n action?: CardAction;\n};\n\n/** What the user did with an interactive card. Becomes the tool result. */\nexport type CardAction = {\n cardId: string;\n callId?: string;\n kind: string;\n type: \"submit\" | \"select\" | \"confirm\" | \"cancel\" | \"dismiss\";\n /** Selected option ids, form values, or nothing for confirm/cancel. */\n value?: unknown;\n at: number;\n};\n\n/** Marker key used to recognise a card inside an arbitrary tool output. */\nexport const CARD_KEY = \"$card\" as const;\n\nexport type CardCarrier = { [CARD_KEY]: Card } & Record<string, unknown>;\n\nexport function isCardCarrier(value: unknown): value is CardCarrier {\n return (\n typeof value === \"object\" &&\n value !== null &&\n CARD_KEY in value &&\n typeof (value as Record<string, unknown>)[CARD_KEY] === \"object\"\n );\n}\n\n/** Attach a card to a tool result without disturbing the data the model reads. */\nexport function withCard<T extends Record<string, unknown>>(data: T, spec: CardSpec, id?: string, placement?: CardPlacement): T & CardCarrier {\n const card: Card = { id: id ?? `card_${Math.random().toString(36).slice(2, 10)}`, spec, ...(placement && placement !== \"inline\" ? { placement } : {}) };\n return { ...data, [CARD_KEY]: card };\n}\n\n/**\n * Remove a card payload from a tool output, leaving a note in its place.\n *\n * The card is for the user's eyes; the model gets the surrounding data. Sending\n * both is double billing — and a chart spec with 2,000 points is the single\n * largest thing a tool result can carry. Applied in two places, which must stay\n * consistent: within a running turn (before each provider call) and when a\n * persisted thread is rebuilt into context.\n */\nexport function stripCardPayload(output: unknown): unknown {\n if (!isCardCarrier(output)) return output;\n const { [CARD_KEY]: card, ...rest } = output as Record<string, unknown>;\n const kind = (card as { spec?: { kind?: string } })?.spec?.kind ?? \"card\";\n return { ...rest, rendered: `[${kind} card shown to the user]` };\n}\n","// History compaction.\n//\n// Two strategies, and the choice between them is a real trade:\n//\n// trim — drop oldest turns until it fits. Free, instant, and loses\n// information silently. Correct as a fallback and for short\n// overflows.\n// summarize — ask a cheap model to compress the older span into a brief, keep\n// recent turns verbatim. Costs a request and latency, preserves\n// the thread's arc. Correct for long-lived conversations.\n//\n// Both preserve two invariants that a naive slice breaks:\n// • a tool-call and its result must stay together, or the next request 400s;\n// • the first kept message must not be a `tool` reply to a dropped call.\n\nimport type { Message } from \"../content/types.js\";\nimport { messageText } from \"../content/parts.js\";\nimport { countMessageTokens, countMessagesTokens } from \"../tokens/budget.js\";\n// countMessageTokens is used to price the pinned summary during a secondary trim.\nimport type { TokenCounter } from \"../tokens/estimate.js\";\n\nexport type CompactionResult = {\n messages: Message[];\n strategy: \"none\" | \"trim\" | \"summarize\";\n droppedCount: number;\n tokensBefore: number;\n tokensAfter: number;\n summary?: string;\n};\n\n/** True if the message pairs with a preceding assistant tool-call. */\nfunction isToolReply(m: Message): boolean {\n return m.parts.some((p) => p.type === \"tool-result\");\n}\n\n/**\n * Move a cut point later until it lands on a message that can legally start a\n * history: a user or assistant turn that is not a dangling tool reply, and not\n * an assistant turn whose tool calls were left behind.\n */\nexport function safeCutIndex(messages: readonly Message[], desired: number): number {\n let index = Math.max(0, Math.min(desired, messages.length));\n while (index < messages.length) {\n const m = messages[index]!;\n if (isToolReply(m)) {\n index += 1;\n continue;\n }\n // An assistant message carrying tool-calls is only safe to start on if its\n // results are in the kept span — they immediately follow, so they are.\n break;\n }\n return index;\n}\n\nexport function trimHistory(\n messages: readonly Message[],\n limitTokens: number,\n counter?: TokenCounter,\n /** Pass this when the caller already scanned `messages` (e.g. `compactHistory`'s `tokensBefore`) to skip a second full-history scan. */\n knownTokensBefore?: number,\n): CompactionResult {\n const tokensBefore = knownTokensBefore ?? countMessagesTokens(messages, counter);\n if (tokensBefore <= limitTokens) {\n return { messages: [...messages], strategy: \"none\", droppedCount: 0, tokensBefore, tokensAfter: tokensBefore };\n }\n\n // Walk backwards accumulating until the budget is spent — the newest turns are\n // the ones worth keeping.\n let used = 0;\n let cut = messages.length;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const size = countMessageTokens(messages[i]!, counter);\n if (used + size > limitTokens) break;\n used += size;\n cut = i;\n }\n\n const start = safeCutIndex(messages, cut);\n const kept = messages.slice(start);\n return {\n messages: [...kept],\n strategy: \"trim\",\n droppedCount: start,\n tokensBefore,\n tokensAfter: countMessagesTokens(kept, counter),\n };\n}\n\nexport type Summarizer = (messages: readonly Message[], signal?: AbortSignal) => Promise<string>;\n\nexport type CompactOptions = {\n limitTokens: number;\n /** Turns always kept verbatim at the tail. */\n keepRecent?: number;\n summarizer?: Summarizer;\n counter?: TokenCounter;\n signal?: AbortSignal;\n};\n\n/**\n * Compact history to fit `limitTokens`.\n *\n * Falls back to `trim` whenever summarization is unavailable or fails —\n * a summarizer that errors must never take the user's turn down with it.\n */\nexport async function compactHistory(\n messages: readonly Message[],\n opts: CompactOptions,\n): Promise<CompactionResult> {\n const counter = opts.counter;\n const tokensBefore = countMessagesTokens(messages, counter);\n if (tokensBefore <= opts.limitTokens) {\n return { messages: [...messages], strategy: \"none\", droppedCount: 0, tokensBefore, tokensAfter: tokensBefore };\n }\n if (!opts.summarizer) return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n\n const keepRecent = opts.keepRecent ?? 8;\n const desiredCut = Math.max(0, messages.length - keepRecent);\n const cut = safeCutIndex(messages, desiredCut);\n const older = messages.slice(0, cut);\n const recent = messages.slice(cut);\n\n // Nothing old enough to be worth a summarization round-trip.\n if (older.length < 2) return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n\n let summary: string;\n try {\n summary = (await opts.summarizer(older, opts.signal)).trim();\n } catch {\n return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n }\n if (!summary) return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n\n const summaryMessage: Message = {\n id: `summary_${cut}`,\n role: \"user\",\n parts: [\n {\n type: \"text\",\n // Framed as context rather than as something the user said, so the model\n // does not answer the summary as if it were a new request.\n text: `[Earlier conversation summary — ${older.length} messages]\\n${summary}`,\n },\n ],\n metadata: { superchat: \"compaction-summary\", replaced: older.length },\n };\n\n const out = [summaryMessage, ...recent];\n const tokensAfter = countMessagesTokens(out, counter);\n\n // Even summarized it may not fit, when the recent tail alone is huge. Trim\n // only the RECENT span and keep the summary: a plain trim walks from the\n // newest backwards, so it would drop the summary first — discarding the one\n // artifact we just paid a model call to produce.\n if (tokensAfter > opts.limitTokens) {\n const summaryTokens = countMessageTokens(summaryMessage, counter);\n // tokensAfter already accounts for summaryMessage + recent, so recent's\n // token count falls out for free instead of a second scan.\n const trimmed = trimHistory(recent, Math.max(0, opts.limitTokens - summaryTokens), counter, tokensAfter - summaryTokens);\n const messages = [summaryMessage, ...trimmed.messages];\n return {\n messages,\n strategy: \"summarize\",\n droppedCount: older.length + trimmed.droppedCount,\n tokensBefore,\n tokensAfter: countMessagesTokens(messages, counter),\n summary,\n };\n }\n\n return { messages: out, strategy: \"summarize\", droppedCount: older.length, tokensBefore, tokensAfter, summary };\n}\n\n/**\n * Default summarization prompt builder. Exposed so a host can reuse the exact\n * framing with its own model call.\n */\nexport function buildSummaryPrompt(messages: readonly Message[]): string {\n const transcript = messages\n .map((m) => {\n const text = messageText(m);\n const calls = m.parts\n .filter((p) => p.type === \"tool-call\")\n .map((p) => `→ called ${(p as { name: string }).name}`)\n .join(\" \");\n return `${m.role}: ${text}${calls ? ` ${calls}` : \"\"}`.trim();\n })\n .filter((line) => line.length > line.indexOf(\":\") + 1)\n .join(\"\\n\");\n\n return [\n \"Compress this conversation span into a brief the assistant can act on.\",\n \"Keep: decisions made, facts established, user preferences, unresolved threads, and identifiers (ids, addresses, filenames).\",\n \"Drop: pleasantries, restatements, and anything superseded by a later turn.\",\n \"Write it as terse notes, not prose. No preamble.\",\n \"\",\n transcript,\n ].join(\"\\n\");\n}\n","// The ContextBuilder — one deterministic pipeline, run fresh every turn.\n//\n// Order matters and is fixed:\n// 1. run sources in parallel (identity, skills, memory, host sources)\n// 2. pack layers into the system budget, pinned first, then by priority\n// 3. compact history into what remains\n// 4. record every decision in the trace\n//\n// Determinism is the point: the same inputs must produce the same request, or\n// prompt caching never hits and debugging becomes archaeology.\n\nimport { lastUserText, stripUiOnlyParts } from \"../content/parts.js\";\nimport type { Message } from \"../content/types.js\";\nimport { isCardCarrier, stripCardPayload } from \"../cards/types.js\";\nimport { compactHistory, type Summarizer } from \"./compaction.js\";\nimport { createBudget, packByPriority, type TokenBudget } from \"../tokens/budget.js\";\nimport { estimateTokens, type TokenCounter } from \"../tokens/estimate.js\";\nimport type { SkillRegistry } from \"../skills/registry.js\";\nimport type { ResolvedSkill } from \"../skills/types.js\";\nimport type { BuiltContext, ContextLayer, ContextSource, ContextTrace, TraceEntry } from \"./types.js\";\n\nexport type ContextBuilderOptions = {\n /** Base instructions. Always pinned — identity is not negotiable under pressure. */\n identity?: string;\n skills?: SkillRegistry;\n sources?: ContextSource[];\n budget?: TokenBudget;\n contextWindow?: number;\n maxOutputTokens?: number;\n counter?: TokenCounter;\n summarizer?: Summarizer;\n /** Verbatim turns kept at the tail when summarizing. */\n keepRecent?: number;\n /**\n * Appended to instructions when any card-capable tool is present. Tells the\n * model where cards appear so its prose reads correctly around them — without\n * this, models narrate \"as you can see in the table below\" above a card that\n * renders above the text.\n */\n cardPlacementNote?: string;\n};\n\nconst DEFAULT_CARD_NOTE = [\n \"CARD PLACEMENT: a card renders immediately where you call the tool, before any text you write afterwards.\",\n \"Write a one-line lead-in before the card, and your interpretation after it. Never re-list the card's contents in prose.\",\n].join(\"\\n\");\n\nexport class ContextBuilder {\n private readonly opts: ContextBuilderOptions;\n\n constructor(opts: ContextBuilderOptions = {}) {\n this.opts = opts;\n }\n\n /** The skill registry this builder draws from, for UI that lists or pins skills. */\n get skillRegistry(): SkillRegistry | undefined {\n return this.opts.skills;\n }\n\n /** The identity block, for a settings pane that lets the user read or edit it. */\n get identity(): string | undefined {\n return this.opts.identity;\n }\n\n async build(input: {\n messages: readonly Message[];\n vars?: Record<string, unknown>;\n /** Skills to force in regardless of matching (a user pinning one in the UI). */\n forceSkillIds?: string[];\n /** Tool names available before skill unlocks. */\n baseTools?: string[];\n signal?: AbortSignal;\n }): Promise<BuiltContext> {\n const counter = this.opts.counter ?? estimateTokens;\n const budget =\n this.opts.budget ??\n createBudget(this.opts.contextWindow ?? 128_000, { maxOutputTokens: this.opts.maxOutputTokens });\n\n const entries: TraceEntry[] = [];\n const warnings: string[] = [];\n const vars = input.vars ?? {};\n const query = lastUserText(input.messages);\n\n const layers: ContextLayer[] = [];\n const unlockedTools = new Set<string>(input.baseTools ?? []);\n let skills: ResolvedSkill[] = [];\n\n // ── 1. identity ─────────────────────────────────────────────────────────\n if (this.opts.identity?.trim()) {\n const text = this.opts.identity.trim();\n layers.push({ id: \"identity\", kind: \"identity\", text, tokens: counter(text), pinned: true, priority: 1_000 });\n }\n\n // ── 2. skills ───────────────────────────────────────────────────────────\n if (this.opts.skills) {\n const started = Date.now();\n try {\n skills = await this.opts.skills.resolveForTurn({ query, vars }, { forceIds: input.forceSkillIds });\n for (const s of skills) {\n layers.push({\n id: `skill:${s.id}`,\n kind: \"skills\",\n text: s.text,\n tokens: s.tokens,\n // `always` skills are pinned; matched ones compete for budget.\n pinned: s.mode === \"always\",\n priority: s.score,\n });\n for (const t of s.tools) unlockedTools.add(t);\n }\n entries.push({\n id: \"skills\",\n kind: \"skills\",\n status: \"included\",\n tokens: skills.reduce((n, s) => n + s.tokens, 0),\n detail: skills.length ? skills.map((s) => `${s.id}(${s.mode})`).join(\", \") : \"none matched\",\n ms: Date.now() - started,\n });\n } catch (e) {\n entries.push({\n id: \"skills\",\n kind: \"skills\",\n status: \"failed\",\n tokens: 0,\n detail: e instanceof Error ? e.message : String(e),\n });\n warnings.push(\"Skill resolution failed; continuing without skills.\");\n }\n\n const index = this.opts.skills.manualIndex();\n if (index) {\n layers.push({ id: \"skill-index\", kind: \"skill-index\", text: index, tokens: counter(index), pinned: true, priority: 900 });\n }\n }\n\n // ── 3. host sources, in parallel ────────────────────────────────────────\n const sources = this.opts.sources ?? [];\n if (sources.length) {\n const results = await Promise.allSettled(\n sources.map(async (s) => {\n const started = Date.now();\n const out = await s.run({ messages: input.messages, query, vars, signal: input.signal });\n return { id: s.id, out, ms: Date.now() - started };\n }),\n );\n for (const [i, r] of results.entries()) {\n const sourceId = sources[i]!.id;\n if (r.status === \"rejected\") {\n // A failed source degrades the turn; it must not kill it. Memory\n // retrieval timing out should cost context, not the conversation.\n entries.push({\n id: sourceId,\n kind: \"source\",\n status: \"failed\",\n tokens: 0,\n detail: r.reason instanceof Error ? r.reason.message : String(r.reason),\n });\n warnings.push(`Context source \"${sourceId}\" failed.`);\n continue;\n }\n const { out, ms } = r.value;\n for (const layer of out.layers ?? []) layers.push(layer);\n for (const t of out.tools ?? []) unlockedTools.add(t);\n entries.push({\n id: sourceId,\n kind: \"source\",\n status: \"included\",\n tokens: (out.layers ?? []).reduce((n, l) => n + l.tokens, 0),\n ms,\n });\n }\n }\n\n // ── 4. card placement contract ──────────────────────────────────────────\n if (unlockedTools.has(\"visualize\")) {\n const note = this.opts.cardPlacementNote ?? DEFAULT_CARD_NOTE;\n layers.push({ id: \"card-contract\", kind: \"custom\", text: note, tokens: counter(note), pinned: true, priority: 850 });\n }\n\n // ── 5. pack the system block ────────────────────────────────────────────\n // Pinned layers are placed first and unconditionally; if they alone exceed\n // the share we warn rather than silently dropping an identity or a safety\n // rule, because dropping those is never the right automatic answer.\n const pinned = layers.filter((l) => l.pinned).sort((a, b) => b.priority - a.priority);\n const optional = layers.filter((l) => !l.pinned).sort((a, b) => b.priority - a.priority);\n const pinnedTokens = pinned.reduce((n, l) => n + l.tokens, 0);\n\n if (pinnedTokens > budget.shares.system + budget.shares.skills) {\n warnings.push(\n `Pinned context (${pinnedTokens} tok) exceeds its budget (${budget.shares.system + budget.shares.skills} tok). ` +\n \"Shorten always-on skills or raise the system share.\",\n );\n }\n\n const optionalLimit = Math.max(0, budget.shares.system + budget.shares.skills - pinnedTokens);\n const packed = packByPriority(optional, optionalLimit, (l) => l.tokens);\n for (const dropped of packed.dropped) {\n entries.push({\n id: dropped.item.id,\n kind: dropped.item.kind,\n status: \"dropped\",\n tokens: 0,\n originalTokens: dropped.size,\n detail: `no room in the ${optionalLimit} tok optional share`,\n });\n // A dropped skill must not leave its tools unlocked — the model would see\n // tools it has no instructions for.\n if (dropped.item.id.startsWith(\"skill:\")) {\n const skillId = dropped.item.id.slice(\"skill:\".length);\n const skill = skills.find((s) => s.id === skillId);\n for (const t of skill?.tools ?? []) unlockedTools.delete(t);\n skills = skills.filter((s) => s.id !== skillId);\n }\n }\n\n const included = [...pinned, ...packed.included];\n for (const layer of packed.included) {\n entries.push({ id: layer.id, kind: layer.kind, status: \"included\", tokens: layer.tokens });\n }\n\n const system = included.map((l) => l.text.trim()).filter(Boolean).join(\"\\n\\n\");\n // Sum of the layers' own precomputed token counts, rather than re-tokenizing\n // the joined string. This slightly undercounts the \"\\n\\n\" join separators,\n // but that's a handful of tokens against an already-approximate counter\n // (see tokens/estimate.ts) — not worth a second full-text scan to close.\n const systemTokens = included.reduce((n, l) => n + l.tokens, 0);\n\n // ── 6. history ──────────────────────────────────────────────────────────\n // Sanitize first: strip UI-only parts and shrink card payloads. A card spec\n // can be tens of KB of chart points, and the model already saw the summary\n // in the tool's `output` — re-sending the pixels is pure waste.\n const sanitized = input.messages\n .filter((m) => m.role !== \"system\")\n .map(stripUiOnlyParts)\n .map(stripCardPayloads);\n\n const historyLimit = Math.max(1_000, budget.shares.history);\n const compaction = await compactHistory(sanitized, {\n limitTokens: historyLimit,\n keepRecent: this.opts.keepRecent ?? 8,\n summarizer: this.opts.summarizer,\n counter,\n signal: input.signal,\n });\n\n if (compaction.strategy !== \"none\") {\n entries.push({\n id: \"history\",\n kind: \"history\",\n status: compaction.strategy === \"summarize\" ? \"compacted\" : \"truncated\",\n tokens: compaction.tokensAfter,\n originalTokens: compaction.tokensBefore,\n detail: `${compaction.strategy}: dropped ${compaction.droppedCount} message(s)`,\n });\n } else {\n entries.push({ id: \"history\", kind: \"history\", status: \"included\", tokens: compaction.tokensAfter });\n }\n\n // compaction.tokensAfter is already an exact count of compaction.messages —\n // computed inside compactHistory/trimHistory with this same counter — so\n // reuse it instead of scanning the history a second time.\n const historyTokens = compaction.tokensAfter;\n const toolNames = [...unlockedTools].sort();\n const total = systemTokens + historyTokens;\n\n const trace: ContextTrace = {\n entries,\n budget,\n totals: { system: systemTokens, history: historyTokens, tools: 0, total },\n headroom: budget.contextWindow - total - budget.shares.output,\n warnings,\n };\n\n if (trace.headroom < 0) {\n warnings.push(`Context overflows its window by ~${-trace.headroom} tokens. The provider may reject this request.`);\n }\n\n return { system, messages: compaction.messages, toolNames, trace, skills };\n }\n}\n\n/** Apply `stripCardPayload` to every tool result in a persisted message. */\nfunction stripCardPayloads(m: Message): Message {\n let changed = false;\n const parts = m.parts.map((p) => {\n if (p.type !== \"tool-result\" || !isCardCarrier(p.output)) return p;\n changed = true;\n return { ...p, output: stripCardPayload(p.output) };\n });\n return changed ? { ...m, parts } : m;\n}\n","// Reading and rewriting a Markdown document, as pure functions.\n//\n// Everything here is string in, string out. That is deliberate: the hard parts\n// of in-chat editing are addressing and refusal, both of which are decidable\n// without a store, a model or a browser — so they are decided in code that a\n// unit test can pin exactly.\n\nimport { splitBlocks, type MarkdownBlock } from \"../content/blocks.js\";\nimport type {\n AppliedEdit,\n DocumentEdit,\n DocumentOutlineEntry,\n EditResult,\n} from \"./types.js\";\n\nconst headingLevel = (line: string): number | undefined => {\n const m = /^ {0,3}(#{1,6})\\s/.exec(line);\n return m ? m[1]!.length : undefined;\n};\n\n/**\n * A map of the document, cheap enough to send every turn.\n *\n * Editing is a directed activity — \"the third section\", \"the bit about\n * renewal\" — not a similarity search, so the model needs to navigate rather\n * than retrieve. An outline costs a line per block and lets it ask for exactly\n * the span it wants; without one it either guesses or is handed the whole\n * document, and the whole document is what this design exists to avoid.\n */\nexport function outlineOf(markdown: string): DocumentOutlineEntry[] {\n return splitBlocks(markdown).map((block, i) => entryOf(markdown, block, i));\n}\n\n/** The outline entry for one block, which is block `i` of `markdown`. */\nfunction entryOf(markdown: string, block: MarkdownBlock, i: number): DocumentOutlineEntry {\n const raw = markdown.slice(block.start, block.end);\n const firstLine = raw.split(\"\\n\", 1)[0] ?? \"\";\n const level = block.kind === \"text\" ? headingLevel(firstLine) : undefined;\n return {\n block: i,\n kind: block.kind,\n ...(level ? { level } : {}),\n preview: firstLine.trim().slice(0, 100),\n chars: raw.length,\n };\n}\n\n/** Source text of a block range, inclusive. Out-of-range yields \"\". */\nexport function spanOf(markdown: string, from: number, to = from): string {\n const blocks = splitBlocks(markdown);\n const first = blocks[Math.max(0, from)];\n const last = blocks[Math.min(blocks.length - 1, to)];\n if (!first || !last || first.start > last.end) return \"\";\n return markdown.slice(first.start, last.end);\n}\n\n/** Blocks whose text contains `query`, case-insensitively. */\nexport function searchBlocks(markdown: string, query: string): DocumentOutlineEntry[] {\n const needle = query.trim().toLowerCase();\n if (!needle) return [];\n // One split, and an outline entry only for the blocks that match. Going\n // through outlineOf split the document a second time and described every\n // block only to throw most of them away.\n const out: DocumentOutlineEntry[] = [];\n splitBlocks(markdown).forEach((block, i) => {\n if (markdown.slice(block.start, block.end).toLowerCase().includes(needle)) {\n out.push(entryOf(markdown, block, i));\n }\n });\n return out;\n}\n\n/**\n * Where `needle` first occurs in `haystack`, and how many times it occurs in\n * all, overlaps included. Only the count is needed past the first hit — it is\n * what the ambiguity message reports — so the hits are counted, not collected.\n */\nfunction occurrences(haystack: string, needle: string, offset = 0): { first: number; count: number } {\n let first = -1;\n let count = 0;\n if (!needle) return { first, count };\n for (let i = haystack.indexOf(needle); i !== -1; i = haystack.indexOf(needle, i + 1)) {\n if (count === 0) first = i + offset;\n count += 1;\n }\n return { first, count };\n}\n\nconst blockOf = (blocks: MarkdownBlock[], index: number): number =>\n Math.max(\n 0,\n blocks.findIndex((b) => index >= b.start && index < b.end),\n );\n\n/**\n * Apply edits to a document, or refuse.\n *\n * Refusing is half the job and the more important half. A find that matches\n * nothing means the model is quoting text that is not there; a find that\n * matches twice means it has not said which one. Guessing either — taking the\n * first match, say — produces a change in the wrong place that the diff will\n * present as if it were intended, and the user approves it. So both are\n * rejections with a reason the model can act on, exactly as tools/repair.ts\n * treats malformed arguments: an invalid input to retry, not a result.\n *\n * Edits are resolved against the ORIGINAL text and spliced into it in one pass,\n * so earlier edits cannot shift the offsets of later ones. Two edits that\n * overlap are a contradiction rather than a merge, and are refused.\n */\nexport function applyEdits(markdown: string, edits: readonly DocumentEdit[]): EditResult {\n if (!edits.length) return { ok: true, markdown, applied: [] };\n\n const blocks = splitBlocks(markdown);\n const applied: AppliedEdit[] = [];\n\n for (const edit of edits) {\n if (!edit.find) {\n return { ok: false, reason: \"not-found\", message: \"An edit needs a non-empty `find`.\", edit };\n }\n\n let hits: { first: number; count: number };\n if (edit.block === undefined) {\n hits = occurrences(markdown, edit.find);\n } else {\n const block = blocks[edit.block];\n if (!block) {\n return {\n ok: false,\n reason: \"no-such-block\",\n message: `Block ${edit.block} does not exist; the document has ${blocks.length}.`,\n edit,\n };\n }\n hits = occurrences(markdown.slice(block.start, block.end), edit.find, block.start);\n }\n\n if (hits.count === 0) {\n return {\n ok: false,\n reason: \"not-found\",\n message:\n `Could not find that text${edit.block === undefined ? \"\" : ` in block ${edit.block}`}. ` +\n \"Re-read the document and quote it exactly, whitespace included.\",\n edit,\n };\n }\n if (hits.count > 1) {\n return {\n ok: false,\n reason: \"ambiguous\",\n message:\n `That text appears ${hits.count} times. Include more surrounding text, or name the block.`,\n edit,\n };\n }\n\n const start = hits.first;\n const end = start + edit.find.length;\n const clash = applied.find((a) => start < a.end && end > a.start);\n if (clash) {\n return {\n ok: false,\n reason: \"ambiguous\",\n message: \"Two edits target overlapping text. Send them as one edit instead.\",\n edit,\n };\n }\n\n applied.push({ edit, start, end, block: blockOf(blocks, start) });\n }\n\n // Front to back, cutting every unchanged stretch straight from the original.\n // Overlaps were refused above, so no edit needs text another one produced —\n // and re-slicing the rewritten string once per edit made this quadratic.\n let out = \"\";\n let from = 0;\n for (const a of [...applied].sort((x, y) => x.start - y.start)) {\n out += markdown.slice(from, a.start) + a.edit.replace;\n from = a.end;\n }\n\n return { ok: true, markdown: out + markdown.slice(from), applied };\n}\n\n/** Line-level view of one edit, for the approval card. */\nexport type EditHunk = {\n index: number;\n block: number;\n removed: string[];\n added: string[];\n};\n\n/**\n * One hunk per edit, rather than a computed diff.\n *\n * The point of hunks here is that the user can accept some and reject others,\n * and an edit is already the smallest independently-applicable unit — it\n * carries its own anchor. Deriving hunks from a text diff instead would produce\n * regions that are not separately applicable, which is the wrong shape for the\n * question being asked.\n */\nexport function hunksOf(applied: readonly AppliedEdit[]): EditHunk[] {\n return applied.map((a, index) => ({\n index,\n block: a.block,\n removed: a.edit.find.split(\"\\n\"),\n added: a.edit.replace === \"\" ? [] : a.edit.replace.split(\"\\n\"),\n }));\n}\n","// Reference DocumentStores.\n//\n// Mirrors JobStore/FileStore: an in-memory one for tests and a localStorage one\n// for a browser, both defensive on read so a corrupted entry degrades to \"that\n// document is gone\" rather than taking the page with it.\n//\n// History is kept as full snapshots, not as inverse edits. Undo is then a\n// checkout of a previous body — which cannot be computed wrongly, whereas an\n// inverse edit can, and does, precisely when the document has moved on.\n\nimport { AgentError } from \"../errors.js\";\nimport type { DocumentSnapshot, DocumentStore } from \"./types.js\";\n\n/** Bounded so a long editing session cannot fill a storage quota. */\nconst MAX_HISTORY = 20;\n\nlet counter = 0;\nconst mintId = () => `doc_${Date.now().toString(36)}${(counter += 1).toString(36)}`;\n\n/**\n * Newest first, with insertion order as the tie-break.\n *\n * `updatedAt` is a millisecond clock and two documents created in the same tick\n * tie on it — which a plain sort resolves as insertion order, i.e. oldest\n * first, i.e. exactly backwards. Both stores hold their documents in insertion\n * order, so reversing before a stable sort puts the later one ahead of the\n * earlier one whenever the timestamps cannot separate them.\n */\nconst byRecency = (docs: DocumentSnapshot[]): DocumentSnapshot[] =>\n [...docs].reverse().sort((a, b) => b.updatedAt - a.updatedAt);\n\nconst staleError = (id: string, expected: number, actual: number) =>\n new AgentError(\n \"invalid-request\",\n `Document ${id} is at revision ${actual}, not ${expected}. Re-read it before editing.`,\n );\n\n/**\n * The snapshot a write produces. `restoredFrom` is set only by an undo and is\n * dropped by every other write — carried over by the spread, it would make an\n * ordinary edit after an undo look like part of the undo, and the next undo\n * would skip it.\n */\nconst nextSnapshot = (current: DocumentSnapshot, markdown: string, restoredFrom: number | undefined): DocumentSnapshot => {\n const { restoredFrom: _previous, ...rest } = current;\n return {\n ...rest,\n markdown,\n revision: current.revision + 1,\n ...(restoredFrom !== undefined ? { restoredFrom } : {}),\n updatedAt: Date.now(),\n };\n};\n\nexport function createMemoryDocumentStore(): DocumentStore {\n const docs = new Map<string, DocumentSnapshot>();\n const past = new Map<string, DocumentSnapshot[]>();\n\n return {\n async list() {\n return byRecency([...docs.values()]);\n },\n async get(id) {\n return docs.get(id);\n },\n async create({ title, markdown, id }) {\n const now = Date.now();\n const doc: DocumentSnapshot = {\n id: id ?? mintId(),\n title,\n markdown,\n revision: 1,\n createdAt: now,\n updatedAt: now,\n };\n docs.set(doc.id, doc);\n past.set(doc.id, []);\n return doc;\n },\n async update(id, markdown, expectedRevision, opts) {\n const current = docs.get(id);\n if (!current) throw new AgentError(\"invalid-request\", `No document ${id}.`);\n if (current.revision !== expectedRevision) {\n throw staleError(id, expectedRevision, current.revision);\n }\n past.set(id, [current, ...(past.get(id) ?? [])].slice(0, MAX_HISTORY));\n const next = nextSnapshot(current, markdown, opts?.restoredFrom);\n docs.set(id, next);\n return next;\n },\n async remove(id) {\n docs.delete(id);\n past.delete(id);\n },\n async history(id) {\n return past.get(id) ?? [];\n },\n };\n}\n\nexport function createLocalDocumentStore(key = \"superchat:documents\"): DocumentStore {\n type Persisted = { docs: Record<string, DocumentSnapshot>; past: Record<string, DocumentSnapshot[]> };\n\n const read = (): Persisted => {\n try {\n const raw = globalThis.localStorage?.getItem(key) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : null;\n if (typeof parsed !== \"object\" || parsed === null) return { docs: {}, past: {} };\n const p = parsed as Partial<Persisted>;\n return { docs: p.docs ?? {}, past: p.past ?? {} };\n } catch {\n return { docs: {}, past: {} };\n }\n };\n\n const write = (all: Persisted) => {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(all));\n } catch {\n // Quota or private mode. A lost document is bad; a thrown exception in\n // the middle of an approved edit is worse — the user already said yes.\n }\n };\n\n return {\n async list() {\n return byRecency(Object.values(read().docs));\n },\n async get(id) {\n return read().docs[id];\n },\n async create({ title, markdown, id }) {\n const all = read();\n const now = Date.now();\n const doc: DocumentSnapshot = {\n id: id ?? mintId(),\n title,\n markdown,\n revision: 1,\n createdAt: now,\n updatedAt: now,\n };\n all.docs[doc.id] = doc;\n all.past[doc.id] = [];\n write(all);\n return doc;\n },\n async update(id, markdown, expectedRevision, opts) {\n const all = read();\n const current = all.docs[id];\n if (!current) throw new AgentError(\"invalid-request\", `No document ${id}.`);\n if (current.revision !== expectedRevision) {\n throw staleError(id, expectedRevision, current.revision);\n }\n all.past[id] = [current, ...(all.past[id] ?? [])].slice(0, MAX_HISTORY);\n const next = nextSnapshot(current, markdown, opts?.restoredFrom);\n all.docs[id] = next;\n write(all);\n return next;\n },\n async remove(id) {\n const all = read();\n delete all.docs[id];\n delete all.past[id];\n write(all);\n },\n async history(id) {\n return read().past[id] ?? [];\n },\n };\n}\n","// The document tools.\n//\n// Storage is the host's — these take a DocumentStore and never assume one. What\n// the framework keeps is the protocol (how a document is addressed and\n// rewritten) and the approval surface (what the user sees before anything\n// changes), which is the same line Transport draws around credentials.\n//\n// Returned rather than registered, exactly as MCP imports and app actions are:\n// a tool that can rewrite the user's document must be given its authority\n// explicitly by whoever wires it up, never by virtue of existing.\n\nimport type { CardSpec } from \"../cards/types.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { ToolDefinition, ToolExecutionContext } from \"../tools/types.js\";\nimport { applyEdits, hunksOf, outlineOf, searchBlocks, spanOf } from \"./edit.js\";\nimport type { DocumentEdit, DocumentSnapshot, DocumentStore } from \"./types.js\";\n\nexport type DocumentToolsOptions = {\n store: DocumentStore;\n /** Cap on what a single read returns, so one call cannot flood context. */\n maxSpanChars?: number;\n /**\n * Cap on how many documents `listDocuments` names at once.\n *\n * The list is the cheapest thing here per entry and the easiest to let grow\n * without noticing: a host that has accumulated four hundred documents would\n * otherwise spend a page of context on the index before the model has read a\n * word of any of them.\n */\n maxListed?: number;\n};\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\nconst num = (v: unknown): number | undefined => (typeof v === \"number\" ? v : undefined);\n\nconst documentSpec = (doc: DocumentSnapshot): CardSpec => ({\n kind: \"document\",\n docId: doc.id,\n title: doc.title,\n markdown: doc.markdown,\n revision: doc.revision,\n});\n\n/**\n * The refusal for a document that moved underneath a write — shaped like\n * applyEdits' own refusals, because it is one: \"stale-revision\" means re-read\n * and propose again, which is a retry the model can make. A thrown error is\n * not; it surfaces as a failed tool, and the model is left guessing whether\n * anything was written.\n */\nconst moved = (docId: string, read: number, now: DocumentSnapshot | undefined, when: string) =>\n now\n ? {\n output: {\n error: `Document ${docId} moved from revision ${read} to ${now.revision} ${when}. Nothing was written. Re-read it and propose again.`,\n reason: \"stale-revision\" as const,\n revision: now.revision,\n },\n failure: \"invalid-input\" as const,\n }\n : {\n output: { error: `Document ${docId} was removed ${when}. Nothing was written.` },\n failure: \"not-found\" as const,\n };\n\n/**\n * Write through the store, turning its revision check into a refusal.\n *\n * The check stays the store's — it is the only place that sees every writer —\n * but its error is the host's to shape, so this does not parse it. It asks the\n * store again instead: if the document is no longer at the revision this write\n * was based on, the throw was that check and the caller gets `moved`; anything\n * else is a real failure and is rethrown.\n */\nasync function writeOrRefuse(\n store: DocumentStore,\n doc: DocumentSnapshot,\n markdown: string,\n when: string,\n opts?: { restoredFrom?: number },\n): Promise<{ next: DocumentSnapshot } | ReturnType<typeof moved>> {\n try {\n return { next: await store.update(doc.id, markdown, doc.revision, opts) };\n } catch (err) {\n const now = await store.get(doc.id);\n if (!now || now.revision !== doc.revision) return moved(doc.id, doc.revision, now, when);\n throw err;\n }\n}\n\nconst CREATE_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"title\", \"markdown\"],\n properties: {\n title: { type: \"string\", description: \"Short, human title. Becomes the filename on download.\" },\n markdown: { type: \"string\", description: \"The document body, in Markdown.\" },\n },\n};\n\nconst READ_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"docId\"],\n properties: {\n docId: { type: \"string\" },\n mode: {\n type: \"string\",\n enum: [\"outline\", \"span\", \"search\"],\n description:\n \"outline: block index + heading + size for the whole document — start here. span: the text of a block range. search: blocks containing a phrase.\",\n },\n from: { type: \"number\", description: \"First block, for mode=span.\" },\n to: { type: \"number\", description: \"Last block, for mode=span. Defaults to `from`.\" },\n query: { type: \"string\", description: \"Phrase to look for, for mode=search.\" },\n },\n};\n\nconst EDIT_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"docId\", \"revision\", \"edits\"],\n properties: {\n docId: { type: \"string\" },\n revision: {\n type: \"number\",\n description: \"The revision you read. If the document has moved on, the edit is refused.\",\n },\n summary: { type: \"string\", description: \"One line on what these changes do.\" },\n edits: {\n type: \"array\",\n description:\n \"Each edit finds exact text and replaces it. Never send the whole document. If `find` matches nothing or matches twice, the edit is refused rather than guessed at.\",\n items: {\n type: \"object\",\n required: [\"find\", \"replace\"],\n properties: {\n block: { type: \"number\", description: \"Restrict the search to this block. Send it whenever you know it.\" },\n find: { type: \"string\", description: \"Exact existing text, whitespace included.\" },\n replace: { type: \"string\", description: \"What replaces it. Empty string deletes.\" },\n },\n },\n },\n },\n};\n\n/**\n * Build the document tools against a host store.\n *\n * `editDocument` is `side: \"confirm\"` and does its own asking: it computes the\n * change, shows it as an edit review, and writes only what came back accepted.\n * There is no path that writes without that answer.\n *\n * `listDocuments` is what makes the rest of them reachable. A docId arrives in\n * a tool result and then lives only in the transcript — which compaction trims,\n * and which a new thread never had. Without an index, \"a document outlives its\n * thread\" is true of the store and false of the agent: the document survives\n * and nothing can name it. It returns titles and sizes, never bodies, so\n * carrying it costs a line per document.\n */\nexport function createDocumentTools(opts: DocumentToolsOptions): ToolDefinition[] {\n const { store, maxSpanChars = 6000, maxListed = 50 } = opts;\n\n const listDocuments: ToolDefinition = {\n name: \"listDocuments\",\n description:\n \"List the documents that exist, newest first — id, title and size, never the body. Use it when the user refers to something they worked on before and you do not have its id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Optional filter on the title, case-insensitive.\" },\n },\n },\n side: \"read\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const needle = str(i[\"query\"]).trim().toLowerCase();\n const all = await store.list();\n const matched = needle ? all.filter((d) => d.title.toLowerCase().includes(needle)) : all;\n return {\n output: {\n documents: matched.slice(0, maxListed).map((d) => ({\n docId: d.id,\n title: d.title,\n revision: d.revision,\n blocks: outlineOf(d.markdown).length,\n chars: d.markdown.length,\n updatedAt: d.updatedAt,\n })),\n // Reported rather than silent, for the same reason a truncated span\n // is: a model that believes it has seen every document will tell the\n // user theirs does not exist.\n total: matched.length,\n truncated: matched.length > maxListed,\n },\n };\n },\n };\n\n const createDocument: ToolDefinition = {\n name: \"createDocument\",\n description:\n \"Create a document the user will keep and come back to — a draft, a report, notes. Use instead of a long reply when the result is a thing rather than an answer. Returns an id for reading and editing it later.\",\n inputSchema: CREATE_SCHEMA,\n side: \"write\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const doc = await store.create({ title: str(i[\"title\"]) || \"Untitled\", markdown: str(i[\"markdown\"]) });\n return {\n // The model gets the handle and the shape, never the body: the card\n // below carries the body for the user, and stripCardPayload keeps it\n // out of context from the next turn on.\n output: {\n docId: doc.id,\n revision: doc.revision,\n title: doc.title,\n blocks: outlineOf(doc.markdown).length,\n },\n card: documentSpec(doc),\n };\n },\n };\n\n const readDocument: ToolDefinition = {\n name: \"readDocument\",\n description:\n \"Read part of a document. Ask for the outline first, then the spans you actually need — the whole body is never returned at once.\",\n inputSchema: READ_SCHEMA,\n side: \"read\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const doc = await store.get(str(i[\"docId\"]));\n if (!doc) return { output: { error: `No document ${str(i[\"docId\"])}.` }, failure: \"not-found\" as const };\n\n const mode = str(i[\"mode\"]) || \"outline\";\n if (mode === \"outline\") {\n return { output: { docId: doc.id, title: doc.title, revision: doc.revision, outline: outlineOf(doc.markdown) } };\n }\n if (mode === \"search\") {\n return { output: { docId: doc.id, revision: doc.revision, matches: searchBlocks(doc.markdown, str(i[\"query\"])) } };\n }\n\n const from = num(i[\"from\"]) ?? 0;\n const to = num(i[\"to\"]) ?? from;\n const text = spanOf(doc.markdown, from, to);\n return {\n output: {\n docId: doc.id,\n revision: doc.revision,\n from,\n to,\n // Truncation is REPORTED, not silent: a model that believes it has\n // read a whole section will quote text that is not there, and the\n // edit will then be refused for a reason that looks like its fault.\n truncated: text.length > maxSpanChars,\n text: text.slice(0, maxSpanChars),\n },\n };\n },\n };\n\n const editDocument: ToolDefinition = {\n name: \"editDocument\",\n description:\n \"Propose changes to a document. The user sees them as a diff and accepts them one at a time; nothing is written until they do.\",\n inputSchema: EDIT_SCHEMA,\n side: \"confirm\",\n // The diff is the approval, and only this tool can compute it.\n confirmation: \"tool\",\n async execute(input, ctx: ToolExecutionContext) {\n const i = (input ?? {}) as Record<string, unknown>;\n const docId = str(i[\"docId\"]);\n const doc = await store.get(docId);\n if (!doc) return { output: { error: `No document ${docId}.` }, failure: \"not-found\" as const };\n\n const revision = num(i[\"revision\"]);\n if (revision !== doc.revision) {\n return {\n output: {\n error: `Document is at revision ${doc.revision}, you read ${revision}. Re-read it and propose again.`,\n reason: \"stale-revision\",\n revision: doc.revision,\n },\n failure: \"invalid-input\" as const,\n };\n }\n\n const edits = Array.isArray(i[\"edits\"]) ? (i[\"edits\"] as DocumentEdit[]) : [];\n const result = applyEdits(doc.markdown, edits);\n if (!result.ok) {\n // A refusal the model can act on, not a thrown error: \"not-found\" means\n // re-read, \"ambiguous\" means widen the anchor. Guessing instead would\n // put a change somewhere nobody asked for and present it for approval\n // as though it were intended.\n return { output: { error: result.message, reason: result.reason, edit: result.edit }, failure: \"invalid-input\" as const };\n }\n\n const hunks = hunksOf(result.applied);\n const answer = (await ctx.requestCard?.({\n kind: \"editreview\",\n docId: doc.id,\n title: doc.title,\n revision: doc.revision,\n ...(str(i[\"summary\"]) ? { summary: str(i[\"summary\"]) } : {}),\n hunks,\n })) as { accepted?: number[] } | undefined;\n\n // No handler, or a cancel, both mean nothing was approved. Defaulting to\n // \"apply everything\" when the answer is missing would turn a broken wire\n // into an unreviewed write.\n const accepted = Array.isArray(answer?.accepted) ? answer.accepted : [];\n if (!accepted.length) {\n return { output: { applied: 0, revision: doc.revision, note: \"The user accepted none of the changes.\" } };\n }\n\n // Re-read: the review is an await on a human, and the document can move\n // while it is open — the user accepts a different edit first, undoes, or\n // types in another tab. What they approved was a diff against `doc`, so\n // if the document is no longer `doc` the approval does not transfer:\n // applying it anyway would put an approved-looking change into a context\n // nobody reviewed. Refused, with the revision to re-read from.\n const latest = await store.get(doc.id);\n if (!latest || latest.revision !== doc.revision) {\n return moved(doc.id, doc.revision, latest, \"while the change was awaiting approval\");\n }\n\n // Only the accepted subset, recomputed from its anchors against the body\n // just re-read rather than spliced in at the proposal's offsets.\n const chosen = result.applied.filter((_, index) => accepted.includes(index)).map((a) => a.edit);\n const partial = applyEdits(latest.markdown, chosen);\n if (!partial.ok) {\n return { output: { error: partial.message, reason: partial.reason }, failure: \"invalid-input\" as const };\n }\n\n // The re-read above narrows the window; the store's own check closes it.\n const written = await writeOrRefuse(store, latest, partial.markdown, \"while the change was being written\");\n if (!(\"next\" in written)) return written;\n const { next } = written;\n return {\n output: {\n docId: next.id,\n revision: next.revision,\n applied: accepted.length,\n rejected: hunks.length - accepted.length,\n },\n card: documentSpec(next),\n };\n },\n };\n\n const undoDocument: ToolDefinition = {\n name: \"undoDocument\",\n description:\n \"Restore an earlier version of a document. With no toRevision it steps back one version, and calling it again keeps stepping back. Each undo is itself a new revision.\",\n inputSchema: {\n type: \"object\",\n required: [\"docId\"],\n properties: {\n docId: { type: \"string\" },\n toRevision: {\n type: \"number\",\n description: \"Restore exactly this earlier revision instead of stepping back one.\",\n },\n },\n },\n side: \"write\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const docId = str(i[\"docId\"]);\n const doc = await store.get(docId);\n if (!doc) return { output: { error: `No document ${docId}.` }, failure: \"not-found\" as const };\n\n const history = await store.history(docId);\n const toRevision = num(i[\"toRevision\"]);\n\n // The cursor. A body that is itself an undo stands for the revision it\n // restored, so stepping back starts from THERE — not from its own,\n // newer number, whose predecessor is the very body that was just undone.\n // That one line is the difference between walking back and ping-ponging.\n const at = doc.restoredFrom ?? doc.revision;\n const target =\n toRevision === undefined\n ? history.find((h) => h.revision < at)\n : history.find((h) => h.revision === toRevision);\n\n if (!target) {\n return {\n output: {\n error:\n toRevision === undefined\n ? \"This document has no earlier version.\"\n : toRevision >= doc.revision\n ? `Revision ${toRevision} is not earlier than the current revision, ${doc.revision}.`\n : `Revision ${toRevision} is not one this document still keeps.`,\n revision: doc.revision,\n available: history.map((h) => h.revision),\n },\n failure: \"not-found\" as const,\n };\n }\n\n // Undo restores a stored body and mints a NEW revision — it does not roll\n // the number back. An inverse edit would have to be computed, and can be\n // computed wrongly; a checkout cannot. And keeping revisions monotonic\n // means an in-flight edit proposed against the undone body is refused\n // rather than silently applied to text that no longer exists.\n const restoredFrom = target.restoredFrom ?? target.revision;\n const written = await writeOrRefuse(store, doc, target.markdown, \"before the undo was written\", { restoredFrom });\n if (!(\"next\" in written)) return written;\n const { next } = written;\n return {\n output: {\n docId: next.id,\n revision: next.revision,\n restoredFrom,\n // Said, so a model asked to go further back can tell whether there\n // is anywhere to go without spending a call to find out.\n canUndoFurther: history.some((h) => h.revision < restoredFrom),\n },\n card: documentSpec(next),\n };\n },\n };\n\n return [listDocuments, createDocument, readDocument, editDocument, undoDocument];\n}\n\nconst EMAIL_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"to\", \"subject\", \"body\"],\n properties: {\n to: { type: \"array\", items: { type: \"string\" } },\n cc: { type: \"array\", items: { type: \"string\" } },\n bcc: { type: \"array\", items: { type: \"string\" } },\n subject: { type: \"string\" },\n body: { type: \"string\", description: \"Plain text. Not Markdown — mail cannot carry it here.\" },\n },\n};\n\n/**\n * Draft an email for the user to send.\n *\n * `draft` tier, and the tier is the whole point: this produces something the\n * user approves and sends themselves. There is no send path and no credential,\n * which is what makes it safe to hand out.\n */\nexport function createEmailDraftTool(): ToolDefinition {\n return {\n name: \"draftEmail\",\n description:\n \"Draft an email for the user to review and send. It is never sent for them — they get an editable draft with the message ready to open in their mail client.\",\n inputSchema: EMAIL_SCHEMA,\n side: \"write\",\n execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const to = Array.isArray(i[\"to\"]) ? (i[\"to\"] as string[]).map(String) : [];\n const spec: CardSpec = {\n kind: \"email\",\n to,\n ...(Array.isArray(i[\"cc\"]) ? { cc: (i[\"cc\"] as string[]).map(String) } : {}),\n ...(Array.isArray(i[\"bcc\"]) ? { bcc: (i[\"bcc\"] as string[]).map(String) } : {}),\n subject: str(i[\"subject\"]),\n body: str(i[\"body\"]),\n };\n return {\n output: { drafted: true, to, subject: str(i[\"subject\"]), note: \"Shown to the user as an editable draft; not sent.\" },\n card: spec,\n };\n },\n };\n}\n","// Getting a draft out of the conversation and into a mail client.\n//\n// Two exits, and the ordering between them is the design.\n//\n// `.eml` is the primary one. It is a real RFC 5322 message: every mail client\n// opens it, it carries recipients, headers and (later) attachments, it survives\n// being saved, and it does not care how long the body is.\n//\n// `mailto:` is the convenience shortcut, and its limits are hard enough to be\n// worth stating rather than discovering:\n// - practical URL ceiling around 2000 characters, past which clients TRUNCATE\n// silently — the user sends a letter with the end missing and no warning\n// - no attachments, at all\n// - plain text only\n// - newline encoding varies between clients\n// - on a desktop with no mail client registered, clicking it does nothing,\n// and reports nothing\n//\n// So the composer offers both and says which is which, rather than shipping the\n// shortcut and calling the feature done.\n//\n// Neither path sends anything. Sending needs a credential, and the framework\n// holding one would break the rule Transport already keeps.\n\nimport type { EmailCard } from \"../cards/types.js\";\n\n/** Roughly where mail clients start truncating a mailto: URL. */\nexport const MAILTO_SAFE_LENGTH = 2000;\n\nconst encode = (s: string) =>\n // encodeURIComponent leaves these legal-in-a-query characters alone, and\n // some clients read them as delimiters. Percent-encoding them costs nothing.\n encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n\nexport type MailtoLink = {\n href: string;\n /** True when the href is long enough that a client may cut it short. */\n mayTruncate: boolean;\n length: number;\n};\n\nexport function buildMailto(email: EmailCard): MailtoLink {\n const params: string[] = [];\n if (email.cc?.length) params.push(`cc=${encode(email.cc.join(\",\"))}`);\n if (email.bcc?.length) params.push(`bcc=${encode(email.bcc.join(\",\"))}`);\n if (email.subject) params.push(`subject=${encode(email.subject)}`);\n // CRLF rather than LF: clients disagree about a bare %0A, and every one of\n // them understands %0D%0A.\n if (email.body) params.push(`body=${encode(email.body.replace(/\\r?\\n/g, \"\\r\\n\"))}`);\n\n const href = `mailto:${encode(email.to.join(\",\"))}${params.length ? `?${params.join(\"&\")}` : \"\"}`;\n return { href, length: href.length, mayTruncate: href.length > MAILTO_SAFE_LENGTH };\n}\n\n// ── Line limits ──────────────────────────────────────────────────────────────\n//\n// RFC 5322 §2.1.1 sets two of them, and the difference between them is the\n// difference between untidy and rejected:\n//\n// 998 octets a hard MUST. Past it a strict MTA or parser is entitled to\n// refuse the message, and several do.\n// 78 octets a SHOULD, for humans reading raw source.\n//\n// A drafted letter reaches the ceiling more easily than it looks: one long\n// unwrapped paragraph is a single line, and \"one long unwrapped paragraph\" is\n// what a model writes unless told otherwise. So the body is measured, and if\n// any line would break the MUST the encoding changes to carry it losslessly\n// rather than the text being folded — folding prose would silently insert line\n// breaks the user did not write into a letter they are about to send.\n\n/** Hard ceiling, excluding the CRLF. */\nconst MAX_LINE_OCTETS = 998;\n/** What folding aims at. */\nconst FOLD_WIDTH = 78;\n/** An RFC 2047 encoded-word may not exceed this, including its delimiters. */\nconst MAX_ENCODED_WORD = 75;\n\nconst octetsOf = (s: string) => new TextEncoder().encode(s).length;\n\nconst base64 = (bytes: Uint8Array): string =>\n typeof btoa === \"function\"\n ? btoa(String.fromCharCode(...bytes))\n : Buffer.from(bytes).toString(\"base64\");\n\n/**\n * RFC 2047 encoded-words, split so none exceeds 75 characters.\n *\n * One word for the whole subject is the tempting version and it breaks on a\n * long non-ASCII subject: over the limit, clients variously truncate the header\n * or show the raw `=?UTF-8?B?…` to the user. The split has to fall on a UTF-8\n * character boundary — cut mid-sequence and the decoder emits a replacement\n * character in the middle of a word, which looks like the sender's mistake.\n */\nfunction encodedWords(value: string): string[] {\n const bytes = new TextEncoder().encode(value);\n // \"=?UTF-8?B?\" + \"?=\" is 12 characters; base64 costs 4 per 3 bytes. 45 bytes\n // is the largest multiple of 3 that still fits inside the limit.\n const perWord = Math.min(45, Math.floor(((MAX_ENCODED_WORD - 12) / 4) * 3));\n const words: string[] = [];\n\n for (let i = 0; i < bytes.length; ) {\n let take = Math.min(perWord, bytes.length - i);\n while (take > 1 && i + take < bytes.length && (bytes[i + take]! & 0xc0) === 0x80) take -= 1;\n words.push(`=?UTF-8?B?${base64(bytes.slice(i, i + take))}?=`);\n i += take;\n }\n return words.length ? words : [\"\"];\n}\n\n/**\n * Fold a header, or leave it exactly as it was.\n *\n * Only long headers are touched. Folding is reversible in principle, but\n * unfolding collapses the inserted whitespace, so a header that already fits\n * should come out byte-identical rather than round-tripped for no reason.\n */\nfunction fold(name: string, pieces: string[], separator: string): string {\n const flat = `${name}: ${pieces.join(`${separator} `)}`;\n if (octetsOf(flat) <= FOLD_WIDTH) return flat;\n\n const lines: string[] = [];\n let line = `${name}:`;\n pieces.forEach((piece, i) => {\n const token = i < pieces.length - 1 ? `${piece}${separator}` : piece;\n // A continuation line starts with whitespace; that is what makes it one.\n if (line !== `${name}:` && octetsOf(`${line} ${token}`) > FOLD_WIDTH) {\n lines.push(line);\n line = ` ${token}`;\n } else {\n line += ` ${token}`;\n }\n });\n lines.push(line);\n return lines.join(\"\\r\\n\");\n}\n\n/** Address lists fold at the commas — the only place a break is legal. */\nconst addressHeader = (name: string, addresses: string[]) => fold(name, addresses, \",\");\n\nfunction subjectHeader(subject: string): string {\n if (/[^\\x20-\\x7e]/.test(subject)) return fold(\"Subject\", encodedWords(subject), \"\");\n // An ASCII subject that already fits goes through untouched. Folding splits\n // on spaces and rejoins with one, so a subject with a deliberate double space\n // would come back altered for no gain.\n const flat = `Subject: ${subject}`;\n if (octetsOf(flat) <= FOLD_WIDTH) return flat;\n return fold(\"Subject\", subject.split(/ +/).filter(Boolean), \"\");\n}\n\n// ── Body ─────────────────────────────────────────────────────────────────────\n\nconst needsQuotedPrintable = (body: string) =>\n body.split(/\\r?\\n/).some((line) => octetsOf(line) > MAX_LINE_OCTETS);\n\n/**\n * Quoted-printable with soft line breaks.\n *\n * Lossless, unlike folding: a trailing `=` tells the receiver the line\n * continues, so the text the user wrote is the text that arrives. Chosen over\n * base64 because the .eml stays readable in a text editor, which is worth\n * keeping for something the user is meant to inspect before sending.\n */\nfunction quotedPrintable(body: string): string {\n const out: string[] = [];\n\n for (const line of body.split(/\\r?\\n/)) {\n const bytes = new TextEncoder().encode(line);\n let current = \"\";\n for (let i = 0; i < bytes.length; i += 1) {\n const b = bytes[i]!;\n const printable = b >= 32 && b <= 126 && b !== 61;\n // Trailing whitespace must be encoded or a transport is allowed to strip\n // it, which silently rewrites the line.\n const trailing = (b === 32 || b === 9) && i === bytes.length - 1;\n const token = printable && !trailing ? String.fromCharCode(b) : `=${b.toString(16).toUpperCase().padStart(2, \"0\")}`;\n // 76 including the soft-break `=`, so a token never straddles the break.\n if (current.length + token.length > 75) {\n out.push(`${current}=`);\n current = \"\";\n }\n current += token;\n }\n out.push(current);\n }\n\n return out.join(\"\\r\\n\");\n}\n\n/**\n * An RFC 5322 message.\n *\n * Deliberately without a Date or Message-ID: this is a DRAFT, and stamping it\n * with a send time it did not have would be a small lie that some clients then\n * display as fact. The user's own client fills both in when they send.\n */\nexport function buildEml(email: EmailCard): string {\n const encoded = needsQuotedPrintable(email.body);\n const lines = [\n addressHeader(\"To\", email.to),\n ...(email.cc?.length ? [addressHeader(\"Cc\", email.cc)] : []),\n ...(email.bcc?.length ? [addressHeader(\"Bcc\", email.bcc)] : []),\n subjectHeader(email.subject),\n \"MIME-Version: 1.0\",\n 'Content-Type: text/plain; charset=\"utf-8\"',\n `Content-Transfer-Encoding: ${encoded ? \"quoted-printable\" : \"8bit\"}`,\n \"\",\n encoded ? quotedPrintable(email.body) : email.body,\n ];\n // CRLF throughout — the spec's line ending, and the one strict parsers want.\n return lines.join(\"\\r\\n\").replace(/(?<!\\r)\\n/g, \"\\r\\n\");\n}\n\n/** A filename that will not upset a filesystem. */\nexport function emlFilename(email: EmailCard): string {\n const stem = (email.subject || \"draft\").replace(/[^\\w\\s.-]/g, \"\").trim().replace(/\\s+/g, \"-\").slice(0, 60);\n return `${stem || \"draft\"}.eml`;\n}\n","// The card registry.\n//\n// One registration binds four things that MUST NOT drift apart:\n// schema — what the model is told it may send\n// validate — what we actually accept (and the error we hand back)\n// interactive— whether this card participates in control flow\n// renderer — resolved by the UI package from the same `kind` key\n//\n// The reference implementation this is modelled on keeps parsers and render\n// branches in two hand-maintained lists, and its own comments record the\n// consequence: a card that had a parser but no render branch disappeared into a\n// generic \"ran ✓\" chip and nobody noticed. Binding them at registration makes\n// that failure unrepresentable — `renderers` is derived from the same map, so a\n// kind is either fully present or absent.\n\nimport type { Card, CardPlacement, CardSpec } from \"./types.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\n\nexport type CardValidation = { ok: true } | { ok: false; error: string; expected?: string };\n\nexport type CardKindDefinition = {\n kind: string;\n /** One line for the `visualize` tool description — this is what steers model choice. */\n summary: string;\n schema: JSONSchema;\n validate: (spec: unknown) => CardValidation;\n /** Interactive cards must render at top level and never collapse. */\n interactive?: boolean;\n /** Approximate token cost of the spec, for context budgeting of replayed cards. */\n estimateTokens?: (spec: CardSpec) => number;\n /**\n * Derive a renderable spec from one that is still streaming in — keep what\n * has fully arrived, drop the entry still being written when the renderer\n * cannot show it yet. Return `undefined` until there is something worth\n * drawing. The result must pass `validate`: `CardRegistry.partial` checks\n * it, so a preview is a VALID card that is merely incomplete, never a\n * malformed one.\n *\n * Omit for kinds that should keep a skeleton until they are whole. Ignored\n * on interactive kinds: a control the user can act on must never be shown\n * before the spec behind it is complete and validated.\n */\n partial?: (spec: Record<string, unknown>) => CardSpec | undefined;\n};\n\nexport const isObj = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/** Small validator helpers — enough to give the model an actionable correction. */\nexport const check = {\n object(spec: unknown, kind: string): CardValidation | Record<string, unknown> {\n if (!isObj(spec)) return { ok: false as const, error: `${kind} spec must be an object.` };\n return spec;\n },\n arrayField(spec: Record<string, unknown>, field: string, kind: string, minLength = 1): CardValidation | unknown[] {\n const value = spec[field];\n if (!Array.isArray(value)) {\n return { ok: false as const, error: `${kind}.${field} must be an array.`, expected: `${field}: [...]` };\n }\n if (value.length < minLength) {\n return { ok: false as const, error: `${kind}.${field} must have at least ${minLength} item(s).` };\n }\n return value;\n },\n};\n\nexport const failed = (v: unknown): v is CardValidation => isObj(v) && \"ok\" in v && (v as { ok: unknown }).ok === false;\n\nexport class CardRegistry {\n private kinds = new Map<string, CardKindDefinition>();\n\n constructor(definitions: readonly CardKindDefinition[] = []) {\n for (const d of definitions) this.register(d);\n }\n\n register(def: CardKindDefinition): this {\n this.kinds.set(def.kind, def);\n return this;\n }\n\n has(kind: string): boolean {\n return this.kinds.has(kind);\n }\n\n get(kind: string): CardKindDefinition | undefined {\n return this.kinds.get(kind);\n }\n\n list(): CardKindDefinition[] {\n return [...this.kinds.values()];\n }\n\n isInteractive(kind: string): boolean {\n return this.kinds.get(kind)?.interactive === true;\n }\n\n /**\n * Validate a spec. An unknown kind is a hard failure with the list of valid\n * kinds attached — a model that receives \"unknown kind: barchart, valid kinds\n * are: chart, table, …\" fixes itself on the next step, whereas one that\n * receives a silently-dropped card repeats the mistake forever.\n */\n validate(spec: unknown): CardValidation {\n if (!isObj(spec)) return { ok: false, error: \"Card spec must be an object with a `kind` field.\" };\n const kind = spec[\"kind\"];\n if (typeof kind !== \"string\") return { ok: false, error: \"Card spec is missing a string `kind`.\" };\n const def = this.kinds.get(kind);\n if (!def) {\n return {\n ok: false,\n error: `Unknown card kind \"${kind}\".`,\n expected: `One of: ${this.list().map((k) => k.kind).join(\", \")}`,\n };\n }\n return def.validate(spec);\n }\n\n /**\n * A preview of a spec that is still streaming, or `undefined` when there\n * should not be one: an unknown kind, an interactive kind, a kind with no\n * `partial`, or a derived spec its own validator rejects. The one place that\n * decides whether a partial spec may reach a renderer.\n */\n partial(spec: unknown): CardSpec | undefined {\n if (!isObj(spec) || typeof spec[\"kind\"] !== \"string\") return undefined;\n const def = this.kinds.get(spec[\"kind\"]);\n if (!def?.partial || def.interactive) return undefined;\n let preview: CardSpec | undefined;\n try {\n preview = def.partial(spec);\n } catch {\n return undefined; // a preview must never be able to fail the call it previews\n }\n if (!isObj(preview) || preview[\"kind\"] !== def.kind) return undefined;\n return def.validate(preview).ok ? preview : undefined;\n }\n\n /** The catalogue text embedded in the `visualize` tool description. */\n describe(): string {\n return this.list()\n .map((k) => `- ${k.kind}${k.interactive ? \" (interactive)\" : \"\"}: ${k.summary}`)\n .join(\"\\n\");\n }\n\n /** Per-kind schemas, for hosts that prefer one tool per card kind. */\n schemas(): Record<string, JSONSchema> {\n return Object.fromEntries(this.list().map((k) => [k.kind, k.schema]));\n }\n}\n\nlet cardCounter = 0;\nexport function makeCard(spec: CardSpec, callId?: string, id?: string, placement?: CardPlacement): Card {\n const where = placement && placement !== \"inline\" ? { placement } : {};\n // An explicit id means \"replace that card\": the reducer upserts by id, so\n // reusing one turns an append into an in-place update (`updateCard`).\n if (id) return { id, spec, ...(callId ? { callId } : {}), ...where };\n cardCounter += 1;\n return { id: `card_${Date.now().toString(36)}${cardCounter.toString(36)}`, spec, ...(callId ? { callId } : {}), ...where };\n}\n","// Card references: how text in a chat message points at something inside a card.\n//\n// The envelope (`ref:<target>?<name>=<value>&...`) is defined once by super-protocol\n// (docs/CARD-REFS.md, `parseCardRef`), and what the params mean is up to the card kind.\n// This is the host's copy of the parser: core has no dependencies, and the host must read links\n// without a card kind's vocabulary anyway. It matches `parseCardRef` in super-protocol 0.3.0\n// exactly, limits and messages included; the plugin package's `card-ref-agreement.test.ts`\n// checks that against the published protocol, so a link one accepts the other accepts.\n\nexport const CARD_REF_SCHEME = \"ref\";\n\nexport const CARD_REF_LIMITS = Object.freeze({\n /** The whole link, in UTF-16 code units. */\n length: 512,\n /** The target (the card's id). */\n target: 128,\n /** Distinct param names. */\n names: 16,\n /** Values of one param name (`key=a&key=b`). */\n values: 32,\n /** One param name. */\n name: 32,\n /** One decoded value, in UTF-16 code units. */\n value: 256,\n});\n\n/** A parsed reference. A repeated param is a list in order; values are decoded once, never split on commas. */\nexport interface CardRef {\n /** The `id` of the card this points into. */\n target: string;\n params: Record<string, string[]>;\n}\n\n/** What the reader did with the link: pointed at it, left it, or chose it (click, Enter, tap). */\nexport type CardRefEvent = \"enter\" | \"leave\" | \"activate\";\n\n/** What a card answers. `ok: false` lets the host show a stale reference as plain text, with the reason. */\nexport type CardRefResult = { ok: true; label?: string } | { ok: false; code: string; reason: string };\n\nexport type CardRefParse = { ok: true; ref: CardRef } | { ok: false; error: string };\n\n/** A host's side of references: hands one on to the card it points into. `null` clears everything shown. */\nexport interface CardRefHost {\n ref(ref: CardRef | null, event: CardRefEvent): CardRefResult;\n}\n\nconst TARGET = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;\nconst NAME = /^[a-z][A-Za-z0-9_-]{0,31}$/;\nconst RAW_VALUE = /^(?:[A-Za-z0-9._~-]|%[0-9A-Fa-f]{2})+$/;\n\nconst hasOwn = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k);\n\nfunction decodeValue(raw: string): string | null {\n const bytes: number[] = [];\n for (let i = 0; i < raw.length; i++) {\n if (raw[i] === \"%\") {\n bytes.push(parseInt(raw.slice(i + 1, i + 3), 16));\n i += 2;\n } else bytes.push(raw.charCodeAt(i));\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(Uint8Array.from(bytes));\n } catch {\n return null;\n }\n}\n\n/** Reads a `ref:` link. */\nexport function parseCardRef(href: unknown): CardRefParse {\n const fail = (error: string): CardRefParse => ({ ok: false, error });\n if (typeof href !== \"string\") return fail(\"a ref must be a string.\");\n if (href.length > CARD_REF_LIMITS.length) return fail(`a ref is at most ${CARD_REF_LIMITS.length} characters.`);\n if (!href.startsWith(`${CARD_REF_SCHEME}:`)) return fail(`a ref starts with \"${CARD_REF_SCHEME}:\".`);\n const rest = href.slice(CARD_REF_SCHEME.length + 1);\n if (rest.includes(\"#\")) return fail(\"a ref has no fragment.\");\n const q = rest.indexOf(\"?\");\n const target = q < 0 ? rest : rest.slice(0, q);\n if (!TARGET.test(target)) return fail(\"a ref target is 1 to 128 letters, digits, dot, underscore, colon or dash, starting with a letter or digit.\");\n const params: Record<string, string[]> = {};\n if (q >= 0) {\n const query = rest.slice(q + 1);\n if (query === \"\") return fail(\"a ref query is empty.\");\n for (const part of query.split(\"&\")) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) return fail(\"each ref param is name=value.\");\n const name = part.slice(0, eq);\n const raw = part.slice(eq + 1);\n if (!NAME.test(name)) return fail(\"a ref param name is 1 to 32 letters, digits, dash or underscore, starting with a lowercase letter.\");\n if (!RAW_VALUE.test(raw)) return fail(\"a ref param value is not empty and uses letters, digits, dot, dash, underscore, tilde or %XX only.\");\n const value = decodeValue(raw);\n if (value === null) return fail(\"a ref param value must be valid UTF-8.\");\n if (value.length > CARD_REF_LIMITS.value) return fail(`a ref param value is at most ${CARD_REF_LIMITS.value} characters.`);\n if (!hasOwn(params, name)) {\n if (Object.keys(params).length >= CARD_REF_LIMITS.names) return fail(`a ref has at most ${CARD_REF_LIMITS.names} param names.`);\n params[name] = [];\n }\n if (params[name]!.length >= CARD_REF_LIMITS.values) return fail(`a ref param has at most ${CARD_REF_LIMITS.values} values.`);\n params[name]!.push(value);\n }\n }\n return { ok: true, ref: { target, params } };\n}\n","// The built-in card catalogue — the agent's default visual vocabulary.\n//\n// Chosen to span the presentations an agent actually needs, not to be\n// exhaustive: comparison (table), magnitude (stats), shape-over-time (chart),\n// sequence (timeline), detail (keyvalue), long work (progress), rich text\n// (markdown/code/diff), media, and the three interactive ones that let the agent\n// ASK rather than assume (choice, form, confirm).\n//\n// Validators are permissive about extra fields and strict about the fields the\n// renderer indexes. A card that renders with a missing optional is fine; a card\n// whose `rows` is a string is a crash, so that is what we reject.\n\nimport { estimateJsonTokens } from \"../tokens/estimate.js\";\nimport { check, failed, isObj, type CardKindDefinition, type CardValidation } from \"./registry.js\";\nimport type { CardSpec } from \"./types.js\";\n\nconst ok: CardValidation = { ok: true };\n\n/**\n * The entries of `spec[field]` that are already renderable. The last entry of\n * a streaming array is usually half-written; `ready` decides whether it can be\n * shown yet (a row with one cell can, a checklist item with no status cannot).\n */\nconst arrived = (spec: Record<string, unknown>, field: string, ready: (item: Record<string, unknown>) => boolean) => {\n const value = spec[field];\n return Array.isArray(value) ? value.filter((item): item is Record<string, unknown> => isObj(item) && ready(item)) : [];\n};\nconst isScalar = (v: unknown) => typeof v === \"string\" || typeof v === \"number\";\n\nconst tokensOf = (spec: CardSpec) => estimateJsonTokens(spec);\n\nconst FORMATS = [\"text\", \"number\", \"currency\", \"percent\", \"bytes\", \"duration\", \"datetime\", \"code\"];\n\nexport const tableCard: CardKindDefinition = {\n kind: \"table\",\n summary: \"Many items sharing the same fields. Search results, inventories, case lists, line items, survey rows.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"columns\", \"rows\"],\n properties: {\n kind: { const: \"table\" },\n title: { type: \"string\" },\n caption: { type: \"string\" },\n columns: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"key\", \"label\"],\n properties: {\n key: { type: \"string\", description: \"Matches a key in each row object.\" },\n label: { type: \"string\" },\n format: { type: \"string\", enum: FORMATS },\n align: { type: \"string\", enum: [\"left\", \"right\", \"center\"] },\n pill: { type: \"boolean\", description: \"Render the cell as a status pill.\" },\n },\n },\n },\n rows: { type: \"array\", items: { type: \"object\" }, description: \"Objects keyed by column.key.\" },\n sortBy: { type: \"string\" },\n sortDir: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"table\");\n if (failed(s)) return s;\n const cols = check.arrayField(s as Record<string, unknown>, \"columns\", \"table\");\n if (failed(cols)) return cols;\n const rows = check.arrayField(s as Record<string, unknown>, \"rows\", \"table\", 0);\n if (failed(rows)) return rows;\n for (const c of cols as unknown[]) {\n if (!isObj(c) || typeof c[\"key\"] !== \"string\" || typeof c[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each table column needs a string `key` and `label`.\", expected: '{ key, label }' };\n }\n }\n return ok;\n },\n partial(spec) {\n const columns = arrived(spec, \"columns\", (c) => typeof c[\"key\"] === \"string\" && typeof c[\"label\"] === \"string\");\n if (!columns.length) return undefined;\n // A row shows from its first cell, so the table fills cell by cell. Sorting\n // waits for the whole card: rows land in arrival order rather than each new\n // one shuffling the ones already on screen.\n const rows = arrived(spec, \"rows\", (r) => Object.keys(r).length > 0);\n const { sortBy: _sortBy, sortDir: _sortDir, ...rest } = spec;\n return { ...rest, kind: \"table\", columns, rows } as CardSpec;\n },\n};\n\nexport const statsCard: CardKindDefinition = {\n kind: \"stats\",\n summary: \"A row of headline numbers, optionally with change vs a prior period. Totals, counts, rates, before/after.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"stats\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: {\n label: { type: \"string\" },\n value: { type: [\"string\", \"number\"] },\n format: { type: \"string\", enum: FORMATS },\n delta: { type: \"number\", description: \"Signed change; drives arrow and colour.\" },\n deltaFormat: { type: \"string\", enum: FORMATS },\n hint: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"stats\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"stats\");\n if (failed(items)) return items;\n for (const i of items as unknown[]) {\n if (!isObj(i) || typeof i[\"label\"] !== \"string\" || i[\"value\"] === undefined) {\n return { ok: false, error: \"Each stat needs a `label` and a `value`.\", expected: \"{ label, value }\" };\n }\n }\n return ok;\n },\n partial(spec) {\n const items = arrived(spec, \"items\", (i) => typeof i[\"label\"] === \"string\" && isScalar(i[\"value\"]));\n return items.length ? ({ ...spec, kind: \"stats\", items } as CardSpec) : undefined;\n },\n};\n\nexport const chartCard: CardKindDefinition = {\n kind: \"chart\",\n summary:\n \"Plot shape over time or across categories. `variant:\\\"series\\\"` with `series[]` for line/area/bar/scatter; `variant:\\\"candlestick\\\"` with `candles[]` for OHLC.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\"],\n properties: {\n kind: { const: \"chart\" },\n title: { type: \"string\" },\n variant: { type: \"string\", enum: [\"series\", \"candlestick\"] },\n xLabel: { type: \"string\" },\n yLabel: { type: \"string\" },\n xType: { type: \"string\", enum: [\"time\", \"number\", \"category\"] },\n stacked: { type: \"boolean\" },\n series: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"name\", \"points\"],\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"line\", \"area\", \"bar\", \"scatter\"] },\n color: { type: \"string\" },\n axis: { type: \"string\", enum: [\"left\", \"right\"] },\n points: {\n type: \"array\",\n description: \"[x, y] pairs. x may be a timestamp, number or category label.\",\n items: { type: \"array\", items: [{ type: [\"string\", \"number\"] }, { type: \"number\" }] },\n },\n },\n },\n },\n candles: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"t\", \"o\", \"h\", \"l\", \"c\"],\n properties: {\n t: { type: [\"string\", \"number\"] },\n o: { type: \"number\" },\n h: { type: \"number\" },\n l: { type: \"number\" },\n c: { type: \"number\" },\n v: { type: \"number\" },\n },\n },\n },\n annotations: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"type\", \"value\"],\n properties: {\n type: { type: \"string\", enum: [\"hline\", \"vline\", \"band\", \"marker\"] },\n value: { type: [\"string\", \"number\"] },\n to: { type: [\"string\", \"number\"] },\n label: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"chart\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n const variant = o[\"variant\"] ?? \"series\";\n if (variant === \"candlestick\") {\n const candles = check.arrayField(o, \"candles\", \"chart\");\n if (failed(candles)) return candles;\n for (const c of candles as unknown[]) {\n if (!isObj(c) || [\"o\", \"h\", \"l\", \"c\"].some((k) => typeof c[k] !== \"number\")) {\n return { ok: false, error: \"Each candle needs numeric o, h, l, c.\", expected: \"{ t, o, h, l, c, v? }\" };\n }\n }\n return ok;\n }\n const series = check.arrayField(o, \"series\", \"chart\");\n if (failed(series)) return series;\n for (const sr of series as unknown[]) {\n if (!isObj(sr) || typeof sr[\"name\"] !== \"string\" || !Array.isArray(sr[\"points\"])) {\n return { ok: false, error: \"Each series needs a `name` and a `points` array.\", expected: '{ name, points: [[x,y],…] }' };\n }\n // Catch the common mistake of `points: [1,2,3]` instead of `[[x,y],…]`.\n const first = (sr[\"points\"] as unknown[])[0];\n if (first !== undefined && !Array.isArray(first)) {\n return { ok: false, error: \"`points` must be [x, y] pairs, not bare values.\", expected: \"points: [[0, 12], [1, 15]]\" };\n }\n }\n return ok;\n },\n};\n\nexport const timelineCard: CardKindDefinition = {\n kind: \"timeline\",\n summary: \"An ordered sequence of events with times and status. Best for history, schedules, execution traces.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"events\"],\n properties: {\n kind: { const: \"timeline\" },\n title: { type: \"string\" },\n events: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"at\", \"label\"],\n properties: {\n at: { type: [\"string\", \"number\"] },\n label: { type: \"string\" },\n detail: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"timeline\");\n if (failed(s)) return s;\n const events = check.arrayField(s as Record<string, unknown>, \"events\", \"timeline\");\n return failed(events) ? events : ok;\n },\n partial(spec) {\n const events = arrived(spec, \"events\", (e) => typeof e[\"label\"] === \"string\" && isScalar(e[\"at\"]));\n return events.length ? ({ ...spec, kind: \"timeline\", events } as CardSpec) : undefined;\n },\n};\n\nexport const keyValueCard: CardKindDefinition = {\n kind: \"keyvalue\",\n summary: \"Labelled detail rows describing ONE thing. A record, a contract's key terms, a config, a profile.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"keyvalue\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: {\n label: { type: \"string\" },\n value: { type: [\"string\", \"number\"] },\n format: { type: \"string\", enum: FORMATS },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n mono: { type: \"boolean\", description: \"Monospace — use for hashes, ids, addresses.\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"keyvalue\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"keyvalue\");\n return failed(items) ? items : ok;\n },\n};\n\nexport const progressCard: CardKindDefinition = {\n kind: \"progress\",\n summary: \"Multi-step work with per-step status. Best for long or background operations the user is waiting on.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"steps\"],\n properties: {\n kind: { const: \"progress\" },\n title: { type: \"string\" },\n fraction: { type: \"number\", minimum: 0, maximum: 1 },\n steps: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"status\"],\n properties: {\n label: { type: \"string\" },\n status: { type: \"string\", enum: [\"pending\", \"active\", \"done\", \"failed\", \"skipped\"] },\n detail: { type: \"string\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"progress\");\n if (failed(s)) return s;\n const steps = check.arrayField(s as Record<string, unknown>, \"steps\", \"progress\");\n if (failed(steps)) return steps;\n const valid = new Set([\"pending\", \"active\", \"done\", \"failed\", \"skipped\"]);\n for (const st of steps as unknown[]) {\n if (!isObj(st) || !valid.has(String(st[\"status\"]))) {\n return { ok: false, error: \"Each step needs a status of pending|active|done|failed|skipped.\" };\n }\n }\n return ok;\n },\n};\n\nexport const mediaCard: CardKindDefinition = {\n kind: \"media\",\n summary: \"Images, audio, or video with captions.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"media\" },\n title: { type: \"string\" },\n layout: { type: \"string\", enum: [\"grid\", \"single\"] },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"url\"],\n properties: {\n url: { type: \"string\" },\n alt: { type: \"string\" },\n caption: { type: \"string\" },\n mediaType: { type: \"string\" },\n width: { type: \"number\" },\n height: { type: \"number\" },\n durationMs: { type: \"number\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"media\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"media\");\n return failed(items) ? items : ok;\n },\n};\n\nexport const markdownCard: CardKindDefinition = {\n kind: \"markdown\",\n summary: \"Formatted long-form text. Use only when structure genuinely needs headings/lists — plain replies do not need a card.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"body\"],\n properties: { kind: { const: \"markdown\" }, title: { type: \"string\" }, body: { type: \"string\" } },\n },\n validate(spec) {\n const s = check.object(spec, \"markdown\");\n if (failed(s)) return s;\n return typeof (s as Record<string, unknown>)[\"body\"] === \"string\"\n ? ok\n : { ok: false, error: \"markdown.body must be a string.\" };\n },\n partial(spec) {\n const body = typeof spec[\"body\"] === \"string\" ? spec[\"body\"] : \"\";\n if (!body && typeof spec[\"title\"] !== \"string\") return undefined;\n return { ...spec, kind: \"markdown\", body } as CardSpec;\n },\n};\n\nexport const documentCard: CardKindDefinition = {\n kind: \"document\",\n // Written for the model, and deliberately about SIZE and REUSE rather than\n // about formatting: the distinction the model has to get right is \"this is a\n // thing we will keep working on\" versus \"this is a long answer\".\n summary:\n \"A document the user will keep, read in a previewer and come back to. Use for something worth revising — a draft, a report, a set of notes — not for a long reply. Returns an id later turns use to re-read or edit it.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"docId\", \"title\", \"markdown\", \"revision\"],\n properties: {\n kind: { const: \"document\" },\n docId: { type: \"string\" },\n title: { type: \"string\" },\n markdown: { type: \"string\" },\n revision: { type: \"number\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"document\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"docId\"] !== \"string\" || !o[\"docId\"]) {\n return { ok: false, error: \"document.docId must be a non-empty string.\" };\n }\n if (typeof o[\"title\"] !== \"string\") return { ok: false, error: \"document.title must be a string.\" };\n if (typeof o[\"markdown\"] !== \"string\") return { ok: false, error: \"document.markdown must be a string.\" };\n // A missing revision would let a stale edit through as revision 0, which is\n // exactly the failure the token exists to prevent — so it is required, not\n // defaulted.\n return typeof o[\"revision\"] === \"number\"\n ? ok\n : { ok: false, error: \"document.revision must be a number.\" };\n },\n};\n\nexport const editReviewCard: CardKindDefinition = {\n kind: \"editreview\",\n interactive: true,\n summary:\n \"Propose changes to a document and let the user accept them hunk by hunk. The only way to change a document — nothing is written until this is answered.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"docId\", \"title\", \"revision\", \"hunks\"],\n properties: {\n kind: { const: \"editreview\" },\n docId: { type: \"string\" },\n title: { type: \"string\" },\n revision: { type: \"number\" },\n summary: { type: \"string\" },\n hunks: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"index\", \"block\", \"removed\", \"added\"],\n properties: {\n index: { type: \"number\" },\n block: { type: \"number\" },\n removed: { type: \"array\", items: { type: \"string\" } },\n added: { type: \"array\", items: { type: \"string\" } },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"editreview\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"docId\"] !== \"string\" || !o[\"docId\"]) {\n return { ok: false, error: \"editreview.docId must be a non-empty string.\" };\n }\n if (typeof o[\"revision\"] !== \"number\") {\n return { ok: false, error: \"editreview.revision must be a number.\" };\n }\n const hunks = o[\"hunks\"];\n if (!Array.isArray(hunks) || hunks.length === 0) {\n // An empty review would render as an approval prompt for nothing, and a\n // user who clicks Apply on it has approved a no-op they cannot see.\n return { ok: false, error: \"editreview.hunks must be a non-empty array.\" };\n }\n return ok;\n },\n};\n\nexport const emailCard: CardKindDefinition = {\n kind: \"email\",\n // NOT interactive, despite being editable. \"Interactive\" here means the run\n // suspends until the user answers, and nothing waits on this: the draft is a\n // deliverable the user takes away, not a question the model asked. Marking it\n // interactive would serialise it against real decisions for no reason.\n summary:\n \"A drafted message for the user to send themselves. Use when the outcome of the work is something that has to reach someone.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"to\", \"subject\", \"body\"],\n properties: {\n kind: { const: \"email\" },\n to: { type: \"array\", items: { type: \"string\" } },\n cc: { type: \"array\", items: { type: \"string\" } },\n bcc: { type: \"array\", items: { type: \"string\" } },\n subject: { type: \"string\" },\n body: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"email\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (!Array.isArray(o[\"to\"])) return { ok: false, error: \"email.to must be an array.\" };\n if (typeof o[\"subject\"] !== \"string\") return { ok: false, error: \"email.subject must be a string.\" };\n return typeof o[\"body\"] === \"string\" ? ok : { ok: false, error: \"email.body must be a string.\" };\n },\n};\n\nexport const codeCard: CardKindDefinition = {\n kind: \"code\",\n summary: \"A code block with language and optional filename.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"code\"],\n properties: {\n kind: { const: \"code\" },\n title: { type: \"string\" },\n language: { type: \"string\" },\n filename: { type: \"string\" },\n code: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"code\");\n if (failed(s)) return s;\n return typeof (s as Record<string, unknown>)[\"code\"] === \"string\" ? ok : { ok: false, error: \"code.code must be a string.\" };\n },\n};\n\nexport const diffCard: CardKindDefinition = {\n kind: \"diff\",\n summary: \"Before/after comparison of two texts.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"before\", \"after\"],\n properties: {\n kind: { const: \"diff\" },\n title: { type: \"string\" },\n language: { type: \"string\" },\n before: { type: \"string\" },\n after: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"diff\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n return typeof o[\"before\"] === \"string\" && typeof o[\"after\"] === \"string\"\n ? ok\n : { ok: false, error: \"diff needs string `before` and `after`.\" };\n },\n};\n\nexport const comparisonCard: CardKindDefinition = {\n kind: \"comparison\",\n summary:\n \"A matrix of options against criteria. Reach for this whenever the user is CHOOSING between things — vendors, clauses, plans, candidates, approaches. Boolean values render as ✓/✗.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"options\", \"criteria\"],\n properties: {\n kind: { const: \"comparison\" },\n title: { type: \"string\" },\n options: {\n type: \"array\",\n description: \"The things being compared. These become columns.\",\n items: {\n type: \"object\",\n required: [\"id\", \"label\"],\n properties: {\n id: { type: \"string\" },\n label: { type: \"string\" },\n note: { type: \"string\" },\n highlight: { type: \"boolean\", description: \"Mark a recommended option.\" },\n },\n },\n },\n criteria: {\n type: \"array\",\n description: \"The dimensions compared on. These become rows.\",\n items: {\n type: \"object\",\n required: [\"label\", \"values\"],\n properties: {\n label: { type: \"string\" },\n detail: { type: \"string\" },\n weight: { type: \"string\", enum: [\"low\", \"normal\", \"high\"] },\n values: {\n type: \"object\",\n description: \"Keyed by option id. true/false render as ✓/✗; null renders as —.\",\n additionalProperties: true,\n },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"comparison\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n const options = check.arrayField(o, \"options\", \"comparison\");\n if (failed(options)) return options;\n const criteria = check.arrayField(o, \"criteria\", \"comparison\");\n if (failed(criteria)) return criteria;\n\n const ids = new Set<string>();\n for (const opt of options as unknown[]) {\n if (!isObj(opt) || typeof opt[\"id\"] !== \"string\" || typeof opt[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each comparison option needs a string `id` and `label`.\" };\n }\n if (ids.has(opt[\"id\"])) return { ok: false, error: `Duplicate comparison option id \"${opt[\"id\"]}\".` };\n ids.add(opt[\"id\"]);\n }\n for (const c of criteria as unknown[]) {\n if (!isObj(c) || typeof c[\"label\"] !== \"string\" || !isObj(c[\"values\"])) {\n return { ok: false, error: \"Each criterion needs a `label` and a `values` object keyed by option id.\", expected: '{ label, values: { optionId: … } }' };\n }\n }\n return ok;\n },\n};\n\nconst CHECK_STATUSES = new Set([\"done\", \"todo\", \"blocked\", \"na\"]);\n\nexport const checklistCard: CardKindDefinition = {\n kind: \"checklist\",\n summary:\n \"Items with a state. Compliance reviews, launch readiness, document requirements, audit findings, QA passes. Use `group` to section a long list.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"checklist\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"status\"],\n properties: {\n label: { type: \"string\" },\n status: { type: \"string\", enum: [\"done\", \"todo\", \"blocked\", \"na\"] },\n detail: { type: \"string\" },\n group: { type: \"string\", description: \"Heading to group consecutive items under.\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"checklist\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"checklist\");\n if (failed(items)) return items;\n for (const i of items as unknown[]) {\n if (!isObj(i) || typeof i[\"label\"] !== \"string\" || !CHECK_STATUSES.has(String(i[\"status\"]))) {\n return { ok: false, error: \"Each checklist item needs a `label` and a status of done|todo|blocked|na.\" };\n }\n }\n return ok;\n },\n partial(spec) {\n // An item waits for its status: showing \"todo\" for one that is about to\n // say \"blocked\" would be a claim the model never made.\n const items = arrived(spec, \"items\", (i) => typeof i[\"label\"] === \"string\" && CHECK_STATUSES.has(String(i[\"status\"])));\n return items.length ? ({ ...spec, kind: \"checklist\", items } as CardSpec) : undefined;\n },\n};\n\nexport const calloutCard: CardKindDefinition = {\n kind: \"callout\",\n summary:\n \"One short highlighted note. Disclaimers, caveats, prerequisites, limits on what you checked. Use `danger` for anything the reader would regret missing.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"tone\", \"body\"],\n properties: {\n kind: { const: \"callout\" },\n tone: { type: \"string\", enum: [\"info\", \"warning\", \"danger\", \"success\", \"note\"] },\n title: { type: \"string\" },\n body: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"callout\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"body\"] !== \"string\") return { ok: false, error: \"callout.body must be a string.\" };\n if (![\"info\", \"warning\", \"danger\", \"success\", \"note\"].includes(String(o[\"tone\"]))) {\n return { ok: false, error: \"callout.tone must be info|warning|danger|success|note.\" };\n }\n return ok;\n },\n};\n\nexport const citationsCard: CardKindDefinition = {\n kind: \"citations\",\n summary:\n \"The sources behind what you just said. Use whenever a claim rests on specific documents — case law, statutes, papers, filings, articles, internal docs. Quote the passage relied on in `snippet`.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"citations\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"title\"],\n properties: {\n title: { type: \"string\" },\n source: { type: \"string\", description: \"Publication, court, statute, dataset, site.\" },\n url: { type: \"string\" },\n date: { type: [\"string\", \"number\"] },\n snippet: { type: \"string\", description: \"The specific passage relied on.\" },\n locator: { type: \"string\", description: \"Page, section, paragraph, or clause.\" },\n relevance: { type: \"string\", enum: [\"high\", \"medium\", \"low\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"citations\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"citations\");\n if (failed(items)) return items;\n for (const i of items as unknown[]) {\n if (!isObj(i) || typeof i[\"title\"] !== \"string\") {\n return { ok: false, error: \"Each citation needs a `title`.\" };\n }\n }\n return ok;\n },\n};\n\nexport const funnelCard: CardKindDefinition = {\n kind: \"funnel\",\n summary:\n \"Staged drop-off, in order. Conversion funnels, hiring pipelines, application intake, case attrition. Stages must be ordered widest to narrowest.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"stages\"],\n properties: {\n kind: { const: \"funnel\" },\n title: { type: \"string\" },\n format: { type: \"string\", enum: FORMATS },\n stages: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: { label: { type: \"string\" }, value: { type: \"number\" }, note: { type: \"string\" } },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"funnel\");\n if (failed(s)) return s;\n const stages = check.arrayField(s as Record<string, unknown>, \"stages\", \"funnel\", 2);\n if (failed(stages)) return stages;\n for (const st of stages as unknown[]) {\n if (!isObj(st) || typeof st[\"label\"] !== \"string\" || typeof st[\"value\"] !== \"number\") {\n return { ok: false, error: \"Each funnel stage needs a string `label` and a numeric `value`.\" };\n }\n }\n return ok;\n },\n};\n\nexport const gaugeCard: CardKindDefinition = {\n kind: \"gauge\",\n summary:\n \"One value on a scale, with optional named bands. Risk levels, readiness scores, sentiment, confidence, utilisation. Label the bands so the number means something.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"value\"],\n properties: {\n kind: { const: \"gauge\" },\n title: { type: \"string\" },\n value: { type: \"number\" },\n min: { type: \"number\", description: \"Default 0.\" },\n max: { type: \"number\", description: \"Default 100.\" },\n label: { type: \"string\", description: \"What the current value means in words.\" },\n format: { type: \"string\", enum: FORMATS },\n bands: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"from\", \"to\", \"label\"],\n properties: {\n from: { type: \"number\" },\n to: { type: \"number\" },\n label: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"gauge\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"value\"] !== \"number\") return { ok: false, error: \"gauge.value must be a number.\" };\n const min = typeof o[\"min\"] === \"number\" ? o[\"min\"] : 0;\n const max = typeof o[\"max\"] === \"number\" ? o[\"max\"] : 100;\n if (max <= min) return { ok: false, error: \"gauge.max must be greater than gauge.min.\" };\n return ok;\n },\n};\n\nexport const treeCard: CardKindDefinition = {\n kind: \"tree\",\n summary:\n \"Nested structure. Document outlines, org charts, taxonomies, decision trees, dependency chains, file layouts.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"nodes\"],\n properties: {\n kind: { const: \"tree\" },\n title: { type: \"string\" },\n nodes: {\n type: \"array\",\n description: \"Each node is { label, detail?, tone?, children?: [ …same shape… ] }.\",\n items: {\n type: \"object\",\n required: [\"label\"],\n properties: {\n label: { type: \"string\" },\n detail: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n children: { type: \"array\", items: { type: \"object\" } },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"tree\");\n if (failed(s)) return s;\n const nodes = check.arrayField(s as Record<string, unknown>, \"nodes\", \"tree\");\n if (failed(nodes)) return nodes;\n\n // Depth-limited walk: a cyclic or absurdly deep tree would hang the renderer.\n const walk = (list: unknown[], depth: number): CardValidation => {\n if (depth > 8) return { ok: false, error: \"tree nesting is limited to 8 levels.\" };\n for (const n of list) {\n if (!isObj(n) || typeof n[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each tree node needs a string `label`.\" };\n }\n const kids = n[\"children\"];\n if (kids !== undefined) {\n if (!Array.isArray(kids)) return { ok: false, error: \"tree node `children` must be an array.\" };\n const inner = walk(kids, depth + 1);\n if (!inner.ok) return inner;\n }\n }\n return ok;\n };\n return walk(nodes as unknown[], 1);\n },\n};\n\n// ── Interactive ─────────────────────────────────────────────────────────────\n\nexport const choiceCard: CardKindDefinition = {\n kind: \"choice\",\n interactive: true,\n summary:\n \"Ask the user to pick from options. Use instead of guessing when several candidates fit. Each option may carry `meta` facts shown on its row.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"options\"],\n properties: {\n kind: { const: \"choice\" },\n title: { type: \"string\" },\n prompt: { type: \"string\" },\n multiple: { type: \"boolean\" },\n options: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"id\", \"label\"],\n properties: {\n id: { type: \"string\" },\n label: { type: \"string\" },\n description: { type: \"string\" },\n imageUrl: { type: \"string\" },\n disabled: { type: \"boolean\" },\n disabledReason: { type: \"string\" },\n meta: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: { label: { type: \"string\" }, value: { type: [\"string\", \"number\"] }, format: { type: \"string\", enum: FORMATS } },\n },\n },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"choice\");\n if (failed(s)) return s;\n const options = check.arrayField(s as Record<string, unknown>, \"options\", \"choice\");\n if (failed(options)) return options;\n const ids = new Set<string>();\n for (const o of options as unknown[]) {\n if (!isObj(o) || typeof o[\"id\"] !== \"string\" || typeof o[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each choice option needs a string `id` and `label`.\" };\n }\n // Duplicate ids make the selection ambiguous when it comes back.\n if (ids.has(o[\"id\"])) return { ok: false, error: `Duplicate choice option id \"${o[\"id\"]}\".` };\n ids.add(o[\"id\"]);\n }\n return ok;\n },\n};\n\nexport const formCard: CardKindDefinition = {\n kind: \"form\",\n interactive: true,\n summary: \"Collect structured input. Use when you need several values at once rather than a back-and-forth.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"fields\"],\n properties: {\n kind: { const: \"form\" },\n title: { type: \"string\" },\n description: { type: \"string\" },\n submitLabel: { type: \"string\" },\n fields: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"name\", \"label\", \"type\"],\n properties: {\n name: { type: \"string\" },\n label: { type: \"string\" },\n type: { type: \"string\", enum: [\"text\", \"textarea\", \"number\", \"select\", \"boolean\"] },\n placeholder: { type: \"string\" },\n required: { type: \"boolean\" },\n min: { type: \"number\" },\n max: { type: \"number\" },\n step: { type: \"number\" },\n suffix: { type: \"string\" },\n options: {\n type: \"array\",\n items: { type: \"object\", required: [\"value\", \"label\"], properties: { value: { type: \"string\" }, label: { type: \"string\" } } },\n },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"form\");\n if (failed(s)) return s;\n const fields = check.arrayField(s as Record<string, unknown>, \"fields\", \"form\");\n if (failed(fields)) return fields;\n const types = new Set([\"text\", \"textarea\", \"number\", \"select\", \"boolean\"]);\n for (const f of fields as unknown[]) {\n if (!isObj(f) || typeof f[\"name\"] !== \"string\" || !types.has(String(f[\"type\"]))) {\n return { ok: false, error: \"Each field needs a `name` and a type of text|textarea|number|select|boolean.\" };\n }\n if (f[\"type\"] === \"select\" && !Array.isArray(f[\"options\"])) {\n return { ok: false, error: `Select field \"${String(f[\"name\"])}\" needs an \\`options\\` array.` };\n }\n }\n return ok;\n },\n};\n\nexport const confirmCard: CardKindDefinition = {\n kind: \"confirm\",\n interactive: true,\n summary:\n \"Get explicit approval before a consequential action. `description` says what will happen in plain words, `summary` lists exact amounts, targets, and anything irreversible, and `title` is the one question the buttons answer.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"title\", \"summary\"],\n properties: {\n kind: { const: \"confirm\" },\n title: { type: \"string\" },\n description: { type: \"string\" },\n confirmLabel: { type: \"string\" },\n cancelLabel: { type: \"string\" },\n danger: { type: \"boolean\" },\n summary: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: {\n label: { type: \"string\" },\n value: { type: [\"string\", \"number\"] },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n mono: { type: \"boolean\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"confirm\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"title\"] !== \"string\") return { ok: false, error: \"confirm.title is required.\" };\n // A card whose sentence already says everything needs no detail rows; one with no sentence needs at least one.\n const hasDescription = typeof o[\"description\"] === \"string\" && o[\"description\"].trim() !== \"\";\n const summary = check.arrayField(o, \"summary\", \"confirm\", hasDescription ? 0 : 1);\n if (failed(summary)) return summary;\n return ok;\n },\n};\n\nexport const BUILTIN_CARDS: CardKindDefinition[] = [\n // structured data\n tableCard,\n statsCard,\n comparisonCard,\n keyValueCard,\n treeCard,\n // quantitative shape\n chartCard,\n funnelCard,\n gaugeCard,\n // sequence and state\n timelineCard,\n progressCard,\n checklistCard,\n // prose and evidence\n markdownCard,\n documentCard,\n calloutCard,\n citationsCard,\n codeCard,\n diffCard,\n mediaCard,\n // interactive — these ask the user and pause the run\n choiceCard,\n formCard,\n confirmCard,\n editReviewCard,\n emailCard,\n];\n","// Surfaces: an interface the agent assembles, instead of one card it picks.\n//\n// A card answers \"which presentation fits this result\". A surface answers \"what\n// does the person need in order to work with this\": a filter next to the chart\n// it filters, a total that follows both, a button that asks the agent to look\n// again. Cards stay what they were and become blocks inside it.\n//\n// The format has four properties, each there for a reason:\n//\n// 1. FLAT. Components are a list that reference each other by id, so a surface\n// can stream one complete entry at a time and be patched without resending\n// the tree. (The same shape A2UI and json-render arrived at.)\n//\n// 2. DATA, NOT CODE. Everything the model writes is JSON from a closed\n// vocabulary. There is no expression language, no script, no HTML and no\n// CSS. `$query` filters and groups rows declaratively, and that is as far as\n// computation goes.\n//\n// 3. LOCAL BY DEFAULT. Each surface owns a data model. Controls write to it and\n// neighbours read from it, so narrowing a filter costs no model call.\n//\n// 4. CLOSED ACTIONS. A button can change local state, call a tool the current\n// presets already allow, or send the agent an event. Nothing else exists to\n// be asked for.\n\nimport type { CardAction } from \"../cards/types.js\";\n\nexport const SURFACE_CARD_KIND = \"surface\" as const;\nexport const SURFACE_FORMAT_VERSION = 1 as const;\n\n/** Hard ceilings. A model that exceeds one receives a correction, never a frozen tab. */\nexport const SURFACE_LIMITS = {\n components: 200,\n depth: 16,\n dataChars: 64_000,\n specChars: 200_000,\n surfaces: 24,\n listItems: 200,\n queryRows: 2_000,\n actionUpdates: 8,\n tabs: 12,\n} as const;\n\n/** Read a value from the data model by JSON Pointer: `{ \"$path\": \"/filters/region\" }`. */\nexport type SurfacePathBinding = { $path: string };\n/** Inside a `List` template, read a field of the current row. `\"\"` is the row itself. */\nexport type SurfaceItemBinding = { $item: string };\n/** Interpolate values into a string: `{ \"$template\": \"Spend in {/region}\" }`, `{.name}` for a row field. */\nexport type SurfaceTemplateBinding = { $template: string };\n/** Filter, group and aggregate an array in the data model. */\nexport type SurfaceQueryBinding = { $query: SurfaceQuery };\n\nexport type SurfaceBinding =\n | SurfacePathBinding\n | SurfaceItemBinding\n | SurfaceTemplateBinding\n | SurfaceQueryBinding;\n\nexport type SurfaceWhereOp = \"eq\" | \"ne\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\" | \"contains\";\n\nexport type SurfaceWhere = {\n field: string;\n op?: SurfaceWhereOp;\n value: unknown;\n /** Skip this clause when the value equals this, so an \"All\" option needs no special case. */\n ignore?: string | number | boolean;\n};\n\nexport type SurfaceAggregateOp = \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n\nexport type SurfaceQuery = {\n /** JSON Pointer to an array of rows. */\n from: string;\n where?: SurfaceWhere[];\n groupBy?: string;\n aggregate?: { op: SurfaceAggregateOp; field?: string };\n /** A row field; after `groupBy`, `key` or `value`. */\n sortBy?: string;\n sortDir?: \"asc\" | \"desc\";\n limit?: number;\n /** Return one field of each row instead of the row. */\n select?: string;\n /** Grouped results: `[key, value]` pairs (default, chart-ready) or `{ key, value }` rows. */\n shape?: \"points\" | \"rows\";\n};\n\nexport type SurfaceConditionOp = \"truthy\" | \"falsy\" | \"eq\" | \"ne\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\";\n\n/** A declarative test over the data model, for `visibleWhen` and `disabledWhen`. */\nexport type SurfaceCondition = {\n path: string;\n op?: SurfaceConditionOp;\n value?: unknown;\n};\n\n/** The whole action vocabulary. Adding a member here is a security decision. */\nexport type SurfaceAction =\n | { type: \"set\"; updates: { path: string; value: unknown }[] }\n | { type: \"tool\"; tool: string; args?: Record<string, unknown>; resultPath?: string }\n | { type: \"event\"; name: string; context?: Record<string, unknown> };\n\nexport type SurfaceComponent = {\n id: string;\n component: string;\n visibleWhen?: SurfaceCondition;\n [prop: string]: unknown;\n};\n\nexport type SurfaceIssueCode =\n | \"invalid-shape\"\n | \"duplicate-id\"\n | \"unknown-component\"\n | \"invalid-prop\"\n | \"invalid-binding\"\n | \"invalid-action\"\n | \"tool-not-allowed\"\n | \"unsafe-content\"\n | \"invalid-card\"\n | \"invalid-data\"\n | \"missing-root\"\n | \"missing-child\"\n | \"cycle\"\n | \"too-deep\"\n | \"limit-exceeded\"\n | \"not-found\"\n | \"expired\"\n | \"stale-revision\";\n\n/** One thing wrong, written for the model that has to fix it. */\nexport type SurfaceIssue = {\n code: SurfaceIssueCode;\n message: string;\n /** What to send instead. */\n fix: string;\n componentId?: string;\n path?: string;\n};\n\n/**\n * The current state of a surface. Travels as a card spec, which is how it uses\n * the thread, history-shedding and renderer seams cards already have.\n */\nexport type SurfaceSpec = {\n kind: typeof SURFACE_CARD_KIND;\n version: typeof SURFACE_FORMAT_VERSION;\n surfaceId: string;\n title?: string;\n root: string;\n components: SurfaceComponent[];\n data: Record<string, unknown>;\n /** Bumped by every agent update and every local edit. */\n revision: number;\n /** The call that created it: where it lives in the transcript. */\n originCallId?: string;\n /** Parts that could not be accepted. The person sees a fallback in their place. */\n issues?: SurfaceIssue[];\n /** Removed by the agent. */\n deleted?: boolean;\n /** The payload was shed from saved history. */\n expired?: boolean;\n /**\n * Only on a streaming preview: the part the model is still writing. Every part\n * listed before it is complete. A renderer holds its place until it lands.\n */\n pending?: SurfacePendingPart;\n};\n\n/** The part of a streaming surface that is still arriving, as far as it has arrived. */\nexport type SurfacePendingPart = { id: string; component?: string; kind?: string };\n\n/** Patches for an existing surface, applied in order and validated before rendering. */\nexport type SurfaceOperation =\n | { op: \"upsertComponents\"; components: unknown[] }\n | { op: \"removeComponents\"; ids: string[] }\n | { op: \"setRoot\"; root: string }\n | { op: \"setTitle\"; title: string }\n | { op: \"setData\"; path: string; value: unknown }\n | { op: \"removeData\"; path: string };\n\nexport type SurfaceActivityState = \"queued\" | \"running\" | \"done\" | \"failed\" | \"refused\" | \"cancelled\";\n\n/** What became of the last thing the person pressed. A press with no visible result reads as broken. */\nexport type SurfaceActivity = {\n componentId: string;\n state: SurfaceActivityState;\n message?: string;\n at: number;\n};\n\n/** Recorded on the user message an action produces, so the transcript can show it as an action. */\nexport type SurfaceEventRecord = {\n surfaceId: string;\n componentId: string;\n title?: string;\n label?: string;\n type: \"event\" | \"tool\";\n name: string;\n context?: Record<string, unknown>;\n};\n\nexport const SURFACE_EVENT_METADATA_KEY = \"surfaceEvent\" as const;\n\n/** How an interactive card answered inside a surface. Stored at the card's `bind` path. */\nexport type SurfaceCardAnswer = Pick<CardAction, \"type\" | \"value\" | \"at\">;\n","// JSON Pointer (RFC 6901) over a surface's data model.\n//\n// Paths come from a model, so this is also a security boundary. Walking\n// `__proto__` or `constructor` would let a spec write to Object.prototype for\n// the whole page; such a pointer does not parse. Writes are structural: the\n// previous state is never mutated, which is what lets a renderer compare by\n// identity.\n\nimport { SURFACE_LIMITS } from \"./types.js\";\n\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\nexport const isForbiddenKey = (key: string): boolean => FORBIDDEN_SEGMENTS.has(key);\n\n/** Segments of a pointer, or `undefined` when it is malformed or unsafe. `\"\"` and `\"/\"` are the root. */\nexport function parsePointer(pointer: unknown): string[] | undefined {\n if (typeof pointer !== \"string\") return undefined;\n if (pointer === \"\" || pointer === \"/\") return [];\n if (!pointer.startsWith(\"/\")) return undefined;\n const segments = pointer\n .slice(1)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n if (segments.length > SURFACE_LIMITS.depth) return undefined;\n if (segments.some((s) => s === \"\" || FORBIDDEN_SEGMENTS.has(s))) return undefined;\n return segments;\n}\n\nconst isContainer = (v: unknown): v is Record<string, unknown> | unknown[] => typeof v === \"object\" && v !== null;\nconst isIndex = (s: string) => /^(0|[1-9]\\d*)$/.test(s);\n\n/** Own properties only: a binding must never read something off a prototype. */\nfunction child(value: unknown, key: string): unknown {\n if (Array.isArray(value)) return isIndex(key) ? value[Number(key)] : undefined;\n if (!isContainer(value)) return undefined;\n return Object.prototype.hasOwnProperty.call(value, key) ? (value as Record<string, unknown>)[key] : undefined;\n}\n\nexport function getAt(data: unknown, pointer: string): unknown {\n const segments = parsePointer(pointer);\n if (!segments) return undefined;\n let current = data;\n for (const segment of segments) current = child(current, segment);\n return current;\n}\n\nfunction writeAt(node: unknown, segments: string[], index: number, value: unknown): unknown {\n if (index === segments.length) return value;\n const key = segments[index]!;\n if (Array.isArray(node)) {\n const at = key === \"-\" ? node.length : isIndex(key) ? Number(key) : -1;\n if (at < 0 || at > node.length) throw new RangeError(key);\n const next = [...node];\n next[at] = writeAt(node[at], segments, index + 1, value);\n return next;\n }\n const base = isContainer(node) ? (node as Record<string, unknown>) : {};\n return { ...base, [key]: writeAt(child(base, key), segments, index + 1, value) };\n}\n\n/** A new data model with `value` at `pointer`, or `undefined` when the pointer cannot be written. */\nexport function setAt(data: Record<string, unknown>, pointer: string, value: unknown): Record<string, unknown> | undefined {\n const segments = parsePointer(pointer);\n if (!segments) return undefined;\n if (!segments.length) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n }\n try {\n return writeAt(data, segments, 0, value) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** A new data model without the value at `pointer`. Removing what is not there changes nothing. */\nexport function removeAt(data: Record<string, unknown>, pointer: string): Record<string, unknown> | undefined {\n const segments = parsePointer(pointer);\n if (!segments?.length) return undefined;\n const parentPath = segments.slice(0, -1);\n const key = segments[segments.length - 1]!;\n let parent: unknown = data;\n for (const segment of parentPath) parent = child(parent, segment);\n if (!isContainer(parent)) return data;\n const without: unknown = Array.isArray(parent)\n ? parent.filter((_, i) => String(i) !== key)\n : Object.fromEntries(Object.entries(parent).filter(([k]) => k !== key));\n if (!parentPath.length) return without as Record<string, unknown>;\n return writeAt(data, parentPath, 0, without) as Record<string, unknown>;\n}\n","// What a spec may never carry, whichever component it is attached to.\n//\n// Rendering is already safe by construction (props are enumerated, text is\n// escaped, nothing reaches innerHTML). This is the second wall, and it exists so\n// the refusal happens where the model can read it: a spec carrying a script URL\n// is corrected at the tool call instead of being quietly neutralised later.\n\nimport { isForbiddenKey } from \"./pointer.js\";\n\nconst DANGEROUS_KEYS = new Set([\"dangerouslysetinnerhtml\", \"innerhtml\", \"outerhtml\", \"srcdoc\"]);\nconst SCRIPT_SCHEMES = /^(javascript|vbscript|livescript|data:text\\/html|data:application\\/xhtml|data:image\\/svg)/;\nconst MARKUP = /<\\s*\\/?\\s*[a-z][a-z0-9-]*(\\s[^<>]*)?\\/?>|<\\s*(script|iframe|object|embed|style|svg|math)\\b/i;\n\n/** Browsers ignore whitespace and control characters inside a scheme, so `java\\tscript:` is one too. */\nconst compact = (s: string) =>\n // eslint-disable-next-line no-control-regex\n s.replace(/[\\u0000-\\u0020\\u007f-\\u009f\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, \"\").toLowerCase();\n\nexport const isScriptUrl = (s: string): boolean => {\n const c = compact(s.slice(0, 256));\n return SCRIPT_SCHEMES.test(c) && (c.startsWith(\"data:\") || /^[a-z]+:/.test(c));\n};\n\nexport type UnsafeFinding = { path: string; reason: string };\n\n/**\n * First unsafe thing in `value`. `markup` also refuses HTML in strings: right for\n * a primitive's props, wrong for a code card, whose whole job is to show source.\n */\nexport function findUnsafe(value: unknown, opts: { markup?: boolean; path?: string } = {}): UnsafeFinding | undefined {\n const markup = opts.markup === true;\n let visited = 0;\n\n const walk = (node: unknown, path: string, depth: number): UnsafeFinding | undefined => {\n visited += 1;\n if (visited > 50_000 || depth > 32) return { path, reason: \"is nested too deeply to inspect\" };\n if (typeof node === \"string\") {\n if (isScriptUrl(node)) return { path, reason: \"is a URL that runs script\" };\n if (markup && MARKUP.test(node)) return { path, reason: \"contains HTML\" };\n return undefined;\n }\n if (typeof node === \"function\") return { path, reason: \"is executable\" };\n if (typeof node !== \"object\" || node === null) return undefined;\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i += 1) {\n const found = walk(node[i], `${path}/${i}`, depth + 1);\n if (found) return found;\n }\n return undefined;\n }\n for (const key of Object.keys(node)) {\n if (isForbiddenKey(key) || DANGEROUS_KEYS.has(key.toLowerCase())) {\n return { path: `${path}/${key}`, reason: \"is not an allowed key\" };\n }\n const found = walk((node as Record<string, unknown>)[key], `${path}/${key}`, depth + 1);\n if (found) return found;\n }\n return undefined;\n };\n\n return walk(value, opts.path ?? \"\", 0);\n}\n\n/** A URL a surface may load or link to: http(s), plus inline raster images for `image`. */\nexport function safeSurfaceUrl(url: unknown, use: \"link\" | \"image\"): string | undefined {\n if (typeof url !== \"string\") return undefined;\n const trimmed = url.trim();\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(trimmed)) return undefined;\n if (/^https?:\\/\\/[^\\s]+$/i.test(trimmed)) return trimmed;\n if (use === \"image\" && /^data:image\\/(png|jpeg|jpg|gif|webp);base64,[a-z0-9+/=]+$/i.test(trimmed)) return trimmed;\n return undefined;\n}\n","// A small JSON Schema checker, for the subset the surface catalogue uses.\n//\n// Core carries no validation dependency (see providers/types.ts), and what a\n// surface needs from one is modest: walk a schema, and say what was wrong in a\n// sentence a model can act on.\n\nimport type { JSONSchema } from \"../providers/types.js\";\n\nexport type SchemaProblem = { path: string; message: string; expected?: string };\n\nexport type SchemaCheckOptions = {\n /** A value this returns true for is checked elsewhere, unless its schema is `x-static`. */\n isDynamic?: (value: unknown) => boolean;\n maxProblems?: number;\n};\n\nconst typeOf = (v: unknown): string => {\n if (v === null) return \"null\";\n if (Array.isArray(v)) return \"array\";\n return typeof v;\n};\n\nconst matchesType = (value: unknown, type: string): boolean => {\n if (type === \"integer\") return typeof value === \"number\" && Number.isInteger(value);\n if (type === \"number\") return typeof value === \"number\" && Number.isFinite(value);\n return typeOf(value) === type;\n};\n\nconst quote = (values: readonly unknown[]) => values.map((v) => JSON.stringify(v)).join(\", \");\n\nexport function checkSchema(schema: JSONSchema, value: unknown, path = \"\", opts: SchemaCheckOptions = {}): SchemaProblem[] {\n const out: SchemaProblem[] = [];\n const max = opts.maxProblems ?? 6;\n\n const walk = (s: JSONSchema, v: unknown, at: string): void => {\n if (out.length >= max) return;\n if (opts.isDynamic?.(v) && s[\"x-static\"] !== true) return;\n const label = at || \"value\";\n\n const anyOf = s[\"anyOf\"];\n if (Array.isArray(anyOf)) {\n const passes = (anyOf as JSONSchema[]).some((option) => checkSchema(option, v, at, opts).length === 0);\n if (!passes) out.push({ path: at, message: `${label} does not match any allowed form.`, expected: s.description });\n return;\n }\n if (s.const !== undefined && v !== s.const) {\n out.push({ path: at, message: `${label} must be ${JSON.stringify(s.const)}.` });\n return;\n }\n if (s.enum && !s.enum.includes(v)) {\n out.push({ path: at, message: `${label} is ${JSON.stringify(v)}.`, expected: `One of: ${quote(s.enum)}` });\n return;\n }\n if (s.type !== undefined) {\n const types = Array.isArray(s.type) ? s.type : [s.type];\n if (!types.some((t) => matchesType(v, t))) {\n out.push({ path: at, message: `${label} must be ${types.join(\" or \")}, got ${typeOf(v)}.` });\n return;\n }\n }\n if (typeof v === \"number\") {\n if (s.minimum != null && v < s.minimum) out.push({ path: at, message: `${label} must be at least ${s.minimum}.` });\n if (s.maximum != null && v > s.maximum) out.push({ path: at, message: `${label} must be at most ${s.maximum}.` });\n }\n if (typeof v === \"string\") {\n const min = s[\"minLength\"];\n const maxLength = s[\"maxLength\"];\n if (typeof min === \"number\" && v.length < min) out.push({ path: at, message: `${label} must not be empty.` });\n if (typeof maxLength === \"number\" && v.length > maxLength) {\n out.push({ path: at, message: `${label} is longer than ${maxLength} characters.` });\n }\n }\n if (Array.isArray(v)) {\n const minItems = s[\"minItems\"];\n const maxItems = s[\"maxItems\"];\n if (typeof minItems === \"number\" && v.length < minItems) out.push({ path: at, message: `${label} needs at least ${minItems} item(s).` });\n if (typeof maxItems === \"number\" && v.length > maxItems) out.push({ path: at, message: `${label} allows at most ${maxItems} item(s).` });\n if (s.items && !Array.isArray(s.items)) {\n const items = s.items;\n v.forEach((item, i) => walk(items, item, `${at}/${i}`));\n }\n }\n if (typeOf(v) === \"object\") {\n const record = v as Record<string, unknown>;\n for (const key of s.required ?? []) {\n if (record[key] === undefined) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : \"\"}${key} is required.` });\n }\n const properties = s.properties ?? {};\n for (const [key, item] of Object.entries(record)) {\n const propSchema = properties[key];\n if (propSchema) walk(propSchema, item, `${at}/${key}`);\n else if (s.additionalProperties === false) {\n out.push({\n path: `${at}/${key}`,\n message: `Unknown prop \"${key}\".`,\n expected: `Allowed: ${Object.keys(properties).join(\", \") || \"(none)\"}`,\n });\n } else if (typeof s.additionalProperties === \"object\") walk(s.additionalProperties, item, `${at}/${key}`);\n }\n }\n };\n\n walk(schema, value, path);\n return out.slice(0, max);\n}\n","// Bindings: how a prop reads the data model.\n//\n// Every form here is data and every evaluation is bounded. Resolution walks the\n// SPEC once and never the values it reads, so a row that happens to contain\n// `{ \"$path\": \"/secret\" }` stays a row. Data cannot promote itself into a binding.\n\nimport { getAt, parsePointer } from \"./pointer.js\";\nimport {\n SURFACE_LIMITS,\n type SurfaceAction,\n type SurfaceBinding,\n type SurfaceCondition,\n type SurfaceQuery,\n type SurfaceWhere,\n} from \"./types.js\";\n\nexport type BindingScope = {\n data: unknown;\n /** The current row, inside a `List` template. */\n item?: unknown;\n index?: number;\n};\n\nconst BINDING_KEYS = [\"$path\", \"$item\", \"$template\", \"$query\"] as const;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/** Exactly one `$` key and nothing else: anything looser would swallow ordinary objects. */\nexport function isSurfaceBinding(value: unknown): value is SurfaceBinding {\n if (!isPlainObject(value)) return false;\n const keys = Object.keys(value);\n return keys.length === 1 && (BINDING_KEYS as readonly string[]).includes(keys[0]!);\n}\n\n/** True when any binding of the given form appears anywhere inside `value`. */\nexport function usesBinding(value: unknown, key: (typeof BINDING_KEYS)[number]): boolean {\n if (Array.isArray(value)) return value.some((v) => usesBinding(v, key));\n if (!isPlainObject(value)) return false;\n if (isSurfaceBinding(value)) {\n if (key in value) return true;\n if (\"$query\" in value) return usesBinding(value.$query.where?.map((w) => w?.value), key);\n return key === \"$item\" && \"$template\" in value && /\\{\\.[^{}]*\\}/.test(String(value.$template));\n }\n return Object.values(value).some((v) => usesBinding(v, key));\n}\n\nconst TEMPLATE_TOKEN = /\\{(\\/[^{}]*|\\.[^{}]*)\\}/g;\n\nconst itemField = (item: unknown, field: string): unknown => {\n if (!field) return item;\n return getAt(item, field.startsWith(\"/\") ? field : `/${field.replace(/\\./g, \"/\")}`);\n};\n\nconst printable = (v: unknown): string =>\n typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\" ? String(v) : \"\";\n\nexport function formatTemplate(template: string, scope: BindingScope): string {\n return template.replace(TEMPLATE_TOKEN, (_, token: string) =>\n printable(token.startsWith(\".\") ? itemField(scope.item, token.slice(1)) : getAt(scope.data, token)),\n );\n}\n\nconst asNumber = (v: unknown): number | undefined => {\n if (typeof v === \"number\") return Number.isFinite(v) ? v : undefined;\n if (typeof v === \"string\" && v.trim() !== \"\") {\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n};\n\nconst sameValue = (a: unknown, b: unknown) => a === b || (a != null && b != null && String(a) === String(b));\n\nfunction compare(left: unknown, op: string, right: unknown): boolean {\n switch (op) {\n case \"eq\":\n return sameValue(left, right);\n case \"ne\":\n return !sameValue(left, right);\n case \"in\":\n return Array.isArray(right) && right.some((r) => sameValue(left, r));\n case \"contains\":\n return String(left ?? \"\").toLowerCase().includes(String(right ?? \"\").toLowerCase());\n default: {\n const a = asNumber(left);\n const b = asNumber(right);\n if (a === undefined || b === undefined) return false;\n return op === \"gt\" ? a > b : op === \"gte\" ? a >= b : op === \"lt\" ? a < b : op === \"lte\" ? a <= b : false;\n }\n }\n}\n\nfunction rowField(row: unknown, field: string): unknown {\n return isPlainObject(row) && Object.prototype.hasOwnProperty.call(row, field) ? row[field] : undefined;\n}\n\nconst clauseApplies = (clause: SurfaceWhere, value: unknown) => {\n if (value === undefined || value === null || value === \"\") return false;\n if (Array.isArray(value) && value.length === 0) return false;\n return clause.ignore === undefined || !sameValue(value, clause.ignore);\n};\n\nconst tidy = (n: number) => Math.round(n * 1e6) / 1e6;\n\nfunction aggregate(rows: readonly unknown[], spec: NonNullable<SurfaceQuery[\"aggregate\"]>): number {\n if (spec.op === \"count\") return rows.length;\n const values = rows.map((r) => asNumber(rowField(r, spec.field ?? \"\"))).filter((n): n is number => n !== undefined);\n if (!values.length) return 0;\n switch (spec.op) {\n case \"sum\":\n return tidy(values.reduce((a, b) => a + b, 0));\n case \"avg\":\n return tidy(values.reduce((a, b) => a + b, 0) / values.length);\n case \"min\":\n return values.reduce((a, b) => Math.min(a, b));\n case \"max\":\n return values.reduce((a, b) => Math.max(a, b));\n }\n}\n\nconst order = (a: unknown, b: unknown): number => {\n const x = asNumber(a);\n const y = asNumber(b);\n if (x !== undefined && y !== undefined) return x - y;\n return String(a ?? \"\").localeCompare(String(b ?? \"\"));\n};\n\n/** Run a declarative query. Bad input yields an empty result, never a throw in a render. */\nexport function runSurfaceQuery(query: SurfaceQuery, scope: BindingScope): unknown {\n const source = getAt(scope.data, query.from);\n let rows: unknown[] = Array.isArray(source) ? source.slice(0, SURFACE_LIMITS.queryRows) : [];\n\n for (const clause of query.where ?? []) {\n const value = resolveSurfaceValue(clause.value, scope);\n if (!clauseApplies(clause, value)) continue;\n rows = rows.filter((row) => compare(rowField(row, clause.field), clause.op ?? \"eq\", value));\n }\n\n const direction = query.sortDir === \"desc\" ? -1 : 1;\n const limit = (list: unknown[]) => (typeof query.limit === \"number\" && query.limit >= 0 ? list.slice(0, query.limit) : list);\n\n if (query.groupBy) {\n const groups = new Map<string, unknown[]>();\n for (const row of rows) {\n const key = printable(rowField(row, query.groupBy));\n const bucket = groups.get(key);\n if (bucket) bucket.push(row);\n else groups.set(key, [row]);\n }\n let pairs = [...groups].map(([key, bucket]) => ({ key, value: aggregate(bucket, query.aggregate ?? { op: \"count\" }) }));\n if (query.sortBy === \"key\" || query.sortBy === \"value\") {\n const by = query.sortBy;\n pairs = [...pairs].sort((a, b) => order(a[by], b[by]) * direction);\n }\n const limited = limit(pairs) as typeof pairs;\n return query.shape === \"rows\" ? limited : limited.map((p) => [p.key, p.value]);\n }\n\n if (query.aggregate) return aggregate(rows, query.aggregate);\n\n if (query.sortBy) {\n const by = query.sortBy;\n rows = [...rows].sort((a, b) => order(rowField(a, by), rowField(b, by)) * direction);\n }\n rows = limit(rows);\n return query.select ? rows.map((r) => rowField(r, query.select!)) : rows;\n}\n\n/** Replace every binding inside a spec value with what it currently reads. */\nexport function resolveSurfaceValue(value: unknown, scope: BindingScope, depth = 0): unknown {\n if (depth > SURFACE_LIMITS.depth * 2) return undefined;\n if (Array.isArray(value)) return value.map((v) => resolveSurfaceValue(v, scope, depth + 1));\n if (!isPlainObject(value)) return value;\n if (isSurfaceBinding(value)) {\n if (\"$path\" in value) return getAt(scope.data, value.$path);\n if (\"$item\" in value) return itemField(scope.item, value.$item);\n if (\"$template\" in value) return formatTemplate(value.$template, scope);\n return runSurfaceQuery(value.$query, scope);\n }\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) out[key] = resolveSurfaceValue(item, scope, depth + 1);\n return out;\n}\n\nexport function evaluateSurfaceCondition(condition: SurfaceCondition | undefined, scope: BindingScope): boolean {\n if (!condition) return true;\n const current = getAt(scope.data, condition.path);\n const op = condition.op ?? (condition.value === undefined ? \"truthy\" : \"eq\");\n if (op === \"truthy\") return Boolean(current) && !(Array.isArray(current) && current.length === 0);\n if (op === \"falsy\") return !current || (Array.isArray(current) && current.length === 0);\n return compare(current, op, condition.value);\n}\n\n/** An action with its bindings read at the moment the person pressed. */\nexport function resolveSurfaceAction(action: SurfaceAction, scope: BindingScope): SurfaceAction {\n switch (action.type) {\n case \"set\":\n return { type: \"set\", updates: action.updates.map((u) => ({ path: u.path, value: resolveSurfaceValue(u.value, scope) })) };\n case \"tool\":\n return { ...action, args: resolveSurfaceValue(action.args ?? {}, scope) as Record<string, unknown> };\n case \"event\":\n return { ...action, context: resolveSurfaceValue(action.context ?? {}, scope) as Record<string, unknown> };\n }\n}\n\n/** Problems with one binding, as sentences. Empty means it is usable. */\nexport function bindingProblems(binding: SurfaceBinding): string[] {\n if (\"$path\" in binding) {\n return parsePointer(binding.$path) ? [] : [`$path ${JSON.stringify(binding.$path)} is not a JSON Pointer such as \"/filters/region\".`];\n }\n if (\"$item\" in binding) {\n return typeof binding.$item === \"string\" ? [] : [\"$item must be a field name of the current row.\"];\n }\n if (\"$template\" in binding) return typeof binding.$template === \"string\" ? [] : [\"$template must be a string.\"];\n\n const query = binding.$query as SurfaceQuery | undefined;\n if (!isPlainObject(query)) return [\"$query must be an object with a `from` pointer.\"];\n const out: string[] = [];\n if (!parsePointer(query.from)) out.push(`$query.from ${JSON.stringify(query.from)} is not a JSON Pointer to an array.`);\n const allowed = new Set([\"from\", \"where\", \"groupBy\", \"aggregate\", \"sortBy\", \"sortDir\", \"limit\", \"select\", \"shape\"]);\n for (const key of Object.keys(query)) if (!allowed.has(key)) out.push(`$query has no \"${key}\". Allowed: ${[...allowed].join(\", \")}.`);\n if (query.where !== undefined && !Array.isArray(query.where)) out.push(\"$query.where must be an array of { field, op, value }.\");\n for (const clause of Array.isArray(query.where) ? query.where : []) {\n if (!isPlainObject(clause) || typeof clause.field !== \"string\") out.push(\"Each $query.where clause needs a string `field`.\");\n else if (clause.op !== undefined && ![\"eq\", \"ne\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\", \"contains\"].includes(clause.op)) {\n out.push(`$query.where op \"${String(clause.op)}\" is not one of eq, ne, gt, gte, lt, lte, in, contains.`);\n }\n }\n if (query.aggregate !== undefined) {\n const ops = [\"count\", \"sum\", \"avg\", \"min\", \"max\"];\n if (!isPlainObject(query.aggregate) || !ops.includes(String(query.aggregate.op))) out.push(`$query.aggregate.op must be one of ${ops.join(\", \")}.`);\n else if (query.aggregate.op !== \"count\" && typeof query.aggregate.field !== \"string\") out.push(`$query.aggregate \"${query.aggregate.op}\" needs a \\`field\\`.`);\n }\n if (query.sortDir !== undefined && query.sortDir !== \"asc\" && query.sortDir !== \"desc\") out.push('$query.sortDir must be \"asc\" or \"desc\".');\n if (query.shape !== undefined && query.shape !== \"points\" && query.shape !== \"rows\") out.push('$query.shape must be \"points\" or \"rows\".');\n return out;\n}\n","// The built-in surface vocabulary: layout, display, input and one action control.\n//\n// Names follow A2UI's basic catalogue where a counterpart exists. Every prop is\n// enumerated and `additionalProperties` is false, which is what makes \"no style,\n// no className, no onClick\" a property of the format rather than a filter on it.\n\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { SurfaceComponentDefinition } from \"./catalogue.js\";\n\nconst TONES = [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"];\nconst FORMATS = [\"text\", \"number\", \"currency\", \"percent\", \"bytes\", \"duration\", \"datetime\", \"code\"];\nconst GAPS = [\"none\", \"xs\", \"sm\", \"md\", \"lg\"];\n\n/** Structural props are never bindings: the graph must be knowable before any data arrives. */\nconst fixed = (schema: JSONSchema): JSONSchema => ({ ...schema, \"x-static\": true });\nconst childIds: JSONSchema = fixed({ type: \"array\", items: { type: \"string\" }, description: \"Component ids, in display order.\" });\nconst childId = (description: string): JSONSchema => fixed({ type: \"string\", description });\n\n/** A control's value must be a `$path`: it has to know where to write. */\nconst boundValue: JSONSchema = {\n type: \"object\",\n required: [\"$path\"],\n properties: { $path: { type: \"string\" } },\n additionalProperties: false,\n description: 'Two-way binding, e.g. { \"$path\": \"/filters/region\" }.',\n \"x-static\": true,\n};\n\nexport const CONDITION_SCHEMA: JSONSchema = fixed({\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\" },\n op: { type: \"string\", enum: [\"truthy\", \"falsy\", \"eq\", \"ne\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"] },\n value: {},\n },\n additionalProperties: false,\n});\n\nexport const ACTION_SCHEMA: JSONSchema = fixed({\n type: \"object\",\n required: [\"type\"],\n description:\n 'One of { \"type\": \"set\", \"updates\": [{ \"path\", \"value\" }] }, { \"type\": \"tool\", \"tool\", \"args\", \"resultPath\" }, { \"type\": \"event\", \"name\", \"context\" }.',\n});\n\nconst props = (properties: Record<string, JSONSchema>, required: string[] = []): JSONSchema => ({\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n});\n\nconst text = (description?: string): JSONSchema => ({ type: \"string\", ...(description ? { description } : {}) });\n\nexport const SURFACE_PRIMITIVES: SurfaceComponentDefinition[] = [\n {\n name: \"Stack\",\n category: \"layout\",\n summary: \"Arrange children in a column or a row.\",\n props: props(\n {\n children: childIds,\n direction: { type: \"string\", enum: [\"vertical\", \"horizontal\"] },\n gap: { type: \"string\", enum: GAPS },\n align: { type: \"string\", enum: [\"start\", \"center\", \"end\", \"stretch\"] },\n justify: { type: \"string\", enum: [\"start\", \"center\", \"end\", \"between\"] },\n wrap: { type: \"boolean\" },\n },\n [\"children\"],\n ),\n slots: (p) => (p[\"children\"] as string[]) ?? [],\n },\n {\n name: \"Grid\",\n category: \"layout\",\n summary: \"Equal columns that collapse on narrow containers.\",\n props: props(\n {\n children: childIds,\n columns: { type: \"integer\", minimum: 1, maximum: 4 },\n gap: { type: \"string\", enum: GAPS },\n },\n [\"children\"],\n ),\n slots: (p) => (p[\"children\"] as string[]) ?? [],\n },\n {\n name: \"Section\",\n category: \"layout\",\n summary: \"A titled group of children.\",\n props: props(\n {\n title: text(),\n description: text(),\n tone: { type: \"string\", enum: TONES },\n children: childIds,\n },\n [\"children\"],\n ),\n slots: (p) => (p[\"children\"] as string[]) ?? [],\n },\n {\n name: \"Tabs\",\n category: \"layout\",\n summary: \"Switch between named panels. Keyboard accessible.\",\n props: props(\n {\n label: text(\"Names the tab list for screen readers.\"),\n value: { ...boundValue, description: \"Optional binding for the selected tab id.\" },\n tabs: fixed({\n type: \"array\",\n minItems: 1,\n maxItems: 12,\n items: {\n type: \"object\",\n required: [\"id\", \"label\", \"child\"],\n properties: { id: { type: \"string\" }, label: { type: \"string\" }, child: { type: \"string\" } },\n additionalProperties: false,\n },\n }),\n },\n [\"tabs\"],\n ),\n slots: (p) => ((p[\"tabs\"] as { child: string }[]) ?? []).map((t) => t.child),\n },\n {\n name: \"List\",\n category: \"layout\",\n summary: \"Repeat one template for each row of an array; the template reads rows with $item.\",\n props: props(\n {\n items: { type: \"array\", description: \"A $path or $query that yields an array.\" },\n child: childId(\"The template component rendered once per row.\"),\n emptyText: text(\"Shown when there are no rows.\"),\n gap: { type: \"string\", enum: GAPS },\n },\n [\"items\", \"child\"],\n ),\n slots: (p) => (typeof p[\"child\"] === \"string\" ? [p[\"child\"]] : []),\n templateSlots: (p) => (typeof p[\"child\"] === \"string\" ? [p[\"child\"]] : []),\n },\n { name: \"Divider\", category: \"layout\", summary: \"A horizontal rule between groups.\", props: props({}) },\n {\n name: \"Text\",\n category: \"display\",\n summary: \"Plain text. Never parsed as HTML or Markdown.\",\n props: props(\n {\n text: { type: [\"string\", \"number\"] },\n variant: { type: \"string\", enum: [\"title\", \"heading\", \"body\", \"caption\", \"label\", \"code\"] },\n tone: { type: \"string\", enum: TONES },\n },\n [\"text\"],\n ),\n },\n {\n name: \"Metric\",\n category: \"display\",\n summary: \"One headline number with a label and optional change.\",\n props: props(\n {\n label: text(),\n value: { type: [\"string\", \"number\", \"null\"] },\n format: { type: \"string\", enum: FORMATS },\n delta: { type: \"number\" },\n deltaFormat: { type: \"string\", enum: FORMATS },\n hint: text(),\n tone: { type: \"string\", enum: TONES },\n },\n [\"label\", \"value\"],\n ),\n },\n {\n name: \"Badge\",\n category: \"display\",\n summary: \"A short status label.\",\n props: props({ text: { type: [\"string\", \"number\"] }, tone: { type: \"string\", enum: TONES } }, [\"text\"]),\n },\n {\n name: \"Image\",\n category: \"display\",\n summary: \"An http(s) image with required alt text.\",\n props: props({ src: text(), alt: text(), caption: text() }, [\"src\", \"alt\"]),\n },\n {\n name: \"Link\",\n category: \"display\",\n summary: \"An http(s) link that opens in a new tab.\",\n props: props({ text: text(), href: text() }, [\"text\", \"href\"]),\n },\n {\n name: \"Field\",\n category: \"input\",\n summary: \"Text, number, date or multi-line input bound to the data model.\",\n props: props(\n {\n label: text(),\n value: boundValue,\n type: { type: \"string\", enum: [\"text\", \"number\", \"date\", \"textarea\"] },\n placeholder: text(),\n helper: text(),\n min: { type: \"number\" },\n max: { type: \"number\" },\n step: { type: \"number\" },\n },\n [\"label\", \"value\"],\n ),\n },\n {\n name: \"Select\",\n category: \"input\",\n summary: \"Choose one option; writes its value to the data model.\",\n props: props(\n {\n label: text(),\n value: boundValue,\n options: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"value\", \"label\"],\n properties: { value: { type: [\"string\", \"number\", \"boolean\"] }, label: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n helper: text(),\n },\n [\"label\", \"value\", \"options\"],\n ),\n },\n {\n name: \"Toggle\",\n category: \"input\",\n summary: \"An on/off switch bound to a boolean.\",\n props: props({ label: text(), value: boundValue, helper: text() }, [\"label\", \"value\"]),\n },\n {\n name: \"Slider\",\n category: \"input\",\n summary: \"Pick a number in a range.\",\n props: props(\n {\n label: text(),\n value: boundValue,\n min: { type: \"number\" },\n max: { type: \"number\" },\n step: { type: \"number\" },\n format: { type: \"string\", enum: FORMATS },\n },\n [\"label\", \"value\", \"min\", \"max\"],\n ),\n },\n {\n name: \"Button\",\n category: \"action\",\n summary: \"Runs one action when pressed: set local state, call an allowed tool, or send the agent an event.\",\n props: props(\n {\n label: text(),\n action: ACTION_SCHEMA,\n variant: { type: \"string\", enum: [\"primary\", \"secondary\", \"ghost\", \"danger\"] },\n disabledWhen: CONDITION_SCHEMA,\n },\n [\"label\", \"action\"],\n ),\n },\n];\n","// The catalogue: everything a surface may be built from, in one place.\n//\n// Three sources, one lookup: the built-in primitives, every kind in the card\n// registry (read live, so a plugin installed after startup is available\n// immediately), and components a host registers with its own renderer.\n//\n// The index is one line per component and the schemas are fetched on request.\n// That split is the progressive disclosure: forty schemas in every prompt would\n// cost more than most of the surfaces they describe.\n\nimport type { CardRegistry } from \"../cards/registry.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\nimport { ACTION_SCHEMA, SURFACE_PRIMITIVES } from \"./primitives.js\";\nimport { SURFACE_CARD_KIND } from \"./types.js\";\n\nexport type SurfaceComponentCategory = \"layout\" | \"display\" | \"input\" | \"action\" | \"card\" | \"custom\";\n\nexport type SurfaceComponentDefinition = {\n name: string;\n category: SurfaceComponentCategory;\n /** One line for the index. Keep domain nouns out of it: this steers the model. */\n summary: string;\n /** Schema for the component's props, excluding `id`, `component` and `visibleWhen`. */\n props: JSONSchema;\n /** Ids of the components this one renders. */\n slots?: (props: Record<string, unknown>) => string[];\n /** The subset of `slots` rendered once per row, where `$item` is in scope. */\n templateSlots?: (props: Record<string, unknown>) => string[];\n};\n\n/** The prefix that addresses one card kind in the index, as in `Card:chart`. */\nexport const CARD_ENTRY_PREFIX = \"Card:\";\n\nexport const CARD_COMPONENT: SurfaceComponentDefinition = {\n name: \"Card\",\n category: \"card\",\n summary: \"Embed any card kind. `spec` may contain bindings.\",\n props: {\n type: \"object\",\n required: [\"kind\", \"spec\"],\n additionalProperties: false,\n properties: {\n kind: { type: \"string\", description: \"A registered card kind.\", \"x-static\": true },\n spec: { type: \"object\", description: \"The card body, without `kind`.\", \"x-static\": true },\n bind: { type: \"string\", description: \"Interactive kinds only: JSON Pointer that stores the answer.\", \"x-static\": true },\n action: ACTION_SCHEMA,\n },\n },\n};\n\nexport type SurfaceCatalogueOptions = {\n cards?: CardRegistry;\n /** Host components. Each needs a renderer under the same name in the UI layer. */\n components?: readonly SurfaceComponentDefinition[];\n};\n\nexport class SurfaceCatalogue {\n readonly cards: CardRegistry | undefined;\n private readonly definitions = new Map<string, SurfaceComponentDefinition>();\n\n constructor(options: SurfaceCatalogueOptions = {}) {\n this.cards = options.cards;\n for (const def of SURFACE_PRIMITIVES) this.definitions.set(def.name, def);\n this.definitions.set(CARD_COMPONENT.name, CARD_COMPONENT);\n for (const def of options.components ?? []) this.register(def);\n }\n\n /** Add a host component. A built-in name cannot be replaced: its meaning is part of the format. */\n register(def: SurfaceComponentDefinition): this {\n const existing = this.definitions.get(def.name);\n if (existing && existing.category !== \"custom\") throw new Error(`Surface component \"${def.name}\" is built in and cannot be replaced.`);\n if (def.name.startsWith(CARD_ENTRY_PREFIX)) throw new Error(`Surface component names cannot start with \"${CARD_ENTRY_PREFIX}\".`);\n this.definitions.set(def.name, { ...def, category: \"custom\" });\n return this;\n }\n\n get(name: string): SurfaceComponentDefinition | undefined {\n return this.definitions.get(name);\n }\n\n has(name: string): boolean {\n return this.definitions.has(name);\n }\n\n /** Card kinds usable inside a surface. A surface cannot contain a surface. */\n cardKinds() {\n return (this.cards?.list() ?? []).filter((k) => k.kind !== SURFACE_CARD_KIND);\n }\n\n /** Every addressable entry: components by name, cards as `Card:<kind>`. */\n names(): string[] {\n return [...this.definitions.keys(), ...this.cardKinds().map((k) => `${CARD_ENTRY_PREFIX}${k.kind}`)];\n }\n\n /** One line per entry. Cheap enough to hand over whenever the model asks what exists. */\n index(): string {\n const lines = [...this.definitions.values()].map((d) => `- ${d.name} (${d.category}): ${d.summary}`);\n for (const k of this.cardKinds()) {\n lines.push(`- ${CARD_ENTRY_PREFIX}${k.kind}${k.interactive ? \" (interactive, needs `bind`)\" : \"\"}: ${k.summary}`);\n }\n return lines.join(\"\\n\");\n }\n\n /** The full schema of one entry, or `undefined` for a name that does not exist. */\n schemaOf(name: string): { name: string; summary: string; props: JSONSchema; interactive?: boolean } | undefined {\n if (name.startsWith(CARD_ENTRY_PREFIX)) {\n const kind = name.slice(CARD_ENTRY_PREFIX.length);\n const def = this.cardKinds().find((k) => k.kind === kind);\n if (!def) return undefined;\n return { name, summary: def.summary, props: def.schema, ...(def.interactive ? { interactive: true } : {}) };\n }\n const def = this.definitions.get(name);\n return def ? { name: def.name, summary: def.summary, props: def.props } : undefined;\n }\n}\n","// Validation: the only road from model output to a rendered component.\n//\n// Every failure is reported per component, in words the model can act on, and the\n// rest of the surface survives it. One bad chart should cost one correction, not\n// the whole interface.\n\nimport { checkSchema } from \"./schema-check.js\";\nimport { bindingProblems, isSurfaceBinding, resolveSurfaceValue, usesBinding } from \"./bindings.js\";\nimport type { SurfaceCatalogue, SurfaceComponentDefinition } from \"./catalogue.js\";\nimport { parsePointer } from \"./pointer.js\";\nimport { findUnsafe } from \"./safety.js\";\nimport {\n SURFACE_CARD_KIND,\n SURFACE_LIMITS,\n type SurfaceAction,\n type SurfaceBinding,\n type SurfaceComponent,\n type SurfaceIssue,\n} from \"./types.js\";\n\nexport type SurfaceValidationContext = {\n catalogue: SurfaceCatalogue;\n data: Record<string, unknown>;\n /** Tools an action may call. Omitted means \"checked at dispatch only\". */\n actionTools?: readonly string[];\n /** Leave cards whose spec has bindings to the render that resolves them. */\n deferBoundCards?: boolean;\n};\n\nconst ID = /^[A-Za-z0-9_.:-]{1,64}$/;\nexport const isSurfaceId = (value: unknown): value is string => typeof value === \"string\" && ID.test(value);\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst RESERVED = new Set([\"id\", \"component\", \"visibleWhen\"]);\n\nfunction collectBindings(value: unknown, out: SurfaceBinding[] = []): SurfaceBinding[] {\n if (Array.isArray(value)) for (const v of value) collectBindings(v, out);\n else if (isSurfaceBinding(value)) {\n out.push(value);\n if (\"$query\" in value && isObject(value.$query) && Array.isArray(value.$query.where)) {\n for (const clause of value.$query.where) collectBindings(isObject(clause) ? clause[\"value\"] : undefined, out);\n }\n } else if (isObject(value)) for (const v of Object.values(value)) collectBindings(v, out);\n return out;\n}\n\nfunction bindingIssues(value: unknown, componentId: string): SurfaceIssue[] {\n return collectBindings(value).flatMap((binding) =>\n bindingProblems(binding).map((message) => ({\n code: \"invalid-binding\" as const,\n componentId,\n message,\n fix: 'Use { \"$path\": \"/a/b\" }, { \"$template\": \"Text {/a}\" }, { \"$query\": { \"from\": \"/rows\" } }, or { \"$item\": \"field\" } inside a List.',\n })),\n );\n}\n\nexport function validateSurfaceAction(action: unknown, componentId: string, ctx: SurfaceValidationContext): SurfaceIssue[] {\n const bad = (message: string, fix: string, code: SurfaceIssue[\"code\"] = \"invalid-action\"): SurfaceIssue[] => [\n { code, componentId, path: \"/action\", message, fix },\n ];\n const closed = 'Use { \"type\": \"set\", \"updates\": [...] }, { \"type\": \"tool\", \"tool\": \"name\", \"args\": {} } or { \"type\": \"event\", \"name\": \"name\" }.';\n if (!isObject(action)) return bad(\"action must be an object.\", closed);\n\n const onlyKeys = (allowed: string[]) => {\n const extra = Object.keys(action).filter((k) => !allowed.includes(k));\n return extra.length ? bad(`action has no \"${extra[0]}\". Actions cannot carry code or URLs.`, `Allowed keys: ${allowed.join(\", \")}.`) : [];\n };\n\n const typed = action as SurfaceAction;\n switch (typed.type) {\n case \"set\": {\n const extra = onlyKeys([\"type\", \"updates\"]);\n if (extra.length) return extra;\n if (!Array.isArray(typed.updates) || !typed.updates.length || typed.updates.length > SURFACE_LIMITS.actionUpdates) {\n return bad(`set needs 1 to ${SURFACE_LIMITS.actionUpdates} updates.`, 'Send \"updates\": [{ \"path\": \"/a\", \"value\": 1 }].');\n }\n for (const update of typed.updates) {\n if (!isObject(update) || !parsePointer(update.path)) return bad(\"Each update needs a JSON Pointer `path`.\", 'Send { \"path\": \"/a\", \"value\": 1 }.');\n }\n return bindingIssues(typed.updates, componentId);\n }\n case \"tool\": {\n const extra = onlyKeys([\"type\", \"tool\", \"args\", \"resultPath\"]);\n if (extra.length) return extra;\n if (typeof typed.tool !== \"string\" || !typed.tool) return bad(\"A tool action needs a `tool` name.\", 'Send { \"type\": \"tool\", \"tool\": \"name\" }.');\n if (typed.args !== undefined && !isObject(typed.args)) return bad(\"Tool `args` must be an object.\", \"Send args as an object of literals or bindings.\");\n if (typed.resultPath !== undefined && !parsePointer(typed.resultPath)) return bad(\"`resultPath` must be a JSON Pointer.\", 'Send \"resultPath\": \"/result\".');\n if (ctx.actionTools && !ctx.actionTools.includes(typed.tool)) {\n return bad(\n `Tool \"${typed.tool}\" is not available to this surface.`,\n ctx.actionTools.length ? `Available: ${ctx.actionTools.slice(0, 24).join(\", \")}.` : 'No tools are available; use an \"event\" action instead.',\n \"tool-not-allowed\",\n );\n }\n return bindingIssues(typed.args, componentId);\n }\n case \"event\": {\n const extra = onlyKeys([\"type\", \"name\", \"context\"]);\n if (extra.length) return extra;\n if (!isSurfaceId(typed.name)) return bad(\"An event needs a short `name`.\", 'Send { \"type\": \"event\", \"name\": \"apply\" }.');\n if (typed.context !== undefined && !isObject(typed.context)) return bad(\"Event `context` must be an object.\", \"Send context as an object of literals or bindings.\");\n return bindingIssues(typed.context, componentId);\n }\n default:\n return bad(`Unknown action type ${JSON.stringify((action as { type?: unknown }).type)}.`, closed);\n }\n}\n\nfunction validateCard(raw: SurfaceComponent, ctx: SurfaceValidationContext): SurfaceIssue[] {\n const id = raw.id;\n const kind = raw[\"kind\"];\n const registry = ctx.catalogue.cards;\n const available = ctx.catalogue.cardKinds().map((k) => k.kind);\n if (typeof kind !== \"string\" || kind === SURFACE_CARD_KIND || !registry?.has(kind)) {\n return [{ code: \"invalid-card\", componentId: id, path: \"/kind\", message: `Unknown card kind ${JSON.stringify(kind)}.`, fix: `One of: ${available.join(\", \") || \"(no card registry)\"}.` }];\n }\n const spec = raw[\"spec\"];\n if (!isObject(spec)) return [{ code: \"invalid-card\", componentId: id, path: \"/spec\", message: \"Card `spec` must be an object.\", fix: \"Send the card body as `spec`.\" }];\n\n const issues = bindingIssues(spec, id);\n if (registry.isInteractive(kind) && !parsePointer(raw[\"bind\"])) {\n issues.push({\n code: \"invalid-card\",\n componentId: id,\n path: \"/bind\",\n message: `Interactive card \"${kind}\" needs \\`bind\\`, the place its answer is stored.`,\n fix: 'Add \"bind\": \"/answers/decision\".',\n });\n }\n if (raw[\"action\"] !== undefined) issues.push(...validateSurfaceAction(raw[\"action\"], id, ctx));\n if (issues.length) return issues;\n\n // Rows from a List do not exist yet, so a template card is checked when it renders.\n if (usesBinding(spec, \"$item\")) return [];\n if (ctx.deferBoundCards && (usesBinding(spec, \"$path\") || usesBinding(spec, \"$query\") || usesBinding(spec, \"$template\"))) return [];\n const verdict = registry.validate({ ...(resolveSurfaceValue(spec, { data: ctx.data }) as Record<string, unknown>), kind });\n return verdict.ok\n ? []\n : [{ code: \"invalid-card\", componentId: id, path: \"/spec\", message: verdict.error, fix: verdict.expected ?? `Call describeSurfaceComponents for ${\"`\"}Card:${kind}${\"`\"}.` }];\n}\n\n/** Everything wrong with one component, judged alone. */\nexport function validateSurfaceComponent(raw: unknown, ctx: SurfaceValidationContext): SurfaceIssue[] {\n if (!isObject(raw)) return [{ code: \"invalid-shape\", message: \"Each component must be an object.\", fix: 'Send { \"id\": \"a\", \"component\": \"Text\", \"text\": \"Hello\" }.' }];\n const id = raw[\"id\"];\n if (!isSurfaceId(id)) return [{ code: \"invalid-shape\", message: `Component id ${JSON.stringify(id)} is invalid.`, fix: \"Use 1 to 64 letters, digits, or . _ : -\" }];\n const component = raw as SurfaceComponent;\n const name = component.component;\n const def: SurfaceComponentDefinition | undefined = typeof name === \"string\" ? ctx.catalogue.get(name) : undefined;\n if (!def) {\n return [{\n code: \"unknown-component\",\n componentId: id,\n path: \"/component\",\n message: `Unknown component ${JSON.stringify(name)}.`,\n fix: `One of: ${ctx.catalogue.names().filter((n) => !n.startsWith(\"Card:\")).join(\", \")}. Cards use \"component\": \"Card\" with a \"kind\".`,\n }];\n }\n\n const isCard = def.name === \"Card\";\n const unsafe = findUnsafe(raw, { markup: !isCard && def.category !== \"custom\" });\n if (unsafe) {\n return [{ code: \"unsafe-content\", componentId: id, path: unsafe.path, message: `${unsafe.path || \"The component\"} ${unsafe.reason}.`, fix: \"Send plain text and http(s) URLs only. Surfaces cannot carry script, HTML or CSS.\" }];\n }\n\n const props = Object.fromEntries(Object.entries(raw).filter(([k]) => !RESERVED.has(k)));\n const issues: SurfaceIssue[] = checkSchema(def.props, props, \"\", { isDynamic: isSurfaceBinding }).map((p) => ({\n code: \"invalid-prop\" as const,\n componentId: id,\n path: p.path,\n message: `${def.name}: ${p.message}`,\n fix: p.expected ?? `Call describeSurfaceComponents for ${def.name}.`,\n }));\n\n if (raw[\"visibleWhen\"] !== undefined) {\n const condition = raw[\"visibleWhen\"];\n if (!isObject(condition) || !parsePointer(condition[\"path\"])) {\n issues.push({ code: \"invalid-binding\", componentId: id, path: \"/visibleWhen\", message: \"visibleWhen needs a JSON Pointer `path`.\", fix: 'Send { \"path\": \"/showDetails\" }.' });\n }\n }\n if (issues.length) return issues;\n\n if (isCard) return validateCard(component, ctx);\n\n const out = bindingIssues(props, id);\n for (const key of [\"value\"] as const) {\n const bound = props[key];\n if (def.category === \"input\" && isObject(bound) && !parsePointer(bound[\"$path\"])) {\n out.push({ code: \"invalid-binding\", componentId: id, path: `/${key}`, message: `${def.name}.value must be a writable $path.`, fix: 'Send \"value\": { \"$path\": \"/filters/region\" }.' });\n }\n }\n if (props[\"action\"] !== undefined) out.push(...validateSurfaceAction(props[\"action\"], id, ctx));\n if (props[\"disabledWhen\"] !== undefined && !parsePointer((props[\"disabledWhen\"] as { path?: unknown }).path)) {\n out.push({ code: \"invalid-binding\", componentId: id, path: \"/disabledWhen\", message: \"disabledWhen needs a JSON Pointer `path`.\", fix: 'Send { \"path\": \"/busy\" }.' });\n }\n return out;\n}\n\n/** Split a component list into what may render and what must be corrected. */\nexport function validateSurfaceComponents(raw: readonly unknown[], ctx: SurfaceValidationContext): { components: SurfaceComponent[]; issues: SurfaceIssue[] } {\n const components: SurfaceComponent[] = [];\n const issues: SurfaceIssue[] = [];\n const seen = new Set<string>();\n for (const entry of raw) {\n const found = validateSurfaceComponent(entry, ctx);\n if (found.length) {\n issues.push(...found);\n continue;\n }\n const component = entry as SurfaceComponent;\n if (seen.has(component.id)) {\n issues.push({ code: \"duplicate-id\", componentId: component.id, message: `Component id \"${component.id}\" is used twice.`, fix: \"Give every component its own id.\" });\n continue;\n }\n seen.add(component.id);\n components.push(component);\n }\n return { components, issues };\n}\n\n/**\n * Whole-graph checks: a root that exists, children that exist, no cycles, bounded\n * depth, and `$item` only where a row is in scope.\n */\nexport function validateSurfaceGraph(\n root: string,\n components: readonly SurfaceComponent[],\n catalogue: SurfaceCatalogue,\n rejected: ReadonlySet<string> = new Set(),\n): SurfaceIssue[] {\n const byId = new Map(components.map((c) => [c.id, c]));\n const issues: SurfaceIssue[] = [];\n if (!byId.has(root)) {\n if (!rejected.has(root)) issues.push({ code: \"missing-root\", componentId: root, message: `Root \"${root}\" is not in the component list.`, fix: \"Add a component with that id, or set `root` to one that exists.\" });\n return issues;\n }\n\n const slotsOf = (c: SurfaceComponent) => {\n try {\n return catalogue.get(c.component)?.slots?.(c) ?? [];\n } catch {\n return [];\n }\n };\n const templatesOf = (c: SurfaceComponent) => {\n try {\n return catalogue.get(c.component)?.templateSlots?.(c) ?? [];\n } catch {\n return [];\n }\n };\n\n const reported = new Set<string>();\n const once = (key: string, issue: SurfaceIssue) => {\n if (reported.has(key)) return;\n reported.add(key);\n issues.push(issue);\n };\n\n const visit = (id: string, trail: string[], inTemplate: boolean): void => {\n const component = byId.get(id);\n if (!component) return;\n if (trail.includes(id)) {\n once(`cycle:${id}`, { code: \"cycle\", componentId: id, message: `Component \"${id}\" contains itself.`, fix: \"Remove the reference that loops back.\" });\n return;\n }\n if (trail.length >= SURFACE_LIMITS.depth) {\n once(`depth:${id}`, { code: \"too-deep\", componentId: id, message: `Nesting is deeper than ${SURFACE_LIMITS.depth} levels.`, fix: \"Flatten the layout.\" });\n return;\n }\n if (!inTemplate && usesBinding(component, \"$item\")) {\n once(`item:${id}`, { code: \"invalid-binding\", componentId: id, message: `\"${id}\" reads $item outside a List template.`, fix: \"Use $path here, or move it under a List's `child`.\" });\n }\n const templates = templatesOf(component);\n for (const child of slotsOf(component)) {\n if (!byId.has(child)) {\n if (!rejected.has(child)) once(`missing:${child}`, { code: \"missing-child\", componentId: id, message: `\"${id}\" references \"${child}\", which does not exist.`, fix: `Add a component with id \"${child}\" or remove the reference.` });\n continue;\n }\n visit(child, [...trail, id], inTemplate || templates.includes(child));\n }\n };\n\n visit(root, [], false);\n return issues;\n}\n","// Building and patching surfaces. Pure functions: spec in, spec and corrections out.\n\nimport type { SurfaceCatalogue } from \"./catalogue.js\";\nimport { removeAt, setAt } from \"./pointer.js\";\nimport { findUnsafe } from \"./safety.js\";\nimport {\n SURFACE_CARD_KIND,\n SURFACE_FORMAT_VERSION,\n SURFACE_LIMITS,\n type SurfaceComponent,\n type SurfaceIssue,\n type SurfaceOperation,\n type SurfaceSpec,\n} from \"./types.js\";\nimport {\n isSurfaceId,\n validateSurfaceComponent,\n validateSurfaceComponents,\n validateSurfaceGraph,\n type SurfaceValidationContext,\n} from \"./validate.js\";\n\nexport type SurfaceBuildContext = {\n catalogue: SurfaceCatalogue;\n actionTools?: readonly string[];\n};\n\n/** `spec` is absent when nothing could be rendered at all. `issues` is what the model must correct. */\nexport type SurfaceBuildResult = { spec?: SurfaceSpec; issues: SurfaceIssue[] };\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst fatal = (issue: SurfaceIssue): SurfaceBuildResult => ({ issues: [issue] });\n\nfunction dataIssue(data: unknown): SurfaceIssue | undefined {\n const unsafe = findUnsafe(data);\n if (unsafe) {\n return { code: \"unsafe-content\", path: unsafe.path, message: `data${unsafe.path} ${unsafe.reason}.`, fix: \"Store plain values and http(s) URLs only.\" };\n }\n if (JSON.stringify(data).length > SURFACE_LIMITS.dataChars) {\n return { code: \"limit-exceeded\", path: \"/data\", message: `data is larger than ${SURFACE_LIMITS.dataChars} characters.`, fix: \"Send a summary or fewer rows.\" };\n }\n return undefined;\n}\n\nconst tooMany = (count: number): SurfaceIssue => ({\n code: \"limit-exceeded\",\n message: `A surface may hold ${SURFACE_LIMITS.components} components; this has ${count}.`,\n fix: \"Use a List template instead of repeating components.\",\n});\n\n/** Issues that belong in the spec: parts the person sees a fallback for. */\nfunction persistentIssues(components: readonly SurfaceComponent[], issues: readonly SurfaceIssue[]): SurfaceIssue[] {\n const present = new Set(components.map((c) => c.id));\n return issues.filter((i) => !i.componentId || !present.has(i.componentId) || i.code === \"missing-child\" || i.code === \"cycle\" || i.code === \"too-deep\" || i.code === \"invalid-binding\");\n}\n\n/** Validate a complete surface from `createSurface` arguments. */\nexport function buildSurface(\n input: unknown,\n ctx: SurfaceBuildContext,\n opts: { revision?: number; originCallId?: string } = {},\n): SurfaceBuildResult {\n if (!isObject(input)) return fatal({ code: \"invalid-shape\", message: \"Surface must be an object.\", fix: \"Send surfaceId, root and components.\" });\n const { surfaceId, root, components, data, title } = input;\n if (!isSurfaceId(surfaceId)) return fatal({ code: \"invalid-shape\", path: \"/surfaceId\", message: \"surfaceId is missing or invalid.\", fix: 'Send a short id such as \"overview\".' });\n if (!isSurfaceId(root)) return fatal({ code: \"missing-root\", path: \"/root\", message: \"root must be the id of a component.\", fix: 'Send \"root\": \"main\" and a component with that id.' });\n if (!Array.isArray(components) || !components.length) return fatal({ code: \"invalid-shape\", path: \"/components\", message: \"components must be a non-empty array.\", fix: 'Send [{ \"id\": \"main\", \"component\": \"Stack\", \"children\": [] }].' });\n if (components.length > SURFACE_LIMITS.components) return fatal(tooMany(components.length));\n if (data !== undefined && !isObject(data)) return fatal({ code: \"invalid-data\", path: \"/data\", message: \"data must be an object.\", fix: 'Send \"data\": { \"filters\": {} }.' });\n const model = (data ?? {}) as Record<string, unknown>;\n const bad = dataIssue(model);\n if (bad) return fatal(bad);\n if (JSON.stringify(components).length > SURFACE_LIMITS.specChars) {\n return fatal({ code: \"limit-exceeded\", path: \"/components\", message: `components exceed ${SURFACE_LIMITS.specChars} characters.`, fix: \"Move repeated content into data and use a List.\" });\n }\n\n const validation: SurfaceValidationContext = { catalogue: ctx.catalogue, data: model, actionTools: ctx.actionTools };\n const checked = validateSurfaceComponents(components, validation);\n const rejected = new Set(checked.issues.flatMap((i) => (i.componentId ? [i.componentId] : [])));\n const graph = validateSurfaceGraph(root, checked.components, ctx.catalogue, rejected);\n const issues = [...checked.issues, ...graph];\n const kept = persistentIssues(checked.components, issues);\n\n return {\n issues,\n spec: {\n kind: SURFACE_CARD_KIND,\n version: SURFACE_FORMAT_VERSION,\n surfaceId,\n ...(typeof title === \"string\" && title ? { title } : {}),\n root,\n components: checked.components,\n data: model,\n revision: opts.revision ?? 1,\n ...(opts.originCallId ? { originCallId: opts.originCallId } : {}),\n ...(kept.length ? { issues: kept } : {}),\n },\n };\n}\n\n/**\n * Apply patches to a surface.\n *\n * Data operations land first, whatever order they were sent in: a component is\n * validated against the data it binds to, and a model naturally writes the new\n * chart before the rows it reads. A rejected upsert keeps the previous version\n * of that component on screen.\n */\nexport function applySurfaceOperations(spec: SurfaceSpec, operations: unknown, ctx: SurfaceBuildContext): SurfaceBuildResult {\n if (!Array.isArray(operations) || !operations.length) {\n return fatal({ code: \"invalid-shape\", path: \"/operations\", message: \"operations must be a non-empty array.\", fix: 'Send [{ \"op\": \"setData\", \"path\": \"/a\", \"value\": 1 }].' });\n }\n\n const issues: SurfaceIssue[] = [];\n let data = spec.data;\n const ops = operations as SurfaceOperation[];\n\n for (const op of ops) {\n if (!isObject(op)) continue;\n if (op.op === \"setData\") {\n const unsafe = findUnsafe(op.value);\n const next = unsafe ? undefined : setAt(data, op.path, op.value);\n if (next) data = next;\n else issues.push({ code: unsafe ? \"unsafe-content\" : \"invalid-data\", path: op.path, message: unsafe ? `The value ${unsafe.path} ${unsafe.reason}.` : `Cannot write to ${JSON.stringify(op.path)}.`, fix: 'Use a JSON Pointer such as \"/filters/region\" with a plain value.' });\n } else if (op.op === \"removeData\") {\n const next = removeAt(data, op.path);\n if (next) data = next;\n else issues.push({ code: \"invalid-data\", path: op.path, message: `Cannot remove ${JSON.stringify(op.path)}.`, fix: 'Use a JSON Pointer such as \"/filters/region\".' });\n }\n }\n const bad = dataIssue(data);\n if (bad) return fatal(bad);\n\n const validation: SurfaceValidationContext = { catalogue: ctx.catalogue, data, actionTools: ctx.actionTools };\n const byId = new Map(spec.components.map((c) => [c.id, c]));\n const rejected = new Set((spec.issues ?? []).flatMap((i) => (i.componentId && !byId.has(i.componentId) ? [i.componentId] : [])));\n const carried = new Map<string, SurfaceIssue[]>();\n for (const issue of spec.issues ?? []) {\n if (issue.componentId && rejected.has(issue.componentId)) carried.set(issue.componentId, [...(carried.get(issue.componentId) ?? []), issue]);\n }\n let root = spec.root;\n let title = spec.title;\n\n for (const op of ops) {\n if (!isObject(op)) {\n issues.push({ code: \"invalid-shape\", message: \"Each operation must be an object.\", fix: \"Send { op, ... }.\" });\n continue;\n }\n switch (op.op) {\n case \"setData\":\n case \"removeData\":\n break;\n case \"upsertComponents\": {\n if (!Array.isArray(op.components)) {\n issues.push({ code: \"invalid-shape\", path: \"/components\", message: \"upsertComponents needs a `components` array.\", fix: \"Send the changed components in full.\" });\n break;\n }\n for (const raw of op.components) {\n const found = validateSurfaceComponent(raw, validation);\n const id = isObject(raw) && typeof raw[\"id\"] === \"string\" ? raw[\"id\"] : undefined;\n if (found.length) {\n issues.push(...found);\n if (id && !byId.has(id)) {\n rejected.add(id);\n carried.set(id, found);\n }\n continue;\n }\n const component = raw as SurfaceComponent;\n byId.set(component.id, component);\n rejected.delete(component.id);\n carried.delete(component.id);\n }\n break;\n }\n case \"removeComponents\": {\n const ids = new Set(Array.isArray(op.ids) ? op.ids : []);\n for (const id of ids) {\n byId.delete(id);\n rejected.delete(id);\n carried.delete(id);\n }\n // Dropping a child from its parent's list is unambiguous, so it is done\n // here rather than bounced back as a dangling reference.\n for (const [id, component] of byId) {\n const children = component[\"children\"];\n if (Array.isArray(children) && children.some((c) => ids.has(c as string))) {\n byId.set(id, { ...component, children: children.filter((c) => !ids.has(c as string)) });\n }\n }\n break;\n }\n case \"setRoot\":\n if (isSurfaceId(op.root)) root = op.root;\n else issues.push({ code: \"missing-root\", path: \"/root\", message: \"setRoot needs a component id.\", fix: 'Send { \"op\": \"setRoot\", \"root\": \"main\" }.' });\n break;\n case \"setTitle\":\n if (typeof op.title === \"string\") title = op.title;\n else issues.push({ code: \"invalid-shape\", path: \"/title\", message: \"setTitle needs a string `title`.\", fix: 'Send { \"op\": \"setTitle\", \"title\": \"Overview\" }.' });\n break;\n default:\n issues.push({\n code: \"invalid-shape\",\n message: `Unknown operation ${JSON.stringify((op as { op?: unknown }).op)}.`,\n fix: \"Use upsertComponents, removeComponents, setRoot, setTitle, setData or removeData.\",\n });\n }\n }\n\n const components = [...byId.values()];\n if (components.length > SURFACE_LIMITS.components) return fatal(tooMany(components.length));\n\n const graph = validateSurfaceGraph(root, components, ctx.catalogue, rejected);\n issues.push(...graph);\n const kept = [...[...carried.values()].flat(), ...graph];\n const { issues: _previous, title: _title, ...rest } = spec;\n\n return {\n issues,\n spec: {\n ...rest,\n ...(title ? { title } : {}),\n root,\n components,\n data,\n revision: spec.revision + 1,\n ...(kept.length ? { issues: kept } : {}),\n },\n };\n}\n\n/**\n * A surface from arguments still streaming in: every complete, valid component so\n * far. The last entry is usually half-written, so a failure here is not an error,\n * only something that has not arrived.\n */\nexport function previewSurface(partial: unknown, catalogue: SurfaceCatalogue): SurfaceSpec | undefined {\n if (!isObject(partial)) return undefined;\n const { surfaceId, root, components, data, title } = partial;\n if (!isSurfaceId(surfaceId) || !isSurfaceId(root) || !Array.isArray(components)) return undefined;\n const model = isObject(data) && !findUnsafe(data) ? data : {};\n const validation: SurfaceValidationContext = { catalogue, data: model };\n const seen = new Set<string>();\n const valid: SurfaceComponent[] = [];\n for (const raw of components.slice(0, SURFACE_LIMITS.components)) {\n if (validateSurfaceComponent(raw, validation).length) continue;\n const component = raw as SurfaceComponent;\n if (seen.has(component.id)) continue;\n seen.add(component.id);\n valid.push(component);\n }\n if (!valid.length) return undefined;\n // The last part listed is the one still being written, whether or not it is valid yet.\n const last: unknown = components.at(-1);\n const pending =\n isObject(last) && typeof last[\"id\"] === \"string\"\n ? {\n id: last[\"id\"],\n ...(typeof last[\"component\"] === \"string\" ? { component: last[\"component\"] } : {}),\n ...(typeof last[\"kind\"] === \"string\" ? { kind: last[\"kind\"] } : {}),\n }\n : undefined;\n return {\n kind: SURFACE_CARD_KIND,\n version: SURFACE_FORMAT_VERSION,\n surfaceId,\n ...(typeof title === \"string\" && title ? { title } : {}),\n root,\n components: valid,\n data: model,\n revision: 0,\n ...(pending ? { pending } : {}),\n };\n}\n\n/**\n * Re-validate a spec at the renderer. A thread can be edited in storage and a\n * catalogue can shrink between sessions, so what was valid when written is not\n * trusted when read. Whether a bound card is valid depends on the data of the\n * moment, so that one check is left to the render that resolves it.\n */\nexport function sanitizeSurfaceSpec(spec: SurfaceSpec, catalogue: SurfaceCatalogue): SurfaceSpec {\n const components = Array.isArray(spec.components) ? spec.components.slice(0, SURFACE_LIMITS.components) : [];\n const data = isObject(spec.data) && !findUnsafe(spec.data) ? spec.data : {};\n const checked = validateSurfaceComponents(components, { catalogue, data, deferBoundCards: true });\n const rejected = new Set(checked.issues.flatMap((i) => (i.componentId ? [i.componentId] : [])));\n const root = typeof spec.root === \"string\" ? spec.root : \"\";\n const graph = validateSurfaceGraph(root, checked.components, catalogue, rejected);\n const previous = (spec.issues ?? []).filter((i) => i?.componentId && !checked.components.some((c) => c.id === i.componentId));\n const issues = [...checked.issues, ...graph, ...previous];\n const { issues: _old, ...rest } = spec;\n return { ...rest, root, components: checked.components, data, ...(issues.length ? { issues } : {}) };\n}\n","// Where surfaces live between tool calls.\n//\n// A surface's state is DERIVED from the active branch: the newest snapshot of it\n// on the path from root to head. Nothing is stored beside the thread, so switching\n// branch, regenerating and reloading all give the right answer for free, and a\n// branch that never updated a surface shows it as that branch left it.\n\nimport type { Message } from \"../content/types.js\";\nimport { SURFACE_CARD_KIND, SURFACE_FORMAT_VERSION, type SurfaceSpec } from \"./types.js\";\n\nconst CARD_ID_PREFIX = \"surface:\";\nexport const SURFACE_ARTIFACT_KIND = `card:${SURFACE_CARD_KIND}`;\n\n/** One card id per surface, so a later snapshot replaces the earlier one in a run. */\nexport const surfaceCardId = (surfaceId: string): string => `${CARD_ID_PREFIX}${surfaceId}`;\n\nexport function isSurfaceSpec(value: unknown): value is SurfaceSpec {\n return typeof value === \"object\" && value !== null && (value as { kind?: unknown }).kind === SURFACE_CARD_KIND && typeof (value as { surfaceId?: unknown }).surfaceId === \"string\";\n}\n\nfunction expiredStub(surfaceId: string): SurfaceSpec {\n return { kind: SURFACE_CARD_KIND, version: SURFACE_FORMAT_VERSION, surfaceId, root: \"\", components: [], data: {}, revision: 0, expired: true };\n}\n\n/** The current state of every surface on a message path. Later snapshots win. */\nexport function foldSurfaces(messages: readonly Message[]): Record<string, SurfaceSpec> {\n const out: Record<string, SurfaceSpec> = {};\n for (const message of messages) {\n for (const part of message.parts) {\n if (part.type !== \"artifact\" || part.kind !== SURFACE_ARTIFACT_KIND) continue;\n const data = part.data as { expired?: boolean } | null;\n if (data?.expired === true && part.id.startsWith(CARD_ID_PREFIX)) {\n const surfaceId = part.id.slice(CARD_ID_PREFIX.length);\n out[surfaceId] = expiredStub(surfaceId);\n } else if (isSurfaceSpec(part.data)) {\n out[part.data.surfaceId] = part.data;\n }\n }\n }\n return out;\n}\n\n/** The working copy a run reads and writes, so two calls in one step see each other. */\nexport class SurfaceLedger {\n private readonly surfaces = new Map<string, SurfaceSpec>();\n\n constructor(initial: Record<string, SurfaceSpec> = {}) {\n for (const [id, spec] of Object.entries(initial)) this.surfaces.set(id, spec);\n }\n\n get(surfaceId: string): SurfaceSpec | undefined {\n return this.surfaces.get(surfaceId);\n }\n\n put(spec: SurfaceSpec): void {\n this.surfaces.set(spec.surfaceId, spec);\n }\n\n list(): SurfaceSpec[] {\n return [...this.surfaces.values()];\n }\n\n /** Surfaces still on screen. */\n live(): SurfaceSpec[] {\n return this.list().filter((s) => !s.deleted && !s.expired);\n }\n}\n","// The agent's handle on surfaces: create, patch, delete, read, and look up schemas.\n//\n// Descriptions stay short on purpose. These definitions ride in every request, so\n// they carry the shape of the format and point at `describeSurfaceComponents` for\n// the rest.\n\nimport { packByPriority } from \"../tokens/budget.js\";\nimport { estimateJsonTokens } from \"../tokens/estimate.js\";\nimport type { ToolDefinition, ToolExecutionContext } from \"../tools/types.js\";\nimport type { SurfaceCatalogue } from \"./catalogue.js\";\nimport { SurfaceLedger, surfaceCardId } from \"./ledger.js\";\nimport { applySurfaceOperations, buildSurface, previewSurface } from \"./operations.js\";\nimport { getAt } from \"./pointer.js\";\nimport { SURFACE_CARD_KIND, SURFACE_FORMAT_VERSION, SURFACE_LIMITS, type SurfaceIssue, type SurfaceSpec } from \"./types.js\";\n\nexport const SURFACE_TOOL_NAMES = [\"createSurface\", \"updateSurface\", \"deleteSurface\", \"readSurface\", \"describeSurfaceComponents\"] as const;\n\nexport const SURFACE_GUIDE = [\n \"A surface is an interface you assemble from a flat list of components that reference each other by id.\",\n \"\",\n 'Shape: { \"surfaceId\": \"overview\", \"title\": \"Overview\", \"data\": { \"region\": \"all\", \"rows\": [] }, \"root\": \"main\", \"components\": [',\n ' { \"id\": \"main\", \"component\": \"Stack\", \"children\": [\"region\", \"total\"] },',\n ' { \"id\": \"region\", \"component\": \"Select\", \"label\": \"Region\", \"value\": { \"$path\": \"/region\" }, \"options\": [{ \"value\": \"all\", \"label\": \"All\" }] },',\n ' { \"id\": \"total\", \"component\": \"Metric\", \"label\": \"Total\", \"format\": \"number\", \"value\": { \"$query\": { \"from\": \"/rows\", \"where\": [{ \"field\": \"region\", \"value\": { \"$path\": \"/region\" }, \"ignore\": \"all\" }], \"aggregate\": { \"op\": \"sum\", \"field\": \"amount\" } } } }',\n \"] }\",\n \"\",\n \"Send `data` first, then `root`, then components parents before children, so the interface can draw as it streams.\",\n \"\",\n \"Bindings work in any prop: $path reads the data model, $template interpolates ({/path}, {.rowField}), $query filters, groups and aggregates rows, and $item reads the current row inside a List.\",\n \"Controls write to their `value` $path, so neighbours update with no call to you. Use `visibleWhen` to show parts conditionally.\",\n 'Cards are blocks: { \"id\": \"trend\", \"component\": \"Card\", \"kind\": \"chart\", \"spec\": { ... } }. Interactive card kinds also need `bind`.',\n \"\",\n \"Button actions are exactly: set (local state), tool (a tool you may already call; it follows the same approval rules) and event (returns to you as a new message).\",\n \"Never send code, HTML, CSS or script URLs. Change an existing surface with updateSurface rather than creating another. Call readSurface before acting on what the person has chosen.\",\n].join(\"\\n\");\n\nconst toCorrections = (issues: readonly SurfaceIssue[]) => issues.slice(0, 12);\n\nfunction outcome(spec: SurfaceSpec, issues: readonly SurfaceIssue[]) {\n const card = { card: spec, cardId: surfaceCardId(spec.surfaceId) };\n const facts = { surfaceId: spec.surfaceId, revision: spec.revision, components: spec.components.length };\n if (!issues.length) return { output: { ok: true, ...facts }, ...card };\n return {\n output: { ok: false, partial: true, ...facts, corrections: toCorrections(issues), next: \"The valid parts are on screen. Send the corrected parts with updateSurface.\" },\n failure: \"invalid-input\" as const,\n ...card,\n };\n}\n\nconst refused = (issues: readonly SurfaceIssue[]) => ({\n output: { ok: false, rendered: false, corrections: toCorrections(issues) },\n failure: \"invalid-input\" as const,\n});\n\nconst unavailable = (surfaceId: unknown, ledger: SurfaceLedger) => {\n const spec = typeof surfaceId === \"string\" ? ledger.get(surfaceId) : undefined;\n return {\n output: {\n ok: false,\n error: spec?.expired\n ? `Surface \"${String(surfaceId)}\" expired from saved history. Call createSurface to rebuild it.`\n : `No surface \"${String(surfaceId)}\".`,\n available: ledger.live().map((s) => s.surfaceId),\n },\n failure: \"not-found\" as const,\n };\n};\n\nexport type SurfaceToolsOptions = { catalogue: SurfaceCatalogue };\n\nexport function createSurfaceTools(options: SurfaceToolsOptions): ToolDefinition[] {\n const { catalogue } = options;\n // Used only when a tool runs outside runAgent, which supplies the real ledger.\n const standalone = new SurfaceLedger();\n const ledgerOf = (ctx: ToolExecutionContext) => ctx.surfaces ?? standalone;\n\n const createSurface: ToolDefinition = {\n name: \"createSurface\",\n side: \"read\",\n description:\n \"Assemble an interactive interface from a flat component list: layout, text, metrics, inputs, buttons and any card. \" +\n \"Use it when the person will explore, filter, compare or act, rather than just read. \" +\n \"Call describeSurfaceComponents first for the format and each component's props.\",\n inputSchema: {\n type: \"object\",\n required: [\"surfaceId\", \"root\", \"components\"],\n properties: {\n surfaceId: { type: \"string\", description: \"Stable id for later updates.\" },\n title: { type: \"string\" },\n data: { type: \"object\", description: \"Initial state that components bind to.\", additionalProperties: true },\n root: { type: \"string\", description: \"Id of the top component.\" },\n components: {\n type: \"array\",\n items: { type: \"object\", required: [\"id\", \"component\"], additionalProperties: true },\n },\n },\n additionalProperties: false,\n },\n loading: { kind: \"generic\", label: \"Building the interface\" },\n partialCard: (input) => previewSurface(input, catalogue),\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const surfaceId = (input as { surfaceId?: unknown } | null)?.surfaceId;\n const prior = typeof surfaceId === \"string\" ? ledger.get(surfaceId) : undefined;\n const replacing = prior && !prior.deleted && !prior.expired ? prior : undefined;\n if (!replacing && ledger.live().length >= SURFACE_LIMITS.surfaces) {\n return refused([{ code: \"limit-exceeded\", message: `A thread may hold ${SURFACE_LIMITS.surfaces} surfaces.`, fix: \"Update or delete an existing surface.\" }]);\n }\n const built = buildSurface(input, { catalogue, actionTools: ctx.surfaceActionTools }, {\n revision: (prior?.revision ?? 0) + 1,\n originCallId: replacing?.originCallId ?? ctx.callId,\n });\n if (!built.spec) return refused(built.issues);\n ledger.put(built.spec);\n return outcome(built.spec, built.issues);\n },\n };\n\n const updateSurface: ToolDefinition = {\n name: \"updateSurface\",\n side: \"read\",\n description:\n \"Patch a surface in place. Operations: upsertComponents { components }, removeComponents { ids }, setRoot { root }, setTitle { title }, setData { path, value }, removeData { path }.\",\n inputSchema: {\n type: \"object\",\n required: [\"surfaceId\", \"operations\"],\n properties: {\n surfaceId: { type: \"string\" },\n operations: { type: \"array\", items: { type: \"object\", required: [\"op\"], additionalProperties: true } },\n expectedRevision: { type: \"number\", description: \"Refuse the patch if the surface has changed since this revision.\" },\n },\n additionalProperties: false,\n },\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const { surfaceId, operations, expectedRevision } = (input ?? {}) as { surfaceId?: string; operations?: unknown; expectedRevision?: number };\n const current = surfaceId ? ledger.get(surfaceId) : undefined;\n if (!current || current.deleted || current.expired) return unavailable(surfaceId, ledger);\n if (expectedRevision != null && expectedRevision !== current.revision) {\n return refused([{\n code: \"stale-revision\",\n message: `The surface is at revision ${current.revision}, not ${expectedRevision}. The person may have changed it.`,\n fix: \"Call readSurface, then patch against the current revision.\",\n }]);\n }\n const built = applySurfaceOperations(current, operations, { catalogue, actionTools: ctx.surfaceActionTools });\n if (!built.spec) return refused(built.issues);\n ledger.put(built.spec);\n return outcome(built.spec, built.issues);\n },\n };\n\n const deleteSurface: ToolDefinition = {\n name: \"deleteSurface\",\n side: \"read\",\n description: \"Remove a surface from the conversation.\",\n inputSchema: {\n type: \"object\",\n required: [\"surfaceId\"],\n properties: { surfaceId: { type: \"string\" } },\n additionalProperties: false,\n },\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const { surfaceId } = (input ?? {}) as { surfaceId?: string };\n const current = surfaceId ? ledger.get(surfaceId) : undefined;\n if (!current || current.deleted) return unavailable(surfaceId, ledger);\n const tombstone: SurfaceSpec = {\n kind: SURFACE_CARD_KIND,\n version: SURFACE_FORMAT_VERSION,\n surfaceId: current.surfaceId,\n ...(current.title ? { title: current.title } : {}),\n root: \"\",\n components: [],\n data: {},\n revision: current.revision + 1,\n ...(current.originCallId ? { originCallId: current.originCallId } : {}),\n deleted: true,\n };\n ledger.put(tombstone);\n return { output: { ok: true, surfaceId: current.surfaceId, deleted: true }, card: tombstone, cardId: surfaceCardId(current.surfaceId) };\n },\n };\n\n const readSurface: ToolDefinition = {\n name: \"readSurface\",\n side: \"read\",\n description: \"Read a surface's current state, including what the person has changed. Omit surfaceId to list surfaces.\",\n inputSchema: {\n type: \"object\",\n properties: {\n surfaceId: { type: \"string\" },\n paths: { type: \"array\", items: { type: \"string\" }, description: \"JSON Pointers to read instead of the whole data model.\" },\n },\n additionalProperties: false,\n },\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const { surfaceId, paths } = (input ?? {}) as { surfaceId?: string; paths?: string[] };\n if (!surfaceId) {\n return { output: { ok: true, surfaces: ledger.live().map((s) => ({ surfaceId: s.surfaceId, title: s.title, revision: s.revision })) } };\n }\n const spec = ledger.get(surfaceId);\n if (!spec || spec.deleted || spec.expired) return unavailable(surfaceId, ledger);\n return {\n output: {\n ok: true,\n surfaceId,\n ...(spec.title ? { title: spec.title } : {}),\n revision: spec.revision,\n root: spec.root,\n components: spec.components.map((c) => ({ id: c.id, component: c.component })),\n ...(Array.isArray(paths) ? { values: Object.fromEntries(paths.map((p) => [p, getAt(spec.data, p)])) } : { data: spec.data }),\n ...(spec.issues?.length ? { issues: toCorrections(spec.issues) } : {}),\n },\n };\n },\n };\n\n const describeSurfaceComponents: ToolDefinition = {\n name: \"describeSurfaceComponents\",\n side: \"read\",\n description: \"Look up the surface format. No arguments returns the guide and component index; `components` returns those schemas, such as [\\\"Select\\\", \\\"Card:chart\\\"].\",\n inputSchema: {\n type: \"object\",\n properties: {\n components: { type: \"array\", items: { type: \"string\" } },\n maxTokens: { type: \"number\", description: \"Budget for the returned schemas. Default 1500.\" },\n },\n additionalProperties: false,\n },\n execute(input) {\n const { components, maxTokens } = (input ?? {}) as { components?: string[]; maxTokens?: number };\n if (!Array.isArray(components) || !components.length) {\n return { output: { ok: true, guide: SURFACE_GUIDE, index: catalogue.index() } };\n }\n const known = components.flatMap((name) => {\n const schema = catalogue.schemaOf(name);\n return schema ? [schema] : [];\n });\n const unknown = components.filter((name) => !catalogue.schemaOf(name));\n const budget = Math.max(200, Math.min(maxTokens ?? 1_500, 6_000));\n const packed = packByPriority(known, budget, estimateJsonTokens);\n return {\n output: {\n ok: true,\n schemas: packed.included,\n ...(packed.dropped.length ? { omitted: packed.dropped.map((d) => d.item.name), next: \"Request the omitted components in another call.\" } : {}),\n ...(unknown.length ? { unknown, available: catalogue.names() } : {}),\n },\n };\n },\n };\n\n return [createSurface, updateSurface, deleteSurface, readSurface, describeSurfaceComponents];\n}\n","// Progressive disclosure, through the seams the framework already has.\n//\n// The skill index carries one line. `loadSkill` pays for the guide when the model\n// decides to build something. The context source keeps surfaces discoverable after\n// compaction has trimmed the calls that created them.\n\nimport type { ContextSource } from \"../context/types.js\";\nimport type { Skill } from \"../skills/types.js\";\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { SurfaceCatalogue } from \"./catalogue.js\";\nimport { foldSurfaces } from \"./ledger.js\";\nimport { SURFACE_GUIDE } from \"./tools.js\";\n\nexport const SURFACE_SKILL_ID = \"surface-authoring\";\n\n/** A `manual` skill: one line in the index until the model loads it. */\nexport function createSurfaceSkill(catalogue: SurfaceCatalogue): Skill {\n return {\n id: SURFACE_SKILL_ID,\n name: \"Building interfaces\",\n description: \"How to assemble an interactive surface from components, bindings and actions.\",\n mode: \"manual\",\n aliases: [\"surface\", \"interface\", \"dashboard\", \"filter\", \"form\"],\n tools: [\"createSurface\", \"updateSurface\", \"deleteSurface\", \"readSurface\", \"describeSurfaceComponents\"],\n body: () => [SURFACE_GUIDE, \"\", \"Components:\", catalogue.index()].join(\"\\n\"),\n };\n}\n\n/**\n * One line per surface on the active path. Data stays out: the model asks for it\n * with `readSurface` when it needs it, so an idle dashboard costs a line a turn.\n */\nexport function createSurfaceContextSource(): ContextSource {\n return {\n id: \"surfaces\",\n run({ messages }) {\n const live = Object.values(foldSurfaces(messages)).filter((s) => !s.deleted && !s.expired);\n if (!live.length) return {};\n const text = [\n \"Surfaces on screen. Call readSurface for their current state before relying on it:\",\n ...live.map((s) => `- ${s.surfaceId}${s.title ? ` (${s.title})` : \"\"}, revision ${s.revision}`),\n ].join(\"\\n\");\n return { layers: [{ id: \"surfaces\", kind: \"custom\", text, tokens: estimateTokens(text), priority: 400 }] };\n },\n };\n}\n","// An async event channel: push from a callback, consume as an async iterable.\n//\n// Needed because tool execution is a plain `await`, not a generator, yet some\n// events MUST reach the UI while a tool is still running:\n//\n// • `awaiting-user` — a card asking for a decision. Buffering this until the\n// tool resolves deadlocks: the tool waits for the user, the user waits for\n// the card, and the card waits for the tool.\n// • `card` — progress updates from a long-running tool.\n// • `tool-result` — each call as it finishes, so a fast lookup is not held\n// back until the slowest call in the same step is done.\n//\n// Collecting events into an array and yielding them afterwards looks equivalent\n// and is not. This is the fix.\n\nexport class EventChannel<T> {\n private queue: T[] = [];\n private waiting: ((result: IteratorResult<T>) => void)[] = [];\n private closed = false;\n\n /** Enqueue an event, handing it straight to a waiting consumer if there is one. */\n push(value: T): void {\n if (this.closed) return;\n const resolve = this.waiting.shift();\n if (resolve) resolve({ value, done: false });\n else this.queue.push(value);\n }\n\n /** No more events. Consumers drain what is buffered, then finish. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n for (const resolve of this.waiting) resolve({ value: undefined as never, done: true });\n this.waiting = [];\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: (): Promise<IteratorResult<T>> => {\n // Buffered events drain first, even after close, so nothing pushed\n // immediately before close() is lost.\n if (this.queue.length) return Promise.resolve({ value: this.queue.shift()!, done: false });\n if (this.closed) return Promise.resolve({ value: undefined as never, done: true });\n return new Promise((resolve) => this.waiting.push(resolve));\n },\n };\n }\n}\n","// The card a person sees before a `side: \"confirm\"` tool runs.\n//\n// It is written for the person approving the action, not for the model or a\n// developer: no tool names, package names or raw JSON. Those stay in the run\n// trace, where a developer can still find them.\n\nimport type { CardSpec } from \"../cards/types.js\";\nimport type { ToolApproval, ToolDefinition } from \"./types.js\";\n\nconst MAX_FIELDS = 6;\nconst MAX_VALUE_CHARS = 160;\nconst MAX_DESCRIPTION_CHARS = 240;\n\nconst clip = (text: string, max: number): string => (text.length > max ? `${text.slice(0, max - 1)}…` : text);\n\n/** \"documentId\" → \"Document\", \"max_retry_count\" → \"Max retry count\". */\nexport function humanizeFieldName(key: string): string {\n const words = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/[\\s_\\-.]+/)\n .filter(Boolean)\n .map((word) => word.toLowerCase());\n if (words.length > 1 && (words[words.length - 1] === \"id\" || words[words.length - 1] === \"ids\")) words.pop();\n const text = words.join(\" \");\n return text ? text.charAt(0).toUpperCase() + text.slice(1) : key;\n}\n\n/** A value as plain text, or `undefined` when it has no short plain form. */\nfunction plainValue(value: unknown): string | undefined {\n if (typeof value === \"string\") return value.trim() ? clip(value.trim(), MAX_VALUE_CHARS) : undefined;\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") return value ? \"Yes\" : \"No\";\n if (Array.isArray(value)) {\n const items = value.map(plainValue);\n if (value.length && items.every((item) => item !== undefined)) return clip(items.join(\", \"), MAX_VALUE_CHARS);\n return value.length === 1 ? \"1 item\" : `${value.length} items`;\n }\n return undefined;\n}\n\n/** The first sentence of a tool description: the part that says what it does. */\nfunction firstSentence(description: string): string {\n const text = description.trim().replace(/\\s+/g, \" \");\n const end = text.search(/[.!?](\\s|$)/);\n return clip(end === -1 ? text : text.slice(0, end + 1), MAX_DESCRIPTION_CHARS);\n}\n\nfunction fieldsOf(input: unknown): { label: string; value: string }[] {\n if (input === undefined || input === null) return [];\n if (typeof input !== \"object\" || Array.isArray(input)) {\n const value = plainValue(input);\n return value === undefined ? [] : [{ label: \"Details\", value }];\n }\n const fields: { label: string; value: string }[] = [];\n for (const [key, raw] of Object.entries(input)) {\n const value = plainValue(raw);\n if (value !== undefined) fields.push({ label: humanizeFieldName(key), value });\n if (fields.length === MAX_FIELDS) break;\n }\n return fields;\n}\n\nconst MAX_TITLE_CHARS = 120;\nconst MAX_LABEL_CHARS = 40;\n\nconst textOr = (value: unknown, max: number): string | undefined =>\n typeof value === \"string\" && value.trim() ? clip(value.trim().replace(/\\s+/g, \" \"), max) : undefined;\n\n/**\n * The tool's own wording, kept to plain text of sane length. A plugin's hook is code\n * the host does not control, so anything that is not a string is dropped.\n */\nfunction customApproval(tool: Pick<ToolDefinition, \"approval\">, input: unknown): ToolApproval | undefined {\n if (typeof tool.approval !== \"function\") return undefined;\n let raw: unknown;\n try {\n raw = tool.approval(input);\n } catch {\n // A broken copy hook must not block the approval itself.\n return undefined;\n }\n if (typeof raw !== \"object\" || raw === null) return undefined;\n const r = raw as Record<string, unknown>;\n const title = textOr(r[\"title\"], MAX_TITLE_CHARS);\n const description = textOr(r[\"description\"], MAX_DESCRIPTION_CHARS);\n const confirmLabel = textOr(r[\"confirmLabel\"], MAX_LABEL_CHARS);\n const cancelLabel = textOr(r[\"cancelLabel\"], MAX_LABEL_CHARS);\n const summary = Array.isArray(r[\"summary\"])\n ? r[\"summary\"].flatMap((row: unknown) => {\n const label = textOr((row as { label?: unknown } | null)?.label, MAX_LABEL_CHARS);\n const value = textOr((row as { value?: unknown } | null)?.value, MAX_VALUE_CHARS);\n return label && value ? [{ label, value }] : [];\n }).slice(0, MAX_FIELDS)\n : undefined;\n // Wording with neither a question nor a sentence says nothing; use the generic card.\n if (!title && !description) return undefined;\n return {\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n ...(summary ? { summary } : {}),\n ...(confirmLabel ? { confirmLabel } : {}),\n ...(cancelLabel ? { cancelLabel } : {}),\n ...(typeof r[\"danger\"] === \"boolean\" ? { danger: r[\"danger\"] } : {}),\n };\n}\n\n/**\n * The approval card for a tool call. A tool's own `approval` wording wins; without it\n * the card uses the first sentence of the description and the input's plain fields.\n */\nexport function approvalCard(\n tool: Pick<ToolDefinition, \"description\" | \"approval\">,\n input: unknown,\n options: { danger?: boolean } = {},\n): CardSpec {\n const custom = customApproval(tool, input);\n let description: string | undefined = custom?.description ?? firstSentence(tool.description);\n // A tool that words its own approval decides which details to list; without wording, the input's plain fields.\n let summary = custom ? (custom.summary ?? []) : fieldsOf(input);\n // With neither a sentence nor details there is nothing to approve but the bare act, so name it.\n if (!summary.length && !description) summary = [{ label: \"Action\", value: \"Run a tool\" }];\n description ||= undefined;\n const danger = custom?.danger ?? options.danger;\n return {\n kind: \"confirm\",\n title: custom?.title ?? \"Allow this?\",\n ...(description ? { description } : {}),\n summary,\n confirmLabel: custom?.confirmLabel ?? \"Allow\",\n cancelLabel: custom?.cancelLabel ?? \"Not now\",\n ...(danger ? { danger: true } : {}),\n };\n}\n","// Tool execution.\n//\n// Two rules that matter more than they look:\n//\n// 1. A tool that throws returns `{ error }` to the model, not an exception to\n// the caller. A model that reads \"no pool found for SUI/FOO\" picks a\n// different pool; a stack trace that kills the run teaches it nothing and\n// costs the user their turn.\n//\n// 2. Errors are COMPACTED. A raw error can be a 40KB stack that then rides in\n// history for the rest of the conversation, crowding out the actual work.\n//\n// 3. `side: \"confirm\"` is enforced HERE, on the one path every tool call takes,\n// whether a model or a button started it. No approval means no execution.\n\nimport { AgentError, toAgentError } from \"../errors.js\";\nimport { makeCard } from \"../cards/registry.js\";\nimport { CARD_KEY, isCardCarrier, withCard, type Card, type CardSpec } from \"../cards/types.js\";\nimport type { SurfaceLedger } from \"../surfaces/ledger.js\";\nimport { approvalCard } from \"../tools/approval.js\";\nimport type { ToolDefinition, ToolExecutionContext, ToolResult } from \"../tools/types.js\";\n\nexport type ToolCallRequest = { callId: string; name: string; input: unknown };\n\nexport type ToolCallOutcome = {\n callId: string;\n name: string;\n output: unknown;\n card?: Card;\n failure?: string;\n /** Tool names this outcome unlocked for the rest of the run (loadSkill). */\n unlockTools?: string[];\n ms: number;\n};\n\nconst MAX_ERROR_CHARS = 400;\n\n/** Shrink an error to something worth carrying in history. */\nexport function compactError(e: unknown): { error: string; kind?: string } {\n if (e instanceof AgentError) {\n return { error: e.message.slice(0, MAX_ERROR_CHARS), kind: e.kind };\n }\n const message = e instanceof Error ? e.message : String(e);\n return { error: message.slice(0, MAX_ERROR_CHARS) || \"Tool failed with no message.\" };\n}\n\n\n/**\n * Why a `side: \"confirm\"` tool may not start, or `undefined` when it may. Anything\n * short of an explicit yes is a no: a host that cannot ask, a dismissed card, a\n * stopped run, an answer this code does not recognise.\n */\nasync function confirmationRefusal(tool: ToolDefinition, call: ToolCallRequest, opts: ExecuteToolOptions): Promise<string | undefined> {\n if (!opts.requestCard) return `\"${tool.name}\" needs the user's approval and this host cannot ask for it.`;\n if (tool.confirmation === \"tool\") return undefined;\n const answer = await opts.requestCard(call.callId, approvalCard(tool, call.input));\n if (opts.signal?.aborted) return \"The run was stopped before this was approved.\";\n return (answer as { confirmed?: unknown } | null | undefined)?.confirmed === true ? undefined : \"The user declined.\";\n}\n\nconst isToolResult = (v: unknown): v is ToolResult =>\n typeof v === \"object\" &&\n v !== null &&\n \"output\" in v &&\n Object.keys(v).every((k) => [\"output\", \"card\", \"failure\", \"cardId\", \"unlockTools\", \"placement\"].includes(k));\n\nexport type ExecuteToolOptions = {\n tools: readonly ToolDefinition[];\n vars: Record<string, unknown>;\n signal?: AbortSignal;\n timeoutMs?: number;\n onCard?: (card: Card) => void;\n /** Suspend and ask the user. Supplied by the runtime; resolves on a CardAction. */\n requestCard?: (callId: string, spec: CardSpec) => Promise<unknown>;\n /** Host-executed tools (no `execute`) are delegated here. */\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /**\n * `executeToolCalls` only: fires as each call settles, in COMPLETION order,\n * exactly once per call — failures and timeouts included. This is how a\n * fast result reaches the UI without waiting on the slowest call in the step.\n */\n onOutcome?: (outcome: ToolCallOutcome) => void;\n /**\n * Precomputed name→tool index. `executeToolCalls` builds this once per\n * batch and reuses it here instead of a linear `tools.find` per call; a\n * standalone `executeToolCall` caller can leave it unset and pay the scan.\n */\n toolIndex?: ReadonlyMap<string, ToolDefinition>;\n surfaces?: SurfaceLedger;\n surfaceActionTools?: readonly string[];\n};\n\nexport async function executeToolCall(call: ToolCallRequest, opts: ExecuteToolOptions): Promise<ToolCallOutcome> {\n const started = Date.now();\n const tool = opts.toolIndex ? opts.toolIndex.get(call.name) : opts.tools.find((t) => t.name === call.name);\n\n if (!tool) {\n // Name the tools that DO exist — a model that hallucinated a name recovers\n // from a list, and loops forever without one.\n return {\n callId: call.callId,\n name: call.name,\n output: {\n error: `Unknown tool \"${call.name}\".`,\n availableTools: opts.tools.map((t) => t.name),\n },\n failure: \"not-found\",\n ms: Date.now() - started,\n };\n }\n\n let emittedCard: Card | undefined;\n // A timed-out tool keeps running in the background. Once its outcome is\n // decided, anything it surfaces would land AFTER its own tool-result — a\n // progress card for a finished call, or a dialog nobody is waiting on.\n let settled = false;\n const ctx: ToolExecutionContext = {\n vars: opts.vars,\n signal: opts.signal,\n callId: call.callId,\n ...(opts.surfaces ? { surfaces: opts.surfaces } : {}),\n ...(opts.surfaceActionTools ? { surfaceActionTools: opts.surfaceActionTools } : {}),\n emitCard: (spec) => {\n if (settled) return;\n const card = makeCard(spec, call.callId);\n emittedCard = card;\n opts.onCard?.(card);\n },\n ...(opts.requestCard\n ? {\n requestCard: (spec: CardSpec) =>\n settled\n ? Promise.reject(new AgentError(\"cancelled\", `Tool \"${call.name}\" already finished.`))\n : opts.requestCard!(call.callId, spec),\n }\n : {}),\n };\n\n try {\n // Before the timeout starts: a person deciding is not a tool running slowly.\n if (tool.side === \"confirm\") {\n const refusal = await confirmationRefusal(tool, call, opts);\n if (refusal) return { callId: call.callId, name: call.name, output: { error: refusal }, failure: \"denied\", ms: Date.now() - started };\n }\n\n const raw = tool.execute\n ? await withTimeout(Promise.resolve(tool.execute(call.input, ctx)), opts.timeoutMs, call.name)\n : opts.onHostTool\n ? await withTimeout(opts.onHostTool(call), opts.timeoutMs, call.name)\n : (() => {\n throw new AgentError(\"not-supported\", `Tool \"${call.name}\" has no executor and no host handler.`);\n })();\n\n const result: ToolResult = isToolResult(raw) ? raw : { output: raw };\n\n // A tool may attach a card three ways, and all three must work — a tool\n // author should not have to know which one the runtime happens to check:\n // 1. `ctx.emitCard(spec)` mid-execution (progress on a long tool)\n // 2. `{ output, card: spec }` the explicit result field\n // 3. `withCard(output, spec)` embedded in the output under $card\n // Whichever is used, the card ends up BOTH surfaced to the UI and carried\n // inside the output — the latter so it survives persistence, since the\n // ContextBuilder strips it again before the next provider call.\n let card = emittedCard;\n let output = result.output;\n\n if (result.card) {\n card = makeCard(result.card, call.callId, result.cardId, result.placement === \"panel\" ? \"panel\" : undefined);\n output = withCard(asRecord(result.output), card.spec, card.id, card.placement);\n opts.onCard?.(card);\n } else if (isCardCarrier(result.output)) {\n const embedded = result.output[CARD_KEY];\n card = { ...embedded, callId: call.callId };\n opts.onCard?.(card);\n }\n\n return {\n callId: call.callId,\n name: call.name,\n output: explainMissingInput(tool, call.input, output, result.failure),\n ...(card ? { card } : {}),\n ...(result.failure ? { failure: result.failure } : {}),\n ...(result.unlockTools?.length ? { unlockTools: result.unlockTools } : {}),\n ms: Date.now() - started,\n };\n } catch (e) {\n const err = toAgentError(e);\n return {\n callId: call.callId,\n name: call.name,\n output: explainMissingInput(tool, call.input, compactError(err), err.kind === \"cancelled\" ? \"denied\" : err.kind === \"timeout\" ? \"timeout\" : \"execution-error\"),\n failure: err.kind === \"cancelled\" ? \"denied\" : \"execution-error\",\n ms: Date.now() - started,\n };\n } finally {\n settled = true;\n }\n}\n\nconst NOT_ABOUT_INPUT = new Set([\"denied\", \"timeout\", \"not-found\"]);\nconst MAX_DESCRIBED = 200;\n\n/**\n * A failed call that never named what the tool requires gets told exactly that.\n *\n * Models sometimes send a call with no arguments (`{}`) for a tool whose schema\n * lists required ones. The tool's own error then says something short and\n * tool-specific (\"No symbol given.\"), and a model that does not see why often\n * sends the identical call again. When the call failed AND a top-level\n * `required` key is absent from its input, this adds `missing` (the names) and\n * `expected` (each one's type, enum and description from the tool's own\n * schema) next to whatever the tool said, so the retry has something to fill.\n *\n * Additive on purpose: only failed outputs, never a rewrite of the tool's own\n * error, and nothing is checked on a call that succeeded — a tool may fall\n * back to a default for a required key (the chart in view) and that stays its\n * decision.\n */\nexport function explainMissingInput(tool: ToolDefinition, input: unknown, output: unknown, failure?: string): unknown {\n if (failure && NOT_ABOUT_INPUT.has(failure)) return output;\n if (typeof output !== \"object\" || output === null || Array.isArray(output)) return output;\n const out = output as Record<string, unknown>;\n const failed = failure !== undefined || (typeof out.error === \"string\" && out.ok !== true);\n if (!failed || \"missing\" in out || \"expected\" in out) return output;\n\n const schema = tool.inputSchema as { required?: unknown; properties?: unknown } | undefined;\n const required = Array.isArray(schema?.required) ? schema.required.filter((k): k is string => typeof k === \"string\") : [];\n if (!required.length) return output;\n const given = typeof input === \"object\" && input !== null && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n const missing = required.filter((k) => given[k] === undefined || given[k] === null);\n if (!missing.length) return output;\n\n const props = (typeof schema?.properties === \"object\" && schema.properties !== null ? schema.properties : {}) as Record<string, unknown>;\n const expected: Record<string, unknown> = {};\n for (const key of missing) expected[key] = describeProperty(props[key]);\n return { ...out, missing, expected };\n}\n\nfunction describeProperty(raw: unknown): Record<string, unknown> {\n if (typeof raw !== \"object\" || raw === null) return {};\n const p = raw as Record<string, unknown>;\n const d: Record<string, unknown> = {};\n for (const k of [\"type\", \"enum\", \"minimum\", \"maximum\"] as const) if (p[k] !== undefined) d[k] = p[k];\n if (typeof p.description === \"string\") {\n d.description = p.description.length > MAX_DESCRIBED ? `${p.description.slice(0, MAX_DESCRIBED)}…` : p.description;\n }\n return d;\n}\n\n/**\n * Execute a step's calls concurrently.\n *\n * Parallel because models emit independent calls in one step and running them\n * serially triples the latency of a three-lookup turn. Two orders, on purpose:\n * `onOutcome` reports each call as it FINISHES, so a 50ms lookup is not held\n * hostage by a 900ms one; the returned array is in CALL order, since that is\n * what gets written back to history and humans read the transcript top to\n * bottom.\n */\nexport async function executeToolCalls(\n calls: readonly ToolCallRequest[],\n opts: ExecuteToolOptions,\n): Promise<ToolCallOutcome[]> {\n // Built once for the whole batch and reused for both the interactive filter\n // below and every executeToolCall — a linear tools.find() per call, twice\n // over, is wasted work once the tool list is more than a handful long.\n const toolIndex = opts.toolIndex ?? new Map(opts.tools.map((t) => [t.name, t] as const));\n const callOpts: ExecuteToolOptions = opts.toolIndex ? opts : { ...opts, toolIndex };\n\n // Interactive tools must NOT run in parallel — two confirm dialogs racing for\n // the same user is not a thing a user can answer.\n const interactive = calls.filter((c) => toolIndex.get(c.name)?.side === \"confirm\");\n const concurrent = calls.filter((c) => !interactive.includes(c));\n\n // executeToolCall never rejects — every failure is already an outcome — so\n // this reports each call exactly once.\n const settle = async (c: ToolCallRequest) => {\n const outcome = await executeToolCall(c, callOpts);\n opts.onOutcome?.(outcome);\n return outcome;\n };\n\n const concurrentResults = await Promise.all(concurrent.map(settle));\n const serialResults: ToolCallOutcome[] = [];\n for (const c of interactive) serialResults.push(await settle(c));\n\n const byId = new Map([...concurrentResults, ...serialResults].map((r) => [r.callId, r]));\n return calls.map((c) => byId.get(c.callId)!).filter(Boolean);\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) return value as Record<string, unknown>;\n return { result: value };\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number | undefined, name: string): Promise<T> {\n if (!ms) return promise;\n return Promise.race([\n promise,\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new AgentError(\"timeout\", `Tool \"${name}\" timed out after ${ms}ms.`)), ms),\n ),\n ]);\n}\n","import type { FinishReason, Usage } from \"../content/types.js\";\nimport type { AgentErrorKind } from \"../errors.js\";\nimport type { RunMode } from \"./events.js\";\n\n/**\n * Where the numbers in a metering record came from.\n *\n * Core currently only emits `provider` or `unavailable`. `estimated` and\n * `mixed` are reserved so hosts can enrich records without replacing this\n * contract when a provider omits usage.\n */\nexport type MeteringSource = \"provider\" | \"estimated\" | \"mixed\" | \"unavailable\";\n\n/** Terminal outcome of a provider step or the containing run. */\nexport type MeteringStatus = \"completed\" | \"failed\" | \"cancelled\";\n\nexport type MeteringError = {\n kind: AgentErrorKind;\n message: string;\n};\n\ntype MeteringBase = {\n /** Stable within a run; suitable as an idempotency key in a host ledger. */\n id: string;\n runId: string;\n provider: string;\n requestedModel: string;\n mode: RunMode;\n status: MeteringStatus;\n usage: Usage;\n source: MeteringSource;\n startedAt: number;\n finishedAt: number;\n durationMs: number;\n /** Host-owned dimensions. Core never interprets or sends these upstream. */\n metadata?: Readonly<Record<string, string>>;\n error?: MeteringError;\n};\n\n/** Exactly one terminal record is emitted for every attempted provider call. */\nexport type StepMeteringRecord = MeteringBase & {\n scope: \"step\";\n step: number;\n /** The provider's actual model, when it reports one. */\n reportedModel?: string;\n responseId?: string;\n finishReason?: FinishReason;\n};\n\n/** Exactly one summary record is emitted when a run terminates. */\nexport type RunMeteringRecord = MeteringBase & {\n scope: \"run\";\n steps: number;\n finishReason: FinishReason;\n /** Unique actual model ids observed across completed steps. */\n reportedModels?: string[];\n};\n\nexport type MeteringRecord = StepMeteringRecord | RunMeteringRecord;\n\n/**\n * Optional delivery target in addition to the public `metering` RunEvent.\n *\n * Delivery is awaited to preserve ordering. A sink failure is fail-open: it\n * is reported to `onError`, when supplied, but never changes the agent run.\n * Durable storage, retries and pricing remain host responsibilities.\n */\nexport type MeterSink = {\n record(record: MeteringRecord): void | Promise<void>;\n onError?(error: unknown, record: MeteringRecord): void | Promise<void>;\n};\n\nexport function usageSource(usage: Usage): MeteringSource {\n return Object.values(usage).some((value) => typeof value === \"number\") ? \"provider\" : \"unavailable\";\n}\n\nexport function combineMeteringSources(sources: readonly MeteringSource[]): MeteringSource {\n if (!sources.length) return \"unavailable\";\n const unique = new Set(sources);\n return unique.size === 1 ? sources[0]! : \"mixed\";\n}\n\nexport async function deliverMetering(sink: MeterSink | undefined, record: MeteringRecord): Promise<void> {\n if (!sink) return;\n try {\n await sink.record(record);\n } catch (error) {\n try {\n await sink.onError?.(error, record);\n } catch {\n // Observability must not change the run it observes.\n }\n }\n}\n","// A tool call that a person started by pressing a button.\n//\n// It goes through `executeToolCall`, the function a model's call goes through, and\n// emits the same run events. So a `confirm` tool asks with the same card, a card it\n// returns lands in the transcript, and the next model turn can read what happened.\n// There is deliberately no second, lighter path for \"the user clicked it\": the spec\n// that put the button there was written by a model.\n\nimport { nextId } from \"../content/parts.js\";\nimport type { FinishReason } from \"../content/types.js\";\nimport { makeCard } from \"../cards/registry.js\";\nimport type { Card, CardAction, CardSpec } from \"../cards/types.js\";\nimport { EventChannel } from \"../runtime/channel.js\";\nimport type { RunEvent } from \"../runtime/events.js\";\nimport { executeToolCall, type ToolCallRequest } from \"../runtime/execute-tools.js\";\nimport { deliverMetering, type MeterSink, type MeteringRecord } from \"../runtime/metering.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\nimport type { ToolDefinition, ToolResolution } from \"../tools/types.js\";\nimport { checkSchema } from \"./schema-check.js\";\nimport { SURFACE_TOOL_NAMES } from \"./tools.js\";\n\n/** Tools about the conversation itself. A button has no business calling these. */\nconst NOT_ACTIONABLE = new Set<string>([...SURFACE_TOOL_NAMES, \"visualize\", \"updateCard\", \"loadSkill\"]);\n\n/**\n * What a surface action may call right now: the presets' grant, with deny applied.\n * `allow` is left out on purpose. A skill grants relevance for a turn, not authority\n * that outlives it on a button.\n */\nexport function surfaceActionTools(tools: ToolRegistry, resolution: ToolResolution): ToolDefinition[] {\n return tools\n .resolve({ presets: resolution.presets, ...(resolution.deny ? { deny: resolution.deny } : {}) })\n .filter((t) => !NOT_ACTIONABLE.has(t.name));\n}\n\nexport type SurfaceToolAuthorization = { ok: true; tool: ToolDefinition } | { ok: false; reason: string };\n\n/** Decided at the moment of the press. What was allowed when the surface was drawn may not be now. */\nexport function authorizeSurfaceTool(name: string, args: unknown, tools: ToolRegistry, resolution: ToolResolution): SurfaceToolAuthorization {\n const tool = surfaceActionTools(tools, resolution).find((t) => t.name === name);\n if (!tool) return { ok: false, reason: `\"${name}\" is not permitted here.` };\n const problems = checkSchema(tool.inputSchema, args ?? {});\n if (problems.length) return { ok: false, reason: `\"${name}\" received invalid input: ${problems[0]!.message}` };\n return { ok: true, tool };\n}\n\nexport type SurfaceToolRunConfig = {\n tool: ToolDefinition;\n args: Record<string, unknown>;\n surfaceId: string;\n componentId: string;\n provider: string;\n model: string;\n vars?: Record<string, unknown>;\n signal?: AbortSignal;\n toolTimeoutMs?: number;\n meter?: MeterSink;\n meteringMetadata?: Readonly<Record<string, string>>;\n onUserDecision?: (callId: string, card: Card) => Promise<CardAction>;\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n};\n\nexport async function* runSurfaceToolAction(config: SurfaceToolRunConfig): AsyncGenerator<RunEvent, void, unknown> {\n const runId = nextId(\"run\");\n const callId = nextId(\"call_surface\");\n const startedAt = Date.now();\n yield { type: \"run-start\", runId, mode: \"sync\" };\n yield { type: \"step-start\", step: 0 };\n yield { type: \"tool-call\", callId, name: config.tool.name, input: config.args };\n\n const channel = new EventChannel<RunEvent>();\n const onUserDecision = config.onUserDecision;\n const running = executeToolCall(\n { callId, name: config.tool.name, input: config.args },\n {\n tools: [config.tool],\n vars: config.vars ?? {},\n signal: config.signal,\n timeoutMs: config.toolTimeoutMs,\n onCard: (card) => channel.push({ type: \"card\", card }),\n onHostTool: config.onHostTool,\n requestCard: onUserDecision\n ? async (id, spec: CardSpec) => {\n const card = makeCard(spec, id);\n channel.push({ type: \"awaiting-user\", callId: id, card });\n const action = await onUserDecision(id, card);\n channel.push({ type: \"user-responded\", callId: id, action });\n return action.type === \"cancel\" || action.type === \"dismiss\"\n ? { cancelled: true, reason: \"The user declined.\" }\n : (action.value ?? { confirmed: true });\n }\n : undefined,\n },\n ).then((outcome) => {\n channel.push({\n type: \"tool-result\",\n callId: outcome.callId,\n name: outcome.name,\n output: outcome.output,\n ...(outcome.failure ? { failure: outcome.failure } : {}),\n ms: outcome.ms,\n });\n return outcome;\n }).finally(() => channel.close());\n\n for await (const event of channel) yield event;\n const outcome = await running;\n\n // A tool action spends no tokens, but it is still an act a host may need to\n // account for, so it produces the same terminal record as any other run.\n const finishedAt = Date.now();\n const finishReason: FinishReason = outcome.failure === \"denied\" && config.signal?.aborted ? \"cancelled\" : \"stop\";\n const record: MeteringRecord = {\n scope: \"run\",\n id: `${runId}:run`,\n runId,\n provider: config.provider,\n requestedModel: config.model,\n mode: \"sync\",\n status: finishReason === \"cancelled\" ? \"cancelled\" : outcome.failure ? \"failed\" : \"completed\",\n usage: {},\n source: \"unavailable\",\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n steps: 0,\n finishReason,\n metadata: { ...config.meteringMetadata, trigger: \"surface-action\", surfaceId: config.surfaceId, componentId: config.componentId, tool: config.tool.name },\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"run-finish\", runId, finishReason, usage: {}, steps: 0 };\n}\n","// One-way export to A2UI v0.9.1 messages (a2ui.org), with no runtime dependency.\n//\n// The formats share their structure: a flat list, ids for children, JSON Pointers\n// for data. Components with a basic-catalogue counterpart are renamed to it; the\n// rest keep their names and rely on this catalogue id, as A2UI's custom catalogues\n// allow. `$query`, `set` and `tool` have no A2UI equivalent and travel as namespaced\n// function calls and events that a receiving client would have to implement.\n\nimport { isSurfaceBinding } from \"./bindings.js\";\nimport type { SurfaceAction, SurfaceComponent, SurfaceSpec } from \"./types.js\";\n\nexport const A2UI_VERSION = \"v0.9.1\" as const;\nexport const SURFACE_A2UI_CATALOG_ID = \"urn:supersolutions:super-chat:surface-catalog:v1\" as const;\n\nexport type A2uiMessage =\n | { version: typeof A2UI_VERSION; createSurface: { surfaceId: string; catalogId: string; sendDataModel: boolean } }\n | { version: typeof A2UI_VERSION; updateComponents: { surfaceId: string; components: Record<string, unknown>[] } }\n | { version: typeof A2UI_VERSION; updateDataModel: { surfaceId: string; path: string; value: unknown } }\n | { version: typeof A2UI_VERSION; deleteSurface: { surfaceId: string } };\n\nconst toDynamic = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(toDynamic);\n if (typeof value !== \"object\" || value === null) return value;\n if (isSurfaceBinding(value)) {\n if (\"$path\" in value) return { path: value.$path };\n if (\"$item\" in value) return { path: value.$item };\n if (\"$template\" in value) {\n return { call: \"formatString\", args: { value: value.$template.replace(/\\{(\\/[^{}]*)\\}/g, \"$${$1}\").replace(/\\{\\.([^{}]*)\\}/g, \"$${$1}\") } };\n }\n return { call: \"superchat.query\", args: toDynamic(value.$query) };\n }\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toDynamic(v)]));\n};\n\nconst toAction = (action: SurfaceAction): unknown => {\n switch (action.type) {\n case \"event\":\n return { event: { name: action.name, ...(action.context ? { context: toDynamic(action.context) } : {}) } };\n case \"set\":\n return { functionCall: { call: \"superchat.set\", args: { updates: toDynamic(action.updates) } } };\n case \"tool\":\n return { event: { name: \"superchat.tool\", context: toDynamic({ tool: action.tool, args: action.args ?? {}, resultPath: action.resultPath }) } };\n }\n};\n\nconst TEXT_VARIANTS: Record<string, string> = { title: \"h2\", heading: \"h4\", body: \"body\", caption: \"caption\", label: \"caption\", code: \"body\" };\n\nfunction toComponents(component: SurfaceComponent, rename: (id: string) => string): Record<string, unknown>[] {\n const { id, component: name, visibleWhen: _visibleWhen, ...rest } = component;\n const base = { id: rename(id) };\n const props = toDynamic(rest) as Record<string, unknown>;\n const children = Array.isArray(rest[\"children\"]) ? (rest[\"children\"] as string[]).map(rename) : undefined;\n\n switch (name) {\n case \"Stack\":\n return [{ ...base, component: rest[\"direction\"] === \"horizontal\" ? \"Row\" : \"Column\", children, ...(rest[\"justify\"] ? { justify: rest[\"justify\"] === \"between\" ? \"spaceBetween\" : rest[\"justify\"] } : {}), ...(rest[\"align\"] ? { align: rest[\"align\"] } : {}) }];\n case \"Text\":\n return [{ ...base, component: \"Text\", text: props[\"text\"], ...(typeof rest[\"variant\"] === \"string\" ? { variant: TEXT_VARIANTS[rest[\"variant\"]] } : {}) }];\n case \"Image\":\n return [{ ...base, component: \"Image\", url: props[\"src\"] }];\n case \"Divider\":\n return [{ ...base, component: \"Divider\" }];\n case \"Tabs\":\n return [{ ...base, component: \"Tabs\", tabs: (rest[\"tabs\"] as { label: string; child: string }[]).map((t) => ({ title: t.label, child: rename(t.child) })) }];\n case \"List\": {\n const items = rest[\"items\"];\n const path = isSurfaceBinding(items) && \"$path\" in items ? items.$path : undefined;\n return path\n ? [{ ...base, component: \"List\", children: { path, componentId: rename(rest[\"child\"] as string) } }]\n : [{ ...base, component: name, ...props, child: rename(rest[\"child\"] as string) }];\n }\n case \"Field\":\n return [{ ...base, component: rest[\"type\"] === \"date\" ? \"DateTimeInput\" : \"TextField\", label: props[\"label\"], value: props[\"value\"] }];\n case \"Select\":\n return [{ ...base, component: \"ChoicePicker\", label: props[\"label\"], value: props[\"value\"], options: props[\"options\"], variant: \"mutuallyExclusive\" }];\n case \"Toggle\":\n return [{ ...base, component: \"CheckBox\", label: props[\"label\"], value: props[\"value\"] }];\n case \"Slider\":\n return [{ ...base, component: \"Slider\", label: props[\"label\"], value: props[\"value\"], min: props[\"min\"], max: props[\"max\"] }];\n case \"Button\": {\n const labelId = rename(`${id}__label`);\n return [\n { ...base, component: \"Button\", child: labelId, variant: rest[\"variant\"] === \"primary\" ? \"primary\" : \"borderless\", action: toAction(rest[\"action\"] as SurfaceAction) },\n { id: labelId, component: \"Text\", text: props[\"label\"] },\n ];\n }\n default:\n return [{ ...base, component: name, ...props, ...(children ? { children } : {}) }];\n }\n}\n\n/** The messages that would recreate this surface in an A2UI client. */\nexport function toA2uiMessages(spec: SurfaceSpec): A2uiMessage[] {\n const { surfaceId } = spec;\n if (spec.deleted) return [{ version: A2UI_VERSION, deleteSurface: { surfaceId } }];\n // A2UI requires the top component to be called \"root\".\n const rename = (id: string) => (id === spec.root ? \"root\" : id === \"root\" ? `${spec.root}__swapped` : id);\n return [\n { version: A2UI_VERSION, createSurface: { surfaceId, catalogId: SURFACE_A2UI_CATALOG_ID, sendDataModel: true } },\n { version: A2UI_VERSION, updateComponents: { surfaceId, components: spec.components.flatMap((c) => toComponents(c, rename)) } },\n { version: A2UI_VERSION, updateDataModel: { surfaceId, path: \"/\", value: spec.data } },\n ];\n}\n","// Tool definitions and capability presets.\n//\n// Presets are EXPLICIT ALLOWLISTS, not blocklists. A newly registered tool is\n// invisible until someone puts it in a preset. The inverse (everything exposed\n// unless denied) means the day you add `deleteEverything` it is already live on\n// every API key you ever minted.\n//\n// Three preset tiers cover most agent products, and they map to genuinely\n// different trust levels rather than arbitrary groupings:\n// observer — pure reads. Safe to hand to anyone.\n// draft — produces something the USER must approve/sign. No side effects.\n// executor — acts on the user's behalf. Needs explicit, scoped authorization.\n// Hosts can define their own tiers; these are just the defaults.\n\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { Card, CardSpec } from \"../cards/types.js\";\nimport type { SurfaceLedger } from \"../surfaces/ledger.js\";\n\nexport type ToolSide = \"read\" | \"write\" | \"confirm\";\n\n/**\n * A truthful preview of the output geometry while a tool is still running.\n *\n * This is host-only metadata: providers never see it. A function is useful for\n * tools such as image generation where count and aspect ratio come from the\n * call input rather than from the tool definition alone.\n */\nexport type ToolLoadingHint = {\n kind: \"media\" | \"chart\" | \"table\" | \"document\" | \"generic\";\n label: string;\n count?: number;\n /** CSS-compatible ratio, for example `1024 / 1536`. */\n aspectRatio?: string;\n};\n\nexport type ToolLoading = ToolLoadingHint | ((input: unknown) => ToolLoadingHint | undefined);\n\nexport type ToolExecutionContext = {\n /** Host-supplied per-run values: user id, session, network, locale. */\n vars: Record<string, unknown>;\n signal?: AbortSignal;\n /** The tool call's id, for correlating a card back to it. */\n callId: string;\n /** Emit a card mid-execution (progress updates on a long tool). */\n emitCard?: (spec: CardSpec) => void;\n /** Ask the user something and await the answer. Absent when this host cannot ask. */\n requestCard?: (spec: CardSpec) => Promise<unknown>;\n /** The surfaces on this conversation's active path, as this run sees them. */\n surfaces?: SurfaceLedger;\n /** Tools a surface button may call in this run. */\n surfaceActionTools?: readonly string[];\n};\n\nexport type ToolResultExtras = {\n /**\n * Where the card should be shown: `inline` (the default) or `panel`, the host's side panel.\n * Ignored without a card; an interactive card stays inline whatever is asked.\n */\n placement?: \"inline\" | \"panel\";\n /**\n * Update an EXISTING card instead of minting a new one: the runtime reuses\n * this id, and the reducer's upsert replaces the old card in place.\n */\n cardId?: string;\n /**\n * Tool names this result unlocks for the REST of the run (`loadSkill`'s pull\n * half). The runtime re-resolves the active set and re-declares specs to the\n * provider from the next step on.\n */\n unlockTools?: string[];\n};\n\nexport type ToolResult = ToolResultExtras & {\n /** What the model sees. Keep it small — this is re-sent every subsequent step. */\n output: unknown;\n /** What the user sees. Not sent to the model. */\n card?: CardSpec;\n failure?: \"execution-error\" | \"denied\" | \"invalid-input\" | \"timeout\" | \"not-found\";\n};\n\n/**\n * How an approval card reads, in the words of the person approving. The card shows\n * `description`, then any `summary` rows, then `title` as the question above the buttons.\n */\nexport type ToolApproval = {\n /** The one question the buttons answer, such as \"Rename the report?\". */\n title?: string;\n /** What will happen, in a sentence or two, such as \"Your report will be titled “Q3 review”.\". */\n description?: string;\n /** Exact details worth checking: amounts, targets, anything irreversible. Omit when the sentence says it all. */\n summary?: { label: string; value: string }[];\n /** The verb on the approve button, such as \"Rename\". Defaults to \"Allow\". */\n confirmLabel?: string;\n /** Defaults to \"Not now\". */\n cancelLabel?: string;\n /** Marks an action that is hard to undo. */\n danger?: boolean;\n};\n\nexport type ToolDefinition = {\n name: string;\n description: string;\n inputSchema: JSONSchema;\n /**\n * Absent `execute` means the HOST runs this tool (browser-side: read the DOM,\n * open a wallet, use a local file). The runtime emits a `tool-call` event and\n * suspends until the host supplies a result.\n */\n execute?: (input: unknown, ctx: ToolExecutionContext) => Promise<ToolResult | unknown> | ToolResult | unknown;\n /**\n * `confirm` suspends the run and shows an approval card before executing.\n * The distinction from `write` is intent: `write` acts, `confirm` asks first.\n * The runtime enforces this: with no approval, and no way to get one, the tool\n * does not run.\n */\n side?: ToolSide;\n /**\n * Who asks, for a `side: \"confirm\"` tool. `\"runtime\"` (the default) shows a\n * generic approval card before the tool starts. `\"tool\"` is for a tool whose\n * approval needs something only it can compute, such as a diff: it must call\n * `ctx.requestCard` itself before acting. A tool that asks for itself without\n * saying so is asked about twice, which is the safe way for that to go wrong.\n */\n confirmation?: \"runtime\" | \"tool\";\n /**\n * The approval card's wording, written for the person approving the action. Without\n * it the card shows the first sentence of `description` and the input's plain fields.\n * Never shown to the model.\n */\n approval?: (input: unknown) => ToolApproval | undefined;\n /** Ask the provider to enforce the schema (OpenAI strict mode). */\n strict?: boolean;\n /** Default card renderer key when the result carries no explicit card. */\n render?: string;\n /** Rough token cost of a typical result, for budgeting. */\n costHint?: number;\n /** Live-only output placeholder. Omit when the result's shape is unknown. */\n loading?: ToolLoading;\n /**\n * For a tool whose ARGUMENTS are a card (`visualize` is the built-in one):\n * a preview of that card from arguments that are still streaming. Called\n * with each tolerant parse of the partial JSON; return `undefined` until\n * there is something worth drawing. Route it through\n * `CardRegistry.partial` so interactive kinds and specs that fail\n * validation never preview. Live-only — the validated card from `execute`\n * replaces it, and it is never written to history.\n *\n * A tool whose card is computed BY `execute` has nothing to preview here:\n * the arguments are a query, not the answer.\n */\n partialCard?: (partialInput: unknown) => CardSpec | undefined;\n};\n\n/** Resolve a tool's streaming card preview; a throwing hook means \"no preview\", never a failed call. */\nexport function resolvePartialCard(tool: ToolDefinition | undefined, partialInput: unknown): CardSpec | undefined {\n if (!tool?.partialCard) return undefined;\n try {\n return tool.partialCard(partialInput);\n } catch {\n return undefined;\n }\n}\n\n/** Resolve a static or input-derived loading hint without leaking a function into run events. */\nexport function resolveToolLoading(loading: ToolLoading | undefined, input: unknown): ToolLoadingHint | undefined {\n try {\n return typeof loading === \"function\" ? loading(input) : loading;\n } catch {\n // Presentation metadata must never be able to fail the tool call itself.\n return undefined;\n }\n}\n\nexport type PresetName = string;\n\nexport type ToolResolution = {\n /** Preset names enabled for this run. */\n presets: readonly PresetName[];\n /** Extra tools unlocked beyond the presets (skills unlock their own tools). */\n allow?: readonly string[];\n /** Removed even if a preset grants them. Applied last. */\n deny?: readonly string[];\n};\n\nexport const DEFAULT_PRESETS = [\"observer\", \"draft\", \"executor\"] as const;\n","import type { ToolSpec } from \"../providers/types.js\";\nimport { normalizeToolName } from \"./repair.js\";\nimport type { PresetName, ToolDefinition, ToolResolution } from \"./types.js\";\n\n/**\n * The tool registry. Holds definitions, maps preset → allowlist, and renders the\n * provider-facing `ToolSpec[]`.\n *\n * `resolve()` is the only way to get a tool set, and it always applies deny\n * last — so a host-level kill switch cannot be re-granted by a preset or by a\n * skill unlocking a tool.\n */\nexport class ToolRegistry {\n private tools = new Map<string, ToolDefinition>();\n private presets = new Map<PresetName, Set<string>>();\n private listeners = new Set<() => void>();\n private version = 0;\n // Reverse of `presets`: tool name → presets that grant it. Lazily rebuilt —\n // `touch()` just nulls it out, so a burst of register()/addToPreset() calls\n // pays for one rebuild on the next presetsFor()/resolve(), not one per call.\n private reversePresetIndex: Map<string, PresetName[]> | null = null;\n\n constructor(tools: readonly ToolDefinition[] = []) {\n for (const t of tools) this.register(t);\n }\n\n register(tool: ToolDefinition, presets: readonly PresetName[] = []): this {\n this.tools.set(tool.name, tool);\n for (const p of presets) this.addToPreset(p, tool.name);\n this.touch();\n return this;\n }\n\n /** Register several tools into the same preset — the common bulk case. */\n registerAll(tools: readonly ToolDefinition[], presets: readonly PresetName[] = []): this {\n for (const t of tools) this.register(t, presets);\n return this;\n }\n\n addToPreset(preset: PresetName, ...names: string[]): this {\n const set = this.presets.get(preset) ?? new Set<string>();\n for (const n of names) set.add(n);\n this.presets.set(preset, set);\n this.touch();\n return this;\n }\n\n /**\n * Change notification, so a UI (or an inspector hook) re-reads after a LATE\n * registration — tools imported from an MCP server arrive long after mount,\n * and a registry nobody can observe leaves them invisible until reload.\n */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Monotonic change counter — a stable snapshot value for useSyncExternalStore. */\n getVersion(): number {\n return this.version;\n }\n\n private touch(): void {\n this.version += 1;\n this.reversePresetIndex = null;\n for (const l of this.listeners) l();\n }\n\n get(name: string): ToolDefinition | undefined {\n // Tolerate router-namespaced names (\"functions.getPrice\") so a call from a\n // provider that rewrites names still dispatches.\n return this.tools.get(name) ?? this.tools.get(normalizeToolName(name));\n }\n\n has(name: string): boolean {\n return this.get(name) !== undefined;\n }\n\n list(): ToolDefinition[] {\n return [...this.tools.values()];\n }\n\n presetNames(): PresetName[] {\n return [...this.presets.keys()];\n }\n\n /** Tool names in a preset that are actually registered. */\n namesInPreset(preset: PresetName): string[] {\n return [...(this.presets.get(preset) ?? [])].filter((n) => this.tools.has(n)).sort();\n }\n\n /** Which presets grant `name`. Used by the UI to explain why a tool is available. */\n presetsFor(name: string): PresetName[] {\n return this.reverseIndex().get(name) ?? [];\n }\n\n /** Tool name → presets that grant it, rebuilt on demand after the last mutation. */\n private reverseIndex(): Map<string, PresetName[]> {\n if (this.reversePresetIndex) return this.reversePresetIndex;\n const index = new Map<string, PresetName[]>();\n for (const [preset, names] of this.presets) {\n for (const name of names) {\n const grants = index.get(name);\n if (grants) grants.push(preset);\n else index.set(name, [preset]);\n }\n }\n this.reversePresetIndex = index;\n return index;\n }\n\n /**\n * Resolve the tool set for a run.\n *\n * Two distinct grants, and keeping them separate is a security property:\n *\n * PRESETS grant AUTHORITY. Whether the caller may act at all.\n * `allow` grants RELEVANCE. Usually a matched skill saying \"these are the\n * tools my instructions describe\".\n *\n * A skill must therefore never be able to escalate past the capability tier.\n * So `allow` can surface a tool that belongs to NO preset (private by\n * default, unlocked by the skill that documents it), but a tool that IS in a\n * preset still requires that preset to be enabled. Otherwise any skill could\n * hand out the executor tier just by naming a tool.\n *\n * A name listed in a preset but never registered is skipped rather than\n * throwing — presets are configuration and often outlive the tools they name.\n */\n resolve(resolution: ToolResolution): ToolDefinition[] {\n const allowed = new Set<string>();\n for (const preset of resolution.presets) {\n for (const name of this.presets.get(preset) ?? []) allowed.add(name);\n }\n for (const name of resolution.allow ?? []) {\n const grants = this.presetsFor(name);\n const skillGated = grants.length === 0;\n const withinTier = grants.some((g) => resolution.presets.includes(g));\n if (skillGated || withinTier) allowed.add(name);\n }\n for (const name of resolution.deny ?? []) allowed.delete(name);\n\n return [...allowed]\n .map((n) => this.tools.get(n))\n .filter((t): t is ToolDefinition => t !== undefined)\n .sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /** Provider-facing specs. The adapter turns these into its own wire shape. */\n toSpecs(tools: readonly ToolDefinition[]): ToolSpec[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict ? { strict: true } : {}),\n }));\n }\n\n /** Tools whose execution happens on the host, not here. */\n hostExecuted(tools: readonly ToolDefinition[]): string[] {\n return tools.filter((t) => typeof t.execute !== \"function\").map((t) => t.name);\n }\n}\n","// Tolerant, incremental JSON for tool arguments that are still streaming.\n//\n// A provider streams a tool call's arguments as raw JSON fragments, and the\n// only thing a UI can do with `{\"kind\":\"table\",\"spec\":{\"columns\":[{\"key\":\"na`\n// is wait — unless something can read it as \"a table spec whose columns have\n// started\". This is that something.\n//\n// What it promises, and what it does not:\n// • Every snapshot is a value `JSON.parse` could have produced from SOME\n// prefix-completion of the input: open containers are closed, an open\n// string VALUE shows the characters received so far.\n// • An open KEY is never shown — `{\"ti` is `{}`, not `{ ti: undefined }`.\n// • An unterminated NUMBER is never shown either. `12` may be the start of\n// `1200`, and a magnitude that is wrong by a factor of a hundred is worse\n// than one that is late. A truncated string reads as truncated; a\n// truncated number reads as a different number.\n// • Literals (`true`/`false`/`null`) appear only once complete.\n// • A half-received escape (`\\`, `\\u00`) and a lone high surrogate are held\n// back until the rest arrives, so a snapshot never contains a broken char.\n// • Prose or a ``` fence before the first `{`/`[` is skipped. Anything else\n// malformed FREEZES the parser at its last good snapshot rather than\n// guessing — the authoritative, repaired and validated value still arrives\n// with the provider's `tool-call-end`. This is a preview, never a source of\n// truth.\n//\n// Incremental rather than re-parse-per-delta because a long spec arrives in\n// thousands of fragments: re-reading the whole accumulated string each time is\n// quadratic over the call. Here each character is read once, and a snapshot\n// copies only the chain of containers that are still open — every finished\n// object or array is frozen and SHARED between snapshots, so a table that has\n// received 200 rows hands the UI the same 199 row objects it saw last time.\n\ntype ObjectFrame = {\n type: \"object\";\n value: Record<string, unknown>;\n /** The key whose value is being read, once its closing quote has arrived. */\n key: string | undefined;\n expect: \"key\" | \"colon\" | \"value\" | \"comma\";\n};\ntype ArrayFrame = { type: \"array\"; value: unknown[]; expect: \"value\" | \"comma\" };\ntype Frame = ObjectFrame | ArrayFrame;\n\ntype Token =\n | { type: \"string\"; isKey: boolean; text: string; escape: \"\" | \"\\\\\" | \"u\"; hex: string }\n | { type: \"number\"; text: string }\n | { type: \"literal\"; text: string };\n\nconst QUOTE = 0x22;\nconst BACKSLASH = 0x5c;\nconst ESCAPES: Record<string, string> = { '\"': '\"', \"\\\\\": \"\\\\\", \"/\": \"/\", b: \"\\b\", f: \"\\f\", n: \"\\n\", r: \"\\r\", t: \"\\t\" };\nconst LITERALS: Record<string, unknown> = { true: true, false: false, null: null };\nconst NUMBER = /^-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\nconst HEX = /^[0-9a-fA-F]$/;\nconst isSpace = (c: string) => c === \" \" || c === \"\\n\" || c === \"\\r\" || c === \"\\t\";\nconst isNumberChar = (c: string) => (c >= \"0\" && c <= \"9\") || c === \"-\" || c === \"+\" || c === \".\" || c === \"e\" || c === \"E\";\n\n/** JSON.parse semantics for an own `__proto__` key: a data property, not a prototype swap. */\nfunction setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\n/** Drop a trailing high surrogate whose low half has not arrived yet. */\nfunction visible(text: string): string {\n const last = text.charCodeAt(text.length - 1);\n return last >= 0xd800 && last <= 0xdbff ? text.slice(0, -1) : text;\n}\n\nexport class PartialJsonParser {\n private stack: Frame[] = [];\n private token: Token | null = null;\n private root: unknown = undefined;\n private started = false;\n private done = false;\n private broken = false;\n private changes = 0;\n private cache: { at: number; value: unknown } | null = null;\n\n /** True once the top-level value has closed. Input after it is ignored. */\n get complete(): boolean {\n return this.done;\n }\n\n /** True once the input stopped being JSON. The parser keeps its last good snapshot. */\n get failed(): boolean {\n return this.broken;\n }\n\n /**\n * Bumped whenever the snapshot would differ. Compare against the value you\n * last rendered to skip deltas that changed nothing visible — whitespace, a\n * key's characters, the digits of an unfinished number.\n */\n get version(): number {\n return this.changes;\n }\n\n push(chunk: string): void {\n let i = 0;\n const len = chunk.length;\n while (i < len && !this.done && !this.broken) {\n const token = this.token;\n if (token?.type === \"string\") {\n i = this.readString(token, chunk, i);\n continue;\n }\n const c = chunk[i]!;\n if (token?.type === \"number\") {\n if (isNumberChar(c)) {\n token.text += c;\n i += 1;\n continue;\n }\n this.token = null;\n if (!NUMBER.test(token.text)) {\n this.broken = true;\n return;\n }\n this.assign(Number(token.text));\n continue; // `c` still needs reading: it is what ended the number\n }\n if (token?.type === \"literal\") {\n token.text += c;\n i += 1;\n if (Object.hasOwn(LITERALS, token.text)) {\n this.token = null;\n this.assign(LITERALS[token.text]);\n } else if (!Object.keys(LITERALS).some((l) => l.startsWith(token.text))) {\n this.broken = true;\n }\n continue;\n }\n i += 1;\n if (isSpace(c)) continue;\n this.structural(c);\n }\n }\n\n /**\n * The value as far as it has arrived, or `undefined` before the top-level\n * container opens. Stable by reference until `version` changes.\n */\n snapshot(): unknown {\n if (this.done) return this.root;\n if (this.cache?.at === this.changes) return this.cache.value;\n let child: unknown = undefined;\n let hasChild = false;\n if (this.token?.type === \"string\" && !this.token.isKey) {\n child = visible(this.token.text);\n hasChild = true;\n }\n for (let i = this.stack.length - 1; i >= 0; i -= 1) {\n const frame = this.stack[i]!;\n if (frame.type === \"object\") {\n const copy = { ...frame.value };\n if (hasChild && frame.key !== undefined) setOwn(copy, frame.key, child);\n child = copy;\n } else {\n const copy = frame.value.slice();\n if (hasChild) copy.push(child);\n child = copy;\n }\n hasChild = true;\n }\n this.cache = { at: this.changes, value: child };\n return child;\n }\n\n private structural(c: string): void {\n const frame = this.stack[this.stack.length - 1];\n if (!frame) {\n // Before the root: tolerate whatever a model wraps JSON in. After it,\n // `done` has already stopped the loop.\n if (c === \"{\" || c === \"[\") {\n this.started = true;\n this.open(c);\n }\n return;\n }\n if (frame.type === \"object\") {\n switch (frame.expect) {\n case \"key\":\n if (c === '\"') this.token = { type: \"string\", isKey: true, text: \"\", escape: \"\", hex: \"\" };\n else if (c === \"}\") this.close(); // `{}`, or a trailing comma\n else this.broken = true;\n return;\n case \"colon\":\n if (c === \":\") frame.expect = \"value\";\n else this.broken = true;\n return;\n case \"value\":\n this.startValue(c);\n return;\n case \"comma\":\n if (c === \",\") frame.expect = \"key\";\n else if (c === \"}\") this.close();\n else this.broken = true;\n return;\n }\n }\n if (frame.expect === \"value\") {\n if (c === \"]\") this.close(); // `[]`, or a trailing comma\n else this.startValue(c);\n } else if (c === \",\") frame.expect = \"value\";\n else if (c === \"]\") this.close();\n else this.broken = true;\n }\n\n private startValue(c: string): void {\n if (c === '\"') {\n this.token = { type: \"string\", isKey: false, text: \"\", escape: \"\", hex: \"\" };\n this.changes += 1; // the key now shows, with an empty value\n } else if (c === \"{\" || c === \"[\") this.open(c);\n else if (c === \"-\" || (c >= \"0\" && c <= \"9\")) this.token = { type: \"number\", text: c };\n else if (c === \"t\" || c === \"f\" || c === \"n\") this.token = { type: \"literal\", text: c };\n else this.broken = true;\n }\n\n private open(c: \"{\" | \"[\"): void {\n this.stack.push(c === \"{\" ? { type: \"object\", value: {}, key: undefined, expect: \"key\" } : { type: \"array\", value: [], expect: \"value\" });\n this.changes += 1;\n }\n\n private close(): void {\n const frame = this.stack.pop()!;\n this.assign(frame.value);\n }\n\n /** A value finished: hand it to the container it belongs to, or finish the root. */\n private assign(value: unknown): void {\n this.changes += 1;\n const parent = this.stack[this.stack.length - 1];\n if (!parent) {\n this.root = value;\n this.done = this.started;\n return;\n }\n if (parent.type === \"object\") {\n setOwn(parent.value, parent.key!, value);\n parent.key = undefined;\n } else {\n parent.value.push(value);\n }\n parent.expect = \"comma\";\n }\n\n /** Consume string characters from `i`; returns where reading stopped. */\n private readString(token: Extract<Token, { type: \"string\" }>, chunk: string, i: number): number {\n const len = chunk.length;\n while (i < len) {\n if (token.escape === \"u\") {\n const c = chunk[i]!;\n if (!HEX.test(c)) {\n this.broken = true;\n return len;\n }\n token.hex += c;\n i += 1;\n if (token.hex.length === 4) {\n token.text += String.fromCharCode(parseInt(token.hex, 16));\n token.escape = \"\";\n token.hex = \"\";\n if (!token.isKey) this.changes += 1;\n }\n continue;\n }\n if (token.escape === \"\\\\\") {\n const c = chunk[i]!;\n i += 1;\n if (c === \"u\") {\n token.escape = \"u\";\n continue;\n }\n // An unknown escape keeps its character: lenient, and lossless enough\n // for a preview that the validated value will replace anyway.\n token.text += ESCAPES[c] ?? c;\n token.escape = \"\";\n if (!token.isKey) this.changes += 1;\n continue;\n }\n // Copy the plain run up to the next quote or backslash in one slice.\n let j = i;\n while (j < len) {\n const code = chunk.charCodeAt(j);\n if (code === QUOTE || code === BACKSLASH) break;\n j += 1;\n }\n if (j > i) {\n token.text += chunk.slice(i, j);\n if (!token.isKey) this.changes += 1;\n i = j;\n }\n if (i >= len) return i;\n if (chunk.charCodeAt(i) === BACKSLASH) {\n token.escape = \"\\\\\";\n i += 1;\n continue;\n }\n // Closing quote.\n this.token = null;\n if (token.isKey) {\n const frame = this.stack[this.stack.length - 1] as ObjectFrame;\n frame.key = token.text;\n frame.expect = \"colon\";\n } else {\n this.assign(token.text);\n }\n return i + 1;\n }\n return i;\n }\n}\n\n/** One-shot form: the best value `text` supports so far, and whether it is whole. */\nexport function parsePartialJson(text: string): { value: unknown; complete: boolean } {\n const parser = new PartialJsonParser();\n parser.push(text);\n return { value: parser.snapshot(), complete: parser.complete };\n}\n","// Built-in tools: the agent's own capabilities, as opposed to the host's domain\n// tools.\n//\n// `visualize` is the important one. Without it an agent can only show what some\n// engineer pre-built a card for; with it the agent CHOOSES a presentation for\n// whatever it is holding — a comparison becomes a table, a trend becomes a\n// chart, an ambiguous match becomes a choice card instead of a guess. That is\n// the difference between an agent that talks about data and one that shows it.\n\nimport { CardRegistry, isObj } from \"../cards/registry.js\";\nimport type { CardSpec } from \"../cards/types.js\";\nimport type { SkillRegistry } from \"../skills/registry.js\";\nimport type { SurfaceCatalogue } from \"../surfaces/catalogue.js\";\nimport { createSurfaceTools } from \"../surfaces/tools.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\n/** Where `visualize` may put a card. `document` is not the agent's to choose from a chat. */\nexport type VisualizePlacement = \"inline\" | \"panel\";\n\nexport type VisualizeToolOptions = {\n cards: CardRegistry;\n /** Restrict which kinds the agent may emit (a read-only chat may want no `confirm`). */\n kinds?: string[];\n /**\n * Where the agent may put a card. Default `[\"inline\"]`: the tool is exactly as before. Add\n * `\"panel\"` when the host shows a side panel (super-chat-ui's `ChatPanel`): the agent can then open\n * a card beside the conversation, for a chart or a document worth room of its own.\n */\n placements?: readonly VisualizePlacement[];\n};\n\n/**\n * The generic visualization tool.\n *\n * The description carries the whole catalogue because model card-choice quality\n * tracks how well the options are described far more than it tracks schema\n * strictness — and a `oneOf` union across 13 shapes both bloats the request and\n * degrades tool-call accuracy on most models. We take a loose schema plus a\n * precise description, then validate and hand back a correction the model can\n * act on.\n */\nexport function createVisualizeTool(opts: VisualizeToolOptions): ToolDefinition {\n const { cards } = opts;\n const available = opts.kinds ? cards.list().filter((k) => opts.kinds!.includes(k.kind)) : cards.list();\n const panel = (opts.placements ?? [\"inline\"]).includes(\"panel\");\n const catalogue = available\n .map((k) => `- ${k.kind}${k.interactive ? \" (interactive — the user replies)\" : \"\"}: ${k.summary}`)\n .join(\"\\n\");\n\n return {\n name: \"visualize\",\n side: \"read\",\n description: [\n \"Render a visual card for the user. Use this whenever a result is easier to SEE than to read:\",\n \"comparisons, trends, sequences, multi-field records, long operations, or a decision the user must make.\",\n \"\",\n \"Available kinds:\",\n catalogue,\n \"\",\n \"Rules:\",\n \"- Put the data IN the card. Do not also repeat every row in your prose — say what it means instead.\",\n \"- Interactive kinds (choice, form, confirm) pause for the user's answer, which is returned to you as this tool's result. Use them instead of guessing.\",\n \"- Use `confirm` before anything consequential or irreversible.\",\n \"- One card per distinct idea. Do not wrap a one-line answer in a card.\",\n ...(panel\n ? [\n '- `placement: \"panel\"` opens the card in the side panel beside the chat, with room to explore: use it for a chart the user will work with or a long document. Keep small results (a few figures, a short table) inline, the default.',\n \"- Interactive kinds are always inline.\",\n ]\n : []),\n ].join(\"\\n\"),\n inputSchema: {\n type: \"object\",\n required: [\"kind\", \"spec\"],\n properties: {\n kind: { type: \"string\", enum: available.map((k) => k.kind), description: \"Which card to render.\" },\n // Before `spec`, so it streams first: a panel card is not previewed in the chat.\n ...(panel\n ? { placement: { type: \"string\", enum: [\"inline\", \"panel\"], description: \"Where to show the card: in the chat (inline, default) or in the side panel.\" } }\n : {}),\n spec: {\n type: \"object\",\n description: \"The card body. Must match the schema for `kind`, and must include `kind` itself.\",\n additionalProperties: true,\n },\n },\n additionalProperties: false,\n },\n loading: (input) => {\n const { kind, spec } = (input ?? {}) as { kind?: string; spec?: Record<string, unknown> };\n if (!kind || cards.get(kind)?.interactive) return undefined;\n const outputKind = kind === \"media\"\n ? \"media\"\n : [\"chart\", \"funnel\", \"gauge\"].includes(kind)\n ? \"chart\"\n : [\"table\", \"comparison\"].includes(kind)\n ? \"table\"\n : [\"document\", \"markdown\", \"code\", \"diff\", \"email\"].includes(kind)\n ? \"document\"\n : \"generic\";\n const mediaItems = kind === \"media\" && Array.isArray(spec?.[\"items\"])\n ? spec[\"items\"] as Record<string, unknown>[]\n : [];\n const first = mediaItems[0];\n const width = typeof first?.[\"width\"] === \"number\" ? first[\"width\"] : undefined;\n const height = typeof first?.[\"height\"] === \"number\" ? first[\"height\"] : undefined;\n return {\n kind: outputKind,\n label: `Preparing ${kind} card`,\n ...(mediaItems.length ? { count: mediaItems.length } : {}),\n ...(width && height ? { aspectRatio: `${width} / ${height}` } : {}),\n };\n },\n // The card IS this tool's arguments, so it can be drawn while they stream.\n // `cards.partial` refuses interactive kinds and anything its own validator\n // rejects; `execute` below stays the only path to a real card.\n partialCard: (input) => {\n const { kind, spec, placement } = (input ?? {}) as { kind?: unknown; spec?: unknown; placement?: unknown };\n if (typeof kind !== \"string\" || !isObj(spec)) return undefined;\n // A card bound for the side panel is drawn there once it is whole, not previewed in the chat.\n if (placement === \"panel\") return undefined;\n if (opts.kinds && !opts.kinds.includes(kind)) return undefined;\n return cards.partial({ ...spec, kind });\n },\n async execute(input, ctx) {\n const { kind, spec, placement } = (input ?? {}) as { kind?: string; spec?: Record<string, unknown>; placement?: unknown };\n if (!kind) return { output: { ok: false, error: \"`kind` is required.\" }, failure: \"invalid-input\" as const };\n if (placement !== undefined && placement !== \"inline\" && !(panel && placement === \"panel\")) {\n const allowed = panel ? '\"inline\" or \"panel\"' : '\"inline\" (this chat has no side panel)';\n return { output: { ok: false, error: `placement must be ${allowed}.` }, failure: \"invalid-input\" as const };\n }\n\n // Models routinely omit `kind` inside `spec` since they already passed it\n // at the top level. Filling it in is unambiguous, so do it rather than\n // bouncing the call.\n const full = { ...(spec ?? {}), kind } as CardSpec;\n\n const verdict = cards.validate(full);\n if (!verdict.ok) {\n // A refusal that names the wrong field but not the right shape (\"symbol must be an object\") costs the model a\n // guess per step. When the kind gave no `expected` of its own, send the kind's own summary: how to build it.\n const shape = verdict.expected ?? cards.get(kind)?.summary;\n return {\n // Returned as data, not thrown: the model reads the correction and\n // retries with a valid spec on the next step.\n output: { ok: false, error: verdict.error, ...(shape ? { expected: shape } : {}) },\n failure: \"invalid-input\" as const,\n };\n }\n\n const def = cards.get(kind);\n if (placement === \"panel\" && def?.interactive) {\n return { output: { ok: false, error: `${kind} asks the user something, so it is shown in the chat: send it without placement.` }, failure: \"invalid-input\" as const };\n }\n if (def?.interactive && ctx.requestCard) {\n // Suspend for the user's answer. The runtime resolves this when the UI\n // reports a CardAction.\n //\n // No `card` in the result: requestCard already surfaced this card and\n // the user has answered it on screen. Returning it again mints a second\n // card with a new id, and the thread renders the same question twice.\n const answer = await ctx.requestCard(full);\n return { output: { ok: true, kind, response: answer } };\n }\n\n if (placement === \"panel\") return { output: { ok: true, kind, rendered: true, placement: \"panel\" }, card: full, placement: \"panel\" as const };\n return { output: { ok: true, kind, rendered: true }, card: full };\n },\n };\n}\n\n/**\n * `loadSkill` — the pull half of progressive disclosure.\n *\n * Paired with `SkillRegistry.manualIndex()` in the system prompt: the model sees\n * a one-line menu every turn and pays for a skill's body only when it decides it\n * needs one.\n */\nexport function createLoadSkillTool(skills: SkillRegistry): ToolDefinition {\n return {\n name: \"loadSkill\",\n side: \"read\",\n description:\n \"Load a skill's full instructions before acting in its area. Skill ids are listed in your instructions. \" +\n \"Loading a skill may also unlock tools specific to it.\",\n inputSchema: {\n type: \"object\",\n required: [\"id\"],\n properties: {\n id: { type: \"string\", description: \"The skill id to load.\" },\n topic: { type: \"string\", description: \"Optional sub-topic, to load only the relevant section.\" },\n },\n additionalProperties: false,\n },\n async execute(input, ctx) {\n const { id, topic } = (input ?? {}) as { id?: string; topic?: string };\n if (!id) return { output: { ok: false, error: \"`id` is required.\" }, failure: \"invalid-input\" as const };\n\n const loaded = await skills.load(id, { query: topic ?? \"\", vars: ctx.vars });\n if (!loaded.found) return { output: { ok: false, error: loaded.text }, failure: \"not-found\" as const };\n\n return {\n output: {\n ok: true,\n id,\n instructions: loaded.text,\n ...(loaded.tools.length ? { unlockedTools: loaded.tools } : {}),\n },\n // The runtime half of the promise: re-resolve the active set so the\n // names announced in `unlockedTools` are actually callable next step.\n ...(loaded.tools.length ? { unlockTools: loaded.tools } : {}),\n };\n },\n };\n}\n\n/**\n * `updateCard` — let the agent revise a card it already emitted.\n *\n * Without this, a long-running operation can only append new progress cards, and\n * the thread fills with near-identical snapshots.\n */\nexport function createUpdateCardTool(cards: CardRegistry): ToolDefinition {\n return {\n name: \"updateCard\",\n side: \"read\",\n description:\n \"Replace a card you previously rendered, by its id. Use for progress updates instead of emitting a new card each time.\",\n inputSchema: {\n type: \"object\",\n required: [\"cardId\", \"spec\"],\n properties: {\n cardId: { type: \"string\" },\n spec: { type: \"object\", additionalProperties: true },\n },\n additionalProperties: false,\n },\n execute(input) {\n const { cardId, spec } = (input ?? {}) as { cardId?: string; spec?: Record<string, unknown> };\n if (!cardId || !spec) {\n return { output: { ok: false, error: \"`cardId` and `spec` are required.\" }, failure: \"invalid-input\" as const };\n }\n const verdict = cards.validate(spec);\n if (!verdict.ok) {\n return { output: { ok: false, error: verdict.error, expected: verdict.expected }, failure: \"invalid-input\" as const };\n }\n // `cardId` makes the runtime REUSE the id, so the reducer's upsert\n // replaces the original card instead of appending a near-identical twin.\n return { output: { ok: true, cardId }, card: spec as CardSpec, cardId };\n },\n };\n}\n\n/** The default built-in set, wired to the given registries. */\nexport function createBuiltinTools(opts: { cards: CardRegistry; skills?: SkillRegistry; surfaces?: SurfaceCatalogue; placements?: readonly VisualizePlacement[] }): ToolDefinition[] {\n const tools = [createVisualizeTool({ cards: opts.cards, ...(opts.placements ? { placements: opts.placements } : {}) }), createUpdateCardTool(opts.cards)];\n // Opt-in: a host that has not asked for surfaces sees the same tool list as before.\n if (opts.surfaces) tools.push(...createSurfaceTools({ catalogue: opts.surfaces }));\n if (opts.skills && opts.skills.list().some((s) => s.mode === \"manual\")) {\n tools.push(createLoadSkillTool(opts.skills));\n }\n return tools;\n}\n","// The event stream a run emits. This is the framework's public runtime surface:\n// React state, server logs, and any host UI are all just reducers over it.\n//\n// Modelled as events rather than a promise because the interesting parts of an\n// agent turn happen BEFORE it finishes — the context trace, the tool calls, the\n// card that needs an answer. A promise-shaped API hides all of it.\n//\n// Ordering guarantees for a step's tools (correlate by `callId`, never by\n// position):\n// 1. Every `tool-call` of the step is emitted before any tool runs.\n// 2. Per callId: `tool-call` → its `card` / `awaiting-user` /\n// `user-responded` → exactly one `tool-result`, failures, timeouts and\n// aborts included.\n// 3. `tool-result`s arrive in COMPLETION order, not call order. `confirm`\n// tools still run one at a time after the parallel ones, so their results\n// come last.\n// 4. All of a step's `tool-result`s arrive before the next `step-start`.\n// 5. The `role: \"tool\"` message runAgent writes back to history keeps CALL\n// order.\n//\n// `tool-call-input-delta` comes earlier still: in stream mode, while the model\n// is WRITING a call's arguments, before the step ends and before `tool-call`.\n// It is a preview — a tolerant parse of the JSON so far, and the card it\n// implies when the tool can say (`ToolDefinition.partialCard`). `tool-call`\n// remains the authoritative, repaired input, and only the tool's own execute\n// path validates and emits a real `card`. Nothing a delta carries is ever\n// written to history.\n\nimport type { Card, CardAction, CardSpec } from \"../cards/types.js\";\nimport type { ContentPart, FinishReason, Usage } from \"../content/types.js\";\nimport type { ContextTrace } from \"../context/types.js\";\nimport type { JobHandle, JobStatus } from \"../providers/types.js\";\nimport type { MeteringRecord } from \"./metering.js\";\nimport type { ToolLoadingHint } from \"../tools/types.js\";\n\nexport type RunEvent =\n | { type: \"run-start\"; runId: string; mode: RunMode }\n /**\n * Everything the run has produced so far, replacing what the consumer holds.\n *\n * For a consumer that joins a run part-way, or lost part of its stream: a\n * turn that runs on a server, followed over a connection that dropped, where\n * replaying every event is not possible. `runAgent` never emits it. The run\n * is live after it — a card still waiting on the person is announced again\n * with `awaiting-user`.\n */\n | { type: \"run-snapshot\"; parts: ContentPart[]; cards: Card[]; usage?: Usage; steps?: number }\n /** Emitted before the first provider call — the whole \"why did it send that\" answer. */\n | { type: \"context-built\"; trace: ContextTrace; system: string; toolNames: string[] }\n | { type: \"step-start\"; step: number }\n | { type: \"text-delta\"; delta: string }\n | { type: \"reasoning-delta\"; delta: string }\n /**\n * Live-only: a tool call's arguments as far as they have streamed. Stream\n * mode only; never sent for a kind that is interactive. `partialCard` is a\n * VALID but incomplete card, present only when the tool previews one.\n */\n | {\n type: \"tool-call-input-delta\";\n callId: string;\n name: string;\n partialInput: unknown;\n partialCard?: CardSpec;\n loading?: ToolLoadingHint;\n }\n | { type: \"tool-call\"; callId: string; name: string; input: unknown; repaired?: boolean; loading?: ToolLoadingHint }\n /** A `confirm`-side tool, or an interactive card, is waiting on the user. */\n | { type: \"awaiting-user\"; callId: string; card: Card }\n | { type: \"user-responded\"; callId: string; action: CardAction }\n | { type: \"tool-result\"; callId: string; name: string; output: unknown; failure?: string; ms: number }\n /** A card was produced — by a tool result, or mid-execution by a long tool. */\n | { type: \"card\"; card: Card }\n | { type: \"card-updated\"; cardId: string; spec: CardSpec }\n | { type: \"step-finish\"; step: number; finishReason: FinishReason; usage?: Usage }\n /** Background mode: the provider accepted the job and we are now polling. */\n | { type: \"job-started\"; handle: JobHandle }\n | { type: \"job-status\"; handle: JobHandle; status: JobStatus }\n | { type: \"message\"; parts: ContentPart[] }\n /** Canonical, idempotent per-step and per-run usage observation. */\n | { type: \"metering\"; record: MeteringRecord }\n | { type: \"usage\"; usage: Usage }\n | { type: \"run-finish\"; runId: string; finishReason: FinishReason; usage: Usage; steps: number }\n | { type: \"error\"; error: unknown; recoverable: boolean };\n\nexport type RunMode = \"stream\" | \"sync\" | \"background\";\n\n/** Accumulated state a host can rebuild from the event stream. */\nexport type RunState = {\n runId: string;\n mode: RunMode;\n status: \"idle\" | \"running\" | \"awaiting-user\" | \"done\" | \"error\";\n parts: ContentPart[];\n cards: Card[];\n usage: Usage;\n steps: number;\n /** Live tool output slots, removed as their correlated result arrives. */\n pendingTools: Record<string, { callId: string; name: string; loading?: ToolLoadingHint }>;\n /**\n * Calls whose arguments are streaming or have streamed, keyed by callId:\n * the latest `tool-call-input-delta` for each. Kept past `tool-call` so a\n * card preview holds its place until the validated card replaces it, and\n * removed with the call's `tool-result`. Live-only — never committed.\n */\n partialTools?: Record<string, PartialToolCall>;\n trace?: ContextTrace;\n /**\n * Tool names actually exposed to the model this run — the base presets PLUS\n * anything a matched skill unlocked. Distinct from what the registry would\n * return for the presets alone, which is why it is recorded rather than\n * recomputed by the UI.\n */\n toolNames?: string[];\n job?: { handle: JobHandle; status: JobStatus };\n pendingCard?: Card;\n error?: unknown;\n finishReason?: FinishReason;\n};\n\nexport type PartialToolCall = {\n callId: string;\n name: string;\n partialInput: unknown;\n partialCard?: CardSpec;\n loading?: ToolLoadingHint;\n};\n\nexport function initialRunState(runId: string, mode: RunMode): RunState {\n return { runId, mode, status: \"idle\", parts: [], cards: [], usage: {}, steps: 0, pendingTools: {}, partialTools: {} };\n}\n\nfunction mergeUsage(a: Usage, b?: Usage): Usage {\n if (!b) return a;\n const add = (x?: number, y?: number) => (x == null && y == null ? undefined : (x ?? 0) + (y ?? 0));\n return {\n inputTokens: add(a.inputTokens, b.inputTokens),\n outputTokens: add(a.outputTokens, b.outputTokens),\n totalTokens: add(a.totalTokens, b.totalTokens),\n cachedInputTokens: add(a.cachedInputTokens, b.cachedInputTokens),\n reasoningTokens: add(a.reasoningTokens, b.reasoningTokens),\n };\n}\n\n/**\n * The canonical reducer. React, a CLI renderer and a server-side recorder all\n * use this one function, so they can never disagree about what a run looked like.\n */\nexport function reduceRunEvent(state: RunState, event: RunEvent): RunState {\n switch (event.type) {\n case \"run-start\":\n return { ...state, runId: event.runId, mode: event.mode, status: \"running\" };\n case \"run-snapshot\":\n // REPLACE, not merge: the sender cannot know what this consumer missed,\n // so anything kept from before could be shown twice. What is live-only\n // (argument previews, a card's wait) is dropped; the stream re-announces\n // whatever still applies.\n return {\n ...state,\n status: \"running\",\n parts: event.parts,\n cards: event.cards,\n pendingCard: undefined,\n pendingTools: Object.fromEntries(\n event.parts.flatMap((p) =>\n p.type === \"tool-call\" && p.status === \"running\" ? [[p.callId, { callId: p.callId, name: p.name }]] : [],\n ),\n ),\n partialTools: {},\n ...(event.usage ? { usage: event.usage } : {}),\n ...(event.steps != null ? { steps: event.steps } : {}),\n };\n case \"context-built\":\n return { ...state, trace: event.trace, toolNames: event.toolNames };\n case \"step-start\":\n return { ...state, steps: event.step + 1 };\n case \"text-delta\": {\n const last = state.parts[state.parts.length - 1];\n const parts =\n last && last.type === \"text\"\n ? [...state.parts.slice(0, -1), { ...last, text: last.text + event.delta }]\n : [...state.parts, { type: \"text\" as const, text: event.delta }];\n return { ...state, parts };\n }\n case \"reasoning-delta\": {\n const last = state.parts[state.parts.length - 1];\n const parts =\n last && last.type === \"reasoning\"\n ? [...state.parts.slice(0, -1), { ...last, text: last.text + event.delta }]\n : [...state.parts, { type: \"reasoning\" as const, text: event.delta }];\n return { ...state, parts };\n }\n case \"tool-call-input-delta\":\n return {\n ...state,\n partialTools: {\n ...state.partialTools,\n [event.callId]: {\n callId: event.callId,\n name: event.name,\n partialInput: event.partialInput,\n ...(event.partialCard ? { partialCard: event.partialCard } : {}),\n ...(event.loading ? { loading: event.loading } : {}),\n },\n },\n };\n case \"tool-call\":\n return {\n ...state,\n pendingTools: {\n ...state.pendingTools,\n [event.callId]: {\n callId: event.callId,\n name: event.name,\n ...(event.loading ? { loading: event.loading } : {}),\n },\n },\n parts: [\n ...state.parts,\n { type: \"tool-call\", callId: event.callId, name: event.name, input: event.input, status: \"running\", ...(event.repaired ? { repaired: true } : {}) },\n ],\n };\n case \"awaiting-user\":\n return { ...state, status: \"awaiting-user\", pendingCard: event.card, cards: upsertCard(state.cards, event.card) };\n case \"user-responded\":\n // Record the answer ON the card. It is the only copy that outlives the\n // run: the renderer's local state dies when the turn commits and the card\n // re-mounts from history.\n return {\n ...state,\n status: \"running\",\n pendingCard: undefined,\n cards: state.cards.map((c) => (c.callId === event.callId ? { ...c, action: event.action } : c)),\n };\n case \"tool-result\": {\n const pendingTools = { ...state.pendingTools };\n delete pendingTools[event.callId];\n return {\n ...state,\n pendingTools,\n ...(state.partialTools?.[event.callId] ? { partialTools: without(state.partialTools, event.callId) } : {}),\n parts: [\n ...markCallDone(state.parts, event.callId, event.failure ? \"error\" : \"done\"),\n {\n type: \"tool-result\",\n callId: event.callId,\n name: event.name,\n output: event.output,\n ms: event.ms,\n ...(event.failure ? { failure: event.failure as never } : {}),\n },\n ],\n };\n }\n case \"card\":\n return { ...state, cards: upsertCard(state.cards, event.card) };\n case \"card-updated\":\n return {\n ...state,\n cards: state.cards.map((c) => (c.id === event.cardId ? { ...c, spec: event.spec } : c)),\n };\n case \"job-started\":\n return { ...state, job: { handle: event.handle, status: \"queued\" } };\n case \"job-status\":\n return { ...state, job: { handle: event.handle, status: event.status } };\n case \"message\":\n return { ...state, parts: [...state.parts, ...event.parts] };\n case \"metering\":\n // Metering is an observation event. The legacy `usage` event remains the\n // sole live accumulator so adding this event is backwards compatible and\n // cannot double-count a turn.\n return state;\n // ── usage: exactly one event accumulates ──────────────────────────────\n // runAgent reports a step's cost three times: `usage` (live), `step-finish`\n // (the same numbers again, for consumers that only watch step boundaries)\n // and `run-finish` (the running total). Adding all three counted every\n // turn 3×, which is not a rounding error — it read as context overflow on\n // a model whose window it had not come close to.\n case \"usage\":\n return { ...state, usage: mergeUsage(state.usage, event.usage) };\n case \"step-finish\":\n // Deliberately does NOT touch usage: the `usage` event above already\n // added this step. `steps` is owned by step-start.\n return state;\n case \"run-finish\":\n // A failed run stays failed: runAgent yields error → run-finish, and an\n // unconditional \"done\" here would mask the error from every consumer.\n // Cancellation maps to \"done\" — a user abort is an outcome, not a fault.\n return {\n ...state,\n status: event.finishReason === \"error\" ? \"error\" : \"done\",\n pendingTools: {},\n partialTools: {},\n finishReason: event.finishReason,\n // REPLACE, not merge. This is runAgent's own total across every step,\n // so it is the authoritative figure — and taking it wholesale also\n // repairs any drift for a consumer that fed the reducer a step-finish\n // without its paired usage event.\n usage: event.usage,\n steps: event.steps,\n };\n case \"error\":\n return {\n ...state,\n status: event.recoverable ? state.status : \"error\",\n ...(event.recoverable ? {} : { pendingTools: {}, partialTools: {} }),\n error: event.error,\n };\n default:\n return state;\n }\n}\n\nfunction without<T>(record: Record<string, T>, key: string): Record<string, T> {\n const next = { ...record };\n delete next[key];\n return next;\n}\n\nfunction upsertCard(cards: Card[], card: Card): Card[] {\n const i = cards.findIndex((c) => c.id === card.id);\n if (i === -1) return [...cards, card];\n const next = [...cards];\n // A revision replaces the content, not the place: the card stays in the slot\n // of the call that first drew it.\n // Nor its placement: an update that names none keeps the panel the card was opened in.\n const prev = cards[i]!;\n const home = prev.callId;\n const placement = card.placement ?? prev.placement;\n next[i] = { ...card, ...(home ? { callId: home } : {}), ...(placement ? { placement } : {}) };\n return next;\n}\n\nfunction markCallDone(parts: ContentPart[], callId: string, status: \"done\" | \"error\"): ContentPart[] {\n return parts.map((p) => (p.type === \"tool-call\" && p.callId === callId ? { ...p, status } : p));\n}\n","// Stop conditions.\n//\n// `maxSteps` alone is a blunt instrument: it either cuts a task short or lets a\n// looping agent burn eight steps re-reading the same file. These are the\n// composable predicates that let a host say what \"done\" actually means for its\n// domain.\n\nimport type { FinishReason, Usage } from \"../content/types.js\";\nimport type { ToolCallOutcome } from \"./execute-tools.js\";\n\nexport type StopContext = {\n step: number;\n finishReason: FinishReason;\n outcomes: readonly ToolCallOutcome[];\n usage: Usage;\n};\n\nexport type StopCondition = (ctx: StopContext) => boolean;\n\nexport const stepCountIs = (n: number): StopCondition => (ctx) => ctx.step >= n;\n\n/** Stop as soon as a specific tool has run — the \"one action then report\" shape. */\nexport const afterTool = (...names: string[]): StopCondition => (ctx) =>\n ctx.outcomes.some((o) => names.includes(o.name) && !o.failure);\n\n/** Stop when the model produced prose with no tool calls. The natural end. */\nexport const noToolCalls: StopCondition = (ctx) => ctx.finishReason !== \"tool-calls\" && ctx.outcomes.length === 0;\n\nexport const tokenBudgetExceeded = (maxTotal: number): StopCondition => (ctx) =>\n (ctx.usage.totalTokens ?? (ctx.usage.inputTokens ?? 0) + (ctx.usage.outputTokens ?? 0)) >= maxTotal;\n\n/**\n * Stop after `n` consecutive failing steps.\n *\n * The failure mode this catches: a tool that errors identically every time\n * (bad credential, missing config). The model will happily retry it until the\n * step cap, producing nothing but latency and spend.\n */\nexport const consecutiveFailures = (n: number): StopCondition => {\n let streak = 0;\n return (ctx) => {\n const allFailed = ctx.outcomes.length > 0 && ctx.outcomes.every((o) => o.failure);\n streak = allFailed ? streak + 1 : 0;\n return streak >= n;\n };\n};\n\n/** Stop when the user declined an interactive card — proceeding would ignore them. */\nexport const userDeclined: StopCondition = (ctx) =>\n ctx.outcomes.some(\n (o) => typeof o.output === \"object\" && o.output !== null && (o.output as { cancelled?: boolean }).cancelled === true,\n );\n\nexport function shouldStop(conditions: readonly StopCondition[] | undefined, ctx: StopContext): boolean {\n if (!conditions?.length) return false;\n return conditions.some((c) => c(ctx));\n}\n\n/** A sane default set for an interactive chat agent. */\nexport const DEFAULT_STOP_CONDITIONS: StopCondition[] = [consecutiveFailures(3), userDeclined];\n","// The agent loop.\n//\n// One async generator drives all three modes (stream / sync / background) so\n// there is exactly one place where \"call model → run tools → loop\" lives. The\n// modes differ only in HOW a step's result is obtained:\n//\n// stream — SSE, deltas surface immediately\n// sync — one request/response\n// background — provider-side job + polling; survives a closed tab\n//\n// Everything after that — tool dispatch, card suspension, stop conditions,\n// history append — is identical, which is the point.\n\nimport { assistantMessage, nextId } from \"../content/parts.js\";\nimport type { ContentPart, FinishReason, Message, Usage } from \"../content/types.js\";\nimport { stripCardPayload, type Card, type CardAction, type CardSpec } from \"../cards/types.js\";\nimport { makeCard } from \"../cards/registry.js\";\nimport type { ContextBuilder } from \"../context/builder.js\";\nimport { AgentError, toAgentError } from \"../errors.js\";\nimport type { GenerateResult, NormalizedRequest, Provider, StreamEvent } from \"../providers/types.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\nimport { resolvePartialCard, resolveToolLoading, type ToolDefinition, type ToolResolution } from \"../tools/types.js\";\nimport { PartialJsonParser } from \"../tools/partial-json.js\";\nimport { awaitJob } from \"./jobs.js\";\nimport { executeToolCalls, type ToolCallRequest } from \"./execute-tools.js\";\nimport { EventChannel } from \"./channel.js\";\nimport type { RunEvent, RunMode } from \"./events.js\";\nimport {\n combineMeteringSources,\n deliverMetering,\n usageSource,\n type MeterSink,\n type MeteringRecord,\n type MeteringSource,\n} from \"./metering.js\";\nimport { shouldStop, type StopCondition } from \"./stop.js\";\nimport { foldSurfaces, SurfaceLedger } from \"../surfaces/ledger.js\";\nimport { surfaceActionTools } from \"../surfaces/action-run.js\";\n\nexport type RunConfig = {\n provider: Provider;\n model: string;\n contextBuilder: ContextBuilder;\n tools: ToolRegistry;\n toolResolution: ToolResolution;\n mode?: RunMode;\n maxSteps?: number;\n stopWhen?: StopCondition[];\n vars?: Record<string, unknown>;\n temperature?: number;\n maxOutputTokens?: number;\n reasoning?: NormalizedRequest[\"reasoning\"];\n // Pass-throughs to NormalizedRequest — the adapter implements all of these;\n // without this block no runAgent caller could ever set them.\n toolChoice?: NormalizedRequest[\"toolChoice\"];\n /** Provider-hosted tools (web search, code interpreter), keyed by provider id. */\n providerTools?: NormalizedRequest[\"providerTools\"];\n responseFormat?: NormalizedRequest[\"responseFormat\"];\n topP?: number;\n stopSequences?: string[];\n /** Provider-side conversation storage opt-out (OpenAI `store`). */\n store?: boolean;\n metadata?: Record<string, string>;\n /** Usage delivery target. Pricing and persistence belong to the host. */\n meter?: MeterSink;\n /** Host-only dimensions copied onto metering records, never sent upstream. */\n meteringMetadata?: Readonly<Record<string, string>>;\n /** The per-provider escape hatch, keyed by provider id. */\n providerOptions?: NormalizedRequest[\"providerOptions\"];\n toolTimeoutMs?: number;\n signal?: AbortSignal;\n /**\n * Resolve an interactive card. The host shows it and returns the user's\n * answer. Absent means interactive cards auto-decline rather than hang.\n */\n onUserDecision?: (callId: string, card: Card) => Promise<CardAction>;\n /** Execute a tool that has no `execute` (browser-side capabilities). */\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /** Persist a background job handle so a reload can resume it. */\n onJobHandle?: (handle: NonNullable<GenerateResult[\"responseId\"]> extends string ? unknown : never) => void;\n /** Skills the user pinned in the UI. */\n forceSkillIds?: string[];\n /**\n * Chain via the provider's stored response instead of resending history.\n * Only used when the provider supports it; cuts input tokens dramatically on\n * long tool loops.\n */\n useServerHistory?: boolean;\n /**\n * The working copy of this conversation's surfaces. A client passes one so\n * edits the person makes mid-run are visible to `readSurface`; without it the\n * run derives its own from `messages`.\n */\n surfaces?: SurfaceLedger;\n};\n\nexport async function* runAgent(\n messages: readonly Message[],\n config: RunConfig,\n): AsyncGenerator<RunEvent, void, unknown> {\n const runId = nextId(\"run\");\n const mode = config.mode ?? \"stream\";\n const maxSteps = config.maxSteps ?? 8;\n const vars = config.vars ?? {};\n const runStartedAt = Date.now();\n const surfaces = config.surfaces ?? new SurfaceLedger(foldSurfaces(messages));\n\n yield { type: \"run-start\", runId, mode };\n\n // Mutable accumulators: `.push()`, not `[...arr, x]` — this loop runs once\n // per step of a potentially long tool-calling turn, and re-copying the\n // whole array every step is wasted work on a long thread. Neither array is\n // returned or exposed outside this generator (see the yields below), so\n // there is no reference-equality contract to preserve.\n const history: Message[] = [...messages];\n let totalUsage: Usage = {};\n let finishReason: FinishReason = \"unknown\";\n let step = 0;\n let attemptedSteps = 0;\n let previousResponseId: string | undefined;\n const meteringSources: MeteringSource[] = [];\n const reportedModels = new Set<string>();\n\n try {\n // ── context, built once per run ────────────────────────────────────────\n // Rebuilding per step would let skills flap in and out mid-turn and would\n // break the cacheable prompt prefix. Tool RESULTS extend history within the\n // loop; the instruction block stays fixed.\n const baseTools = config.tools.resolve(config.toolResolution);\n const context = await config.contextBuilder.build({\n messages: history,\n vars,\n forceSkillIds: config.forceSkillIds,\n baseTools: baseTools.map((t) => t.name),\n signal: config.signal,\n });\n\n yield { type: \"context-built\", trace: context.trace, system: context.system, toolNames: context.toolNames };\n\n // Skills may have unlocked tools beyond the base presets. `let`, not\n // `const`: a loadSkill outcome can unlock more mid-run (see below).\n let unlockedNames = [...context.toolNames];\n let activeTools = config.tools.resolve({ ...config.toolResolution, allow: unlockedNames });\n let specs = config.tools.toSpecs(activeTools);\n\n const working: Message[] = [...context.messages];\n\n while (step < maxSteps) {\n if (config.signal?.aborted) throw new AgentError(\"cancelled\", \"Run was cancelled.\");\n yield { type: \"step-start\", step };\n attemptedSteps += 1;\n const stepStartedAt = Date.now();\n\n const request: NormalizedRequest = {\n model: config.model,\n system: context.system,\n messages: working,\n ...(specs.length ? { tools: specs } : {}),\n ...(config.providerTools ? { providerTools: config.providerTools } : {}),\n ...(config.toolChoice ? { toolChoice: config.toolChoice } : {}),\n ...(config.temperature != null ? { temperature: config.temperature } : {}),\n ...(config.topP != null ? { topP: config.topP } : {}),\n ...(config.maxOutputTokens != null ? { maxOutputTokens: config.maxOutputTokens } : {}),\n ...(config.stopSequences?.length ? { stopSequences: config.stopSequences } : {}),\n ...(config.responseFormat ? { responseFormat: config.responseFormat } : {}),\n ...(config.store != null ? { store: config.store } : {}),\n ...(config.metadata ? { metadata: config.metadata } : {}),\n ...(config.providerOptions ? { providerOptions: config.providerOptions } : {}),\n ...(config.reasoning ? { reasoning: config.reasoning } : {}),\n ...(config.useServerHistory && previousResponseId && config.provider.capabilities.serverSideHistory\n ? { previousResponseId }\n : {}),\n };\n\n // ── obtain this step's result ────────────────────────────────────────\n let parts: ContentPart[] = [];\n let stepFinish: FinishReason = \"unknown\";\n let stepUsage: Usage | undefined;\n let responseId: string | undefined;\n let reportedModel: string | undefined;\n let streamSnapshot: (() => GenerateResult) | undefined;\n\n try {\n if (mode === \"stream\" && config.provider.capabilities.streaming) {\n const collected = collectStream(config.provider.stream(request, { signal: config.signal }));\n streamSnapshot = collected.result;\n // Arguments still being written, per call. Parsed incrementally, and\n // forwarded only when the parse visibly changed: whitespace, a key's\n // characters or an unfinished number are not worth a re-render.\n const writing = new Map<string, { name: string; tool?: ToolDefinition; parser: PartialJsonParser; seen: number }>();\n for await (const event of collected.events()) {\n if (event.type === \"text-delta\") yield { type: \"text-delta\", delta: event.delta };\n else if (event.type === \"reasoning-delta\") yield { type: \"reasoning-delta\", delta: event.delta };\n else if (event.type === \"tool-call-start\") {\n const tool = activeTools.find((t) => t.name === event.name);\n writing.set(event.callId, { name: event.name, tool, parser: new PartialJsonParser(), seen: 0 });\n } else if (event.type === \"tool-call-delta\") {\n const call = writing.get(event.callId);\n if (!call) continue;\n call.parser.push(event.argsDelta);\n if (call.parser.version === call.seen) continue;\n call.seen = call.parser.version;\n const partialInput = call.parser.snapshot();\n if (partialInput === undefined) continue;\n const partialCard = resolvePartialCard(call.tool, partialInput);\n const loading = resolveToolLoading(call.tool?.loading, partialInput);\n yield {\n type: \"tool-call-input-delta\",\n callId: event.callId,\n name: call.name,\n partialInput,\n ...(partialCard ? { partialCard } : {}),\n ...(loading ? { loading } : {}),\n };\n } else if (event.type === \"error\") throw toAgentError(event.error, config.provider.id);\n }\n const done = collected.result();\n parts = done.parts;\n stepFinish = done.finishReason;\n stepUsage = done.usage;\n responseId = done.responseId;\n reportedModel = done.modelId || undefined;\n } else if (mode === \"background\") {\n if (!config.provider.startJob || !config.provider.capabilities.backgroundJobs) {\n throw new AgentError(\n \"not-supported\",\n `Provider \"${config.provider.id}\" has no background mode. Use mode \"stream\" or \"sync\".`,\n );\n }\n const handle = await config.provider.startJob({ ...request, background: true }, { signal: config.signal });\n reportedModel = handle.model || undefined;\n responseId = handle.id;\n yield { type: \"job-started\", handle };\n\n // Polling, not streaming: the entire value of background mode is that it\n // survives a dropped connection, and a stream does not.\n const snapshot = await awaitJob(config.provider, handle, { signal: config.signal });\n yield { type: \"job-status\", handle, status: snapshot.status };\n\n if (snapshot.status === \"cancelled\") {\n throw new AgentError(\"cancelled\", snapshot.error?.message ?? \"Background job was cancelled.\", {\n provider: config.provider.id,\n });\n }\n if (snapshot.status === \"failed\" || !snapshot.result) {\n throw new AgentError(\"unknown\", snapshot.error?.message ?? `Background job ended as ${snapshot.status}.`, {\n provider: config.provider.id,\n });\n }\n parts = snapshot.result.parts;\n stepFinish = snapshot.result.finishReason;\n stepUsage = snapshot.result.usage;\n responseId = snapshot.result.responseId ?? responseId;\n reportedModel = snapshot.result.modelId || reportedModel;\n // Deltas never streamed, so surface the text as one block.\n const textParts = parts.filter((p) => p.type === \"text\");\n if (textParts.length) yield { type: \"message\", parts: textParts };\n } else {\n const result = await config.provider.generate(request, { signal: config.signal });\n parts = result.parts;\n stepFinish = result.finishReason;\n stepUsage = result.usage;\n responseId = result.responseId;\n reportedModel = result.modelId || undefined;\n const textParts = parts.filter((p) => p.type === \"text\");\n if (textParts.length) yield { type: \"message\", parts: textParts };\n }\n } catch (cause) {\n const error = toAgentError(cause, config.provider.id);\n const partial = streamSnapshot?.();\n stepUsage = partial?.usage ?? stepUsage ?? {};\n responseId = partial?.responseId ?? responseId;\n reportedModel = partial?.modelId || reportedModel;\n const source = usageSource(stepUsage);\n meteringSources.push(source);\n if (reportedModel) reportedModels.add(reportedModel);\n if (source !== \"unavailable\") {\n totalUsage = addUsage(totalUsage, stepUsage);\n yield { type: \"usage\", usage: stepUsage };\n }\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"step\",\n id: `${runId}:step:${step}`,\n runId,\n step,\n provider: config.provider.id,\n requestedModel: config.model,\n ...(reportedModel ? { reportedModel } : {}),\n mode,\n status: error.kind === \"cancelled\" ? \"cancelled\" : \"failed\",\n usage: stepUsage,\n source,\n startedAt: stepStartedAt,\n finishedAt,\n durationMs: finishedAt - stepStartedAt,\n ...(responseId ? { responseId } : {}),\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n error: { kind: error.kind, message: error.message },\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n throw error;\n }\n\n previousResponseId = responseId;\n if (stepUsage) {\n totalUsage = addUsage(totalUsage, stepUsage);\n yield { type: \"usage\", usage: stepUsage };\n }\n const source = usageSource(stepUsage ?? {});\n meteringSources.push(source);\n if (reportedModel) reportedModels.add(reportedModel);\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"step\",\n id: `${runId}:step:${step}`,\n runId,\n step,\n provider: config.provider.id,\n requestedModel: config.model,\n ...(reportedModel ? { reportedModel } : {}),\n mode,\n status: meteringStatus(stepFinish),\n usage: stepUsage ?? {},\n source,\n startedAt: stepStartedAt,\n finishedAt,\n durationMs: finishedAt - stepStartedAt,\n ...(responseId ? { responseId } : {}),\n finishReason: stepFinish,\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"step-finish\", step, finishReason: stepFinish, ...(stepUsage ? { usage: stepUsage } : {}) };\n\n const assistant = assistantMessage(parts);\n working.push(assistant);\n history.push(assistant);\n\n const calls: ToolCallRequest[] = parts\n .filter((p): p is Extract<ContentPart, { type: \"tool-call\" }> => p.type === \"tool-call\")\n .map((p) => ({ callId: p.callId, name: p.name, input: p.input }));\n\n if (!calls.length) {\n finishReason = stepFinish;\n break;\n }\n\n for (const call of calls) {\n const source = parts.find((p) => p.type === \"tool-call\" && p.callId === call.callId) as\n | Extract<ContentPart, { type: \"tool-call\" }>\n | undefined;\n const loading = resolveToolLoading(config.tools.get(call.name)?.loading, call.input);\n yield {\n type: \"tool-call\",\n callId: call.callId,\n name: call.name,\n input: call.input,\n ...(source?.repaired ? { repaired: true } : {}),\n ...(loading ? { loading } : {}),\n };\n }\n\n // ── run tools ────────────────────────────────────────────────────────\n // Tool execution is a plain async call and cannot yield into this loop, so\n // it pushes into a channel that we drain CONCURRENTLY. Draining afterwards\n // would deadlock the human-in-the-loop path: the tool waits on the user,\n // the user waits to see the card, and the card waits on the tool.\n //\n // Results go through the same channel, in COMPLETION order: yielding them\n // after `await running` made every result in a step land together, when\n // the slowest tool finished. History below stays in CALL order.\n const channel = new EventChannel<RunEvent>();\n const running = executeToolCalls(calls, {\n tools: activeTools,\n vars,\n signal: config.signal,\n timeoutMs: config.toolTimeoutMs,\n surfaces,\n surfaceActionTools: surfaceActionTools(config.tools, config.toolResolution).map((t) => t.name),\n onCard: (card) => channel.push({ type: \"card\", card }),\n onOutcome: (outcome) =>\n channel.push({\n type: \"tool-result\",\n callId: outcome.callId,\n name: outcome.name,\n output: outcome.output,\n ...(outcome.failure ? { failure: outcome.failure } : {}),\n ms: outcome.ms,\n }),\n onHostTool: config.onHostTool,\n requestCard: config.onUserDecision\n ? async (callId, spec: CardSpec) => {\n const card = makeCard(spec, callId);\n channel.push({ type: \"awaiting-user\", callId, card });\n const action = await config.onUserDecision!(callId, card);\n channel.push({ type: \"user-responded\", callId, action });\n return action.type === \"cancel\" || action.type === \"dismiss\"\n ? { cancelled: true, reason: \"The user declined.\" }\n : (action.value ?? { confirmed: true });\n }\n : undefined,\n }).finally(() => channel.close());\n\n for await (const event of channel) yield event;\n const outcomes = await running;\n\n // Two versions of each tool result, deliberately:\n // • the EVENT (already sent via `onOutcome`) carries the full output,\n // card payload included, so the UI can render it and the host can\n // persist it;\n // • the message fed back to the provider has the card stripped. The\n // model already read the surrounding data, and re-sending a chart\n // spec on every subsequent step of the same turn is pure waste.\n // No events here: every card and every result already went out through\n // the channel. Re-yielding would double-count in any host recording the\n // stream.\n const providerParts: ContentPart[] = [];\n const persistedParts: ContentPart[] = [];\n for (const outcome of outcomes) {\n const base = {\n type: \"tool-result\" as const,\n callId: outcome.callId,\n name: outcome.name,\n ...(outcome.failure ? { failure: outcome.failure as never } : {}),\n };\n providerParts.push({ ...base, output: stripCardPayload(outcome.output) });\n persistedParts.push({ ...base, output: outcome.output });\n }\n\n const createdAt = Date.now();\n const toolId = nextId(\"tool\");\n working.push({ id: toolId, role: \"tool\", parts: providerParts, createdAt });\n history.push({ id: toolId, role: \"tool\", parts: persistedParts, createdAt });\n\n // loadSkill's pull half: an outcome that unlocked tools re-resolves the\n // active set so the names it announced are callable from the NEXT step.\n // This does change the declared tool block mid-run — accepted: a cache\n // miss on the remaining steps beats advertising tools that 404.\n const unlocked = outcomes.flatMap((o) => o.unlockTools ?? []).filter((n) => !unlockedNames.includes(n));\n if (unlocked.length) {\n unlockedNames = [...unlockedNames, ...unlocked];\n activeTools = config.tools.resolve({ ...config.toolResolution, allow: unlockedNames });\n specs = config.tools.toSpecs(activeTools);\n }\n\n step += 1;\n finishReason = stepFinish;\n\n const stop = shouldStop(config.stopWhen, { step, finishReason: stepFinish, outcomes, usage: totalUsage });\n if (stop) {\n finishReason = \"stop\";\n break;\n }\n }\n\n // Hitting the cap with the model still wanting to act means the answer is\n // truncated. Saying so is better than presenting half a task as finished.\n if (step >= maxSteps && finishReason === \"tool-calls\") {\n yield {\n type: \"message\",\n parts: [\n {\n type: \"text\",\n text: `\\n\\n_(Reached the ${maxSteps}-step limit while still working — this may be incomplete. Ask me to continue.)_`,\n },\n ],\n };\n }\n\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"run\",\n id: `${runId}:run`,\n runId,\n provider: config.provider.id,\n requestedModel: config.model,\n mode,\n status: meteringStatus(finishReason),\n usage: totalUsage,\n source: combineMeteringSources(meteringSources),\n startedAt: runStartedAt,\n finishedAt,\n durationMs: finishedAt - runStartedAt,\n steps: attemptedSteps,\n finishReason,\n ...(reportedModels.size ? { reportedModels: [...reportedModels] } : {}),\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"run-finish\", runId, finishReason, usage: totalUsage, steps: attemptedSteps };\n } catch (e) {\n const error = toAgentError(e, config.provider.id);\n yield { type: \"error\", error, recoverable: false };\n const terminalReason: FinishReason = error.kind === \"cancelled\" ? \"cancelled\" : \"error\";\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"run\",\n id: `${runId}:run`,\n runId,\n provider: config.provider.id,\n requestedModel: config.model,\n mode,\n status: error.kind === \"cancelled\" ? \"cancelled\" : \"failed\",\n usage: totalUsage,\n source: combineMeteringSources(meteringSources),\n startedAt: runStartedAt,\n finishedAt,\n durationMs: finishedAt - runStartedAt,\n steps: attemptedSteps,\n finishReason: terminalReason,\n ...(reportedModels.size ? { reportedModels: [...reportedModels] } : {}),\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n error: { kind: error.kind, message: error.message },\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"run-finish\", runId, finishReason: terminalReason, usage: totalUsage, steps: attemptedSteps };\n }\n}\n\n/**\n * Tee a provider stream: forward deltas for live rendering while accumulating\n * the parts that become the assistant message.\n *\n * Necessary because the loop needs BOTH — the UI wants tokens as they arrive,\n * and the next step needs a complete, well-formed message.\n */\nfunction collectStream(stream: AsyncIterable<StreamEvent>) {\n const parts: ContentPart[] = [];\n let finishReason: FinishReason = \"unknown\";\n let usage: Usage | undefined;\n let responseId: string | undefined;\n let modelId = \"\";\n\n async function* events(): AsyncGenerator<StreamEvent> {\n for await (const event of stream) {\n switch (event.type) {\n case \"start\":\n responseId = event.responseId;\n modelId = event.modelId;\n break;\n case \"text-delta\": {\n const last = parts[parts.length - 1];\n if (last?.type === \"text\") last.text += event.delta;\n else parts.push({ type: \"text\", text: event.delta });\n break;\n }\n case \"reasoning-delta\": {\n const last = parts[parts.length - 1];\n if (last?.type === \"reasoning\") {\n last.text += event.delta;\n // Anthropic's replay token (signature_delta) arrives at the END of\n // a thinking block — stamp it onto the accumulated part, or replay\n // never works in stream mode.\n if (event.signature) last.signature = event.signature;\n } else {\n parts.push({ type: \"reasoning\", text: event.delta, ...(event.signature ? { signature: event.signature } : {}) });\n }\n break;\n }\n case \"tool-call-end\":\n parts.push({\n type: \"tool-call\",\n callId: event.callId,\n name: event.name,\n input: event.input,\n status: \"pending\",\n ...(event.repaired ? { repaired: true } : {}),\n });\n break;\n case \"usage\":\n usage = event.usage;\n break;\n case \"finish\":\n finishReason = event.finishReason;\n if (event.usage) usage = event.usage;\n if (event.responseId) responseId = event.responseId;\n break;\n default:\n break;\n }\n yield event;\n }\n }\n\n return {\n events,\n result: (): GenerateResult => ({\n parts,\n finishReason,\n usage: usage ?? {},\n modelId,\n ...(responseId ? { responseId } : {}),\n }),\n };\n}\n\nfunction addUsage(a: Usage, b: Usage): Usage {\n const add = (x?: number, y?: number) => (x == null && y == null ? undefined : (x ?? 0) + (y ?? 0));\n return {\n inputTokens: add(a.inputTokens, b.inputTokens),\n outputTokens: add(a.outputTokens, b.outputTokens),\n totalTokens: add(a.totalTokens, b.totalTokens),\n cachedInputTokens: add(a.cachedInputTokens, b.cachedInputTokens),\n reasoningTokens: add(a.reasoningTokens, b.reasoningTokens),\n };\n}\n\nfunction meteringStatus(reason: FinishReason): \"completed\" | \"failed\" | \"cancelled\" {\n if (reason === \"cancelled\") return \"cancelled\";\n if (reason === \"error\") return \"failed\";\n return \"completed\";\n}\n","// Uploaded-file persistence.\n//\n// A providerFile id is only worth minting if it OUTLIVES the page — the whole\n// point of uploading once is not re-encoding the same bytes as base64 on every\n// turn. Messages that reference a file persist through the ThreadStore; this\n// store is the cross-thread registry that answers \"what have I already\n// uploaded\", so a host can offer re-attach instead of re-upload.\n//\n// Mirrors JobStore deliberately: same shape, same defensiveness. A corrupted\n// entry degrades to \"upload again\", never a crash.\n\nimport type { ProviderFileRef } from \"../providers/types.js\";\n\nexport type StoredFile = {\n ref: ProviderFileRef;\n filename: string;\n mediaType?: string;\n sizeBytes?: number;\n /** Thread the file was first attached in, if any. */\n threadId?: string;\n createdAt: number;\n};\n\nexport type FileStore = {\n list(): Promise<StoredFile[]>;\n /** Keyed by `ref.id`. */\n get(id: string): Promise<StoredFile | undefined>;\n put(file: StoredFile): Promise<void>;\n remove(id: string): Promise<void>;\n};\n\nexport function createMemoryFileStore(): FileStore {\n const files = new Map<string, StoredFile>();\n return {\n async list() {\n return [...files.values()].sort((a, b) => b.createdAt - a.createdAt);\n },\n async get(id) {\n return files.get(id);\n },\n async put(file) {\n files.set(file.ref.id, file);\n },\n async remove(id) {\n files.delete(id);\n },\n };\n}\n\n/** localStorage-backed store. Every read is defensive — see JobStore. */\nexport function createLocalFileStore(key = \"superchat:files\"): FileStore {\n const read = (): Record<string, StoredFile> => {\n try {\n const raw = globalThis.localStorage?.getItem(key) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : {};\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, StoredFile>) : {};\n } catch {\n return {};\n }\n };\n const write = (all: Record<string, StoredFile>) => {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(all));\n } catch {\n // Quota or private mode — a lost ref degrades to \"upload again\", not a crash.\n }\n };\n\n return {\n async list() {\n return Object.values(read()).sort((a, b) => b.createdAt - a.createdAt);\n },\n async get(id) {\n return read()[id];\n },\n async put(file) {\n const all = read();\n all[file.ref.id] = file;\n write(all);\n },\n async remove(id) {\n const all = read();\n delete all[id];\n write(all);\n },\n };\n}\n","// Thread persistence.\n//\n// Snapshot-per-thread, not event sourcing: the client folds a finished run into\n// messages at exactly one point, which makes \"after that fold\" a natural save\n// point, and a snapshot needs no replay machinery to load. Hosts that want an\n// event log can record `RunEvent`s through `reduceRunEvent` themselves — the\n// seam exists; this module just doesn't require it.\n//\n// What is deliberately NOT persisted: compaction summaries and any other\n// derived context. Context is derived, never accumulated — persisting it would\n// freeze one turn's derivation into every later turn.\n//\n// Three implementations ship: memory, localStorage, and REST\n// (`createRestThreadStore`) — the last one so \"bring your own backend\" is a\n// config line rather than an exercise, and so the interface is proven against\n// something that isn't synchronous key-value storage.\n\nimport { linkLinear } from \"../content/branching.js\";\nimport type { Message } from \"../content/types.js\";\n\nexport type ThreadMeta = {\n id: string;\n /** Derived at save time from the first user message; never model-generated. */\n title?: string;\n createdAt: number;\n updatedAt: number;\n messageCount: number;\n};\n\nexport const THREAD_SCHEMA_VERSION = 2 as const;\n\nexport type StoredThread = {\n version: typeof THREAD_SCHEMA_VERSION;\n meta: ThreadMeta;\n /** The full message TREE (flat, parentId pointers) — abandoned branches included. */\n messages: Message[];\n /** Leaf of the active branch. Absent → the last message (v1-era linearity). */\n headId?: string | null;\n};\n\n/**\n * v1 stored threads (linear, no parent pointers) migrate on read: the list is\n * linked into a chain and the head is the last message. Never thrown away —\n * a stored conversation outliving a schema bump is the whole point of the\n * version field.\n */\nfunction migrate(parsed: { version?: number; meta?: ThreadMeta; messages?: Message[]; headId?: string | null }): StoredThread | undefined {\n if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta) return undefined;\n if (parsed.version === THREAD_SCHEMA_VERSION) return parsed as StoredThread;\n if (parsed.version === 1) {\n const messages = linkLinear(parsed.messages);\n return {\n version: THREAD_SCHEMA_VERSION,\n meta: parsed.meta,\n messages,\n headId: messages.at(-1)?.id ?? null,\n };\n }\n return undefined; // a FUTURE version reads as absent, never a crash\n}\n\nexport type ThreadStore = {\n /** Metadata only — a thread picker must not load every message ever sent. */\n list(): Promise<ThreadMeta[]>;\n load(id: string): Promise<StoredThread | undefined>;\n save(thread: StoredThread): Promise<void>;\n remove(id: string): Promise<void>;\n};\n\nconst TITLE_MAX = 64;\n\nfunction deriveTitle(messages: readonly Message[]): string | undefined {\n for (const m of messages) {\n if (m.role !== \"user\") continue;\n for (const p of m.parts) {\n if (p.type === \"text\" && p.text.trim()) {\n const line = p.text.trim().split(\"\\n\", 1)[0]!;\n return line.length > TITLE_MAX ? `${line.slice(0, TITLE_MAX - 1)}…` : line;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Deep-clone through JSON, per message.\n *\n * Tool inputs/outputs and artifact data are `unknown` — a host's execute can\n * return a Date, a Map, or something circular. The round-trip normalizes what\n * JSON can carry and a per-message fallback replaces what it can't, because\n * persistence must never take down a run.\n */\nfunction safeCloneMessages(messages: readonly Message[]): Message[] {\n try {\n return JSON.parse(JSON.stringify(messages)) as Message[];\n } catch {\n return messages.map((m) => {\n try {\n return JSON.parse(JSON.stringify(m)) as Message;\n } catch {\n return {\n id: m.id,\n role: m.role,\n parts: [{ type: \"text\", text: \"[unserializable message dropped]\" }],\n ...(m.createdAt != null ? { createdAt: m.createdAt } : {}),\n };\n }\n });\n }\n}\n\n/** Build a JSON-safe snapshot: safe-clone, derive title, stamp meta. */\nexport function threadSnapshot(\n id: string,\n messages: readonly Message[],\n prior?: ThreadMeta,\n headId?: string | null,\n): StoredThread {\n const cloned = safeCloneMessages(messages);\n const title = deriveTitle(cloned) ?? prior?.title;\n return {\n version: THREAD_SCHEMA_VERSION,\n meta: {\n id,\n ...(title ? { title } : {}),\n createdAt: prior?.createdAt ?? Date.now(),\n updatedAt: Date.now(),\n messageCount: cloned.length,\n },\n messages: cloned,\n headId: headId !== undefined ? headId : (cloned.at(-1)?.id ?? null),\n };\n}\n\nexport function createMemoryThreadStore(): ThreadStore {\n const threads = new Map<string, StoredThread>();\n return {\n async list() {\n return [...threads.values()].map((t) => t.meta).sort((a, b) => b.updatedAt - a.updatedAt);\n },\n async load(id) {\n const t = threads.get(id);\n return t ? migrate(t) : undefined;\n },\n async save(thread) {\n threads.set(thread.meta.id, thread);\n },\n async remove(id) {\n threads.delete(id);\n },\n };\n}\n\n/**\n * localStorage-backed store, key per thread: `{prefix}:index` holds the meta\n * list, `{prefix}:{id}` holds one thread. One growing thread must not rewrite\n * every other thread on each save (the job store's single-blob layout is fine\n * for handles; it is wrong for conversations).\n *\n * Every read is defensive — a corrupted entry reads as absent, never a throw.\n * A version other than the current one also reads as absent: v2 migrates\n * deliberately, it does not crash v1 readers.\n */\nexport function createLocalThreadStore(prefix = \"superchat:threads\"): ThreadStore {\n const indexKey = `${prefix}:index`;\n const threadKey = (id: string) => `${prefix}:${id}`;\n\n const readIndex = (): ThreadMeta[] => {\n try {\n const raw = globalThis.localStorage?.getItem(indexKey) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : [];\n return Array.isArray(parsed) ? (parsed as ThreadMeta[]).filter((m) => typeof m?.id === \"string\") : [];\n } catch {\n return [];\n }\n };\n const writeIndex = (metas: ThreadMeta[]): void => {\n try {\n globalThis.localStorage?.setItem(indexKey, JSON.stringify(metas));\n } catch {\n // Quota or private mode — the thread entries themselves may still exist;\n // a stale index degrades to an incomplete picker, not a crash.\n }\n };\n\n return {\n async list() {\n return readIndex().sort((a, b) => b.updatedAt - a.updatedAt);\n },\n\n async load(id) {\n try {\n const raw = globalThis.localStorage?.getItem(threadKey(id)) ?? null;\n if (!raw) return undefined;\n return migrate(JSON.parse(raw) as StoredThread);\n } catch {\n return undefined;\n }\n },\n\n async save(thread) {\n const store = globalThis.localStorage;\n if (!store) return;\n const key = threadKey(thread.meta.id);\n let payload = thread;\n try {\n store.setItem(key, JSON.stringify(payload));\n } catch {\n // Quota. Shed the heaviest cargo — artifact payloads (card specs,\n // chart data) — and mark them expired so the UI says \"this result\n // expired, ask again\" instead of rendering an empty shell. One retry;\n // if that also fails, the previous snapshot stays.\n payload = { ...thread, messages: expireArtifacts(thread.messages) };\n try {\n store.setItem(key, JSON.stringify(payload));\n } catch {\n return;\n }\n }\n const index = readIndex().filter((m) => m.id !== thread.meta.id);\n index.push(payload.meta);\n writeIndex(index);\n },\n\n async remove(id) {\n try {\n globalThis.localStorage?.removeItem(threadKey(id));\n } catch {\n // removeItem does not throw for quota; being defensive costs nothing.\n }\n writeIndex(readIndex().filter((m) => m.id !== id));\n },\n };\n}\n\nexport type RestThreadStoreConfig = {\n /** Base path of your thread API, e.g. \"/api/threads\". */\n url: string;\n /** Extra headers (auth, CSRF). A function is called per request. */\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);\n credentials?: RequestCredentials;\n fetchImpl?: typeof fetch;\n /**\n * Called when a request fails. Default: swallow. Persistence is\n * fire-and-forget at the call site, so a thrown error would surface as an\n * unhandled rejection rather than anything a user can act on — but a host\n * that wants telemetry needs the hook.\n */\n onError?: (error: unknown, op: \"list\" | \"load\" | \"save\" | \"remove\") => void;\n};\n\n/**\n * REST-backed store — the \"bring your own backend\" implementation.\n *\n * The wire contract, four calls:\n * GET {url} → ThreadMeta[]\n * GET {url}/{id} → StoredThread (404 = absent, not an error)\n * PUT {url}/{id} ← StoredThread\n * DELETE {url}/{id}\n *\n * Reads stay defensive in the same way the localStorage store is: a failed or\n * malformed response degrades to \"not found\" / \"empty list\" rather than\n * throwing into a render or a run. Records still go through `migrate`, so a\n * server that stored v1 payloads keeps working.\n */\nexport function createRestThreadStore(config: RestThreadStoreConfig): ThreadStore {\n const doFetch = config.fetchImpl ?? globalThis.fetch;\n const base = config.url.replace(/\\/$/, \"\");\n const path = (id: string) => `${base}/${encodeURIComponent(id)}`;\n\n const headers = async (): Promise<Record<string, string>> =>\n typeof config.headers === \"function\" ? await config.headers() : (config.headers ?? {});\n\n const request = async (input: string, init: RequestInit, op: \"list\" | \"load\" | \"save\" | \"remove\"): Promise<Response | undefined> => {\n try {\n const res = await doFetch(input, {\n ...init,\n headers: { ...(init.body ? { \"content-type\": \"application/json\" } : {}), ...(await headers()), ...init.headers },\n credentials: config.credentials ?? \"same-origin\",\n });\n // 404 on load is a legitimate \"no such thread\", not a failure.\n if (!res.ok && !(op === \"load\" && res.status === 404)) {\n config.onError?.(new Error(`Thread store ${op} failed: ${res.status}`), op);\n return undefined;\n }\n return res;\n } catch (e) {\n config.onError?.(e, op);\n return undefined;\n }\n };\n\n return {\n async list() {\n const res = await request(base, { method: \"GET\" }, \"list\");\n if (!res) return [];\n try {\n const parsed = (await res.json()) as unknown;\n return Array.isArray(parsed)\n ? (parsed as ThreadMeta[]).filter((m) => typeof m?.id === \"string\").sort((a, b) => b.updatedAt - a.updatedAt)\n : [];\n } catch (e) {\n config.onError?.(e, \"list\");\n return [];\n }\n },\n\n async load(id) {\n const res = await request(path(id), { method: \"GET\" }, \"load\");\n if (!res || res.status === 404) return undefined;\n try {\n return migrate((await res.json()) as StoredThread);\n } catch (e) {\n config.onError?.(e, \"load\");\n return undefined;\n }\n },\n\n async save(thread) {\n await request(path(thread.meta.id), { method: \"PUT\", body: JSON.stringify(thread) }, \"save\");\n },\n\n async remove(id) {\n await request(path(id), { method: \"DELETE\" }, \"remove\");\n },\n };\n}\n\n/** Replace every artifact part's data with an expired stub. */\nfunction expireArtifacts(messages: readonly Message[]): Message[] {\n return messages.map((m) => ({\n ...m,\n parts: m.parts.map((p) =>\n p.type === \"artifact\"\n ? { ...p, data: { kind: (p.data as { kind?: string } | null)?.kind ?? p.kind, expired: true } }\n : p,\n ),\n }));\n}\n","// Persistent cross-thread memory.\n//\n// The seam, not a database: `MemoryStore` is four async methods a host backs\n// with anything (localStorage here, a row per user in production), and the two\n// halves that plug it into the machinery that already exists —\n//\n// READ → `createMemorySource()` a ContextSource injecting remembered facts\n// as a \"memory\" layer, under the same token budget and trace as\n// every other layer (\"why does the model know that\" stays answerable);\n// WRITE → `createRememberTool()` a tool the model calls to save, update or\n// forget a fact — memory the USER can see forming, not a hidden\n// profile.\n//\n// Deliberately NOT persisted: conversation history (that is the ThreadStore's\n// job) or derived context. Memory is small, structured, and cross-thread:\n// preferences, standing facts, corrections.\n\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { ContextSource } from \"../context/types.js\";\nimport type { ToolDefinition } from \"../tools/types.js\";\n\nexport type MemoryEntry = {\n /** Stable slug (\"preferred-language\"), so a fact updates instead of duplicating. */\n key: string;\n value: string;\n updatedAt: number;\n};\n\nexport type MemoryStore = {\n /** `vars` carries host scoping (user id, workspace) — the store decides what it means. */\n list(vars?: Record<string, unknown>): Promise<MemoryEntry[]>;\n set(key: string, value: string, vars?: Record<string, unknown>): Promise<void>;\n remove(key: string, vars?: Record<string, unknown>): Promise<void>;\n};\n\n/**\n * Total facts a store keeps before it starts evicting. Distinct from\n * `MemorySourceOptions.maxEntries` (below), which caps how many of the\n * stored facts are injected into a single turn's context — this cap bounds\n * the store itself so it doesn't grow forever.\n */\nconst DEFAULT_STORE_CAP = 500;\n\n/** Most-recently-updated first, so a cap-and-slice keeps the freshest facts. */\nfunction byRecency(a: MemoryEntry, b: MemoryEntry): number {\n return b.updatedAt - a.updatedAt;\n}\n\nexport function createMemoryMemoryStore(opts: { maxEntries?: number } = {}): MemoryStore {\n const cap = opts.maxEntries ?? DEFAULT_STORE_CAP;\n const entries = new Map<string, MemoryEntry>();\n return {\n async list() {\n return [...entries.values()].sort(byRecency);\n },\n async set(key, value) {\n entries.set(key, { key, value, updatedAt: Date.now() });\n if (entries.size > cap) {\n // Evict oldest-by-updatedAt beyond the cap, at write time — a store\n // that only trims at read time never actually shrinks.\n const overflow = [...entries.values()].sort(byRecency).slice(cap);\n for (const e of overflow) entries.delete(e.key);\n }\n },\n async remove(key) {\n entries.delete(key);\n },\n };\n}\n\n/** localStorage-backed store — same defensiveness as the job/file stores. */\nexport function createLocalMemoryStore(storageKey = \"superchat:memory\", opts: { maxEntries?: number } = {}): MemoryStore {\n const cap = opts.maxEntries ?? DEFAULT_STORE_CAP;\n const read = (): Record<string, MemoryEntry> => {\n try {\n const raw = globalThis.localStorage?.getItem(storageKey) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : {};\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, MemoryEntry>) : {};\n } catch {\n return {};\n }\n };\n const write = (all: Record<string, MemoryEntry>) => {\n try {\n globalThis.localStorage?.setItem(storageKey, JSON.stringify(all));\n } catch {\n // Quota/private mode — a lost memory degrades to \"not remembered\".\n }\n };\n return {\n async list() {\n return Object.values(read()).sort(byRecency);\n },\n async set(key, value) {\n const all = read();\n all[key] = { key, value, updatedAt: Date.now() };\n const keys = Object.keys(all);\n if (keys.length > cap) {\n const overflow = keys.map((k) => all[k]!).sort(byRecency).slice(cap);\n for (const e of overflow) delete all[e.key];\n }\n write(all);\n },\n async remove(key) {\n const all = read();\n delete all[key];\n write(all);\n },\n };\n}\n\nexport type MemorySourceOptions = {\n id?: string;\n /** Budget-pressure priority; identity is 1000, skills ~800. */\n priority?: number;\n /** Cap on injected entries — memory must not crowd out the conversation. */\n maxEntries?: number;\n};\n\n/** The read half: remembered facts as a context layer, every turn. */\nexport function createMemorySource(store: MemoryStore, opts: MemorySourceOptions = {}): ContextSource {\n return {\n id: opts.id ?? \"memory\",\n async run({ vars }) {\n const entries = (await store.list(vars)).slice(0, opts.maxEntries ?? 50);\n if (!entries.length) return {};\n const text = [\n \"Things you remember about this user, from earlier conversations:\",\n ...entries.map((e) => `- ${e.key}: ${e.value}`),\n \"Apply them without re-asking. Update them with the `remember` tool when they change.\",\n ].join(\"\\n\");\n return {\n layers: [\n {\n id: opts.id ?? \"memory\",\n kind: \"memory\",\n text,\n tokens: estimateTokens(text),\n priority: opts.priority ?? 500,\n },\n ],\n };\n },\n };\n}\n\n/** The write half: the model saves/updates/forgets a fact, visibly. */\nexport function createRememberTool(store: MemoryStore): ToolDefinition {\n return {\n name: \"remember\",\n side: \"write\",\n description:\n \"Save a durable fact about the user for future conversations — a preference, a standing constraint, a correction. \" +\n \"Use a stable key so updating a fact replaces it instead of duplicating it. \" +\n \"Pass value: null to forget a fact. Do NOT store conversation history or anything the user would not expect to be remembered.\",\n inputSchema: {\n type: \"object\",\n required: [\"key\"],\n properties: {\n key: { type: \"string\", description: 'Stable slug, e.g. \"preferred-language\".' },\n value: { type: [\"string\", \"null\"], description: \"The fact to remember, or null to forget the key.\" },\n },\n additionalProperties: false,\n },\n async execute(input, ctx) {\n const { key, value } = (input ?? {}) as { key?: string; value?: string | null };\n if (!key) return { output: { ok: false, error: \"`key` is required.\" }, failure: \"invalid-input\" as const };\n if (value == null || value === \"\") {\n await store.remove(key, ctx.vars);\n return { output: { ok: true, forgot: key } };\n }\n await store.set(key, value, ctx.vars);\n return { output: { ok: true, remembered: { key, value } } };\n },\n };\n}\n","// Retrieval seam.\n//\n// The framework's position: retrieval is a CONTEXT SOURCE, not a vector\n// database. `Retriever` is one method a host backs with whatever it already\n// runs (pgvector, Elasticsearch, a SaaS RAG API); `createRetrievalSource()`\n// runs it against the turn's query and injects the hits as a numbered\n// evidence layer — under the same token budget, recorded in the same trace,\n// with reference markers the model can cite via the `citations` card. That\n// closes the loop the card system left open: a citations renderer with no way\n// to produce citations.\n//\n// `createKeywordRetriever()` is the zero-dependency reference implementation —\n// honest lexical overlap scoring for demos and tests, not a semantic index.\n\nimport { tokenize } from \"../skills/match.js\";\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { ContextSource } from \"../context/types.js\";\n\nexport type RetrievedChunk = {\n id: string;\n text: string;\n /** Where this came from — shown to the user in citations. */\n source?: string;\n title?: string;\n uri?: string;\n /** Higher is better; used only for ordering, scale is the retriever's. */\n score?: number;\n};\n\nexport type Retriever = {\n retrieve(query: string, opts?: { limit?: number; signal?: AbortSignal; vars?: Record<string, unknown> }): Promise<RetrievedChunk[]>;\n};\n\nexport type RetrievalSourceOptions = {\n id?: string;\n /** Max chunks injected per turn. */\n limit?: number;\n /** Budget-pressure priority; memory is 500. */\n priority?: number;\n /** Skip retrieval entirely for queries shorter than this (greetings). */\n minQueryLength?: number;\n};\n\n/** Plug a retriever into context assembly as a cited-evidence layer. */\nexport function createRetrievalSource(retriever: Retriever, opts: RetrievalSourceOptions = {}): ContextSource {\n return {\n id: opts.id ?? \"retrieval\",\n async run({ query, vars, signal }) {\n if (query.trim().length < (opts.minQueryLength ?? 8)) return {};\n const chunks = (await retriever.retrieve(query, { limit: opts.limit ?? 5, signal, vars })).slice(\n 0,\n opts.limit ?? 5,\n );\n if (!chunks.length) return {};\n\n const text = [\n \"Reference material retrieved for this question. Ground your answer in it when relevant:\",\n ...chunks.map(\n (c, i) =>\n `[${i + 1}] ${c.title ?? c.id}${c.source ? ` (${c.source})` : \"\"}\\n${c.text.trim()}`,\n ),\n \"When your answer draws on a reference, cite it — use the `citations` card via the visualize tool, quoting the passage you relied on, so the reader can check the work.\",\n ].join(\"\\n\\n\");\n\n return {\n layers: [\n {\n id: opts.id ?? \"retrieval\",\n kind: \"custom\",\n text,\n tokens: estimateTokens(text),\n priority: opts.priority ?? 400,\n },\n ],\n };\n },\n };\n}\n\nexport type RetrievalDoc = { id: string; text: string; title?: string; source?: string; uri?: string };\n\n/**\n * Zero-dependency lexical retriever: paragraphs scored by token overlap with\n * the query (CJK-safe via the skills tokenizer). The reference implementation\n * a host swaps for a real index — and enough for a playground to demonstrate\n * the whole retrieve → inject → cite loop honestly.\n */\nexport function createKeywordRetriever(docs: readonly RetrievalDoc[]): Retriever {\n type Chunk = RetrievedChunk & { terms: Set<string>; idx: number };\n const chunks: Chunk[] = docs\n .flatMap((doc) =>\n doc.text\n .split(/\\n\\s*\\n/)\n .map((p) => p.trim())\n .filter((p) => p.length > 0)\n .map((paragraph, i) => ({\n id: `${doc.id}#${i}`,\n text: paragraph,\n ...(doc.title ? { title: doc.title } : {}),\n ...(doc.source ? { source: doc.source } : {}),\n ...(doc.uri ? { uri: doc.uri } : {}),\n terms: new Set(tokenize(paragraph)),\n })),\n )\n // `idx` records original corpus order so candidate gathering below (which\n // visits chunks per query term, not in corpus order) can restore it before\n // scoring — ties must break the same way the old full scan did.\n .map((c, idx) => ({ ...c, idx }));\n\n // term → chunks containing it, built once so a query only touches chunks\n // sharing at least one query term instead of rescanning the whole corpus.\n const invertedIndex = new Map<string, Chunk[]>();\n for (const chunk of chunks) {\n for (const term of chunk.terms) {\n const bucket = invertedIndex.get(term);\n if (bucket) bucket.push(chunk);\n else invertedIndex.set(term, [chunk]);\n }\n }\n\n return {\n async retrieve(query, opts = {}) {\n const queryTerms = tokenize(query);\n if (!queryTerms.length) return [];\n\n const seen = new Set<Chunk>();\n const candidates: Chunk[] = [];\n for (const term of queryTerms) {\n for (const chunk of invertedIndex.get(term) ?? []) {\n if (!seen.has(chunk)) {\n seen.add(chunk);\n candidates.push(chunk);\n }\n }\n }\n candidates.sort((a, b) => a.idx - b.idx);\n\n const scored = candidates\n .map((c) => {\n const hits = queryTerms.filter((t) => c.terms.has(t)).length;\n return { chunk: c, score: hits / Math.sqrt(c.terms.size || 1) };\n })\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, opts.limit ?? 5);\n return scored.map(({ chunk, score }) => {\n const { terms: _terms, idx: _idx, ...rest } = chunk;\n return { ...rest, score };\n });\n },\n };\n}\n","// The app-state seam — the agent reading and operating the HOST APPLICATION,\n// not just the transcript.\n//\n// This is the piece that makes \"an agent surface inside your own product\"\n// literal. Without it an agent can only talk about the product; with it the\n// agent sees what the user sees (a form's current values, the selected rows,\n// the open document) and can act on it (fill the field, apply the filter,\n// navigate) — while the UI stays the source of truth and re-renders normally.\n//\n// Two halves, both built on machinery that already exists:\n//\n// READ → `createAppStateSource()` is a ContextSource. State enters context\n// the same way memory and retrieval do: budgeted, traced, derived\n// fresh every turn — never accumulated, so a stale snapshot from\n// three turns ago can't contradict the screen.\n// WRITE → `createAppActionTools()` are ordinary ToolDefinitions, which means\n// they inherit the whole security model for free: preset allowlists,\n// `side: \"confirm\"` suspension, deny-last. An action that mutates a\n// user's document belongs in `executor`, and the framework already\n// knows what that means.\n//\n// The deliberate non-goal: no diffing, no CRDT, no bidirectional sync\n// protocol. The host owns its state and already has a way to render it; this\n// reads a snapshot and calls a handler. Anything more would be a state\n// manager competing with the one the host already uses.\n\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { ContextSource } from \"../context/types.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { ToolDefinition, ToolSide } from \"../tools/types.js\";\n\nexport type AppStateBinding<T = unknown> = {\n /** Stable id — also the context layer id and the trace entry name. */\n id: string;\n /**\n * What this state IS, in the model's vocabulary. This is the description the\n * model reasons about, so write it for the model: \"the checkout form the\n * user is filling in\", not \"checkoutFormState\".\n */\n description: string;\n /** Read the CURRENT value. Called fresh every turn — never cached. */\n read(): T | Promise<T>;\n /**\n * Serialize for the prompt. Default is pretty JSON; override to summarize a\n * large store down to what the model actually needs.\n */\n serialize?(value: T): string;\n /** Skip injection entirely (a closed dialog's state is noise). */\n when?(value: T): boolean;\n};\n\nexport type AppAction<I = Record<string, unknown>> = {\n /** Tool name the model calls — verb-shaped: `applyFilter`, `openDocument`. */\n name: string;\n description: string;\n inputSchema: JSONSchema;\n /**\n * Perform it against the host app. The return value is what the model reads\n * back, so return the RESULT (\"filter applied, 12 rows match\"), not `void` —\n * an action whose outcome the model can't observe is an action it will\n * repeat.\n */\n run(input: I): unknown | Promise<unknown>;\n /**\n * `confirm` suspends the run behind an interactive card before executing —\n * the right default for anything the user would want to see first.\n */\n side?: ToolSide;\n};\n\nexport type AppStateSourceOptions = {\n id?: string;\n /** Budget-pressure priority. Memory is 500, retrieval 400. */\n priority?: number;\n};\n\nconst defaultSerialize = (value: unknown): string => {\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n return \"[unserializable state]\";\n }\n};\n\n/**\n * The read half: host application state as a context layer, refreshed every\n * turn. Bindings that throw are skipped rather than failing the turn — a\n * component unmounting mid-run must cost context, not the conversation.\n */\nexport function createAppStateSource(\n // Bindings are heterogeneous by nature — a form's values and a selection's\n // ids have nothing in common — so the array is typed at the erased boundary\n // and each binding keeps its own type at its definition site.\n bindings: readonly AppStateBinding<any>[],\n opts: AppStateSourceOptions = {},\n): ContextSource {\n return {\n id: opts.id ?? \"app-state\",\n async run() {\n const blocks: string[] = [];\n for (const binding of bindings) {\n try {\n const value = await binding.read();\n if (binding.when && !binding.when(value)) continue;\n const body = (binding.serialize ?? defaultSerialize)(value);\n if (!body?.trim()) continue;\n blocks.push(`### ${binding.id} — ${binding.description}\\n${body}`);\n } catch {\n // A binding that throws is a component that went away. Skip it.\n }\n }\n if (!blocks.length) return {};\n\n const text = [\n \"Current state of the application the user is looking at. This is live — it reflects the screen right now, not the conversation:\",\n ...blocks,\n \"Refer to it directly rather than asking the user to repeat what is already on screen.\",\n ].join(\"\\n\\n\");\n\n return {\n layers: [\n {\n id: opts.id ?? \"app-state\",\n kind: \"environment\",\n text,\n tokens: estimateTokens(text),\n priority: opts.priority ?? 600,\n },\n ],\n };\n },\n };\n}\n\n/**\n * The write half: host actions as ordinary tools.\n *\n * Returned, not registered — the host calls `registry.registerAll(...)` with\n * the preset it decides these deserve. That is the same rule MCP imports\n * follow, and for the same reason: a tool that can mutate the user's document\n * must get its authority explicitly, never by virtue of being wired up.\n */\nexport function createAppActionTools(actions: readonly AppAction<any>[]): ToolDefinition[] {\n return actions.map((action) => ({\n name: action.name,\n description: action.description,\n inputSchema: action.inputSchema,\n side: action.side ?? \"write\",\n execute: async (input) => {\n const result = await action.run((input ?? {}) as Record<string, unknown>);\n // A bare undefined reads as failure to a model; say it worked.\n return { output: result === undefined ? { ok: true } : result };\n },\n }));\n}\n","// A minimal MCP client — Streamable HTTP only, deliberately.\n//\n// This is a FRONTEND framework: the MCP servers it can reach are remote HTTP\n// ones. stdio transport means spawning a process, which a browser cannot do —\n// hosts that want stdio servers put them behind an HTTP gateway.\n//\n// The client rides the same `Transport` seam the LLM adapters use, and for the\n// same reason: credentials. An MCP server whose token must stay server-side is\n// one more entry in `createProxyHandler`'s provider map ({ baseUrl: the MCP\n// server, apiKey: its token, allowPaths: [\"POST /mcp\"] }) and this client runs\n// over the same proxy transport, no new machinery. For unauthenticated or\n// local servers, `createHttpTransport` below talks straight HTTP.\n\nimport { AgentError } from \"../errors.js\";\nimport { errorFromResponse } from \"../transport/retry.js\";\nimport { parseSSEJson } from \"../transport/sse.js\";\nimport type { Transport, TransportRequest } from \"../transport/types.js\";\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n McpCallResult,\n McpElicitHandler,\n McpElicitRequest,\n McpServerInfo,\n McpTool,\n} from \"./types.js\";\n\nexport type McpClientConfig = {\n transport: Transport;\n /** Routing id in the proxy's provider map. Default \"mcp\". */\n provider?: string;\n /** Server-relative path of the MCP endpoint. Default \"/\". */\n path?: string;\n protocolVersion?: string;\n clientInfo?: { name: string; version: string };\n /**\n * Answer `elicitation/create` — the server asking the USER for structured\n * input mid-call. Without a handler, elicitations are declined (never hung).\n * `importMcpTools` bridges this onto the interactive-card suspension, so an\n * eliciting server gets the same form-card UX as a local `confirm` tool.\n */\n onElicit?: McpElicitHandler;\n};\n\nconst DEFAULT_PROTOCOL = \"2025-06-18\";\n\n/** Bounds every request when the caller supplies no signal of its own — a hung MCP server must not block forever. */\nconst DEFAULT_RPC_TIMEOUT_MS = 30_000;\n\n/**\n * Combine signals so any one of them can abort the request. Prefers the\n * platform `AbortSignal.any` where available; falls back to a manual\n * listener-based combine for runtimes that lack it.\n */\nfunction combineSignals(signals: readonly (AbortSignal | undefined)[]): AbortSignal {\n const present = signals.filter((s): s is AbortSignal => s != null);\n if (present.length === 0) return new AbortController().signal; // never aborts\n if (present.length === 1) return present[0]!;\n if (typeof AbortSignal.any === \"function\") return AbortSignal.any(present);\n\n const controller = new AbortController();\n for (const s of present) {\n if (s.aborted) {\n controller.abort(s.reason);\n break;\n }\n s.addEventListener(\"abort\", () => controller.abort(s.reason), { once: true });\n }\n return controller.signal;\n}\n\n/** Thrown for protocol-level JSON-RPC errors (unknown method, bad params). */\nexport class McpRpcError extends Error {\n readonly code: number;\n readonly data?: unknown;\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = \"McpRpcError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/** More pages than any real server has; past this, pagination is treated as a loop. */\nconst MAX_TOOL_PAGES = 1000;\n\nexport class McpClient {\n private readonly transport: Transport;\n private readonly provider: string;\n private readonly path: string;\n private readonly protocolVersion: string;\n private readonly clientInfo: { name: string; version: string };\n private readonly onElicit: McpElicitHandler | undefined;\n private rpcId = 0;\n private sessionId: string | undefined;\n private handshake: { serverInfo: McpServerInfo; protocolVersion: string } | undefined;\n /** The in-flight `connect()` call, if any — concurrent callers await this instead of starting their own `initialize` round trip. */\n private connecting: Promise<{ serverInfo: McpServerInfo; protocolVersion: string }> | undefined;\n\n constructor(config: McpClientConfig) {\n this.transport = config.transport;\n this.provider = config.provider ?? \"mcp\";\n this.path = config.path ?? \"/\";\n this.protocolVersion = config.protocolVersion ?? DEFAULT_PROTOCOL;\n this.clientInfo = config.clientInfo ?? { name: \"superchat\", version: \"0.1.0\" };\n this.onElicit = config.onElicit;\n }\n\n /**\n * Idempotent: a second call returns the cached handshake. Concurrent calls\n * while the first is still in flight share that same call rather than each\n * firing their own `initialize` round trip.\n */\n async connect(): Promise<{ serverInfo: McpServerInfo; protocolVersion: string }> {\n if (this.handshake) return this.handshake;\n if (this.connecting) return this.connecting;\n this.connecting = this.doConnect().finally(() => {\n this.connecting = undefined;\n });\n return this.connecting;\n }\n\n private async doConnect(): Promise<{ serverInfo: McpServerInfo; protocolVersion: string }> {\n const result = (await this.rpc(\"initialize\", {\n protocolVersion: this.protocolVersion,\n // Declaring elicitation is what permits the server to ask; without a\n // handler we keep the capability undeclared and decline defensively.\n capabilities: this.onElicit ? { elicitation: {} } : {},\n clientInfo: this.clientInfo,\n })) as { protocolVersion?: string; serverInfo?: McpServerInfo };\n\n // Fire the initialized notification; a server may 202 it with no body.\n await this.post({ jsonrpc: \"2.0\", method: \"notifications/initialized\" });\n\n this.handshake = {\n serverInfo: result.serverInfo ?? { name: \"unknown\" },\n protocolVersion: result.protocolVersion ?? this.protocolVersion,\n };\n return this.handshake;\n }\n\n /** All tools, following `nextCursor` pagination to exhaustion. */\n async listTools(opts: { signal?: AbortSignal } = {}): Promise<McpTool[]> {\n await this.ensureConnected();\n const tools: McpTool[] = [];\n // A server that keeps handing back the same cursor (or never stops paginating) would otherwise\n // loop here for ever, growing `tools` without bound.\n const seen = new Set<string>();\n let cursor: string | undefined;\n do {\n const page = (await this.rpc(\"tools/list\", cursor ? { cursor } : {}, opts)) as {\n tools?: McpTool[];\n nextCursor?: string;\n };\n if (Array.isArray(page.tools)) tools.push(...page.tools);\n cursor = typeof page.nextCursor === \"string\" && page.nextCursor !== \"\" ? page.nextCursor : undefined;\n if (cursor !== undefined) {\n if (seen.has(cursor) || seen.size >= MAX_TOOL_PAGES) {\n throw new McpRpcError(-32603, \"tools/list pagination does not terminate (repeated cursor or too many pages)\");\n }\n seen.add(cursor);\n }\n } while (cursor);\n return tools;\n }\n\n /**\n * Call a tool. A JSON-RPC error comes back as a failed `McpCallResult`\n * rather than a throw — tool errors are for the model to read, and an\n * exception here would abort the whole agent turn instead of one step.\n */\n async callTool(\n name: string,\n args: unknown,\n opts: { signal?: AbortSignal; onElicit?: McpElicitHandler } = {},\n ): Promise<McpCallResult> {\n await this.ensureConnected();\n try {\n const result = (await this.rpc(\"tools/call\", { name, arguments: args ?? {} }, opts)) as McpCallResult;\n return { ...result, content: result.content ?? [] };\n } catch (e) {\n if (e instanceof McpRpcError) {\n return { content: [{ type: \"text\", text: e.message }], isError: true };\n }\n throw e;\n }\n }\n\n /** Best-effort session teardown; servers may not support DELETE. */\n async close(): Promise<void> {\n if (!this.sessionId) return;\n try {\n await this.transport.fetch(this.request(\"DELETE\"));\n } catch {\n // The session expires server-side regardless.\n }\n this.sessionId = undefined;\n this.handshake = undefined;\n }\n\n private async ensureConnected(): Promise<void> {\n if (!this.handshake) await this.connect();\n }\n\n private request(method: TransportRequest[\"method\"], body?: unknown): TransportRequest {\n return {\n provider: this.provider,\n path: this.path,\n method,\n ...(body !== undefined ? { body } : {}),\n headers: {\n // Streamable HTTP: a POST response may be JSON or an SSE stream.\n accept: \"application/json, text/event-stream\",\n ...(this.sessionId ? { \"mcp-session-id\": this.sessionId } : {}),\n },\n };\n }\n\n private async post(body: JsonRpcRequest, signal?: AbortSignal): Promise<Response> {\n // Every call gets bounded by DEFAULT_RPC_TIMEOUT_MS, even when the caller\n // supplies its own signal — a caller's signal is typically for run-level\n // cancellation, not a guarantee the server will ever respond.\n const combined = combineSignals([signal, AbortSignal.timeout(DEFAULT_RPC_TIMEOUT_MS)]);\n const res = await this.transport.fetch({ ...this.request(\"POST\", body), signal: combined });\n const sid = res.headers.get(\"mcp-session-id\");\n if (sid) this.sessionId = sid;\n if (!res.ok) throw await errorFromResponse(res, this.provider);\n return res;\n }\n\n private async rpc(\n method: string,\n params: unknown,\n opts: { signal?: AbortSignal; onElicit?: McpElicitHandler } = {},\n ): Promise<unknown> {\n this.rpcId += 1;\n const id = this.rpcId;\n const res = await this.post({ jsonrpc: \"2.0\", id, method, params }, opts.signal);\n\n const contentType = res.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"text/event-stream\")) {\n if (!res.body) throw new AgentError(\"network\", \"MCP response had no body to stream.\", { provider: this.provider });\n // The stream carries our response, server notifications, AND possibly\n // server-initiated REQUESTS (elicitation). Answer those inline — the\n // final tool result cannot arrive until the elicitation is settled, so\n // awaiting here is the correct ordering, not a stall.\n for await (const frame of parseSSEJson<JsonRpcResponse & JsonRpcRequest>(res.body)) {\n const msg = frame.data;\n if (!msg) continue;\n if (typeof msg.method === \"string\" && msg.id != null) {\n await this.answerServerRequest(msg as JsonRpcRequest & { id: number | string }, opts.onElicit, opts.signal);\n continue;\n }\n if (msg.id === id) return this.settle(msg as JsonRpcResponse);\n }\n throw new AgentError(\"network\", `MCP stream ended without a response to \"${method}\".`, { provider: this.provider });\n }\n\n return this.settle((await res.json()) as JsonRpcResponse);\n }\n\n /** Answer a server-initiated request (elicitation); unknown methods get a JSON-RPC error. */\n private async answerServerRequest(\n request: JsonRpcRequest & { id: number | string },\n override: McpElicitHandler | undefined,\n signal?: AbortSignal,\n ): Promise<void> {\n if (request.method === \"elicitation/create\") {\n const handler = override ?? this.onElicit;\n let result: unknown;\n try {\n result = handler ? await handler((request.params ?? { message: \"\" }) as McpElicitRequest) : { action: \"decline\" };\n } catch {\n result = { action: \"cancel\" }; // the user's card was dismissed / the run aborted\n }\n await this.post({ jsonrpc: \"2.0\", id: request.id, result } as unknown as JsonRpcRequest, signal).catch(() => {});\n return;\n }\n await this.post(\n {\n jsonrpc: \"2.0\",\n id: request.id,\n error: { code: -32601, message: `Method not supported: ${request.method}` },\n } as unknown as JsonRpcRequest,\n signal,\n ).catch(() => {});\n }\n\n private settle(response: JsonRpcResponse): unknown {\n if (response.error) throw new McpRpcError(response.error.code, response.error.message, response.error.data);\n return response.result;\n }\n}\n\n/**\n * Credential-free direct HTTP transport for MCP servers that need no key (a\n * local dev server, the playground's mock route). Anything with a token that\n * must stay secret belongs behind `createProxyHandler` instead.\n */\nexport function createHttpTransport(opts: {\n baseUrl: string;\n headers?: Record<string, string>;\n fetchImpl?: typeof fetch;\n}): Transport {\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const isBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\n return {\n kind: \"custom\",\n credentialSafe: !isBrowser || !opts.headers,\n async fetch(req: TransportRequest): Promise<Response> {\n // `baseUrl` may be relative (\"/api/mcp\") in a browser host.\n const full = `${opts.baseUrl.replace(/\\/$/, \"\")}${req.path === \"/\" ? \"\" : req.path}` || opts.baseUrl;\n const url = new URL(full, isBrowser ? window.location.origin : undefined);\n for (const [k, v] of Object.entries(req.query ?? {})) {\n if (v !== undefined && v !== null) url.searchParams.set(k, String(v));\n }\n return doFetch(url.toString(), {\n method: req.method,\n headers: {\n ...(req.body !== undefined ? { \"content-type\": \"application/json\" } : {}),\n ...opts.headers,\n ...req.headers,\n },\n body: req.body === undefined ? undefined : JSON.stringify(req.body),\n signal: req.signal,\n });\n },\n };\n}\n","// MCP tools → ToolDefinitions.\n//\n// Import grants EXISTENCE, never authority. `importMcpTools` returns\n// definitions; registering them is the host's move, and registering with no\n// preset makes them skill-gated — private until a skill (or an explicit\n// `allow`) surfaces them, exactly like any locally defined domain tool. An MCP\n// server must not be able to walk its tools into the executor tier by being\n// connected.\n\nimport type { CardSpec, FormField } from \"../cards/types.js\";\nimport type { Skill } from \"../skills/types.js\";\nimport type { ToolDefinition, ToolResult, ToolSide } from \"../tools/types.js\";\nimport type { McpClient } from \"./client.js\";\nimport type { McpCallResult, McpContent, McpElicitHandler, McpElicitRequest } from \"./types.js\";\n\nexport type McpImportOptions = {\n /**\n * Prefix for imported tool names (\"namespace_toolName\"), so two servers with\n * a `search` tool can coexist. Defaults to the server's sanitized name.\n */\n namespace?: string;\n /** Defaults to \"read\": a remote server's tools are reads until the host says otherwise. */\n side?: ToolSide;\n costHint?: number;\n /** Override the result mapping per server. */\n mapResult?: (result: McpCallResult) => ToolResult;\n};\n\n/** `normalizeToolName` strips a leading \"mcp_\", so that namespace would break dispatch. */\nconst RESERVED_NAMESPACE = \"mcp\";\n\nfunction sanitizeNamespace(raw: string | undefined): string {\n const cleaned = (raw ?? \"\").replace(/[^a-zA-Z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n if (!cleaned || cleaned.toLowerCase() === RESERVED_NAMESPACE) return \"srv\";\n return cleaned;\n}\n\n/**\n * Fetch the server's tool list and wrap each tool in a `ToolDefinition` whose\n * executor calls back through the client. Throws when two tools collide after\n * namespacing — a silent overwrite would drop a tool with no trace.\n */\nexport async function importMcpTools(client: McpClient, opts: McpImportOptions = {}): Promise<ToolDefinition[]> {\n const { serverInfo } = await client.connect();\n const namespace = sanitizeNamespace(opts.namespace ?? serverInfo.name);\n const mapResult = opts.mapResult ?? mapMcpResult;\n\n const tools = await client.listTools();\n const out: ToolDefinition[] = [];\n const seen = new Set<string>();\n\n for (const tool of tools) {\n const name = `${namespace}_${tool.name}`;\n if (seen.has(name)) {\n throw new Error(`MCP import: two tools map to \"${name}\". Give the servers distinct namespaces.`);\n }\n seen.add(name);\n\n out.push({\n name,\n description: tool.description ?? `Tool \"${tool.name}\" from the ${namespace} MCP server.`,\n inputSchema: tool.inputSchema ?? { type: \"object\" },\n side: opts.side ?? \"read\",\n ...(opts.costHint != null ? { costHint: opts.costHint } : {}),\n execute: async (input, ctx) => {\n // The model calls the namespaced name; the server knows the original.\n // If the server elicits mid-call, the ask surfaces as an interactive\n // form card — the same suspension a local `confirm` tool gets.\n const result = await client.callTool(tool.name, input, {\n signal: ctx.signal,\n ...(ctx.requestCard ? { onElicit: elicitViaCard(ctx.requestCard) } : {}),\n });\n return mapResult(result);\n },\n });\n }\n\n return out;\n}\n\n/**\n * Default MCP result → ToolResult mapping.\n *\n * The model reads `output`; a UI-worthy image rides as a card. Kept small on\n * purpose — the output is billed on every later turn of the thread.\n */\nexport function mapMcpResult(result: McpCallResult): ToolResult {\n if (result.isError) {\n return { output: { error: textOf(result.content) || \"MCP tool failed.\" }, failure: \"execution-error\" };\n }\n if (result.structuredContent !== undefined) {\n return { output: result.structuredContent };\n }\n\n const texts = result.content.filter((c): c is Extract<McpContent, { type: \"text\" }> => c.type === \"text\");\n const resources = result.content.filter((c): c is Extract<McpContent, { type: \"resource\" }> => c.type === \"resource\");\n const image = result.content.find((c): c is Extract<McpContent, { type: \"image\" }> => c.type === \"image\");\n\n let output: unknown;\n if (texts.length === 1) {\n // A single text that parses as JSON becomes the parsed value — models do\n // better with structure than with a string of escaped braces.\n output = parseMaybeJson(texts[0]!.text);\n } else if (texts.length > 1) {\n output = texts.map((t) => t.text).join(\"\\n\");\n }\n\n if (resources.length) {\n const refs = resources.map((r) => ({ uri: r.resource.uri, ...(r.resource.text ? { text: r.resource.text } : {}) }));\n output = output === undefined ? { resources: refs } : { text: output, resources: refs };\n }\n if (output === undefined) output = image ? \"(image result)\" : null;\n\n return {\n output,\n ...(image\n ? {\n card: {\n kind: \"media\",\n items: [{ url: `data:${image.mimeType};base64,${image.data}`, mediaType: image.mimeType }],\n layout: \"single\",\n },\n }\n : {}),\n };\n}\n\n/**\n * The relevance half of the composition: a `matched` skill that names the\n * imported tools, so they surface when the conversation is about them —\n * exactly how a locally defined domain tool becomes visible. Registering the\n * tools makes them EXIST; registering this skill makes them REACHABLE. The\n * authority tier still comes from presets, which this never touches.\n */\nexport function createMcpSkill(\n serverName: string,\n defs: readonly ToolDefinition[],\n opts: { id?: string; priority?: number } = {},\n): Skill {\n // \"utils_word_count\" → alias \"word count\"; the original tool vocabulary is\n // what a user's request will actually contain.\n const bare = (name: string) => name.slice(name.indexOf(\"_\") + 1);\n const aliases = [...new Set(defs.flatMap((d) => [bare(d.name).replace(/_/g, \" \"), bare(d.name)]))];\n\n return {\n id: opts.id ?? `mcp-${serverName.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\")}`,\n name: `MCP: ${serverName}`,\n description: `Tools provided by the ${serverName} MCP server.`,\n mode: \"matched\",\n aliases,\n ...(opts.priority != null ? { priority: opts.priority } : {}),\n body: [\n `The ${serverName} MCP server provides these tools:`,\n ...defs.map((d) => `- ${d.name}: ${d.description.split(\"\\n\")[0]}`),\n \"Call them like any other tool.\",\n ].join(\"\\n\"),\n tools: defs.map((d) => d.name),\n };\n}\n\n/**\n * MCP elicitation → interactive form card. The server's `requestedSchema`\n * becomes form fields; the user's submission becomes the `accept` content, a\n * dismissal becomes `decline`. This is the bridge that makes an eliciting MCP\n * server feel like a first-class interactive tool instead of a hang.\n */\nexport function elicitViaCard(requestCard: (spec: CardSpec) => Promise<unknown>): McpElicitHandler {\n return async (params: McpElicitRequest) => {\n const props = params.requestedSchema?.properties ?? {};\n const required = new Set(params.requestedSchema?.required ?? []);\n const fields: FormField[] = Object.entries(props).map(([name, p]) => {\n const label = p.title ?? name;\n if (Array.isArray(p.enum) && p.enum.length) {\n return {\n name,\n label,\n type: \"select\",\n options: p.enum.map((v) => ({ value: String(v), label: String(v) })),\n ...(required.has(name) ? { required: true } : {}),\n };\n }\n if (p.type === \"boolean\") return { name, label, type: \"boolean\", ...(p.default != null ? { value: Boolean(p.default) } : {}) };\n if (p.type === \"number\" || p.type === \"integer\") {\n return { name, label, type: \"number\", ...(required.has(name) ? { required: true } : {}) };\n }\n return {\n name,\n label,\n type: \"text\",\n ...(p.description ? { placeholder: p.description } : {}),\n ...(required.has(name) ? { required: true } : {}),\n };\n });\n\n const answer = await requestCard({\n kind: \"form\",\n title: \"This tool needs your input\",\n description: params.message,\n fields: fields.length ? fields : [{ name: \"response\", label: params.message || \"Response\", type: \"text\" }],\n submitLabel: \"Send\",\n });\n\n if (answer && typeof answer === \"object\" && (answer as { cancelled?: boolean }).cancelled) {\n return { action: \"decline\" };\n }\n const content =\n answer && typeof answer === \"object\" && !Array.isArray(answer) ? (answer as Record<string, unknown>) : { response: answer };\n return { action: \"accept\", content };\n };\n}\n\nconst textOf = (content: McpContent[]): string =>\n content\n .filter((c): c is Extract<McpContent, { type: \"text\" }> => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n\nfunction parseMaybeJson(text: string): unknown {\n const trimmed = text.trim();\n if (!trimmed.startsWith(\"{\") && !trimmed.startsWith(\"[\")) return text;\n try {\n return JSON.parse(trimmed);\n } catch {\n return text;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAI,UAAU;AAOP,SAAS,OAAO,SAAS,OAAe;AAC7C,aAAW;AACX,SAAO,GAAG,MAAM,IAAI,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,GAAG,QAAQ,SAAS,EAAE,CAAC;AACpE;AAEO,IAAM,OAAO,CAAC,WAAgC,EAAE,MAAM,QAAQ,MAAM,MAAM;AAE1E,IAAM,QAAQ,CACnB,QACA,OAAiE,CAAC,OACjD,EAAE,MAAM,SAAS,QAAQ,GAAG,KAAK;AAE7C,IAAM,OAAO,CAAC,QAAqB,WAAmB,cAAoC;AAAA,EAC/F,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AACjC;AAEO,IAAM,WAAW,CACtB,QACA,MACA,OACA,OAAwD,CAAC,OACxC,EAAE,MAAM,aAAa,QAAQ,MAAM,OAAO,QAAQ,KAAK,UAAU,WAAW,GAAG,KAAK;AAEhG,IAAM,aAAa,CACxB,QACA,MACA,QACA,OAAuD,CAAC,OACvC,EAAE,MAAM,eAAe,QAAQ,MAAM,QAAQ,GAAG,KAAK;AAEjE,SAAS,QAAQ,MAAmB,OAA+B,IAAsB;AAC9F,SAAO;AAAA,IACL,IAAI,MAAM,OAAO,SAAS,cAAc,SAAS,IAAI;AAAA,IACrD;AAAA,IACA,OAAO,OAAO,UAAU,WAAW,CAAC,KAAK,KAAK,CAAC,IAAI;AAAA,IACnD,WAAW,KAAK,IAAI;AAAA,EACtB;AACF;AAEO,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;AAC5H,WAAO,EAAE,QAAQ,UAAU,QAAQ;AAAA,EACrC;AACF;AAEA,IAAM,SAAS,CAAC,YACd,QACG,OAAO,CAAC,MAAkD,EAAE,SAAS,MAAM,EAC3E,IAAI,CAAC,MAAM,EAAE,IAAI,EACjB,KAAK,IAAI;AAEd,SAAS,eAAeC,OAAuB;AAC7C,QAAM,UAAUA,MAAK,KAAK;AAC1B,MAAI,CAAC,QAAQ,WAAW,GAAG,KAAK,CAAC,QAAQ,WAAW,GAAG,EAAG,QAAOA;AACjE,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAOA;AAAA,EACT;AACF;","names":["text","j","last","quote","text","text","counter","text","counter","messages","text","counter","text","counter","text","printable","without","FORMATS","text","def","message","props","child","isObject","message","text","text","message","failed","props","outcome","outcome","props","QUOTE","text","child","source","finishedAt","record","outcome","file","byRecency","text","text","text","message","isBrowser","image","props","text"]}
|
|
1
|
+
{"version":3,"sources":["../src/content/parts.ts","../src/content/branching.ts","../src/content/blocks.ts","../src/content/turn-layout.ts","../src/content/quotes.ts","../src/transport/binary.ts","../src/transport/direct.ts","../src/transport/proxy.ts","../src/providers/profile.ts","../src/media/types.ts","../src/media/openai.ts","../src/media/tools.ts","../src/tokens/estimate.ts","../src/tokens/budget.ts","../src/skills/match.ts","../src/skills/registry.ts","../src/cards/types.ts","../src/context/compaction.ts","../src/context/builder.ts","../src/documents/edit.ts","../src/documents/store.ts","../src/documents/tools.ts","../src/documents/email.ts","../src/cards/registry.ts","../src/cards/card-ref.ts","../src/cards/builtin.ts","../src/surfaces/types.ts","../src/surfaces/pointer.ts","../src/surfaces/safety.ts","../src/surfaces/schema-check.ts","../src/surfaces/bindings.ts","../src/surfaces/primitives.ts","../src/surfaces/catalogue.ts","../src/surfaces/validate.ts","../src/surfaces/operations.ts","../src/surfaces/ledger.ts","../src/surfaces/tools.ts","../src/surfaces/disclosure.ts","../src/runtime/channel.ts","../src/tools/approval.ts","../src/runtime/execute-tools.ts","../src/runtime/metering.ts","../src/surfaces/action-run.ts","../src/surfaces/a2ui.ts","../src/tools/types.ts","../src/tools/registry.ts","../src/tools/partial-json.ts","../src/tools/builtin.ts","../src/runtime/events.ts","../src/runtime/stop.ts","../src/runtime/run.ts","../src/runtime/files.ts","../src/runtime/threads.ts","../src/memory/memory.ts","../src/retrieval/retrieval.ts","../src/app-state/app-state.ts","../src/mcp/client.ts","../src/mcp/import.ts"],"sourcesContent":["// Constructors, guards and small readers for the content model. Kept dependency\n// free so both the browser bundle and a server route can use them.\n\nimport type {\n ContentPart,\n MediaSource,\n Message,\n MessageRole,\n ToolCallStatus,\n ToolFailureKind,\n} from \"./types.js\";\n\nlet counter = 0;\n/**\n * Monotonic id. Deliberately not `crypto.randomUUID()` — ids show up in test\n * snapshots and in `previous_response_id` correlation logs, and a stable,\n * readable prefix is worth more here than global uniqueness. Callers that need\n * cross-device uniqueness pass their own id.\n */\nexport function nextId(prefix = \"msg\"): string {\n counter += 1;\n return `${prefix}_${Date.now().toString(36)}${counter.toString(36)}`;\n}\n\nexport const text = (value: string): ContentPart => ({ type: \"text\", text: value });\n\nexport const image = (\n source: MediaSource,\n opts: { mediaType?: string; detail?: \"auto\" | \"low\" | \"high\" } = {},\n): ContentPart => ({ type: \"image\", source, ...opts });\n\nexport const file = (source: MediaSource, mediaType: string, filename?: string): ContentPart => ({\n type: \"file\",\n source,\n mediaType,\n ...(filename ? { filename } : {}),\n});\n\nexport const toolCall = (\n callId: string,\n name: string,\n input: unknown,\n opts: { status?: ToolCallStatus; repaired?: boolean } = {},\n): ContentPart => ({ type: \"tool-call\", callId, name, input, status: opts.status ?? \"pending\", ...opts });\n\nexport const toolResult = (\n callId: string,\n name: string,\n output: unknown,\n opts: { failure?: ToolFailureKind; render?: string } = {},\n): ContentPart => ({ type: \"tool-result\", callId, name, output, ...opts });\n\nexport function message(role: MessageRole, parts: ContentPart[] | string, id?: string): Message {\n return {\n id: id ?? nextId(role === \"assistant\" ? \"asst\" : role),\n role,\n parts: typeof parts === \"string\" ? [text(parts)] : parts,\n createdAt: Date.now(),\n };\n}\n\nexport const userMessage = (parts: ContentPart[] | string, id?: string) => message(\"user\", parts, id);\nexport const assistantMessage = (parts: ContentPart[] | string, id?: string) => message(\"assistant\", parts, id);\n\nexport const isTextPart = (p: ContentPart): p is Extract<ContentPart, { type: \"text\" }> => p.type === \"text\";\nexport const isToolCallPart = (p: ContentPart): p is Extract<ContentPart, { type: \"tool-call\" }> =>\n p.type === \"tool-call\";\nexport const isToolResultPart = (p: ContentPart): p is Extract<ContentPart, { type: \"tool-result\" }> =>\n p.type === \"tool-result\";\n\n/** Concatenated text of a message — the \"what did it actually say\" reader. */\nexport function messageText(m: Message): string {\n return m.parts.filter(isTextPart).map((p) => p.text).join(\"\");\n}\n\n/** Last user-authored text in a thread. Drives skill matching and intent checks. */\nexport function lastUserText(messages: readonly Message[]): string {\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const m = messages[i];\n if (m && m.role === \"user\") return messageText(m).trim();\n }\n return \"\";\n}\n\nexport function toolCallsIn(messages: readonly Message[]): Extract<ContentPart, { type: \"tool-call\" }>[] {\n return messages.flatMap((m) => m.parts.filter(isToolCallPart));\n}\n\n/**\n * Merge streamed text deltas into the trailing text part instead of appending a\n * new part per token — otherwise a 2k-token reply becomes 2k parts and every\n * React render walks all of them.\n */\nexport function appendText(parts: ContentPart[], delta: string): ContentPart[] {\n const last = parts[parts.length - 1];\n if (last && last.type === \"text\") {\n return [...parts.slice(0, -1), { type: \"text\", text: last.text + delta }];\n }\n return [...parts, { type: \"text\", text: delta }];\n}\n\n/** Same merge, for reasoning streams (which arrive interleaved with text). */\nexport function appendReasoning(parts: ContentPart[], delta: string, signature?: string): ContentPart[] {\n const last = parts[parts.length - 1];\n if (last && last.type === \"reasoning\") {\n return [\n ...parts.slice(0, -1),\n { ...last, text: last.text + delta, ...(signature ? { signature } : {}) },\n ];\n }\n return [...parts, { type: \"reasoning\", text: delta, ...(signature ? { signature } : {}) }];\n}\n\n/**\n * Strip parts that exist only for the UI. Artifacts are host-rendered and have\n * no provider representation; sending them would either 400 or waste tokens on\n * a JSON blob the model can't act on.\n */\nexport function stripUiOnlyParts(m: Message): Message {\n const parts = m.parts.filter((p) => p.type !== \"artifact\");\n return parts.length === m.parts.length ? m : { ...m, parts };\n}\n","// Branching over a flat message list.\n//\n// The tree is stored FLAT — an array of messages with `parentId` pointers —\n// because that is what serializes, diffs and persists cleanly. These helpers\n// derive everything else: the active path (what the UI renders and the run\n// consumes), siblings (the \"< 2/3 >\" switcher), and leaves (where a switched\n// branch resumes). A thread with no branching is the degenerate case: every\n// message's parent is the previous one and the path IS the array.\n\nimport type { Message } from \"./types.js\";\n\n/** Root-first path from the root to `headId`. Unknown/missing head → []. */\nexport function pathTo(tree: readonly Message[], headId: string | null | undefined): Message[] {\n if (!headId) return [];\n const byId = new Map(tree.map((m) => [m.id, m]));\n const path: Message[] = [];\n let cursor = byId.get(headId);\n const seen = new Set<string>(); // cycle guard — corrupted data must not hang the UI\n while (cursor && !seen.has(cursor.id)) {\n seen.add(cursor.id);\n path.push(cursor);\n cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;\n }\n return path.reverse();\n}\n\n/** parentId → children, in tree insertion order. Built once per call site that needs repeated lookups. */\nfunction indexByParent(tree: readonly Message[]): Map<string | null, Message[]> {\n const index = new Map<string | null, Message[]>();\n for (const m of tree) {\n const parentId = m.parentId ?? null;\n const kids = index.get(parentId);\n if (kids) kids.push(m);\n else index.set(parentId, [m]);\n }\n return index;\n}\n\n/** Direct children of `parentId` (null = roots), in tree insertion order. */\nexport function childrenOf(tree: readonly Message[], parentId: string | null): Message[] {\n return indexByParent(tree).get(parentId) ?? [];\n}\n\n/** The message plus its siblings (shared parent), in insertion order. */\nexport function siblingsOf(tree: readonly Message[], id: string): Message[] {\n const self = tree.find((m) => m.id === id);\n if (!self) return [];\n return indexByParent(tree).get(self.parentId ?? null) ?? [];\n}\n\n/**\n * Deepest descendant of `fromId`, following the LATEST child at each level —\n * switching to a branch resumes at where that branch last left off.\n */\nexport function latestLeaf(tree: readonly Message[], fromId: string): string {\n // Built once here rather than via repeated `childrenOf` scans — one O(n)\n // pass instead of one per level of depth.\n const index = indexByParent(tree);\n let cursor = fromId;\n const seen = new Set<string>();\n for (;;) {\n if (seen.has(cursor)) return cursor;\n seen.add(cursor);\n const kids = index.get(cursor) ?? [];\n if (!kids.length) return cursor;\n cursor = kids[kids.length - 1]!.id;\n }\n}\n\n/**\n * Give a linear (pre-branching) message list its parent pointers. Used to\n * migrate v1 stored threads and to accept plain arrays as `initialMessages`.\n * Messages that already carry a parentId are left untouched.\n */\nexport function linkLinear(messages: readonly Message[]): Message[] {\n if (messages.some((m) => m.parentId !== undefined)) return [...messages];\n return messages.map((m, i) => ({ ...m, parentId: i === 0 ? null : messages[i - 1]!.id }));\n}\n","// Block structure of a Markdown source, addressed by offsets.\n//\n// This lives in core rather than beside the renderer because two very different\n// consumers have to agree on it exactly: the previewer, which turns a DOM\n// selection into a block index, and the edit protocol, which resolves that same\n// index back to text it is allowed to rewrite. Two implementations would drift,\n// and the drift would be silent — a quote pointing at block 4 and an edit\n// landing in block 5 both look fine until someone reads the result.\n//\n// Which is exactly why the first version's shortcuts had to go. It matched a\n// fence with `startsWith(\"```\")` and nothing else, so a four-backtick block\n// containing a three-backtick one closed on the inner fence and shattered into\n// four blocks with the code stranded in the middle as prose — and a `~~~` fence\n// was not a fence at all, which left the NEXT ``` in the document opening one\n// that ran to the end. Both produce anchors that point at the wrong text while\n// the page still renders plausibly, which is the failure mode this file exists\n// to prevent.\n\nexport type MarkdownBlockKind =\n /** A fenced code block, ``` or ~~~. Verbatim: no inline transforms. */\n | \"fence\"\n /** An indented (four-space or tab) code block. Also verbatim. */\n | \"code\"\n /** Everything else: a paragraph, heading, list, quote or table. */\n | \"text\";\n\n/** A top-level block, addressed by its half-open span in the SOURCE string. */\nexport type MarkdownBlock = {\n start: number;\n end: number;\n kind: MarkdownBlockKind;\n};\n\ntype Line = { text: string; start: number; end: number };\n\nfunction scanLines(src: string): Line[] {\n const out: Line[] = [];\n let start = 0;\n for (let i = 0; i <= src.length; i += 1) {\n if (i === src.length || src[i] === \"\\n\") {\n out.push({ text: src.slice(start, i), start, end: i });\n start = i + 1;\n }\n }\n return out;\n}\n\nconst isBlank = (text: string) => text.trim() === \"\";\n\n/** Up to three leading spaces still counts as the left margin, per CommonMark. */\nconst FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/;\nconst INDENTED = /^(?: {4}|\\t)/;\nconst LIST_ITEM = /^ {0,3}(?:[-*+]|\\d{1,9}[.)])(?:\\s|$)/;\nconst QUOTE = /^ {0,3}>/;\n\ntype Fence = { marker: string; char: string };\n\n/**\n * A fence opener, or null.\n *\n * The info string is rejected when it contains a backtick: ``` `a` ``` on one\n * line is an inline code span, not the start of a code block, and treating it\n * as one swallows the rest of the paragraph.\n */\nfunction fenceOpen(text: string): Fence | null {\n const m = FENCE_OPEN.exec(text);\n if (!m) return null;\n const marker = m[1]!;\n const char = marker[0]!;\n if (char === \"`\" && m[2]!.includes(\"`\")) return null;\n return { marker, char };\n}\n\n/**\n * Does this line close `open`?\n *\n * Same character, at least as long, and nothing but whitespace after it. The\n * length rule is the whole point: a ``` inside a ```` block is content, and\n * closing on it is what split a code sample into four bogus blocks.\n */\nfunction closesFence(text: string, open: Fence): boolean {\n const m = /^ {0,3}(`{3,}|~{3,})\\s*$/.exec(text);\n if (!m) return false;\n const marker = m[1]!;\n return marker[0] === open.char && marker.length >= open.marker.length;\n}\n\n/**\n * Whether a blank line inside `construct` is an interior gap rather than a\n * boundary.\n *\n * A loose list — items separated by blank lines — is one list, and splitting it\n * per item is not merely cosmetic: the previewer would render three `<ul>`s\n * where the document has one, and the outline would report three entries the\n * user reads as one thing. A quote continues the same way, but only through a\n * line that is still quoted; lazy continuation after a blank is not a thing.\n */\nfunction continues(construct: \"list\" | \"quote\" | \"other\", text: string): boolean {\n if (construct === \"list\") return LIST_ITEM.test(text) || INDENTED.test(text);\n if (construct === \"quote\") return QUOTE.test(text);\n return false;\n}\n\nconst constructOf = (text: string): \"list\" | \"quote\" | \"other\" =>\n QUOTE.test(text) ? \"quote\" : LIST_ITEM.test(text) ? \"list\" : \"other\";\n\n/**\n * Top-level blocks in source order, with their spans.\n *\n * Blank lines that separate blocks belong to none of them, so a span always\n * slices back to exactly the block's own text. Blank lines *inside* a block —\n * within a fence, between the items of a loose list — are part of it.\n */\nexport function splitBlocks(src: string): MarkdownBlock[] {\n const lines = scanLines(src);\n const blocks: MarkdownBlock[] = [];\n let i = 0;\n\n while (i < lines.length) {\n const line = lines[i]!;\n if (isBlank(line.text)) {\n i += 1;\n continue;\n }\n\n const open = fenceOpen(line.text);\n if (open) {\n let j = i + 1;\n while (j < lines.length && !closesFence(lines[j]!.text, open)) j += 1;\n // An unterminated fence runs to the end of the source rather than\n // swallowing the rest as prose — a half-streamed code block is a normal\n // state to render, not a malformed document.\n const closing = j < lines.length ? lines[j]! : lines[lines.length - 1]!;\n blocks.push({ start: line.start, end: closing.end, kind: \"fence\" });\n i = j + 1;\n continue;\n }\n\n if (INDENTED.test(line.text)) {\n // Indented code, with its interior blank lines kept and its trailing ones\n // returned to the separator. Only reachable at a block boundary: inside a\n // list the same indentation is item content, and the list branch below\n // consumes it first.\n let j = i;\n let last = i;\n while (j < lines.length && (isBlank(lines[j]!.text) || INDENTED.test(lines[j]!.text))) {\n if (!isBlank(lines[j]!.text)) last = j;\n j += 1;\n }\n blocks.push({ start: line.start, end: lines[last]!.end, kind: \"code\" });\n i = last + 1;\n continue;\n }\n\n const construct = constructOf(line.text);\n let j = i;\n let last = i;\n for (;;) {\n // Run to the next blank line or fence opener.\n while (j < lines.length && !isBlank(lines[j]!.text) && !fenceOpen(lines[j]!.text)) {\n last = j;\n j += 1;\n }\n // Then decide whether the gap is interior. Look past the blanks: if what\n // follows still belongs to this list or quote, absorb them and keep going.\n let k = j;\n while (k < lines.length && isBlank(lines[k]!.text)) k += 1;\n if (k > j && k < lines.length && continues(construct, lines[k]!.text)) {\n j = k;\n continue;\n }\n break;\n }\n blocks.push({ start: line.start, end: lines[last]!.end, kind: \"text\" });\n i = last + 1;\n }\n\n return blocks;\n}\n","// The order a turn actually happened in.\n//\n// A turn is text, then a tool's output, then more text. Rendering all cards above\n// all text loses that: the model writes \"here is the breakdown\" and \"so the second\n// row matters\" around a chart, and both land below it. Live and finished turns share\n// this one function so a turn does not rearrange itself the moment it commits.\n\nimport type { Card } from \"../cards/types.js\";\nimport type { ContentPart } from \"./types.js\";\n\nexport type TurnSegment =\n | { type: \"text\"; key: string; text: string }\n /** The output slot of one tool call. Stable from first preview to final card. */\n | { type: \"output\"; key: string; callId: string; cards: Card[] }\n /** A card no call in this turn accounts for. */\n | { type: \"card\"; key: string; card: Card };\n\nexport type TurnLayoutOptions = {\n /** Keep a slot for a call with no card yet. A live turn needs it for previews and skeletons. */\n keepEmptyOutputs?: boolean;\n};\n\n/**\n * True when a stored turn recorded where its cards belong. Turns saved before this\n * existed carry no `callId` on their artifacts and keep the layout they had.\n */\nexport function hasTurnOrder(parts: readonly ContentPart[]): boolean {\n return parts.some((p) => p.type === \"artifact\" && p.kind.startsWith(\"card:\") && typeof p.callId === \"string\");\n}\n\nexport function layoutTurn(parts: readonly ContentPart[], cards: readonly Card[], options: TurnLayoutOptions = {}): TurnSegment[] {\n const byCall = new Map<string, Card[]>();\n for (const card of cards) {\n if (!card.callId) continue;\n const list = byCall.get(card.callId);\n if (list) list.push(card);\n else byCall.set(card.callId, [card]);\n }\n\n const segments: TurnSegment[] = [];\n const placed = new Set<string>();\n let textCount = 0;\n // A call that drew nothing should not split a paragraph into two blocks, but\n // the words either side of it were still written apart.\n let crossedCall = false;\n\n for (const part of parts) {\n if (part.type === \"text\") {\n if (!part.text) continue;\n const last = segments[segments.length - 1];\n if (last?.type === \"text\") {\n last.text += (crossedCall ? \"\\n\\n\" : \"\") + part.text;\n } else {\n segments.push({ type: \"text\", key: `text:${textCount}`, text: part.text });\n textCount += 1;\n }\n crossedCall = false;\n } else if (part.type === \"tool-call\") {\n const owned = byCall.get(part.callId) ?? [];\n for (const card of owned) placed.add(card.id);\n if (owned.length || options.keepEmptyOutputs) {\n segments.push({ type: \"output\", key: `call:${part.callId}`, callId: part.callId, cards: owned });\n crossedCall = false;\n } else {\n crossedCall = true;\n }\n }\n }\n\n for (const card of cards) {\n if (!placed.has(card.id)) segments.push({ type: \"card\", key: `card:${card.id}`, card });\n }\n return segments;\n}\n","// Quoted document spans — what the user pointed at, carried into one request.\n//\n// The load-bearing decision is where a quote LIVES, and the obvious answer is\n// wrong. A selection looks like screen state, so app-state seems to be its\n// home. It is not:\n//\n// - app-state answers \"what is the user looking at now\" and is re-read every\n// turn. A quote is pinned to ONE request; the turn after, the user has not\n// selected anything and it must be gone.\n// - It would go stale in history. Select A, send, select B — and the first\n// message, re-read later, would show B, because app-state has no memory of\n// what it said three turns ago.\n// - It is droppable. app-state losing its slot to budget pressure costs some\n// environment detail. A span the user deliberately highlighted losing its\n// slot loses part of what the user SAID — a correctness bug wearing a\n// budget optimisation's clothes.\n//\n// So a quote is part of the user's message: flattened into a text part for the\n// model, and kept structurally on `Message.metadata`, which is documented as\n// never reaching a provider. Nothing in the adapters changes.\n//\n// Drift follows the same rule. Whether the document has moved past the quoted\n// revision is checked once, when the message is sent, and recorded on the\n// quote — not re-derived on every turn, which would make an old message\n// describe the document's present rather than what was true when the user\n// spoke.\n\nimport type { DocumentSnapshot, DocumentStore } from \"../documents/types.js\";\n\n/** A span of a document artifact, resolved to source offsets. */\nexport type DocumentQuoteRef = {\n docId: string;\n title: string;\n /** Revision the span was taken from — compared at send time; see `drift`. */\n revision: number;\n /** Inclusive block index range. */\n blocks: [number, number];\n start: number;\n end: number;\n /** SOURCE markdown, not rendered text. */\n text: string;\n /**\n * How the document had moved past `revision` when the message was sent.\n * Absent when it had not, or when nothing checked — see `checkQuoteDrift`.\n */\n drift?: QuoteDrift;\n};\n\n/**\n * What a quote's document did between the quoted revision and the send.\n *\n * The quoted revision can be old the moment it is taken — a document card\n * further up the thread still shows the body it was created with — and the\n * model cannot tell from the text alone. Told, it re-reads; not told, it\n * proposes an edit against text that may no longer be there, or answers about\n * a paragraph the user has since rewritten.\n */\nexport type QuoteDrift =\n /** Past the quoted revision. `intact`: the quoted text still appears verbatim. */\n | { status: \"moved\"; revision: number; intact: boolean }\n /** The document no longer exists. */\n | { status: \"removed\" };\n\n/**\n * Compare a quote against the document as it is now. `undefined` when the\n * quote is current.\n *\n * Any revision other than the quoted one counts — a lower one means the id now\n * names a different document, which is drift too.\n */\nexport function quoteDrift(\n quote: DocumentQuoteRef,\n current: Pick<DocumentSnapshot, \"revision\" | \"markdown\"> | undefined,\n): QuoteDrift | undefined {\n if (!current) return { status: \"removed\" };\n if (current.revision === quote.revision) return undefined;\n return { status: \"moved\", revision: current.revision, intact: current.markdown.includes(quote.text) };\n}\n\n/**\n * Stamp each quote with its drift against the store, ready to send.\n *\n * A lookup that throws leaves that quote unstamped rather than failing the\n * send: the user's message matters more than the annotation, the quote still\n * names its revision, and an edit made from it is still checked against the\n * current one.\n */\nexport async function checkQuoteDrift(\n quotes: readonly DocumentQuoteRef[],\n documents: Pick<DocumentStore, \"get\">,\n): Promise<DocumentQuoteRef[]> {\n const lookups = new Map<string, Promise<DocumentSnapshot | undefined | null>>();\n return Promise.all(\n quotes.map(async (quote) => {\n let lookup = lookups.get(quote.docId);\n if (!lookup) {\n lookup = documents.get(quote.docId).catch(() => null);\n lookups.set(quote.docId, lookup);\n }\n const current = await lookup;\n const { drift: _unchecked, ...rest } = quote;\n if (current === null) return rest;\n const drift = quoteDrift(quote, current);\n return drift ? { ...rest, drift } : rest;\n }),\n );\n}\n\nconst driftNote = (drift: QuoteDrift | undefined): string => {\n if (!drift) return \"\";\n if (drift.status === \"removed\") return \"Note: this document no longer exists.\\n\";\n return drift.intact\n ? `Note: the document is now at v${drift.revision}. This text is still in it, but its block numbers may have shifted — re-read before editing.\\n`\n : `Note: the document is now at v${drift.revision}, and this text is no longer in it. Re-read before acting on the quote.\\n`;\n};\n\n/** Key under `Message.metadata` where quotes are stored for re-rendering. */\nexport const QUOTES_METADATA_KEY = \"documentQuotes\";\n\nconst fence = (text: string) => {\n // A quote can itself contain a ``` fence, so the wrapper grows past the\n // longest run inside it rather than truncating or escaping the content.\n const longest = [...text.matchAll(/`{3,}/g)].reduce((n, m) => Math.max(n, m[0].length), 2);\n return \"`\".repeat(longest + 1);\n};\n\n/**\n * Render quotes as the prefix of the user's message.\n *\n * Fenced rather than indented, and labelled with the document and block range,\n * so the model can tell quoted material from the user's own words — and can\n * name what it is about to change when the edit tools arrive. A stamped drift\n * becomes a note between the label and the text.\n */\nexport function formatQuotes(quotes: readonly DocumentQuoteRef[]): string {\n if (!quotes.length) return \"\";\n return quotes\n .map((q) => {\n const [from, to] = q.blocks;\n const where = from === to ? `block ${from}` : `blocks ${from}–${to}`;\n const f = fence(q.text);\n return `Quoted from \"${q.title}\" (${q.docId} v${q.revision}, ${where}):\\n${driftNote(q.drift)}${f}markdown\\n${q.text}\\n${f}`;\n })\n .join(\"\\n\\n\");\n}\n\n/** Prefix `text` with the quotes, keeping a blank line between them. */\nexport function withQuotes(text: string, quotes: readonly DocumentQuoteRef[]): string {\n const prefix = formatQuotes(quotes);\n if (!prefix) return text;\n return text.trim() ? `${prefix}\\n\\n${text}` : prefix;\n}\n\n/** Read quotes back off a message, for re-rendering the chips in history. */\nexport function quotesOf(metadata: Record<string, unknown> | undefined): DocumentQuoteRef[] {\n const raw = metadata?.[QUOTES_METADATA_KEY];\n return Array.isArray(raw) ? (raw as DocumentQuoteRef[]) : [];\n}\n","// Base64 for the proxy envelope, where a 20 MB upload is the sizing case.\n// `Buffer` is Node-only (core is isomorphic), so each direction takes the\n// fastest codec the runtime has: `Uint8Array.prototype.toBase64` /\n// `Uint8Array.fromBase64` where they exist, else `btoa` / `atob` over a binary\n// string built in bounded chunks (`String.fromCharCode(...bytes)` in one call\n// blows the call stack on anything bigger than a small image), and the\n// hand-rolled table below only for a runtime with neither, or for input that\n// is not a Uint8Array.\n\nconst ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\nconst REVERSE: Int16Array = (() => {\n const table = new Int16Array(128).fill(-1);\n for (let i = 0; i < ALPHABET.length; i += 1) table[ALPHABET.charCodeAt(i)] = i;\n return table;\n})();\n\n// Bytes per `String.fromCharCode.apply` call, far below every engine's argument limit.\nconst APPLY_CHUNK = 0x2000;\n\ntype NativeBase64 = {\n toBase64?: (this: Uint8Array) => string;\n fromBase64?: (s: string) => Uint8Array;\n};\n\nexport function bytesToBase64(bytes: Uint8Array): string {\n // An untyped caller's array or other typed array keeps the old answer: the\n // platform encoders reject it or read it differently.\n if (!(bytes instanceof Uint8Array)) return encodeWithTable(bytes);\n // Also keeps a detached buffer at \"\" — the native encoder throws on one.\n if (bytes.length === 0) return \"\";\n const { toBase64 } = Uint8Array.prototype as NativeBase64;\n if (typeof toBase64 === \"function\") return toBase64.call(bytes);\n if (typeof btoa === \"function\") {\n const binary: string[] = [];\n for (let i = 0; i < bytes.length; i += APPLY_CHUNK) {\n binary.push(String.fromCharCode.apply(null, bytes.subarray(i, i + APPLY_CHUNK) as unknown as number[]));\n }\n return btoa(binary.join(\"\"));\n }\n return encodeWithTable(bytes);\n}\n\nfunction encodeWithTable(bytes: Uint8Array): string {\n const chunks: string[] = [];\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const b0 = bytes[i]!;\n const b1 = i + 1 < bytes.length ? bytes[i + 1]! : 0;\n const b2 = i + 2 < bytes.length ? bytes[i + 2]! : 0;\n out +=\n ALPHABET[b0 >> 2]! +\n ALPHABET[((b0 & 0x03) << 4) | (b1 >> 4)]! +\n (i + 1 < bytes.length ? ALPHABET[((b1 & 0x0f) << 2) | (b2 >> 6)]! : \"=\") +\n (i + 2 < bytes.length ? ALPHABET[b2 & 0x3f]! : \"=\");\n // Flush periodically so the accumulator never becomes one enormous rope.\n if (out.length >= 0x8000) {\n chunks.push(out);\n out = \"\";\n }\n }\n chunks.push(out);\n return chunks.join(\"\");\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n // Tolerate whitespace/newlines (some serializers wrap long values).\n const clean = s.replace(/[\\s=]+/g, \"\");\n // The platform decoders reject a lone trailing character, which the table\n // silently drops; leave that input to the table so the answer stays the same.\n if (clean.length % 4 !== 1) {\n try {\n const native = Uint8Array as NativeBase64;\n if (typeof native.fromBase64 === \"function\") return native.fromBase64(clean);\n if (typeof atob === \"function\") {\n const binary = atob(clean);\n const out = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);\n return out;\n }\n } catch {\n // A character outside the alphabet. Find the first one, to report which\n // and where exactly as the table does, without decoding the input again.\n for (let i = 0; i < clean.length; i += 1) {\n const code = clean.charCodeAt(i);\n if (code >= 128 || REVERSE[code]! < 0) {\n throw new Error(`Invalid base64 character \"${clean[i]}\" at position ${i}.`);\n }\n }\n }\n }\n return decodeWithTable(clean);\n}\n\nfunction decodeWithTable(clean: string): Uint8Array {\n const out = new Uint8Array(Math.floor((clean.length * 3) / 4));\n let outPos = 0;\n let buffer = 0;\n let bits = 0;\n for (let i = 0; i < clean.length; i += 1) {\n const code = clean.charCodeAt(i);\n const value = code < 128 ? REVERSE[code]! : -1;\n if (value < 0) throw new Error(`Invalid base64 character \"${clean[i]}\" at position ${i}.`);\n buffer = (buffer << 6) | value;\n bits += 6;\n if (bits >= 8) {\n bits -= 8;\n out[outPos] = (buffer >> bits) & 0xff;\n outPos += 1;\n }\n }\n return out.subarray(0, outPos);\n}\n","// DirectTransport — browser (or server) talks straight to the provider with a\n// key you supply.\n//\n// In a browser this puts the key in client memory and in the network tab. That\n// is fine for a local playground or a desktop app with the user's own key, and\n// wrong for anything multi-tenant. `credentialSafe` is false so the runtime can\n// warn, and `assertBrowserUseAcknowledged` makes the footgun explicit rather\n// than silent.\n\nimport { isMultipartBody, type Transport, type TransportRequest } from \"./types.js\";\n\nexport type DirectTransportConfig = {\n /** Provider API root, no trailing slash. e.g. \"https://api.openai.com/v1\". */\n baseUrl: string;\n /** Static key, or a getter for keys that rotate / come from a keychain. */\n apiKey: string | (() => string | Promise<string>);\n /**\n * How the key rides on the wire. \"bearer\" (default) sends\n * `Authorization: Bearer <key>`; \"x-api-key\" sends the `x-api-key` header —\n * what Anthropic's Messages API expects.\n */\n authStyle?: \"bearer\" | \"x-api-key\";\n /** Sent on every request; merged under per-request headers. */\n headers?: Record<string, string>;\n /**\n * Required to use this transport in a browser. Naming it forces the caller to\n * state the risk out loud instead of discovering it in production.\n */\n dangerouslyAllowBrowser?: boolean;\n fetchImpl?: typeof fetch;\n};\n\nconst isBrowser = () => typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\nexport function buildUrl(baseUrl: string, path: string, query?: TransportRequest[\"query\"]): string {\n const url = new URL(`${baseUrl.replace(/\\/$/, \"\")}${path.startsWith(\"/\") ? path : `/${path}`}`);\n for (const [k, v] of Object.entries(query ?? {})) {\n if (v !== undefined && v !== null) url.searchParams.set(k, String(v));\n }\n return url.toString();\n}\n\nexport function createDirectTransport(config: DirectTransportConfig): Transport {\n if (isBrowser() && !config.dangerouslyAllowBrowser) {\n throw new Error(\n \"DirectTransport sends your API key from the browser. Pass `dangerouslyAllowBrowser: true` to accept that, \" +\n \"or use createProxyTransport() so the key stays on your server.\",\n );\n }\n const doFetch = config.fetchImpl ?? globalThis.fetch;\n\n return {\n kind: \"direct\",\n credentialSafe: !isBrowser(),\n async fetch(req: TransportRequest): Promise<Response> {\n const apiKey = typeof config.apiKey === \"function\" ? await config.apiKey() : config.apiKey;\n const headers: Record<string, string> = {\n ...(config.authStyle === \"x-api-key\" ? { \"x-api-key\": apiKey } : { authorization: `Bearer ${apiKey}` }),\n ...config.headers,\n ...req.headers,\n };\n if (req.stream) headers[\"accept\"] = \"text/event-stream\";\n\n let body: BodyInit | undefined;\n if (isMultipartBody(req.body)) {\n // No content-type here — fetch sets multipart/form-data with the boundary.\n const form = new FormData();\n for (const [k, v] of Object.entries(req.body.fields)) form.set(k, v);\n for (const f of req.body.files) {\n form.set(f.field, new Blob([f.data as BlobPart], f.mediaType ? { type: f.mediaType } : {}), f.filename);\n }\n body = form;\n } else if (req.body !== undefined) {\n headers[\"content-type\"] = \"application/json\";\n body = JSON.stringify(req.body);\n }\n\n return doFetch(buildUrl(config.baseUrl, req.path, req.query), {\n method: req.method,\n headers,\n body,\n signal: req.signal,\n });\n },\n };\n}\n","// ProxyTransport — the browser calls your own backend, which injects the key and\n// forwards to the provider. This is the default, and the only shape that is\n// honest in a multi-user app.\n//\n// The wire format between client and BFF is intentionally trivial: the client\n// declares which provider, path, method and body it wants; the server decides\n// whether to allow it. `createProxyHandler` (@supersolutions/super-chat-server) is the matching half,\n// and it allowlists paths — a proxy that forwards any path is an open relay for\n// your API key.\n\nimport { bytesToBase64 } from \"./binary.js\";\nimport { isMultipartBody, type Transport, type TransportRequest } from \"./types.js\";\n\nexport type ProxyTransportConfig = {\n /** Base path of your proxy route, e.g. \"/api/agent\". */\n url: string;\n /** Extra headers (session cookie is automatic; use this for CSRF tokens). */\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);\n credentials?: RequestCredentials;\n fetchImpl?: typeof fetch;\n};\n\n/** The envelope a ProxyTransport POSTs to the BFF. Exported so the server half can type it. */\nexport type ProxyEnvelope = {\n provider: string;\n path: string;\n method: \"GET\" | \"POST\" | \"DELETE\";\n body?: unknown;\n query?: Record<string, string | number | boolean | undefined>;\n stream?: boolean;\n /**\n * Per-request headers for the UPSTREAM call (org ids, beta flags, an MCP\n * session id). The server half forwards them after stripping credential\n * headers and then applies its own key on top — a client can request\n * headers, never substitute the credential.\n */\n headers?: Record<string, string>;\n};\n\n/**\n * A `MultipartBody` as it travels inside the JSON envelope: bytes become\n * base64 strings so the client→BFF wire stays one method, one body shape.\n * Base64 costs +33%, so treat ~20 MB per upload as the practical ceiling —\n * beyond that, use a direct transport or your own upload route.\n */\nexport type SerializedMultipartBody = {\n kind: \"multipart\";\n fields: Record<string, string>;\n files: { field: string; filename: string; mediaType?: string; data: string }[];\n};\n\nexport function createProxyTransport(config: ProxyTransportConfig): Transport {\n const doFetch = config.fetchImpl ?? globalThis.fetch;\n\n return {\n kind: \"proxy\",\n credentialSafe: true,\n async fetch(req: TransportRequest): Promise<Response> {\n const extra = typeof config.headers === \"function\" ? await config.headers() : config.headers;\n const body: unknown = isMultipartBody(req.body)\n ? ({\n kind: \"multipart\",\n fields: req.body.fields,\n files: req.body.files.map((f) => ({\n field: f.field,\n filename: f.filename,\n ...(f.mediaType ? { mediaType: f.mediaType } : {}),\n data: bytesToBase64(f.data),\n })),\n } satisfies SerializedMultipartBody)\n : req.body;\n\n const envelope: ProxyEnvelope = {\n provider: req.provider,\n path: req.path,\n method: req.method,\n body,\n query: req.query,\n stream: req.stream,\n // Inside the envelope, not on the outer request — the BFF builds the\n // upstream headers itself, and anything on the outer request is\n // between the browser and the BFF (cookies, CSRF), not for upstream.\n ...(req.headers ? { headers: req.headers } : {}),\n };\n\n // Always POST the envelope, even for provider-side GETs (job polling):\n // one method and one body shape keeps the server handler and any CSRF\n // middleware simple, and provider GETs carry no cacheable semantics for us.\n return doFetch(config.url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(req.stream ? { accept: \"text/event-stream\" } : {}),\n ...extra,\n },\n body: JSON.stringify(envelope),\n credentials: config.credentials ?? \"same-origin\",\n signal: req.signal,\n });\n },\n };\n}\n","// Public provider profiles describe an endpoint without carrying its secret.\n// A profile is safe to render in a picker or persist in localStorage; the API\n// key stays in a Transport (direct/BYOK) or in createProxyHandler (server).\n\nimport { createDirectTransport, type DirectTransportConfig } from \"../transport/direct.js\";\nimport type { Transport } from \"../transport/types.js\";\nimport { createAnthropicProvider } from \"./anthropic/adapter.js\";\nimport { createOpenAIProvider } from \"./openai/adapter.js\";\nimport type { ModelInfo, Provider, ProviderCapabilities } from \"./types.js\";\n\nexport type ProviderProtocol = \"openai-responses\" | \"openai-chat\" | \"anthropic-messages\";\n\nexport type ProviderProfile = {\n /** Stable routing id. It must match the proxy provider key in proxy mode. */\n id: string;\n label: string;\n protocol: ProviderProtocol;\n /** Provider API root including its version prefix, without a trailing slash. */\n baseUrl: string;\n models?: ModelInfo[];\n capabilities?: Partial<ProviderCapabilities>;\n};\n\nexport const OPENAI_OFFICIAL_PROFILE: ProviderProfile = {\n id: \"openai\",\n label: \"OpenAI\",\n protocol: \"openai-responses\",\n baseUrl: \"https://api.openai.com/v1\",\n};\n\nexport const ANTHROPIC_OFFICIAL_PROFILE: ProviderProfile = {\n id: \"anthropic\",\n label: \"Anthropic\",\n protocol: \"anthropic-messages\",\n baseUrl: \"https://api.anthropic.com/v1\",\n};\n\nexport function createOpenAICompatibleProfile(\n profile: Omit<ProviderProfile, \"protocol\"> & { protocol?: \"openai-chat\" },\n): ProviderProfile {\n return normalizeProviderProfile({ ...profile, protocol: \"openai-chat\" });\n}\n\n/** Normalize user-authored profile fields and reject unsafe/ambiguous roots. */\nexport function normalizeProviderProfile(profile: ProviderProfile): ProviderProfile {\n const id = profile.id.trim();\n const label = profile.label.trim();\n if (!id || !/^[a-z0-9][a-z0-9._-]*$/i.test(id)) {\n throw new Error(\"Provider profile id must use letters, numbers, dots, underscores, or hyphens.\");\n }\n if (!label) throw new Error(\"Provider profile label is required.\");\n\n let url: URL;\n try {\n url = new URL(profile.baseUrl);\n } catch {\n throw new Error(\"Provider profile baseUrl must be an absolute URL.\");\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new Error(\"Provider profile baseUrl must use http or https.\");\n }\n if (url.username || url.password) {\n throw new Error(\"Provider profile baseUrl cannot contain credentials.\");\n }\n if (url.search || url.hash) {\n throw new Error(\"Provider profile baseUrl cannot include a query or fragment.\");\n }\n\n return {\n ...profile,\n id,\n label,\n baseUrl: url.toString().replace(/\\/$/, \"\"),\n };\n}\n\n/** Build the wire adapter for a profile. Credentials remain in the transport. */\nexport function createProviderFromProfile(profileInput: ProviderProfile, transport: Transport): Provider {\n const profile = normalizeProviderProfile(profileInput);\n const common = {\n transport,\n id: profile.id,\n label: profile.label,\n ...(profile.models ? { models: profile.models } : {}),\n ...(profile.capabilities ? { capabilities: profile.capabilities } : {}),\n };\n\n if (profile.protocol === \"anthropic-messages\") return createAnthropicProvider(common);\n return createOpenAIProvider({\n ...common,\n dialect: profile.protocol === \"openai-chat\" ? \"chat\" : \"responses\",\n });\n}\n\nexport type ProfileDirectTransportConfig = Omit<DirectTransportConfig, \"baseUrl\" | \"authStyle\">;\n\n/** Build a BYOK/server-direct transport with the profile's URL and auth style. */\nexport function createDirectTransportForProfile(\n profileInput: ProviderProfile,\n config: ProfileDirectTransportConfig,\n): Transport {\n const profile = normalizeProviderProfile(profileInput);\n return createDirectTransport({\n ...config,\n baseUrl: profile.baseUrl,\n ...(profile.protocol === \"anthropic-messages\" ? { authStyle: \"x-api-key\" as const } : {}),\n });\n}\n","import type { MediaSource } from \"../content/types.js\";\nimport type { CallOptions } from \"../providers/types.js\";\n\nexport type GeneratedMediaKind = \"image\" | \"audio\" | \"video\";\n\nexport type GeneratedMedia = {\n id: string;\n kind: GeneratedMediaKind;\n source: MediaSource;\n mediaType: string;\n provider: string;\n model?: string;\n revisedPrompt?: string;\n width?: number;\n height?: number;\n durationMs?: number;\n createdAt: number;\n};\n\nexport type MediaProviderCapabilities = {\n imageGeneration: boolean;\n speechGeneration: boolean;\n transcription: boolean;\n videoGeneration: boolean;\n asyncJobs: boolean;\n};\n\nexport type ImageGenerationRequest = {\n prompt: string;\n model?: string;\n n?: number;\n size?: string;\n quality?: string;\n style?: string;\n /** OpenAI-compatible response representation. Defaults to provider behavior. */\n responseFormat?: \"url\" | \"b64_json\";\n /** Escape hatch for endpoint-specific fields; normalized fields above win. */\n providerOptions?: Record<string, unknown>;\n};\n\nexport type SpeechGenerationRequest = {\n input: string;\n model?: string;\n voice?: string;\n format?: string;\n providerOptions?: Record<string, unknown>;\n};\n\nexport type TranscriptionRequest = {\n data: Blob | ArrayBuffer | Uint8Array;\n filename: string;\n mediaType?: string;\n model?: string;\n providerOptions?: Record<string, unknown>;\n};\n\nexport type Transcript = { text: string; language?: string; durationMs?: number; raw?: unknown };\n\nexport type VideoGenerationRequest = {\n prompt: string;\n model?: string;\n image?: MediaSource;\n durationSeconds?: number;\n providerOptions?: Record<string, unknown>;\n};\n\nexport type MediaJobHandle = { provider: string; id: string; kind: GeneratedMediaKind; createdAt: number };\nexport type MediaJobSnapshot = {\n handle: MediaJobHandle;\n status: \"queued\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n result?: GeneratedMedia[];\n error?: { message: string; code?: string };\n};\n\nexport type MediaProvider = {\n readonly id: string;\n readonly label: string;\n readonly capabilities: MediaProviderCapabilities;\n generateImage?(req: ImageGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia[]>;\n generateSpeech?(req: SpeechGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia>;\n transcribe?(req: TranscriptionRequest, opts?: CallOptions): Promise<Transcript>;\n startVideoJob?(req: VideoGenerationRequest, opts?: CallOptions): Promise<MediaJobHandle>;\n pollMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;\n cancelMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;\n};\n\n/** Resolve an asset for HTML renderers without losing its MIME type. */\nexport function generatedMediaUrl(asset: GeneratedMedia): string | null {\n if (asset.source.kind === \"url\") return asset.source.url;\n if (asset.source.kind === \"base64\") return `data:${asset.mediaType};base64,${asset.source.data}`;\n return null;\n}\n","// OpenAI-compatible image generation. This deliberately uses Transport, so the\n// same implementation works against official OpenAI, oneAPI, or a server proxy.\n\nimport { nextId } from \"../content/parts.js\";\nimport { errorFromResponse } from \"../transport/retry.js\";\nimport type { Transport } from \"../transport/types.js\";\nimport type { GeneratedMedia, ImageGenerationRequest, MediaProvider } from \"./types.js\";\n\ntype ImageGenerationResponse = {\n created?: number;\n data?: { url?: string; b64_json?: string; revised_prompt?: string }[];\n};\n\nconst dimensionsFromSize = (size?: string): { width: number; height: number } | undefined => {\n const match = /^(\\d+)x(\\d+)$/i.exec(size?.trim() ?? \"\");\n if (!match) return undefined;\n const width = Number(match[1]);\n const height = Number(match[2]);\n return width > 0 && height > 0 ? { width, height } : undefined;\n};\n\nexport type OpenAIImageProviderConfig = {\n transport: Transport;\n /** Must match the provider key registered by createProxyHandler. */\n id?: string;\n label?: string;\n defaultModel?: string;\n};\n\nexport function createOpenAIImageProvider(config: OpenAIImageProviderConfig): MediaProvider {\n const id = config.id ?? \"openai\";\n return {\n id,\n label: config.label ?? \"OpenAI Images\",\n capabilities: {\n imageGeneration: true,\n speechGeneration: false,\n transcription: false,\n videoGeneration: false,\n asyncJobs: false,\n },\n async generateImage(req: ImageGenerationRequest, opts): Promise<GeneratedMedia[]> {\n const prompt = req.prompt.trim();\n if (!prompt) throw new Error(\"Image generation prompt is required.\");\n const body = {\n ...req.providerOptions,\n prompt,\n ...(req.model ?? config.defaultModel ? { model: req.model ?? config.defaultModel } : {}),\n ...(req.n != null ? { n: req.n } : {}),\n ...(req.size ? { size: req.size } : {}),\n ...(req.quality ? { quality: req.quality } : {}),\n ...(req.style ? { style: req.style } : {}),\n ...(req.responseFormat ? { response_format: req.responseFormat } : {}),\n };\n const res = await config.transport.fetch({\n provider: id,\n path: \"/images/generations\",\n method: \"POST\",\n body,\n headers: opts?.headers,\n signal: opts?.signal,\n });\n if (!res.ok) throw await errorFromResponse(res, id);\n const json = (await res.json()) as ImageGenerationResponse;\n if (!json.data?.length) throw new Error(`Provider \"${id}\" returned no generated images.`);\n const createdAt = (json.created ?? Math.floor(Date.now() / 1000)) * 1000;\n const dimensions = dimensionsFromSize(req.size);\n return json.data.map((item) => {\n if (!item.url && !item.b64_json) throw new Error(`Provider \"${id}\" returned an image without url or b64_json.`);\n return {\n id: nextId(\"media\"),\n kind: \"image\" as const,\n source: item.url ? { kind: \"url\" as const, url: item.url } : { kind: \"base64\" as const, data: item.b64_json! },\n mediaType: \"image/png\",\n provider: id,\n ...(req.model ?? config.defaultModel ? { model: req.model ?? config.defaultModel } : {}),\n ...(item.revised_prompt ? { revisedPrompt: item.revised_prompt } : {}),\n ...(dimensions ?? {}),\n createdAt,\n };\n });\n },\n };\n}\n","import type { MediaCard } from \"../cards/types.js\";\nimport type { ToolDefinition } from \"../tools/types.js\";\nimport { generatedMediaUrl, type ImageGenerationRequest, type MediaProvider } from \"./types.js\";\n\nexport type GenerateImageToolOptions = {\n name?: string;\n /** Used when the model does not explicitly select one. */\n defaultModel?: string;\n};\n\n/**\n * Expose a MediaProvider to an agent without teaching the chat Provider any\n * image-generation wire format. The compact output goes back to the model;\n * the binary/URL payload stays in a media card for the user.\n */\nexport function createGenerateImageTool(provider: MediaProvider, options: GenerateImageToolOptions = {}): ToolDefinition {\n return {\n name: options.name ?? \"generateImage\",\n side: \"write\",\n strict: true,\n description: \"Generate one or more images from a prompt and show them to the user.\",\n loading: (input) => {\n const request = (input ?? {}) as Partial<ImageGenerationRequest>;\n const count = Math.max(1, Math.min(10, Number.isFinite(request.n) ? Math.round(request.n!) : 1));\n const size = /^(\\d+)x(\\d+)$/i.exec(request.size?.trim() ?? \"\");\n return {\n kind: \"media\",\n label: count === 1 ? \"Generating image\" : `Generating ${count} images`,\n count,\n ...(size ? { aspectRatio: `${Number(size[1])} / ${Number(size[2])}` } : {}),\n };\n },\n inputSchema: {\n type: \"object\",\n required: [\"prompt\"],\n properties: {\n prompt: { type: \"string\", description: \"A concrete visual description of the image to generate.\" },\n model: { type: \"string\" },\n n: { type: \"integer\", minimum: 1, maximum: 10 },\n size: { type: \"string\", description: \"Provider-supported size, for example 1024x1024.\" },\n quality: { type: \"string\" },\n style: { type: \"string\" },\n },\n additionalProperties: false,\n },\n async execute(input, ctx) {\n if (!provider.generateImage || !provider.capabilities.imageGeneration) {\n return { output: { ok: false, error: `Provider \"${provider.id}\" cannot generate images.` }, failure: \"execution-error\" as const };\n }\n const request = (input ?? {}) as ImageGenerationRequest;\n if (!request.prompt?.trim()) {\n return { output: { ok: false, error: \"`prompt` is required.\" }, failure: \"invalid-input\" as const };\n }\n const assets = await provider.generateImage(\n { ...request, ...(request.model || !options.defaultModel ? {} : { model: options.defaultModel }) },\n { signal: ctx.signal },\n );\n const items = assets.flatMap((asset) => {\n const url = generatedMediaUrl(asset);\n return url\n ? [{\n url,\n mediaType: asset.mediaType,\n alt: asset.revisedPrompt ?? request.prompt,\n caption: asset.revisedPrompt,\n ...(asset.width ? { width: asset.width } : {}),\n ...(asset.height ? { height: asset.height } : {}),\n ...(asset.durationMs ? { durationMs: asset.durationMs } : {}),\n }]\n : [];\n });\n const card: MediaCard | undefined = items.length\n ? { kind: \"media\", title: assets.length === 1 ? \"Generated image\" : \"Generated images\", layout: assets.length === 1 ? \"single\" : \"grid\", items }\n : undefined;\n return {\n output: {\n ok: true,\n provider: provider.id,\n count: assets.length,\n assets: assets.map((asset) => ({\n id: asset.id,\n kind: asset.kind,\n mediaType: asset.mediaType,\n ...(asset.model ? { model: asset.model } : {}),\n ...(asset.revisedPrompt ? { revisedPrompt: asset.revisedPrompt } : {}),\n })),\n },\n ...(card ? { card } : {}),\n };\n },\n };\n}\n","// Token estimation without a tokenizer.\n//\n// Shipping tiktoken to the browser costs ~1MB of WASM plus a rank table, to\n// answer a question we only need approximately: \"will this fit in the budget\".\n// A byte-aware heuristic gets within roughly ±15% on ordinary prose and is\n// deliberately biased to OVER-estimate, because the failure mode of\n// over-estimating is dropping one extra history turn, while the failure mode of\n// under-estimating is a 400 from the provider mid-conversation.\n//\n// Hosts that need exactness inject their own counter through `TokenCounter`.\n\nexport type TokenCounter = (text: string) => number;\n\nconst LATIN_CHARS_PER_TOKEN = 3.7; // GPT-family BPE on English prose\nconst CJK_CHARS_PER_TOKEN = 1.1; // CJK is close to one token per character\n\n/**\n * Estimate tokens for a string. Splits CJK from Latin because a single ratio is\n * wrong by 3x on Chinese/Japanese text — which matters here, since this\n * framework is being built by someone who writes prompts in both.\n */\nexport function estimateTokens(text: string): number {\n if (!text) return 0;\n\n let cjk = 0;\n let other = 0;\n for (const ch of text) {\n const code = ch.codePointAt(0)!;\n const isCjk =\n (code >= 0x3040 && code <= 0x30ff) || // kana\n (code >= 0x3400 && code <= 0x4dbf) || // CJK ext A\n (code >= 0x4e00 && code <= 0x9fff) || // CJK unified\n (code >= 0xac00 && code <= 0xd7af) || // hangul\n (code >= 0xf900 && code <= 0xfaff);\n if (isCjk) cjk += 1;\n else other += 1;\n }\n\n const base = cjk / CJK_CHARS_PER_TOKEN + other / LATIN_CHARS_PER_TOKEN;\n // Structural overhead: JSON punctuation and whitespace tokenize poorly and\n // are common in tool payloads, so add a small margin rather than under-count.\n return Math.ceil(base * 1.05);\n}\n\n/** JSON payloads (tool args/results) tokenize worse than prose — count the serialized form. */\nexport function estimateJsonTokens(value: unknown): number {\n if (value == null) return 1;\n if (typeof value === \"string\") return estimateTokens(value);\n try {\n return estimateTokens(JSON.stringify(value));\n } catch {\n return estimateTokens(String(value));\n }\n}\n\n/** Fixed per-message overhead the provider adds for role markers and separators. */\nexport const MESSAGE_OVERHEAD_TOKENS = 4;\n","// Token budgeting.\n//\n// The context window is a fixed resource contended for by five claimants:\n// instructions, skills, memory, history, and the model's own output. Without an\n// explicit allocator whichever one grows fastest (history) silently starves the\n// rest, and the first symptom is the model \"forgetting\" its rules on long\n// threads — which reads like a prompt problem and isn't.\n\nimport { estimateTokens, MESSAGE_OVERHEAD_TOKENS, type TokenCounter } from \"./estimate.js\";\nimport type { Message } from \"../content/types.js\";\n\nexport type BudgetShares = {\n /** Reserved for the model's reply. Never lent out. */\n output: number;\n system: number;\n skills: number;\n memory: number;\n history: number;\n tools: number;\n};\n\nexport type TokenBudget = {\n contextWindow: number;\n shares: BudgetShares;\n /** Safety margin, since estimation is approximate. */\n reservePct: number;\n};\n\nexport function createBudget(contextWindow: number, opts: Partial<BudgetShares> & { reservePct?: number; maxOutputTokens?: number } = {}): TokenBudget {\n const output = opts.output ?? opts.maxOutputTokens ?? Math.min(8_000, Math.floor(contextWindow * 0.15));\n const reservePct = opts.reservePct ?? 0.05;\n const usable = Math.floor(contextWindow * (1 - reservePct)) - output;\n\n // Defaults chosen so that on a 128k window the fixed layers get generous room\n // and history still takes the majority — history is where the actual\n // conversation lives, and starving it to preserve skills is the wrong trade.\n return {\n contextWindow,\n reservePct,\n shares: {\n output,\n system: opts.system ?? Math.floor(usable * 0.08),\n skills: opts.skills ?? Math.floor(usable * 0.2),\n memory: opts.memory ?? Math.floor(usable * 0.07),\n tools: opts.tools ?? Math.floor(usable * 0.15),\n history: opts.history ?? Math.floor(usable * 0.5),\n },\n };\n}\n\nexport const totalAllocated = (b: TokenBudget): number =>\n b.shares.system + b.shares.skills + b.shares.memory + b.shares.tools + b.shares.history;\n\n/**\n * Fill a budget with prioritized items, greedily, highest first.\n *\n * Greedy rather than optimal (knapsack) because the ordering is meaningful:\n * skill priority encodes the author's intent about what must survive, and an\n * optimal packer would happily drop a critical high-priority skill to fit two\n * cheap ones.\n */\nexport function packByPriority<T>(\n items: readonly T[],\n limit: number,\n sizeOf: (item: T) => number,\n): { included: T[]; dropped: { item: T; size: number }[]; used: number } {\n const included: T[] = [];\n const dropped: { item: T; size: number }[] = [];\n let used = 0;\n\n for (const item of items) {\n const size = sizeOf(item);\n if (used + size <= limit) {\n included.push(item);\n used += size;\n } else {\n dropped.push({ item, size });\n }\n }\n return { included, dropped, used };\n}\n\n// Per-message token counts, cached by message object identity. Persisted\n// messages are never mutated in place (a new object is built for every\n// change — see runtime/run.ts), so a cached count never goes stale, and a\n// context build that re-walks the same history on every step (budget checks,\n// compaction, the builder's own summation) does not re-count every character\n// of every message it already counted last time.\n//\n// Keyed by object identity rather than `message.id`: compaction mints\n// synthetic summary messages with a formulaic, non-unique id\n// (`summary_${cut}`), so two DIFFERENT messages can share an id — an id-keyed\n// cache would risk serving one message's count for another's. The counter is\n// also part of the key: a caller-supplied counter and the default estimator\n// must not share a cache entry.\nconst messageTokenCache = new WeakMap<Message, WeakMap<TokenCounter, number>>();\n\nexport function countMessageTokens(m: Message, counter: TokenCounter = estimateTokens): number {\n const cached = messageTokenCache.get(m)?.get(counter);\n if (cached !== undefined) return cached;\n\n let total = MESSAGE_OVERHEAD_TOKENS;\n for (const part of m.parts) {\n switch (part.type) {\n case \"text\":\n case \"reasoning\":\n total += counter(part.text);\n break;\n case \"tool-call\":\n total += counter(part.name) + counter(typeof part.input === \"string\" ? part.input : JSON.stringify(part.input ?? {})) + 8;\n break;\n case \"tool-result\":\n total += counter(typeof part.output === \"string\" ? part.output : JSON.stringify(part.output ?? null)) + 8;\n break;\n case \"image\":\n // Images bill by tiles, not characters. 1105 is the low-detail flat cost\n // for a 512px tile; high detail scales with dimensions we don't know\n // here, so assume a common 2-tile image rather than guessing zero.\n total += part.detail === \"low\" ? 85 : 1_105;\n break;\n case \"file\":\n total += 2_000; // a parsed PDF page is roughly this; deliberately pessimistic\n break;\n case \"audio\":\n total += part.transcript ? counter(part.transcript) : 500;\n break;\n case \"artifact\":\n break; // stripped before send — costs nothing\n }\n }\n\n let byCounter = messageTokenCache.get(m);\n if (!byCounter) {\n byCounter = new WeakMap();\n messageTokenCache.set(m, byCounter);\n }\n byCounter.set(counter, total);\n return total;\n}\n\nexport const countMessagesTokens = (messages: readonly Message[], counter: TokenCounter = estimateTokens): number =>\n messages.reduce((sum, m) => sum + countMessageTokens(m, counter), 0);\n","// Skill matching. Deliberately lexical — no embeddings, no network call.\n//\n// Retrieval that requires an API round-trip before the *first* token of the real\n// request is a latency tax on every turn, and for a curated skill set (tens, not\n// millions) alias scoring is both faster and more predictable. A host that wants\n// semantic retrieval implements `SkillRegistry`'s matcher hook instead; this is\n// the default, not the only option.\n\nimport type { Skill, SkillMatch, SkillSection } from \"./types.js\";\n\nconst STOPWORDS = new Set([\n \"a\", \"an\", \"the\", \"and\", \"or\", \"but\", \"if\", \"then\", \"to\", \"of\", \"in\", \"on\", \"for\", \"with\", \"at\", \"by\",\n \"is\", \"are\", \"was\", \"were\", \"be\", \"been\", \"do\", \"does\", \"did\", \"can\", \"could\", \"would\", \"should\",\n \"i\", \"me\", \"my\", \"you\", \"your\", \"it\", \"its\", \"this\", \"that\", \"what\", \"how\", \"please\", \"help\",\n]);\n\nexport function tokenize(input: string): string[] {\n return input\n .toLowerCase()\n // Keep CJK runs as single tokens; they carry meaning without spaces.\n .split(/[^\\p{L}\\p{N}]+/u)\n .filter((t) => t.length > 1 && !STOPWORDS.has(t));\n}\n\n// Aliases/tags/names are registered once and matched against on every query\n// thereafter, so their tokenization is cached rather than redone per call.\n// Unbounded by design: the keys are the distinct alias/tag/name strings a\n// process ever sees, which for a curated skill set is tens, not millions.\nconst aliasTokenCache = new Map<string, string[]>();\nfunction tokenizeAlias(a: string): string[] {\n let tokens = aliasTokenCache.get(a);\n if (!tokens) {\n tokens = tokenize(a);\n aliasTokenCache.set(a, tokens);\n }\n return tokens;\n}\n\n/**\n * Score one alias against the query.\n *\n * Both containment directions are checked on purpose: a query \"add liquidity to\n * the SUI pool\" should hit the alias \"add liquidity\" (alias ⊂ query), and a\n * query \"clmm\" should hit the alias \"clmm liquidity\" (query ⊂ alias). Only one\n * direction and half the natural phrasings miss.\n */\nfunction scoreAlias(alias: string, query: string, queryTokens: Set<string>): number {\n const a = alias.toLowerCase().trim();\n if (!a) return 0;\n if (a === query) return 6;\n if (queryTokens.has(a)) return 4;\n if (query.includes(a)) return 3;\n if (a.includes(query) && query.length >= 3) return 2;\n // Partial token overlap for multi-word aliases: \"provide liquidity\" vs \"liquidity\".\n const aliasTokens = tokenizeAlias(a);\n if (aliasTokens.length > 1) {\n const hits = aliasTokens.filter((t) => queryTokens.has(t)).length;\n if (hits) return 1.5 * (hits / aliasTokens.length);\n }\n return 0;\n}\n\nexport function scoreSkill(skill: Skill, query: string): { score: number; reason: string; sections: SkillSection[] } {\n const q = query.toLowerCase().trim();\n if (!q) return { score: 0, reason: \"empty query\", sections: [] };\n const queryTokens = new Set(tokenize(q));\n\n let score = 0;\n const reasons: string[] = [];\n\n const nameScore = scoreAlias(skill.name, q, queryTokens);\n if (nameScore) {\n score += nameScore * 1.2;\n reasons.push(`name:${nameScore.toFixed(1)}`);\n }\n if (scoreAlias(skill.id, q, queryTokens)) {\n score += 4;\n reasons.push(\"id\");\n }\n\n let bestAlias = 0;\n for (const alias of skill.aliases ?? []) bestAlias = Math.max(bestAlias, scoreAlias(alias, q, queryTokens));\n if (bestAlias) {\n score += bestAlias;\n reasons.push(`alias:${bestAlias.toFixed(1)}`);\n }\n\n let tagHits = 0;\n for (const tag of skill.tags ?? []) if (scoreAlias(tag, q, queryTokens)) tagHits += 1;\n if (tagHits) {\n score += Math.min(tagHits, 3) * 1.2;\n reasons.push(`tags:${tagHits}`);\n }\n\n // Sections matched independently so a long skill can contribute just the\n // relevant part rather than its whole body.\n const sections: SkillSection[] = [];\n for (const section of skill.sections ?? []) {\n const secScore = Math.max(\n scoreAlias(section.id, q, queryTokens),\n scoreAlias(section.name, q, queryTokens),\n ...(section.aliases ?? []).map((a) => scoreAlias(a, q, queryTokens)),\n );\n if (secScore >= 1.5) {\n sections.push(section);\n score += secScore * 0.6;\n }\n }\n if (sections.length) reasons.push(`sections:${sections.length}`);\n\n score += skill.priority ?? 0;\n\n return { score, reason: reasons.join(\" \") || \"no match\", sections };\n}\n\n/** Rank skills by relevance. `threshold` filters noise; sorting is stable by id for determinism. */\nexport function matchSkills(skills: readonly Skill[], query: string, threshold = 1.5): SkillMatch[] {\n return skills\n .map((skill) => {\n const { score, reason, sections } = scoreSkill(skill, query);\n return { skill, score, reason, sections };\n })\n .filter((m) => m.score >= threshold)\n .sort((a, b) => b.score - a.score || a.skill.id.localeCompare(b.skill.id));\n}\n","// The skill registry: one store, three delivery modes, plus the tool surface\n// that makes `manual` skills reachable by the model.\n\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport { matchSkills } from \"./match.js\";\nimport type { ResolvedSkill, Skill, SkillContext, SkillMatch, SkillSection } from \"./types.js\";\n\nexport type SkillMatcher = (skills: readonly Skill[], query: string) => SkillMatch[];\n\nexport type SkillRegistryOptions = {\n /** Swap in embeddings/BM25 without touching the rest of the pipeline. */\n matcher?: SkillMatcher;\n /** Max `matched`-mode skills injected per turn. Guards against a query that hits everything. */\n maxMatched?: number;\n threshold?: number;\n};\n\n/** Render a skill (or just its matched sections) to the text that goes in context. */\nexport async function renderSkill(\n skill: Skill,\n ctx: SkillContext,\n sections?: SkillSection[],\n): Promise<string> {\n const body = typeof skill.body === \"function\" ? await skill.body(ctx) : skill.body;\n const chosen = sections?.length ? sections : skill.sections ?? [];\n\n const parts = [`## ${skill.name}`, body.trim()];\n for (const section of chosen) {\n parts.push(`### ${section.name}`, section.body.trim());\n }\n if (skill.resources?.length) {\n parts.push(\n \"Resources:\",\n skill.resources.map((r) => `- ${r.name}${r.description ? ` — ${r.description}` : \"\"}: ${r.uri}`).join(\"\\n\"),\n );\n }\n return parts.filter(Boolean).join(\"\\n\\n\");\n}\n\nexport class SkillRegistry {\n private skills = new Map<string, Skill>();\n private readonly matcher: SkillMatcher;\n private readonly maxMatched: number;\n private readonly threshold: number;\n /** Cached `manualIndex()` render; invalidated by `register`/`unregister`. */\n private manualIndexCache: string | undefined;\n\n constructor(skills: readonly Skill[] = [], options: SkillRegistryOptions = {}) {\n this.threshold = options.threshold ?? 1.5;\n this.matcher = options.matcher ?? ((s, q) => matchSkills(s, q, this.threshold));\n this.maxMatched = options.maxMatched ?? 3;\n for (const s of skills) this.register(s);\n }\n\n register(skill: Skill): this {\n this.skills.set(skill.id, skill);\n this.manualIndexCache = undefined;\n return this;\n }\n\n unregister(id: string): this {\n this.skills.delete(id);\n this.manualIndexCache = undefined;\n return this;\n }\n\n get(id: string): Skill | undefined {\n return this.skills.get(id);\n }\n\n list(): Skill[] {\n return [...this.skills.values()];\n }\n\n match(query: string): SkillMatch[] {\n return this.matcher(this.list(), query);\n }\n\n /**\n * The skills that should be *pushed* into this turn's context: every `always`\n * skill, plus the top-scoring `matched` ones.\n *\n * `manual` skills are excluded by design — they are pulled by the model via\n * `loadSkill`, and pushing them would defeat the point of having the mode.\n */\n async resolveForTurn(ctx: SkillContext, opts: { forceIds?: string[] } = {}): Promise<ResolvedSkill[]> {\n const forced = new Set(opts.forceIds ?? []);\n // Computed once and fed to the matcher directly (rather than through\n // `this.match`, which would call `this.list()` again) — one array\n // allocation per turn instead of two.\n const list = this.list();\n const always = list.filter((s) => s.mode === \"always\" || forced.has(s.id));\n const matched = this.matcher(list, ctx.query)\n .filter((m) => m.skill.mode === \"matched\" && !forced.has(m.skill.id))\n .slice(0, this.maxMatched);\n\n const out: ResolvedSkill[] = [];\n for (const skill of always) {\n const text = await renderSkill(skill, ctx);\n out.push({\n id: skill.id,\n name: skill.name,\n text,\n tokens: estimateTokens(text),\n // Sort key: `always` outranks any matched score so it survives packing.\n score: 1_000 + (skill.priority ?? 0),\n mode: skill.mode,\n tools: skill.tools ?? [],\n });\n }\n for (const m of matched) {\n const text = await renderSkill(m.skill, ctx, m.sections);\n out.push({\n id: m.skill.id,\n name: m.skill.name,\n text,\n tokens: estimateTokens(text),\n score: m.score,\n mode: m.skill.mode,\n tools: m.skill.tools ?? [],\n });\n }\n return out.sort((a, b) => b.score - a.score);\n }\n\n /**\n * One-line index of the skills the model may load on demand. Cheap enough to\n * include every turn — this is the \"menu\" half of progressive disclosure.\n */\n manualIndex(): string {\n if (this.manualIndexCache !== undefined) return this.manualIndexCache;\n const manual = this.list().filter((s) => s.mode === \"manual\");\n const lines = manual.map((s) => `- ${s.id}: ${s.description}`);\n const index = !manual.length\n ? \"\"\n : [\"Loadable skills — call `loadSkill` with an id before acting in these areas:\", ...lines].join(\"\\n\");\n this.manualIndexCache = index;\n return index;\n }\n\n /** Everything a `loadSkill` call should return for `id`. */\n async load(id: string, ctx: SkillContext): Promise<{ found: boolean; text: string; tools: string[] }> {\n const skill = this.skills.get(id);\n if (!skill) {\n const near = this.list()\n .map((s) => s.id)\n .filter((sid) => sid.includes(id) || id.includes(sid));\n return {\n found: false,\n // Return a suggestion, not just a failure: a model that gets \"unknown\n // id\" retries the same id, while one that gets alternatives recovers.\n text: near.length\n ? `No skill \"${id}\". Did you mean: ${near.join(\", \")}?`\n : `No skill \"${id}\". Available: ${this.list().map((s) => s.id).join(\", \") || \"(none)\"}`,\n tools: [],\n };\n }\n return { found: true, text: await renderSkill(skill, ctx), tools: skill.tools ?? [] };\n }\n}\n","// Agent cards — the agent's visual vocabulary.\n//\n// A card is a structured tool output that the host renders as UI instead of as\n// JSON. Two ways one gets produced:\n// • a DOMAIN tool attaches a card to its result (\"here are the pools I found\"), or\n// • the agent calls the generic `visualize` tool and CHOOSES a presentation.\n// The second is what makes the agent visually flexible rather than limited to\n// whatever cards someone hard-coded.\n//\n// Three design rules, each learned from a real failure mode:\n//\n// 1. Validator and renderer are registered TOGETHER (registry.ts). In a\n// hand-maintained dispatch chain, adding a payload parser and forgetting the\n// render branch degrades the card to a bare \"ran ✓\" chip — silently, in\n// production, and only for that one card.\n//\n// 2. Interactive cards are never collapsible. A card that asks for a decision\n// (confirm, pick, fill) is part of the conversation's control flow; hiding\n// it inside a \"3 steps completed\" accordion makes it unreachable, which\n// reads to the user as the agent hanging.\n//\n// 3. Cards carry their own `expired` state. Card payloads are large and often\n// trimmed out of persisted history; a reloaded thread must say \"this result\n// expired, ask again\" rather than rendering an empty shell.\n\nexport type CardTone = \"neutral\" | \"positive\" | \"negative\" | \"warning\" | \"info\";\n\nexport type CardValueFormat = \"text\" | \"number\" | \"currency\" | \"percent\" | \"bytes\" | \"duration\" | \"datetime\" | \"code\";\n\n// ── Built-in card specs ─────────────────────────────────────────────────────\n\nexport type TableColumn = {\n key: string;\n label: string;\n format?: CardValueFormat;\n align?: \"left\" | \"right\" | \"center\";\n /** Render this column's cell as an emphasis/status pill. */\n pill?: boolean;\n};\n\nexport type TableCard = {\n kind: \"table\";\n title?: string;\n caption?: string;\n columns: TableColumn[];\n rows: Record<string, unknown>[];\n /** Column key to sort by on first render. */\n sortBy?: string;\n sortDir?: \"asc\" | \"desc\";\n};\n\nexport type StatItem = {\n label: string;\n value: string | number;\n format?: CardValueFormat;\n /** Signed change vs a prior period; drives colour and arrow. */\n delta?: number;\n deltaFormat?: CardValueFormat;\n hint?: string;\n tone?: CardTone;\n};\n\nexport type StatsCard = {\n kind: \"stats\";\n title?: string;\n items: StatItem[];\n};\n\nexport type ChartSeries = {\n name: string;\n /** `[x, y]` pairs; x is a number, a timestamp, or a category label. */\n points: [string | number, number][];\n type?: \"line\" | \"area\" | \"bar\" | \"scatter\";\n color?: string;\n /** Plot against a secondary axis — volume under price, for instance. */\n axis?: \"left\" | \"right\";\n};\n\nexport type ChartAnnotation = {\n type: \"hline\" | \"vline\" | \"band\" | \"marker\";\n value: string | number;\n /** Second bound, for `band`. */\n to?: string | number;\n label?: string;\n tone?: CardTone;\n};\n\nexport type ChartCard = {\n kind: \"chart\";\n title?: string;\n /** OHLC candles are their own shape; series charts use `series`. */\n variant?: \"series\" | \"candlestick\";\n xLabel?: string;\n yLabel?: string;\n xType?: \"time\" | \"number\" | \"category\";\n series?: ChartSeries[];\n candles?: { t: string | number; o: number; h: number; l: number; c: number; v?: number }[];\n annotations?: ChartAnnotation[];\n stacked?: boolean;\n};\n\nexport type TimelineCard = {\n kind: \"timeline\";\n title?: string;\n events: {\n at: string | number;\n label: string;\n detail?: string;\n tone?: CardTone;\n }[];\n};\n\nexport type KeyValueCard = {\n kind: \"keyvalue\";\n title?: string;\n items: { label: string; value: string | number; format?: CardValueFormat; tone?: CardTone; mono?: boolean }[];\n};\n\nexport type ProgressStep = {\n label: string;\n status: \"pending\" | \"active\" | \"done\" | \"failed\" | \"skipped\";\n detail?: string;\n};\n\nexport type ProgressCard = {\n kind: \"progress\";\n title?: string;\n steps: ProgressStep[];\n /** 0–1. Omit for indeterminate. */\n fraction?: number;\n};\n\nexport type MediaCard = {\n kind: \"media\";\n title?: string;\n items: {\n url: string;\n alt?: string;\n caption?: string;\n mediaType?: string;\n /** Known intrinsic geometry keeps generated media from shifting on decode. */\n width?: number;\n height?: number;\n durationMs?: number;\n }[];\n layout?: \"grid\" | \"single\";\n};\n\nexport type MarkdownCard = { kind: \"markdown\"; title?: string; body: string };\n\n/**\n * A document artifact — long-form Markdown the agent authored and the user\n * reads in a previewer rather than inline in the transcript.\n *\n * `docId` is the stable handle every later turn addresses: the body here is for\n * display only, and stripCardPayload removes it from what the model sees after\n * the turn that produced it. A model that wants to re-read the document calls\n * the read tool with this id — which is the point, because a document large\n * enough to deserve a previewer is too large to re-send every turn.\n *\n * `revision` is the optimistic-concurrency token. An edit carrying a stale one\n * is refused rather than applied to text that has since moved.\n */\nexport type DocumentCard = {\n kind: \"document\";\n docId: string;\n title: string;\n markdown: string;\n revision: number;\n};\n\n/**\n * A matrix of options against criteria.\n *\n * The most domain-portable card there is: legal clause-vs-clause, vendor\n * selection, pricing tiers, candidate evaluation, feature comparison. Boolean\n * values render as ✓/✗, so \"does it have X\" tables need no encoding by the model.\n */\nexport type ComparisonCard = {\n kind: \"comparison\";\n title?: string;\n /** The things being compared — these become columns. */\n options: { id: string; label: string; note?: string; highlight?: boolean }[];\n /** The dimensions they are compared on — these become rows. */\n criteria: {\n label: string;\n /** Keyed by option id. `true`/`false` render as ✓/✗; `null` renders as “—”. */\n values: Record<string, string | number | boolean | null>;\n detail?: string;\n weight?: \"low\" | \"normal\" | \"high\";\n }[];\n};\n\n/** Items with a state. Compliance reviews, launch readiness, QA passes, audits. */\nexport type ChecklistCard = {\n kind: \"checklist\";\n title?: string;\n items: {\n label: string;\n status: \"done\" | \"todo\" | \"blocked\" | \"na\";\n detail?: string;\n /** Optional heading to group consecutive items under. */\n group?: string;\n }[];\n};\n\n/** A single highlighted note. Disclaimers, caveats, prerequisites, warnings. */\nexport type CalloutCard = {\n kind: \"callout\";\n tone: \"info\" | \"warning\" | \"danger\" | \"success\" | \"note\";\n title?: string;\n body: string;\n};\n\n/**\n * Sources behind a claim.\n *\n * Domain-agnostic and unusually important for agents specifically: it is the\n * card that lets a reader check the work rather than trust the summary.\n */\nexport type CitationsCard = {\n kind: \"citations\";\n title?: string;\n items: {\n title: string;\n /** Publication, court, statute, dataset, site — whatever the source is. */\n source?: string;\n url?: string;\n date?: string | number;\n /** The specific passage relied on. */\n snippet?: string;\n locator?: string;\n relevance?: \"high\" | \"medium\" | \"low\";\n }[];\n};\n\n/** Staged drop-off. Conversion funnels, hiring pipelines, case attrition, intake flows. */\nexport type FunnelCard = {\n kind: \"funnel\";\n title?: string;\n stages: { label: string; value: number; note?: string }[];\n format?: CardValueFormat;\n};\n\n/** One value against a scale, with optional named bands. Scores, risk levels, sentiment. */\nexport type GaugeCard = {\n kind: \"gauge\";\n title?: string;\n value: number;\n min?: number;\n max?: number;\n label?: string;\n bands?: { from: number; to: number; label: string; tone?: CardTone }[];\n format?: CardValueFormat;\n};\n\nexport type TreeNode = {\n label: string;\n detail?: string;\n tone?: CardTone;\n children?: TreeNode[];\n};\n\n/** Nested structure. Document outlines, org charts, taxonomies, decision trees. */\nexport type TreeCard = {\n kind: \"tree\";\n title?: string;\n nodes: TreeNode[];\n};\n\nexport type CodeCard = { kind: \"code\"; title?: string; language?: string; code: string; filename?: string };\n\nexport type DiffCard = {\n kind: \"diff\";\n title?: string;\n before: string;\n after: string;\n language?: string;\n};\n\n// ── Interactive card specs ──────────────────────────────────────────────────\n// These produce a CardAction when the user responds, which the runtime feeds\n// back as the tool's result — that is the human-in-the-loop seam.\n\nexport type ChoiceCard = {\n kind: \"choice\";\n title?: string;\n prompt?: string;\n multiple?: boolean;\n options: {\n id: string;\n label: string;\n description?: string;\n /** Small facts shown on the option row: APR, TVL, price. */\n meta?: { label: string; value: string | number; format?: CardValueFormat }[];\n imageUrl?: string;\n disabled?: boolean;\n disabledReason?: string;\n }[];\n};\n\nexport type FormField =\n | { name: string; label: string; type: \"text\" | \"textarea\"; placeholder?: string; required?: boolean; value?: string }\n | { name: string; label: string; type: \"number\"; min?: number; max?: number; step?: number; required?: boolean; value?: number; suffix?: string }\n | { name: string; label: string; type: \"select\"; options: { value: string; label: string }[]; required?: boolean; value?: string }\n | { name: string; label: string; type: \"boolean\"; value?: boolean };\n\nexport type FormCard = {\n kind: \"form\";\n title?: string;\n description?: string;\n fields: FormField[];\n submitLabel?: string;\n};\n\nexport type ConfirmCard = {\n kind: \"confirm\";\n /** The one question the buttons answer, such as \"Rename the report?\". Shown last, above the buttons. */\n title: string;\n /** The consequential details — amounts, targets, anything irreversible. May be empty when `description` already says all of it. */\n summary: { label: string; value: string | number; tone?: CardTone; mono?: boolean }[];\n /** What will happen, in a sentence or two. Shown first. */\n description?: string;\n confirmLabel?: string;\n cancelLabel?: string;\n /** Renders the confirm control as destructive. */\n danger?: boolean;\n};\n\nexport type BuiltinCard =\n | TableCard\n | StatsCard\n | ChartCard\n | TimelineCard\n | KeyValueCard\n | ProgressCard\n | MediaCard\n | MarkdownCard\n | DocumentCard\n | EditReviewCard\n | EmailCard\n | CodeCard\n | DiffCard\n | ComparisonCard\n | ChecklistCard\n | CalloutCard\n | CitationsCard\n | FunnelCard\n | GaugeCard\n | TreeCard\n | ChoiceCard\n | FormCard\n | ConfirmCard;\n\nexport type BuiltinCardKind = BuiltinCard[\"kind\"];\n\n/**\n * The approval surface for a proposed document edit.\n *\n * Interactive, because in in-chat editing the diff IS the approval: there is no\n * other moment at which the user gets to see what is about to happen. Hunks are\n * accepted individually rather than all-or-nothing — partial acceptance is what\n * makes the exchange read as collaboration instead of take-it-or-leave-it, and\n * an edit is already the smallest independently applicable unit because it\n * carries its own anchor.\n */\nexport type EditReviewCard = {\n kind: \"editreview\";\n docId: string;\n title: string;\n /** Revision the edits were computed against; a stale one is refused. */\n revision: number;\n /** One line on why, in the model's words. */\n summary?: string;\n hunks: {\n index: number;\n block: number;\n removed: string[];\n added: string[];\n }[];\n};\n\n/**\n * A drafted email, before it is anyone's outbox.\n *\n * Always a draft the user completes — which is exactly the `draft` preset tier\n * (\"produces something the USER must approve/sign. No side effects\"). The\n * framework never holds a mail credential, for the same reason a Transport\n * never holds an API key.\n *\n * Editable but not interactive: nothing waits on it. The run does not suspend,\n * because the model asked no question — it produced a thing.\n */\nexport type EmailCard = {\n kind: \"email\";\n to: string[];\n cc?: string[];\n bcc?: string[];\n subject: string;\n /** Plain text. Markdown here would be a lie: mailto cannot carry it. */\n body: string;\n};\n\n/** A host-registered card is any `{kind}` object; built-ins are the typed subset. */\nexport type CardSpec = BuiltinCard | ({ kind: string } & Record<string, unknown>);\n\n/** Envelope attached to a tool result, or returned by `visualize`. */\n/**\n * Where a host shows a card: in the conversation (`inline`, the default), in its side panel\n * (`panel`), or inside a document block (`document`). The same renderer draws it in every place.\n * Structurally the same as super-protocol's `CardPlacement`; core has no dependencies, so it is\n * repeated here. An interactive card is only ever inline.\n */\nexport type CardPlacement = \"inline\" | \"panel\" | \"document\";\n\nexport const CARD_PLACEMENTS: readonly CardPlacement[] = [\"inline\", \"panel\", \"document\"];\n\nexport const isCardPlacement = (value: unknown): value is CardPlacement => CARD_PLACEMENTS.includes(value as CardPlacement);\n\nexport type Card = {\n id: string;\n spec: CardSpec;\n /**\n * Where the agent or tool asked for the card to be shown. Absent means `inline`. A host with no\n * side panel shows a `panel` card inline; it never drops it.\n */\n placement?: CardPlacement;\n /** Set when the payload was dropped from persisted history. */\n expired?: boolean;\n /** Tool call this card belongs to, for correlating an action back. */\n callId?: string;\n /**\n * What the user answered, once they have.\n *\n * Lives on the card rather than in the renderer's local state because the card\n * is re-mounted from history when the turn commits — state does not survive\n * that, and a renderer left guessing shows the wrong answer.\n */\n action?: CardAction;\n};\n\n/** What the user did with an interactive card. Becomes the tool result. */\nexport type CardAction = {\n cardId: string;\n callId?: string;\n kind: string;\n type: \"submit\" | \"select\" | \"confirm\" | \"cancel\" | \"dismiss\";\n /** Selected option ids, form values, or nothing for confirm/cancel. */\n value?: unknown;\n at: number;\n};\n\n/** Marker key used to recognise a card inside an arbitrary tool output. */\nexport const CARD_KEY = \"$card\" as const;\n\nexport type CardCarrier = { [CARD_KEY]: Card } & Record<string, unknown>;\n\nexport function isCardCarrier(value: unknown): value is CardCarrier {\n return (\n typeof value === \"object\" &&\n value !== null &&\n CARD_KEY in value &&\n typeof (value as Record<string, unknown>)[CARD_KEY] === \"object\"\n );\n}\n\n/** Attach a card to a tool result without disturbing the data the model reads. */\nexport function withCard<T extends Record<string, unknown>>(data: T, spec: CardSpec, id?: string, placement?: CardPlacement): T & CardCarrier {\n const card: Card = { id: id ?? `card_${Math.random().toString(36).slice(2, 10)}`, spec, ...(placement && placement !== \"inline\" ? { placement } : {}) };\n return { ...data, [CARD_KEY]: card };\n}\n\n/**\n * Remove a card payload from a tool output, leaving a note in its place.\n *\n * The card is for the user's eyes; the model gets the surrounding data. Sending\n * both is double billing — and a chart spec with 2,000 points is the single\n * largest thing a tool result can carry. Applied in two places, which must stay\n * consistent: within a running turn (before each provider call) and when a\n * persisted thread is rebuilt into context.\n */\nexport function stripCardPayload(output: unknown): unknown {\n if (!isCardCarrier(output)) return output;\n const { [CARD_KEY]: card, ...rest } = output as Record<string, unknown>;\n const kind = (card as { spec?: { kind?: string } })?.spec?.kind ?? \"card\";\n return { ...rest, rendered: `[${kind} card shown to the user]` };\n}\n","// History compaction.\n//\n// Two strategies, and the choice between them is a real trade:\n//\n// trim — drop oldest turns until it fits. Free, instant, and loses\n// information silently. Correct as a fallback and for short\n// overflows.\n// summarize — ask a cheap model to compress the older span into a brief, keep\n// recent turns verbatim. Costs a request and latency, preserves\n// the thread's arc. Correct for long-lived conversations.\n//\n// Both preserve two invariants that a naive slice breaks:\n// • a tool-call and its result must stay together, or the next request 400s;\n// • the first kept message must not be a `tool` reply to a dropped call.\n\nimport type { Message } from \"../content/types.js\";\nimport { messageText } from \"../content/parts.js\";\nimport { countMessageTokens, countMessagesTokens } from \"../tokens/budget.js\";\n// countMessageTokens is used to price the pinned summary during a secondary trim.\nimport type { TokenCounter } from \"../tokens/estimate.js\";\n\nexport type CompactionResult = {\n messages: Message[];\n strategy: \"none\" | \"trim\" | \"summarize\";\n droppedCount: number;\n tokensBefore: number;\n tokensAfter: number;\n summary?: string;\n};\n\n/** True if the message pairs with a preceding assistant tool-call. */\nfunction isToolReply(m: Message): boolean {\n return m.parts.some((p) => p.type === \"tool-result\");\n}\n\n/**\n * Move a cut point later until it lands on a message that can legally start a\n * history: a user or assistant turn that is not a dangling tool reply, and not\n * an assistant turn whose tool calls were left behind.\n */\nexport function safeCutIndex(messages: readonly Message[], desired: number): number {\n let index = Math.max(0, Math.min(desired, messages.length));\n while (index < messages.length) {\n const m = messages[index]!;\n if (isToolReply(m)) {\n index += 1;\n continue;\n }\n // An assistant message carrying tool-calls is only safe to start on if its\n // results are in the kept span — they immediately follow, so they are.\n break;\n }\n return index;\n}\n\nexport function trimHistory(\n messages: readonly Message[],\n limitTokens: number,\n counter?: TokenCounter,\n /** Pass this when the caller already scanned `messages` (e.g. `compactHistory`'s `tokensBefore`) to skip a second full-history scan. */\n knownTokensBefore?: number,\n): CompactionResult {\n const tokensBefore = knownTokensBefore ?? countMessagesTokens(messages, counter);\n if (tokensBefore <= limitTokens) {\n return { messages: [...messages], strategy: \"none\", droppedCount: 0, tokensBefore, tokensAfter: tokensBefore };\n }\n\n // Walk backwards accumulating until the budget is spent — the newest turns are\n // the ones worth keeping.\n let used = 0;\n let cut = messages.length;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const size = countMessageTokens(messages[i]!, counter);\n if (used + size > limitTokens) break;\n used += size;\n cut = i;\n }\n\n const start = safeCutIndex(messages, cut);\n const kept = messages.slice(start);\n return {\n messages: [...kept],\n strategy: \"trim\",\n droppedCount: start,\n tokensBefore,\n tokensAfter: countMessagesTokens(kept, counter),\n };\n}\n\nexport type Summarizer = (messages: readonly Message[], signal?: AbortSignal) => Promise<string>;\n\nexport type CompactOptions = {\n limitTokens: number;\n /** Turns always kept verbatim at the tail. */\n keepRecent?: number;\n summarizer?: Summarizer;\n counter?: TokenCounter;\n signal?: AbortSignal;\n};\n\n/**\n * Compact history to fit `limitTokens`.\n *\n * Falls back to `trim` whenever summarization is unavailable or fails —\n * a summarizer that errors must never take the user's turn down with it.\n */\nexport async function compactHistory(\n messages: readonly Message[],\n opts: CompactOptions,\n): Promise<CompactionResult> {\n const counter = opts.counter;\n const tokensBefore = countMessagesTokens(messages, counter);\n if (tokensBefore <= opts.limitTokens) {\n return { messages: [...messages], strategy: \"none\", droppedCount: 0, tokensBefore, tokensAfter: tokensBefore };\n }\n if (!opts.summarizer) return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n\n const keepRecent = opts.keepRecent ?? 8;\n const desiredCut = Math.max(0, messages.length - keepRecent);\n const cut = safeCutIndex(messages, desiredCut);\n const older = messages.slice(0, cut);\n const recent = messages.slice(cut);\n\n // Nothing old enough to be worth a summarization round-trip.\n if (older.length < 2) return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n\n let summary: string;\n try {\n summary = (await opts.summarizer(older, opts.signal)).trim();\n } catch {\n return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n }\n if (!summary) return trimHistory(messages, opts.limitTokens, counter, tokensBefore);\n\n const summaryMessage: Message = {\n id: `summary_${cut}`,\n role: \"user\",\n parts: [\n {\n type: \"text\",\n // Framed as context rather than as something the user said, so the model\n // does not answer the summary as if it were a new request.\n text: `[Earlier conversation summary — ${older.length} messages]\\n${summary}`,\n },\n ],\n metadata: { superchat: \"compaction-summary\", replaced: older.length },\n };\n\n const out = [summaryMessage, ...recent];\n const tokensAfter = countMessagesTokens(out, counter);\n\n // Even summarized it may not fit, when the recent tail alone is huge. Trim\n // only the RECENT span and keep the summary: a plain trim walks from the\n // newest backwards, so it would drop the summary first — discarding the one\n // artifact we just paid a model call to produce.\n if (tokensAfter > opts.limitTokens) {\n const summaryTokens = countMessageTokens(summaryMessage, counter);\n // tokensAfter already accounts for summaryMessage + recent, so recent's\n // token count falls out for free instead of a second scan.\n const trimmed = trimHistory(recent, Math.max(0, opts.limitTokens - summaryTokens), counter, tokensAfter - summaryTokens);\n const messages = [summaryMessage, ...trimmed.messages];\n return {\n messages,\n strategy: \"summarize\",\n droppedCount: older.length + trimmed.droppedCount,\n tokensBefore,\n tokensAfter: countMessagesTokens(messages, counter),\n summary,\n };\n }\n\n return { messages: out, strategy: \"summarize\", droppedCount: older.length, tokensBefore, tokensAfter, summary };\n}\n\n/**\n * Default summarization prompt builder. Exposed so a host can reuse the exact\n * framing with its own model call.\n */\nexport function buildSummaryPrompt(messages: readonly Message[]): string {\n const transcript = messages\n .map((m) => {\n const text = messageText(m);\n const calls = m.parts\n .filter((p) => p.type === \"tool-call\")\n .map((p) => `→ called ${(p as { name: string }).name}`)\n .join(\" \");\n return `${m.role}: ${text}${calls ? ` ${calls}` : \"\"}`.trim();\n })\n .filter((line) => line.length > line.indexOf(\":\") + 1)\n .join(\"\\n\");\n\n return [\n \"Compress this conversation span into a brief the assistant can act on.\",\n \"Keep: decisions made, facts established, user preferences, unresolved threads, and identifiers (ids, addresses, filenames).\",\n \"Drop: pleasantries, restatements, and anything superseded by a later turn.\",\n \"Write it as terse notes, not prose. No preamble.\",\n \"\",\n transcript,\n ].join(\"\\n\");\n}\n","// The ContextBuilder — one deterministic pipeline, run fresh every turn.\n//\n// Order matters and is fixed:\n// 1. run sources in parallel (identity, skills, memory, host sources)\n// 2. pack layers into the system budget, pinned first, then by priority\n// 3. compact history into what remains\n// 4. record every decision in the trace\n//\n// Determinism is the point: the same inputs must produce the same request, or\n// prompt caching never hits and debugging becomes archaeology.\n\nimport { lastUserText, stripUiOnlyParts } from \"../content/parts.js\";\nimport type { Message } from \"../content/types.js\";\nimport { isCardCarrier, stripCardPayload } from \"../cards/types.js\";\nimport { compactHistory, type Summarizer } from \"./compaction.js\";\nimport { createBudget, packByPriority, type TokenBudget } from \"../tokens/budget.js\";\nimport { estimateTokens, type TokenCounter } from \"../tokens/estimate.js\";\nimport type { SkillRegistry } from \"../skills/registry.js\";\nimport type { ResolvedSkill } from \"../skills/types.js\";\nimport type { BuiltContext, ContextLayer, ContextSource, ContextTrace, TraceEntry } from \"./types.js\";\n\nexport type ContextBuilderOptions = {\n /** Base instructions. Always pinned — identity is not negotiable under pressure. */\n identity?: string;\n skills?: SkillRegistry;\n sources?: ContextSource[];\n budget?: TokenBudget;\n contextWindow?: number;\n maxOutputTokens?: number;\n counter?: TokenCounter;\n summarizer?: Summarizer;\n /** Verbatim turns kept at the tail when summarizing. */\n keepRecent?: number;\n /**\n * Appended to instructions when any card-capable tool is present. Tells the\n * model where cards appear so its prose reads correctly around them — without\n * this, models narrate \"as you can see in the table below\" above a card that\n * renders above the text.\n */\n cardPlacementNote?: string;\n};\n\nconst DEFAULT_CARD_NOTE = [\n \"CARD PLACEMENT: a card renders immediately where you call the tool, before any text you write afterwards.\",\n \"Write a one-line lead-in before the card, and your interpretation after it. Never re-list the card's contents in prose.\",\n].join(\"\\n\");\n\nexport class ContextBuilder {\n private readonly opts: ContextBuilderOptions;\n\n constructor(opts: ContextBuilderOptions = {}) {\n this.opts = opts;\n }\n\n /** The skill registry this builder draws from, for UI that lists or pins skills. */\n get skillRegistry(): SkillRegistry | undefined {\n return this.opts.skills;\n }\n\n /** The identity block, for a settings pane that lets the user read or edit it. */\n get identity(): string | undefined {\n return this.opts.identity;\n }\n\n async build(input: {\n messages: readonly Message[];\n vars?: Record<string, unknown>;\n /** Skills to force in regardless of matching (a user pinning one in the UI). */\n forceSkillIds?: string[];\n /** Tool names available before skill unlocks. */\n baseTools?: string[];\n signal?: AbortSignal;\n }): Promise<BuiltContext> {\n const counter = this.opts.counter ?? estimateTokens;\n const budget =\n this.opts.budget ??\n createBudget(this.opts.contextWindow ?? 128_000, { maxOutputTokens: this.opts.maxOutputTokens });\n\n const entries: TraceEntry[] = [];\n const warnings: string[] = [];\n const vars = input.vars ?? {};\n const query = lastUserText(input.messages);\n\n const layers: ContextLayer[] = [];\n const unlockedTools = new Set<string>(input.baseTools ?? []);\n let skills: ResolvedSkill[] = [];\n\n // ── 1. identity ─────────────────────────────────────────────────────────\n if (this.opts.identity?.trim()) {\n const text = this.opts.identity.trim();\n layers.push({ id: \"identity\", kind: \"identity\", text, tokens: counter(text), pinned: true, priority: 1_000 });\n }\n\n // ── 2. skills ───────────────────────────────────────────────────────────\n if (this.opts.skills) {\n const started = Date.now();\n try {\n skills = await this.opts.skills.resolveForTurn({ query, vars }, { forceIds: input.forceSkillIds });\n for (const s of skills) {\n layers.push({\n id: `skill:${s.id}`,\n kind: \"skills\",\n text: s.text,\n tokens: s.tokens,\n // `always` skills are pinned; matched ones compete for budget.\n pinned: s.mode === \"always\",\n priority: s.score,\n });\n for (const t of s.tools) unlockedTools.add(t);\n }\n entries.push({\n id: \"skills\",\n kind: \"skills\",\n status: \"included\",\n tokens: skills.reduce((n, s) => n + s.tokens, 0),\n detail: skills.length ? skills.map((s) => `${s.id}(${s.mode})`).join(\", \") : \"none matched\",\n ms: Date.now() - started,\n });\n } catch (e) {\n entries.push({\n id: \"skills\",\n kind: \"skills\",\n status: \"failed\",\n tokens: 0,\n detail: e instanceof Error ? e.message : String(e),\n });\n warnings.push(\"Skill resolution failed; continuing without skills.\");\n }\n\n const index = this.opts.skills.manualIndex();\n if (index) {\n layers.push({ id: \"skill-index\", kind: \"skill-index\", text: index, tokens: counter(index), pinned: true, priority: 900 });\n }\n }\n\n // ── 3. host sources, in parallel ────────────────────────────────────────\n const sources = this.opts.sources ?? [];\n if (sources.length) {\n const results = await Promise.allSettled(\n sources.map(async (s) => {\n const started = Date.now();\n const out = await s.run({ messages: input.messages, query, vars, signal: input.signal });\n return { id: s.id, out, ms: Date.now() - started };\n }),\n );\n for (const [i, r] of results.entries()) {\n const sourceId = sources[i]!.id;\n if (r.status === \"rejected\") {\n // A failed source degrades the turn; it must not kill it. Memory\n // retrieval timing out should cost context, not the conversation.\n entries.push({\n id: sourceId,\n kind: \"source\",\n status: \"failed\",\n tokens: 0,\n detail: r.reason instanceof Error ? r.reason.message : String(r.reason),\n });\n warnings.push(`Context source \"${sourceId}\" failed.`);\n continue;\n }\n const { out, ms } = r.value;\n for (const layer of out.layers ?? []) layers.push(layer);\n for (const t of out.tools ?? []) unlockedTools.add(t);\n entries.push({\n id: sourceId,\n kind: \"source\",\n status: \"included\",\n tokens: (out.layers ?? []).reduce((n, l) => n + l.tokens, 0),\n ms,\n });\n }\n }\n\n // ── 4. card placement contract ──────────────────────────────────────────\n if (unlockedTools.has(\"visualize\")) {\n const note = this.opts.cardPlacementNote ?? DEFAULT_CARD_NOTE;\n layers.push({ id: \"card-contract\", kind: \"custom\", text: note, tokens: counter(note), pinned: true, priority: 850 });\n }\n\n // ── 5. pack the system block ────────────────────────────────────────────\n // Pinned layers are placed first and unconditionally; if they alone exceed\n // the share we warn rather than silently dropping an identity or a safety\n // rule, because dropping those is never the right automatic answer.\n const pinned = layers.filter((l) => l.pinned).sort((a, b) => b.priority - a.priority);\n const optional = layers.filter((l) => !l.pinned).sort((a, b) => b.priority - a.priority);\n const pinnedTokens = pinned.reduce((n, l) => n + l.tokens, 0);\n\n if (pinnedTokens > budget.shares.system + budget.shares.skills) {\n warnings.push(\n `Pinned context (${pinnedTokens} tok) exceeds its budget (${budget.shares.system + budget.shares.skills} tok). ` +\n \"Shorten always-on skills or raise the system share.\",\n );\n }\n\n const optionalLimit = Math.max(0, budget.shares.system + budget.shares.skills - pinnedTokens);\n const packed = packByPriority(optional, optionalLimit, (l) => l.tokens);\n for (const dropped of packed.dropped) {\n entries.push({\n id: dropped.item.id,\n kind: dropped.item.kind,\n status: \"dropped\",\n tokens: 0,\n originalTokens: dropped.size,\n detail: `no room in the ${optionalLimit} tok optional share`,\n });\n // A dropped skill must not leave its tools unlocked — the model would see\n // tools it has no instructions for.\n if (dropped.item.id.startsWith(\"skill:\")) {\n const skillId = dropped.item.id.slice(\"skill:\".length);\n const skill = skills.find((s) => s.id === skillId);\n for (const t of skill?.tools ?? []) unlockedTools.delete(t);\n skills = skills.filter((s) => s.id !== skillId);\n }\n }\n\n const included = [...pinned, ...packed.included];\n for (const layer of packed.included) {\n entries.push({ id: layer.id, kind: layer.kind, status: \"included\", tokens: layer.tokens });\n }\n\n const system = included.map((l) => l.text.trim()).filter(Boolean).join(\"\\n\\n\");\n // Sum of the layers' own precomputed token counts, rather than re-tokenizing\n // the joined string. This slightly undercounts the \"\\n\\n\" join separators,\n // but that's a handful of tokens against an already-approximate counter\n // (see tokens/estimate.ts) — not worth a second full-text scan to close.\n const systemTokens = included.reduce((n, l) => n + l.tokens, 0);\n\n // ── 6. history ──────────────────────────────────────────────────────────\n // Sanitize first: strip UI-only parts and shrink card payloads. A card spec\n // can be tens of KB of chart points, and the model already saw the summary\n // in the tool's `output` — re-sending the pixels is pure waste.\n const sanitized = input.messages\n .filter((m) => m.role !== \"system\")\n .map(stripUiOnlyParts)\n .map(stripCardPayloads);\n\n const historyLimit = Math.max(1_000, budget.shares.history);\n const compaction = await compactHistory(sanitized, {\n limitTokens: historyLimit,\n keepRecent: this.opts.keepRecent ?? 8,\n summarizer: this.opts.summarizer,\n counter,\n signal: input.signal,\n });\n\n if (compaction.strategy !== \"none\") {\n entries.push({\n id: \"history\",\n kind: \"history\",\n status: compaction.strategy === \"summarize\" ? \"compacted\" : \"truncated\",\n tokens: compaction.tokensAfter,\n originalTokens: compaction.tokensBefore,\n detail: `${compaction.strategy}: dropped ${compaction.droppedCount} message(s)`,\n });\n } else {\n entries.push({ id: \"history\", kind: \"history\", status: \"included\", tokens: compaction.tokensAfter });\n }\n\n // compaction.tokensAfter is already an exact count of compaction.messages —\n // computed inside compactHistory/trimHistory with this same counter — so\n // reuse it instead of scanning the history a second time.\n const historyTokens = compaction.tokensAfter;\n const toolNames = [...unlockedTools].sort();\n const total = systemTokens + historyTokens;\n\n const trace: ContextTrace = {\n entries,\n budget,\n totals: { system: systemTokens, history: historyTokens, tools: 0, total },\n headroom: budget.contextWindow - total - budget.shares.output,\n warnings,\n };\n\n if (trace.headroom < 0) {\n warnings.push(`Context overflows its window by ~${-trace.headroom} tokens. The provider may reject this request.`);\n }\n\n return { system, messages: compaction.messages, toolNames, trace, skills };\n }\n}\n\n/** Apply `stripCardPayload` to every tool result in a persisted message. */\nfunction stripCardPayloads(m: Message): Message {\n let changed = false;\n const parts = m.parts.map((p) => {\n if (p.type !== \"tool-result\" || !isCardCarrier(p.output)) return p;\n changed = true;\n return { ...p, output: stripCardPayload(p.output) };\n });\n return changed ? { ...m, parts } : m;\n}\n","// Reading and rewriting a Markdown document, as pure functions.\n//\n// Everything here is string in, string out. That is deliberate: the hard parts\n// of in-chat editing are addressing and refusal, both of which are decidable\n// without a store, a model or a browser — so they are decided in code that a\n// unit test can pin exactly.\n\nimport { splitBlocks, type MarkdownBlock } from \"../content/blocks.js\";\nimport type {\n AppliedEdit,\n DocumentEdit,\n DocumentOutlineEntry,\n EditResult,\n} from \"./types.js\";\n\nconst headingLevel = (line: string): number | undefined => {\n const m = /^ {0,3}(#{1,6})\\s/.exec(line);\n return m ? m[1]!.length : undefined;\n};\n\n/**\n * A map of the document, cheap enough to send every turn.\n *\n * Editing is a directed activity — \"the third section\", \"the bit about\n * renewal\" — not a similarity search, so the model needs to navigate rather\n * than retrieve. An outline costs a line per block and lets it ask for exactly\n * the span it wants; without one it either guesses or is handed the whole\n * document, and the whole document is what this design exists to avoid.\n */\nexport function outlineOf(markdown: string): DocumentOutlineEntry[] {\n return splitBlocks(markdown).map((block, i) => entryOf(markdown, block, i));\n}\n\n/** The outline entry for one block, which is block `i` of `markdown`. */\nfunction entryOf(markdown: string, block: MarkdownBlock, i: number): DocumentOutlineEntry {\n const raw = markdown.slice(block.start, block.end);\n const firstLine = raw.split(\"\\n\", 1)[0] ?? \"\";\n const level = block.kind === \"text\" ? headingLevel(firstLine) : undefined;\n return {\n block: i,\n kind: block.kind,\n ...(level ? { level } : {}),\n preview: firstLine.trim().slice(0, 100),\n chars: raw.length,\n };\n}\n\n/** Source text of a block range, inclusive. Out-of-range yields \"\". */\nexport function spanOf(markdown: string, from: number, to = from): string {\n const blocks = splitBlocks(markdown);\n const first = blocks[Math.max(0, from)];\n const last = blocks[Math.min(blocks.length - 1, to)];\n if (!first || !last || first.start > last.end) return \"\";\n return markdown.slice(first.start, last.end);\n}\n\n/** Blocks whose text contains `query`, case-insensitively. */\nexport function searchBlocks(markdown: string, query: string): DocumentOutlineEntry[] {\n const needle = query.trim().toLowerCase();\n if (!needle) return [];\n // One split, and an outline entry only for the blocks that match. Going\n // through outlineOf split the document a second time and described every\n // block only to throw most of them away.\n const out: DocumentOutlineEntry[] = [];\n splitBlocks(markdown).forEach((block, i) => {\n if (markdown.slice(block.start, block.end).toLowerCase().includes(needle)) {\n out.push(entryOf(markdown, block, i));\n }\n });\n return out;\n}\n\n/**\n * Where `needle` first occurs in `haystack`, and how many times it occurs in\n * all, overlaps included. Only the count is needed past the first hit — it is\n * what the ambiguity message reports — so the hits are counted, not collected.\n */\nfunction occurrences(haystack: string, needle: string, offset = 0): { first: number; count: number } {\n let first = -1;\n let count = 0;\n if (!needle) return { first, count };\n for (let i = haystack.indexOf(needle); i !== -1; i = haystack.indexOf(needle, i + 1)) {\n if (count === 0) first = i + offset;\n count += 1;\n }\n return { first, count };\n}\n\nconst blockOf = (blocks: MarkdownBlock[], index: number): number =>\n Math.max(\n 0,\n blocks.findIndex((b) => index >= b.start && index < b.end),\n );\n\n/**\n * Apply edits to a document, or refuse.\n *\n * Refusing is half the job and the more important half. A find that matches\n * nothing means the model is quoting text that is not there; a find that\n * matches twice means it has not said which one. Guessing either — taking the\n * first match, say — produces a change in the wrong place that the diff will\n * present as if it were intended, and the user approves it. So both are\n * rejections with a reason the model can act on, exactly as tools/repair.ts\n * treats malformed arguments: an invalid input to retry, not a result.\n *\n * Edits are resolved against the ORIGINAL text and spliced into it in one pass,\n * so earlier edits cannot shift the offsets of later ones. Two edits that\n * overlap are a contradiction rather than a merge, and are refused.\n */\nexport function applyEdits(markdown: string, edits: readonly DocumentEdit[]): EditResult {\n if (!edits.length) return { ok: true, markdown, applied: [] };\n\n const blocks = splitBlocks(markdown);\n const applied: AppliedEdit[] = [];\n\n for (const edit of edits) {\n if (!edit.find) {\n return { ok: false, reason: \"not-found\", message: \"An edit needs a non-empty `find`.\", edit };\n }\n\n let hits: { first: number; count: number };\n if (edit.block === undefined) {\n hits = occurrences(markdown, edit.find);\n } else {\n const block = blocks[edit.block];\n if (!block) {\n return {\n ok: false,\n reason: \"no-such-block\",\n message: `Block ${edit.block} does not exist; the document has ${blocks.length}.`,\n edit,\n };\n }\n hits = occurrences(markdown.slice(block.start, block.end), edit.find, block.start);\n }\n\n if (hits.count === 0) {\n return {\n ok: false,\n reason: \"not-found\",\n message:\n `Could not find that text${edit.block === undefined ? \"\" : ` in block ${edit.block}`}. ` +\n \"Re-read the document and quote it exactly, whitespace included.\",\n edit,\n };\n }\n if (hits.count > 1) {\n return {\n ok: false,\n reason: \"ambiguous\",\n message:\n `That text appears ${hits.count} times. Include more surrounding text, or name the block.`,\n edit,\n };\n }\n\n const start = hits.first;\n const end = start + edit.find.length;\n const clash = applied.find((a) => start < a.end && end > a.start);\n if (clash) {\n return {\n ok: false,\n reason: \"ambiguous\",\n message: \"Two edits target overlapping text. Send them as one edit instead.\",\n edit,\n };\n }\n\n applied.push({ edit, start, end, block: blockOf(blocks, start) });\n }\n\n // Front to back, cutting every unchanged stretch straight from the original.\n // Overlaps were refused above, so no edit needs text another one produced —\n // and re-slicing the rewritten string once per edit made this quadratic.\n let out = \"\";\n let from = 0;\n for (const a of [...applied].sort((x, y) => x.start - y.start)) {\n out += markdown.slice(from, a.start) + a.edit.replace;\n from = a.end;\n }\n\n return { ok: true, markdown: out + markdown.slice(from), applied };\n}\n\n/** Line-level view of one edit, for the approval card. */\nexport type EditHunk = {\n index: number;\n block: number;\n removed: string[];\n added: string[];\n};\n\n/**\n * One hunk per edit, rather than a computed diff.\n *\n * The point of hunks here is that the user can accept some and reject others,\n * and an edit is already the smallest independently-applicable unit — it\n * carries its own anchor. Deriving hunks from a text diff instead would produce\n * regions that are not separately applicable, which is the wrong shape for the\n * question being asked.\n */\nexport function hunksOf(applied: readonly AppliedEdit[]): EditHunk[] {\n return applied.map((a, index) => ({\n index,\n block: a.block,\n removed: a.edit.find.split(\"\\n\"),\n added: a.edit.replace === \"\" ? [] : a.edit.replace.split(\"\\n\"),\n }));\n}\n","// Reference DocumentStores.\n//\n// Mirrors JobStore/FileStore: an in-memory one for tests and a localStorage one\n// for a browser, both defensive on read so a corrupted entry degrades to \"that\n// document is gone\" rather than taking the page with it.\n//\n// History is kept as full snapshots, not as inverse edits. Undo is then a\n// checkout of a previous body — which cannot be computed wrongly, whereas an\n// inverse edit can, and does, precisely when the document has moved on.\n\nimport { AgentError } from \"../errors.js\";\nimport type { DocumentSnapshot, DocumentStore } from \"./types.js\";\n\n/** Bounded so a long editing session cannot fill a storage quota. */\nconst MAX_HISTORY = 20;\n\nlet counter = 0;\nconst mintId = () => `doc_${Date.now().toString(36)}${(counter += 1).toString(36)}`;\n\n/**\n * Newest first, with insertion order as the tie-break.\n *\n * `updatedAt` is a millisecond clock and two documents created in the same tick\n * tie on it — which a plain sort resolves as insertion order, i.e. oldest\n * first, i.e. exactly backwards. Both stores hold their documents in insertion\n * order, so reversing before a stable sort puts the later one ahead of the\n * earlier one whenever the timestamps cannot separate them.\n */\nconst byRecency = (docs: DocumentSnapshot[]): DocumentSnapshot[] =>\n [...docs].reverse().sort((a, b) => b.updatedAt - a.updatedAt);\n\nconst staleError = (id: string, expected: number, actual: number) =>\n new AgentError(\n \"invalid-request\",\n `Document ${id} is at revision ${actual}, not ${expected}. Re-read it before editing.`,\n );\n\n/**\n * The snapshot a write produces. `restoredFrom` is set only by an undo and is\n * dropped by every other write — carried over by the spread, it would make an\n * ordinary edit after an undo look like part of the undo, and the next undo\n * would skip it.\n */\nconst nextSnapshot = (current: DocumentSnapshot, markdown: string, restoredFrom: number | undefined): DocumentSnapshot => {\n const { restoredFrom: _previous, ...rest } = current;\n return {\n ...rest,\n markdown,\n revision: current.revision + 1,\n ...(restoredFrom !== undefined ? { restoredFrom } : {}),\n updatedAt: Date.now(),\n };\n};\n\nexport function createMemoryDocumentStore(): DocumentStore {\n const docs = new Map<string, DocumentSnapshot>();\n const past = new Map<string, DocumentSnapshot[]>();\n\n return {\n async list() {\n return byRecency([...docs.values()]);\n },\n async get(id) {\n return docs.get(id);\n },\n async create({ title, markdown, id }) {\n const now = Date.now();\n const doc: DocumentSnapshot = {\n id: id ?? mintId(),\n title,\n markdown,\n revision: 1,\n createdAt: now,\n updatedAt: now,\n };\n docs.set(doc.id, doc);\n past.set(doc.id, []);\n return doc;\n },\n async update(id, markdown, expectedRevision, opts) {\n const current = docs.get(id);\n if (!current) throw new AgentError(\"invalid-request\", `No document ${id}.`);\n if (current.revision !== expectedRevision) {\n throw staleError(id, expectedRevision, current.revision);\n }\n past.set(id, [current, ...(past.get(id) ?? [])].slice(0, MAX_HISTORY));\n const next = nextSnapshot(current, markdown, opts?.restoredFrom);\n docs.set(id, next);\n return next;\n },\n async remove(id) {\n docs.delete(id);\n past.delete(id);\n },\n async history(id) {\n return past.get(id) ?? [];\n },\n };\n}\n\nexport function createLocalDocumentStore(key = \"superchat:documents\"): DocumentStore {\n type Persisted = { docs: Record<string, DocumentSnapshot>; past: Record<string, DocumentSnapshot[]> };\n\n const read = (): Persisted => {\n try {\n const raw = globalThis.localStorage?.getItem(key) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : null;\n if (typeof parsed !== \"object\" || parsed === null) return { docs: {}, past: {} };\n const p = parsed as Partial<Persisted>;\n return { docs: p.docs ?? {}, past: p.past ?? {} };\n } catch {\n return { docs: {}, past: {} };\n }\n };\n\n const write = (all: Persisted) => {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(all));\n } catch {\n // Quota or private mode. A lost document is bad; a thrown exception in\n // the middle of an approved edit is worse — the user already said yes.\n }\n };\n\n return {\n async list() {\n return byRecency(Object.values(read().docs));\n },\n async get(id) {\n return read().docs[id];\n },\n async create({ title, markdown, id }) {\n const all = read();\n const now = Date.now();\n const doc: DocumentSnapshot = {\n id: id ?? mintId(),\n title,\n markdown,\n revision: 1,\n createdAt: now,\n updatedAt: now,\n };\n all.docs[doc.id] = doc;\n all.past[doc.id] = [];\n write(all);\n return doc;\n },\n async update(id, markdown, expectedRevision, opts) {\n const all = read();\n const current = all.docs[id];\n if (!current) throw new AgentError(\"invalid-request\", `No document ${id}.`);\n if (current.revision !== expectedRevision) {\n throw staleError(id, expectedRevision, current.revision);\n }\n all.past[id] = [current, ...(all.past[id] ?? [])].slice(0, MAX_HISTORY);\n const next = nextSnapshot(current, markdown, opts?.restoredFrom);\n all.docs[id] = next;\n write(all);\n return next;\n },\n async remove(id) {\n const all = read();\n delete all.docs[id];\n delete all.past[id];\n write(all);\n },\n async history(id) {\n return read().past[id] ?? [];\n },\n };\n}\n","// The document tools.\n//\n// Storage is the host's — these take a DocumentStore and never assume one. What\n// the framework keeps is the protocol (how a document is addressed and\n// rewritten) and the approval surface (what the user sees before anything\n// changes), which is the same line Transport draws around credentials.\n//\n// Returned rather than registered, exactly as MCP imports and app actions are:\n// a tool that can rewrite the user's document must be given its authority\n// explicitly by whoever wires it up, never by virtue of existing.\n\nimport type { CardSpec } from \"../cards/types.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { ToolDefinition, ToolExecutionContext } from \"../tools/types.js\";\nimport { applyEdits, hunksOf, outlineOf, searchBlocks, spanOf } from \"./edit.js\";\nimport type { DocumentEdit, DocumentSnapshot, DocumentStore } from \"./types.js\";\n\nexport type DocumentToolsOptions = {\n store: DocumentStore;\n /** Cap on what a single read returns, so one call cannot flood context. */\n maxSpanChars?: number;\n /**\n * Cap on how many documents `listDocuments` names at once.\n *\n * The list is the cheapest thing here per entry and the easiest to let grow\n * without noticing: a host that has accumulated four hundred documents would\n * otherwise spend a page of context on the index before the model has read a\n * word of any of them.\n */\n maxListed?: number;\n};\n\nconst str = (v: unknown): string => (typeof v === \"string\" ? v : \"\");\nconst num = (v: unknown): number | undefined => (typeof v === \"number\" ? v : undefined);\n\nconst documentSpec = (doc: DocumentSnapshot): CardSpec => ({\n kind: \"document\",\n docId: doc.id,\n title: doc.title,\n markdown: doc.markdown,\n revision: doc.revision,\n});\n\n/**\n * The refusal for a document that moved underneath a write — shaped like\n * applyEdits' own refusals, because it is one: \"stale-revision\" means re-read\n * and propose again, which is a retry the model can make. A thrown error is\n * not; it surfaces as a failed tool, and the model is left guessing whether\n * anything was written.\n */\nconst moved = (docId: string, read: number, now: DocumentSnapshot | undefined, when: string) =>\n now\n ? {\n output: {\n error: `Document ${docId} moved from revision ${read} to ${now.revision} ${when}. Nothing was written. Re-read it and propose again.`,\n reason: \"stale-revision\" as const,\n revision: now.revision,\n },\n failure: \"invalid-input\" as const,\n }\n : {\n output: { error: `Document ${docId} was removed ${when}. Nothing was written.` },\n failure: \"not-found\" as const,\n };\n\n/**\n * Write through the store, turning its revision check into a refusal.\n *\n * The check stays the store's — it is the only place that sees every writer —\n * but its error is the host's to shape, so this does not parse it. It asks the\n * store again instead: if the document is no longer at the revision this write\n * was based on, the throw was that check and the caller gets `moved`; anything\n * else is a real failure and is rethrown.\n */\nasync function writeOrRefuse(\n store: DocumentStore,\n doc: DocumentSnapshot,\n markdown: string,\n when: string,\n opts?: { restoredFrom?: number },\n): Promise<{ next: DocumentSnapshot } | ReturnType<typeof moved>> {\n try {\n return { next: await store.update(doc.id, markdown, doc.revision, opts) };\n } catch (err) {\n const now = await store.get(doc.id);\n if (!now || now.revision !== doc.revision) return moved(doc.id, doc.revision, now, when);\n throw err;\n }\n}\n\nconst CREATE_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"title\", \"markdown\"],\n properties: {\n title: { type: \"string\", description: \"Short, human title. Becomes the filename on download.\" },\n markdown: { type: \"string\", description: \"The document body, in Markdown.\" },\n },\n};\n\nconst READ_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"docId\"],\n properties: {\n docId: { type: \"string\" },\n mode: {\n type: \"string\",\n enum: [\"outline\", \"span\", \"search\"],\n description:\n \"outline: block index + heading + size for the whole document — start here. span: the text of a block range. search: blocks containing a phrase.\",\n },\n from: { type: \"number\", description: \"First block, for mode=span.\" },\n to: { type: \"number\", description: \"Last block, for mode=span. Defaults to `from`.\" },\n query: { type: \"string\", description: \"Phrase to look for, for mode=search.\" },\n },\n};\n\nconst EDIT_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"docId\", \"revision\", \"edits\"],\n properties: {\n docId: { type: \"string\" },\n revision: {\n type: \"number\",\n description: \"The revision you read. If the document has moved on, the edit is refused.\",\n },\n summary: { type: \"string\", description: \"One line on what these changes do.\" },\n edits: {\n type: \"array\",\n description:\n \"Each edit finds exact text and replaces it. Never send the whole document. If `find` matches nothing or matches twice, the edit is refused rather than guessed at.\",\n items: {\n type: \"object\",\n required: [\"find\", \"replace\"],\n properties: {\n block: { type: \"number\", description: \"Restrict the search to this block. Send it whenever you know it.\" },\n find: { type: \"string\", description: \"Exact existing text, whitespace included.\" },\n replace: { type: \"string\", description: \"What replaces it. Empty string deletes.\" },\n },\n },\n },\n },\n};\n\n/**\n * Build the document tools against a host store.\n *\n * `editDocument` is `side: \"confirm\"` and does its own asking: it computes the\n * change, shows it as an edit review, and writes only what came back accepted.\n * There is no path that writes without that answer.\n *\n * `listDocuments` is what makes the rest of them reachable. A docId arrives in\n * a tool result and then lives only in the transcript — which compaction trims,\n * and which a new thread never had. Without an index, \"a document outlives its\n * thread\" is true of the store and false of the agent: the document survives\n * and nothing can name it. It returns titles and sizes, never bodies, so\n * carrying it costs a line per document.\n */\nexport function createDocumentTools(opts: DocumentToolsOptions): ToolDefinition[] {\n const { store, maxSpanChars = 6000, maxListed = 50 } = opts;\n\n const listDocuments: ToolDefinition = {\n name: \"listDocuments\",\n description:\n \"List the documents that exist, newest first — id, title and size, never the body. Use it when the user refers to something they worked on before and you do not have its id.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Optional filter on the title, case-insensitive.\" },\n },\n },\n side: \"read\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const needle = str(i[\"query\"]).trim().toLowerCase();\n const all = await store.list();\n const matched = needle ? all.filter((d) => d.title.toLowerCase().includes(needle)) : all;\n return {\n output: {\n documents: matched.slice(0, maxListed).map((d) => ({\n docId: d.id,\n title: d.title,\n revision: d.revision,\n blocks: outlineOf(d.markdown).length,\n chars: d.markdown.length,\n updatedAt: d.updatedAt,\n })),\n // Reported rather than silent, for the same reason a truncated span\n // is: a model that believes it has seen every document will tell the\n // user theirs does not exist.\n total: matched.length,\n truncated: matched.length > maxListed,\n },\n };\n },\n };\n\n const createDocument: ToolDefinition = {\n name: \"createDocument\",\n description:\n \"Create a document the user will keep and come back to — a draft, a report, notes. Use instead of a long reply when the result is a thing rather than an answer. Returns an id for reading and editing it later.\",\n inputSchema: CREATE_SCHEMA,\n side: \"write\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const doc = await store.create({ title: str(i[\"title\"]) || \"Untitled\", markdown: str(i[\"markdown\"]) });\n return {\n // The model gets the handle and the shape, never the body: the card\n // below carries the body for the user, and stripCardPayload keeps it\n // out of context from the next turn on.\n output: {\n docId: doc.id,\n revision: doc.revision,\n title: doc.title,\n blocks: outlineOf(doc.markdown).length,\n },\n card: documentSpec(doc),\n };\n },\n };\n\n const readDocument: ToolDefinition = {\n name: \"readDocument\",\n description:\n \"Read part of a document. Ask for the outline first, then the spans you actually need — the whole body is never returned at once.\",\n inputSchema: READ_SCHEMA,\n side: \"read\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const doc = await store.get(str(i[\"docId\"]));\n if (!doc) return { output: { error: `No document ${str(i[\"docId\"])}.` }, failure: \"not-found\" as const };\n\n const mode = str(i[\"mode\"]) || \"outline\";\n if (mode === \"outline\") {\n return { output: { docId: doc.id, title: doc.title, revision: doc.revision, outline: outlineOf(doc.markdown) } };\n }\n if (mode === \"search\") {\n return { output: { docId: doc.id, revision: doc.revision, matches: searchBlocks(doc.markdown, str(i[\"query\"])) } };\n }\n\n const from = num(i[\"from\"]) ?? 0;\n const to = num(i[\"to\"]) ?? from;\n const text = spanOf(doc.markdown, from, to);\n return {\n output: {\n docId: doc.id,\n revision: doc.revision,\n from,\n to,\n // Truncation is REPORTED, not silent: a model that believes it has\n // read a whole section will quote text that is not there, and the\n // edit will then be refused for a reason that looks like its fault.\n truncated: text.length > maxSpanChars,\n text: text.slice(0, maxSpanChars),\n },\n };\n },\n };\n\n const editDocument: ToolDefinition = {\n name: \"editDocument\",\n description:\n \"Propose changes to a document. The user sees them as a diff and accepts them one at a time; nothing is written until they do.\",\n inputSchema: EDIT_SCHEMA,\n side: \"confirm\",\n // The diff is the approval, and only this tool can compute it.\n confirmation: \"tool\",\n async execute(input, ctx: ToolExecutionContext) {\n const i = (input ?? {}) as Record<string, unknown>;\n const docId = str(i[\"docId\"]);\n const doc = await store.get(docId);\n if (!doc) return { output: { error: `No document ${docId}.` }, failure: \"not-found\" as const };\n\n const revision = num(i[\"revision\"]);\n if (revision !== doc.revision) {\n return {\n output: {\n error: `Document is at revision ${doc.revision}, you read ${revision}. Re-read it and propose again.`,\n reason: \"stale-revision\",\n revision: doc.revision,\n },\n failure: \"invalid-input\" as const,\n };\n }\n\n const edits = Array.isArray(i[\"edits\"]) ? (i[\"edits\"] as DocumentEdit[]) : [];\n const result = applyEdits(doc.markdown, edits);\n if (!result.ok) {\n // A refusal the model can act on, not a thrown error: \"not-found\" means\n // re-read, \"ambiguous\" means widen the anchor. Guessing instead would\n // put a change somewhere nobody asked for and present it for approval\n // as though it were intended.\n return { output: { error: result.message, reason: result.reason, edit: result.edit }, failure: \"invalid-input\" as const };\n }\n\n const hunks = hunksOf(result.applied);\n const answer = (await ctx.requestCard?.({\n kind: \"editreview\",\n docId: doc.id,\n title: doc.title,\n revision: doc.revision,\n ...(str(i[\"summary\"]) ? { summary: str(i[\"summary\"]) } : {}),\n hunks,\n })) as { accepted?: number[] } | undefined;\n\n // No handler, or a cancel, both mean nothing was approved. Defaulting to\n // \"apply everything\" when the answer is missing would turn a broken wire\n // into an unreviewed write.\n const accepted = Array.isArray(answer?.accepted) ? answer.accepted : [];\n if (!accepted.length) {\n return { output: { applied: 0, revision: doc.revision, note: \"The user accepted none of the changes.\" } };\n }\n\n // Re-read: the review is an await on a human, and the document can move\n // while it is open — the user accepts a different edit first, undoes, or\n // types in another tab. What they approved was a diff against `doc`, so\n // if the document is no longer `doc` the approval does not transfer:\n // applying it anyway would put an approved-looking change into a context\n // nobody reviewed. Refused, with the revision to re-read from.\n const latest = await store.get(doc.id);\n if (!latest || latest.revision !== doc.revision) {\n return moved(doc.id, doc.revision, latest, \"while the change was awaiting approval\");\n }\n\n // Only the accepted subset, recomputed from its anchors against the body\n // just re-read rather than spliced in at the proposal's offsets.\n const chosen = result.applied.filter((_, index) => accepted.includes(index)).map((a) => a.edit);\n const partial = applyEdits(latest.markdown, chosen);\n if (!partial.ok) {\n return { output: { error: partial.message, reason: partial.reason }, failure: \"invalid-input\" as const };\n }\n\n // The re-read above narrows the window; the store's own check closes it.\n const written = await writeOrRefuse(store, latest, partial.markdown, \"while the change was being written\");\n if (!(\"next\" in written)) return written;\n const { next } = written;\n return {\n output: {\n docId: next.id,\n revision: next.revision,\n applied: accepted.length,\n rejected: hunks.length - accepted.length,\n },\n card: documentSpec(next),\n };\n },\n };\n\n const undoDocument: ToolDefinition = {\n name: \"undoDocument\",\n description:\n \"Restore an earlier version of a document. With no toRevision it steps back one version, and calling it again keeps stepping back. Each undo is itself a new revision.\",\n inputSchema: {\n type: \"object\",\n required: [\"docId\"],\n properties: {\n docId: { type: \"string\" },\n toRevision: {\n type: \"number\",\n description: \"Restore exactly this earlier revision instead of stepping back one.\",\n },\n },\n },\n side: \"write\",\n async execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const docId = str(i[\"docId\"]);\n const doc = await store.get(docId);\n if (!doc) return { output: { error: `No document ${docId}.` }, failure: \"not-found\" as const };\n\n const history = await store.history(docId);\n const toRevision = num(i[\"toRevision\"]);\n\n // The cursor. A body that is itself an undo stands for the revision it\n // restored, so stepping back starts from THERE — not from its own,\n // newer number, whose predecessor is the very body that was just undone.\n // That one line is the difference between walking back and ping-ponging.\n const at = doc.restoredFrom ?? doc.revision;\n const target =\n toRevision === undefined\n ? history.find((h) => h.revision < at)\n : history.find((h) => h.revision === toRevision);\n\n if (!target) {\n return {\n output: {\n error:\n toRevision === undefined\n ? \"This document has no earlier version.\"\n : toRevision >= doc.revision\n ? `Revision ${toRevision} is not earlier than the current revision, ${doc.revision}.`\n : `Revision ${toRevision} is not one this document still keeps.`,\n revision: doc.revision,\n available: history.map((h) => h.revision),\n },\n failure: \"not-found\" as const,\n };\n }\n\n // Undo restores a stored body and mints a NEW revision — it does not roll\n // the number back. An inverse edit would have to be computed, and can be\n // computed wrongly; a checkout cannot. And keeping revisions monotonic\n // means an in-flight edit proposed against the undone body is refused\n // rather than silently applied to text that no longer exists.\n const restoredFrom = target.restoredFrom ?? target.revision;\n const written = await writeOrRefuse(store, doc, target.markdown, \"before the undo was written\", { restoredFrom });\n if (!(\"next\" in written)) return written;\n const { next } = written;\n return {\n output: {\n docId: next.id,\n revision: next.revision,\n restoredFrom,\n // Said, so a model asked to go further back can tell whether there\n // is anywhere to go without spending a call to find out.\n canUndoFurther: history.some((h) => h.revision < restoredFrom),\n },\n card: documentSpec(next),\n };\n },\n };\n\n return [listDocuments, createDocument, readDocument, editDocument, undoDocument];\n}\n\nconst EMAIL_SCHEMA: JSONSchema = {\n type: \"object\",\n required: [\"to\", \"subject\", \"body\"],\n properties: {\n to: { type: \"array\", items: { type: \"string\" } },\n cc: { type: \"array\", items: { type: \"string\" } },\n bcc: { type: \"array\", items: { type: \"string\" } },\n subject: { type: \"string\" },\n body: { type: \"string\", description: \"Plain text. Not Markdown — mail cannot carry it here.\" },\n },\n};\n\n/**\n * Draft an email for the user to send.\n *\n * `draft` tier, and the tier is the whole point: this produces something the\n * user approves and sends themselves. There is no send path and no credential,\n * which is what makes it safe to hand out.\n */\nexport function createEmailDraftTool(): ToolDefinition {\n return {\n name: \"draftEmail\",\n description:\n \"Draft an email for the user to review and send. It is never sent for them — they get an editable draft with the message ready to open in their mail client.\",\n inputSchema: EMAIL_SCHEMA,\n side: \"write\",\n execute(input) {\n const i = (input ?? {}) as Record<string, unknown>;\n const to = Array.isArray(i[\"to\"]) ? (i[\"to\"] as string[]).map(String) : [];\n const spec: CardSpec = {\n kind: \"email\",\n to,\n ...(Array.isArray(i[\"cc\"]) ? { cc: (i[\"cc\"] as string[]).map(String) } : {}),\n ...(Array.isArray(i[\"bcc\"]) ? { bcc: (i[\"bcc\"] as string[]).map(String) } : {}),\n subject: str(i[\"subject\"]),\n body: str(i[\"body\"]),\n };\n return {\n output: { drafted: true, to, subject: str(i[\"subject\"]), note: \"Shown to the user as an editable draft; not sent.\" },\n card: spec,\n };\n },\n };\n}\n","// Getting a draft out of the conversation and into a mail client.\n//\n// Two exits, and the ordering between them is the design.\n//\n// `.eml` is the primary one. It is a real RFC 5322 message: every mail client\n// opens it, it carries recipients, headers and (later) attachments, it survives\n// being saved, and it does not care how long the body is.\n//\n// `mailto:` is the convenience shortcut, and its limits are hard enough to be\n// worth stating rather than discovering:\n// - practical URL ceiling around 2000 characters, past which clients TRUNCATE\n// silently — the user sends a letter with the end missing and no warning\n// - no attachments, at all\n// - plain text only\n// - newline encoding varies between clients\n// - on a desktop with no mail client registered, clicking it does nothing,\n// and reports nothing\n//\n// So the composer offers both and says which is which, rather than shipping the\n// shortcut and calling the feature done.\n//\n// Neither path sends anything. Sending needs a credential, and the framework\n// holding one would break the rule Transport already keeps.\n\nimport type { EmailCard } from \"../cards/types.js\";\n\n/** Roughly where mail clients start truncating a mailto: URL. */\nexport const MAILTO_SAFE_LENGTH = 2000;\n\nconst encode = (s: string) =>\n // encodeURIComponent leaves these legal-in-a-query characters alone, and\n // some clients read them as delimiters. Percent-encoding them costs nothing.\n encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n\nexport type MailtoLink = {\n href: string;\n /** True when the href is long enough that a client may cut it short. */\n mayTruncate: boolean;\n length: number;\n};\n\nexport function buildMailto(email: EmailCard): MailtoLink {\n const params: string[] = [];\n if (email.cc?.length) params.push(`cc=${encode(email.cc.join(\",\"))}`);\n if (email.bcc?.length) params.push(`bcc=${encode(email.bcc.join(\",\"))}`);\n if (email.subject) params.push(`subject=${encode(email.subject)}`);\n // CRLF rather than LF: clients disagree about a bare %0A, and every one of\n // them understands %0D%0A.\n if (email.body) params.push(`body=${encode(email.body.replace(/\\r?\\n/g, \"\\r\\n\"))}`);\n\n const href = `mailto:${encode(email.to.join(\",\"))}${params.length ? `?${params.join(\"&\")}` : \"\"}`;\n return { href, length: href.length, mayTruncate: href.length > MAILTO_SAFE_LENGTH };\n}\n\n// ── Line limits ──────────────────────────────────────────────────────────────\n//\n// RFC 5322 §2.1.1 sets two of them, and the difference between them is the\n// difference between untidy and rejected:\n//\n// 998 octets a hard MUST. Past it a strict MTA or parser is entitled to\n// refuse the message, and several do.\n// 78 octets a SHOULD, for humans reading raw source.\n//\n// A drafted letter reaches the ceiling more easily than it looks: one long\n// unwrapped paragraph is a single line, and \"one long unwrapped paragraph\" is\n// what a model writes unless told otherwise. So the body is measured, and if\n// any line would break the MUST the encoding changes to carry it losslessly\n// rather than the text being folded — folding prose would silently insert line\n// breaks the user did not write into a letter they are about to send.\n\n/** Hard ceiling, excluding the CRLF. */\nconst MAX_LINE_OCTETS = 998;\n/** What folding aims at. */\nconst FOLD_WIDTH = 78;\n/** An RFC 2047 encoded-word may not exceed this, including its delimiters. */\nconst MAX_ENCODED_WORD = 75;\n\nconst octetsOf = (s: string) => new TextEncoder().encode(s).length;\n\nconst base64 = (bytes: Uint8Array): string =>\n typeof btoa === \"function\"\n ? btoa(String.fromCharCode(...bytes))\n : Buffer.from(bytes).toString(\"base64\");\n\n/**\n * RFC 2047 encoded-words, split so none exceeds 75 characters.\n *\n * One word for the whole subject is the tempting version and it breaks on a\n * long non-ASCII subject: over the limit, clients variously truncate the header\n * or show the raw `=?UTF-8?B?…` to the user. The split has to fall on a UTF-8\n * character boundary — cut mid-sequence and the decoder emits a replacement\n * character in the middle of a word, which looks like the sender's mistake.\n */\nfunction encodedWords(value: string): string[] {\n const bytes = new TextEncoder().encode(value);\n // \"=?UTF-8?B?\" + \"?=\" is 12 characters; base64 costs 4 per 3 bytes. 45 bytes\n // is the largest multiple of 3 that still fits inside the limit.\n const perWord = Math.min(45, Math.floor(((MAX_ENCODED_WORD - 12) / 4) * 3));\n const words: string[] = [];\n\n for (let i = 0; i < bytes.length; ) {\n let take = Math.min(perWord, bytes.length - i);\n while (take > 1 && i + take < bytes.length && (bytes[i + take]! & 0xc0) === 0x80) take -= 1;\n words.push(`=?UTF-8?B?${base64(bytes.slice(i, i + take))}?=`);\n i += take;\n }\n return words.length ? words : [\"\"];\n}\n\n/**\n * Fold a header, or leave it exactly as it was.\n *\n * Only long headers are touched. Folding is reversible in principle, but\n * unfolding collapses the inserted whitespace, so a header that already fits\n * should come out byte-identical rather than round-tripped for no reason.\n */\nfunction fold(name: string, pieces: string[], separator: string): string {\n const flat = `${name}: ${pieces.join(`${separator} `)}`;\n if (octetsOf(flat) <= FOLD_WIDTH) return flat;\n\n const lines: string[] = [];\n let line = `${name}:`;\n pieces.forEach((piece, i) => {\n const token = i < pieces.length - 1 ? `${piece}${separator}` : piece;\n // A continuation line starts with whitespace; that is what makes it one.\n if (line !== `${name}:` && octetsOf(`${line} ${token}`) > FOLD_WIDTH) {\n lines.push(line);\n line = ` ${token}`;\n } else {\n line += ` ${token}`;\n }\n });\n lines.push(line);\n return lines.join(\"\\r\\n\");\n}\n\n/** Address lists fold at the commas — the only place a break is legal. */\nconst addressHeader = (name: string, addresses: string[]) => fold(name, addresses, \",\");\n\nfunction subjectHeader(subject: string): string {\n if (/[^\\x20-\\x7e]/.test(subject)) return fold(\"Subject\", encodedWords(subject), \"\");\n // An ASCII subject that already fits goes through untouched. Folding splits\n // on spaces and rejoins with one, so a subject with a deliberate double space\n // would come back altered for no gain.\n const flat = `Subject: ${subject}`;\n if (octetsOf(flat) <= FOLD_WIDTH) return flat;\n return fold(\"Subject\", subject.split(/ +/).filter(Boolean), \"\");\n}\n\n// ── Body ─────────────────────────────────────────────────────────────────────\n\nconst needsQuotedPrintable = (body: string) =>\n body.split(/\\r?\\n/).some((line) => octetsOf(line) > MAX_LINE_OCTETS);\n\n/**\n * Quoted-printable with soft line breaks.\n *\n * Lossless, unlike folding: a trailing `=` tells the receiver the line\n * continues, so the text the user wrote is the text that arrives. Chosen over\n * base64 because the .eml stays readable in a text editor, which is worth\n * keeping for something the user is meant to inspect before sending.\n */\nfunction quotedPrintable(body: string): string {\n const out: string[] = [];\n\n for (const line of body.split(/\\r?\\n/)) {\n const bytes = new TextEncoder().encode(line);\n let current = \"\";\n for (let i = 0; i < bytes.length; i += 1) {\n const b = bytes[i]!;\n const printable = b >= 32 && b <= 126 && b !== 61;\n // Trailing whitespace must be encoded or a transport is allowed to strip\n // it, which silently rewrites the line.\n const trailing = (b === 32 || b === 9) && i === bytes.length - 1;\n const token = printable && !trailing ? String.fromCharCode(b) : `=${b.toString(16).toUpperCase().padStart(2, \"0\")}`;\n // 76 including the soft-break `=`, so a token never straddles the break.\n if (current.length + token.length > 75) {\n out.push(`${current}=`);\n current = \"\";\n }\n current += token;\n }\n out.push(current);\n }\n\n return out.join(\"\\r\\n\");\n}\n\n/**\n * An RFC 5322 message.\n *\n * Deliberately without a Date or Message-ID: this is a DRAFT, and stamping it\n * with a send time it did not have would be a small lie that some clients then\n * display as fact. The user's own client fills both in when they send.\n */\nexport function buildEml(email: EmailCard): string {\n const encoded = needsQuotedPrintable(email.body);\n const lines = [\n addressHeader(\"To\", email.to),\n ...(email.cc?.length ? [addressHeader(\"Cc\", email.cc)] : []),\n ...(email.bcc?.length ? [addressHeader(\"Bcc\", email.bcc)] : []),\n subjectHeader(email.subject),\n \"MIME-Version: 1.0\",\n 'Content-Type: text/plain; charset=\"utf-8\"',\n `Content-Transfer-Encoding: ${encoded ? \"quoted-printable\" : \"8bit\"}`,\n \"\",\n encoded ? quotedPrintable(email.body) : email.body,\n ];\n // CRLF throughout — the spec's line ending, and the one strict parsers want.\n return lines.join(\"\\r\\n\").replace(/(?<!\\r)\\n/g, \"\\r\\n\");\n}\n\n/** A filename that will not upset a filesystem. */\nexport function emlFilename(email: EmailCard): string {\n const stem = (email.subject || \"draft\").replace(/[^\\w\\s.-]/g, \"\").trim().replace(/\\s+/g, \"-\").slice(0, 60);\n return `${stem || \"draft\"}.eml`;\n}\n","// The card registry.\n//\n// One registration binds four things that MUST NOT drift apart:\n// schema — what the model is told it may send\n// validate — what we actually accept (and the error we hand back)\n// interactive— whether this card participates in control flow\n// renderer — resolved by the UI package from the same `kind` key\n//\n// The reference implementation this is modelled on keeps parsers and render\n// branches in two hand-maintained lists, and its own comments record the\n// consequence: a card that had a parser but no render branch disappeared into a\n// generic \"ran ✓\" chip and nobody noticed. Binding them at registration makes\n// that failure unrepresentable — `renderers` is derived from the same map, so a\n// kind is either fully present or absent.\n\nimport type { Card, CardPlacement, CardSpec } from \"./types.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\n\nexport type CardValidation = { ok: true } | { ok: false; error: string; expected?: string };\n\nexport type CardKindDefinition = {\n kind: string;\n /** One line for the `visualize` tool description — this is what steers model choice. */\n summary: string;\n schema: JSONSchema;\n validate: (spec: unknown) => CardValidation;\n /** Interactive cards must render at top level and never collapse. */\n interactive?: boolean;\n /** Approximate token cost of the spec, for context budgeting of replayed cards. */\n estimateTokens?: (spec: CardSpec) => number;\n /**\n * Derive a renderable spec from one that is still streaming in — keep what\n * has fully arrived, drop the entry still being written when the renderer\n * cannot show it yet. Return `undefined` until there is something worth\n * drawing. The result must pass `validate`: `CardRegistry.partial` checks\n * it, so a preview is a VALID card that is merely incomplete, never a\n * malformed one.\n *\n * Omit for kinds that should keep a skeleton until they are whole. Ignored\n * on interactive kinds: a control the user can act on must never be shown\n * before the spec behind it is complete and validated.\n */\n partial?: (spec: Record<string, unknown>) => CardSpec | undefined;\n};\n\nexport const isObj = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/** Small validator helpers — enough to give the model an actionable correction. */\nexport const check = {\n object(spec: unknown, kind: string): CardValidation | Record<string, unknown> {\n if (!isObj(spec)) return { ok: false as const, error: `${kind} spec must be an object.` };\n return spec;\n },\n arrayField(spec: Record<string, unknown>, field: string, kind: string, minLength = 1): CardValidation | unknown[] {\n const value = spec[field];\n if (!Array.isArray(value)) {\n return { ok: false as const, error: `${kind}.${field} must be an array.`, expected: `${field}: [...]` };\n }\n if (value.length < minLength) {\n return { ok: false as const, error: `${kind}.${field} must have at least ${minLength} item(s).` };\n }\n return value;\n },\n};\n\nexport const failed = (v: unknown): v is CardValidation => isObj(v) && \"ok\" in v && (v as { ok: unknown }).ok === false;\n\nexport class CardRegistry {\n private kinds = new Map<string, CardKindDefinition>();\n\n constructor(definitions: readonly CardKindDefinition[] = []) {\n for (const d of definitions) this.register(d);\n }\n\n register(def: CardKindDefinition): this {\n this.kinds.set(def.kind, def);\n return this;\n }\n\n has(kind: string): boolean {\n return this.kinds.has(kind);\n }\n\n get(kind: string): CardKindDefinition | undefined {\n return this.kinds.get(kind);\n }\n\n list(): CardKindDefinition[] {\n return [...this.kinds.values()];\n }\n\n isInteractive(kind: string): boolean {\n return this.kinds.get(kind)?.interactive === true;\n }\n\n /**\n * Validate a spec. An unknown kind is a hard failure with the list of valid\n * kinds attached — a model that receives \"unknown kind: barchart, valid kinds\n * are: chart, table, …\" fixes itself on the next step, whereas one that\n * receives a silently-dropped card repeats the mistake forever.\n */\n validate(spec: unknown): CardValidation {\n if (!isObj(spec)) return { ok: false, error: \"Card spec must be an object with a `kind` field.\" };\n const kind = spec[\"kind\"];\n if (typeof kind !== \"string\") return { ok: false, error: \"Card spec is missing a string `kind`.\" };\n const def = this.kinds.get(kind);\n if (!def) {\n return {\n ok: false,\n error: `Unknown card kind \"${kind}\".`,\n expected: `One of: ${this.list().map((k) => k.kind).join(\", \")}`,\n };\n }\n return def.validate(spec);\n }\n\n /**\n * A preview of a spec that is still streaming, or `undefined` when there\n * should not be one: an unknown kind, an interactive kind, a kind with no\n * `partial`, or a derived spec its own validator rejects. The one place that\n * decides whether a partial spec may reach a renderer.\n */\n partial(spec: unknown): CardSpec | undefined {\n if (!isObj(spec) || typeof spec[\"kind\"] !== \"string\") return undefined;\n const def = this.kinds.get(spec[\"kind\"]);\n if (!def?.partial || def.interactive) return undefined;\n let preview: CardSpec | undefined;\n try {\n preview = def.partial(spec);\n } catch {\n return undefined; // a preview must never be able to fail the call it previews\n }\n if (!isObj(preview) || preview[\"kind\"] !== def.kind) return undefined;\n return def.validate(preview).ok ? preview : undefined;\n }\n\n /** The catalogue text embedded in the `visualize` tool description. */\n describe(): string {\n return this.list()\n .map((k) => `- ${k.kind}${k.interactive ? \" (interactive)\" : \"\"}: ${k.summary}`)\n .join(\"\\n\");\n }\n\n /** Per-kind schemas, for hosts that prefer one tool per card kind. */\n schemas(): Record<string, JSONSchema> {\n return Object.fromEntries(this.list().map((k) => [k.kind, k.schema]));\n }\n}\n\nlet cardCounter = 0;\nexport function makeCard(spec: CardSpec, callId?: string, id?: string, placement?: CardPlacement): Card {\n const where = placement && placement !== \"inline\" ? { placement } : {};\n // An explicit id means \"replace that card\": the reducer upserts by id, so\n // reusing one turns an append into an in-place update (`updateCard`).\n if (id) return { id, spec, ...(callId ? { callId } : {}), ...where };\n cardCounter += 1;\n return { id: `card_${Date.now().toString(36)}${cardCounter.toString(36)}`, spec, ...(callId ? { callId } : {}), ...where };\n}\n","// Card references: how text in a chat message points at something inside a card.\n//\n// The envelope (`ref:<target>?<name>=<value>&...`) is defined once by super-protocol\n// (docs/CARD-REFS.md, `parseCardRef`), and what the params mean is up to the card kind.\n// This is the host's copy of the parser: core has no dependencies, and the host must read links\n// without a card kind's vocabulary anyway. It matches `parseCardRef` in super-protocol 0.3.0\n// exactly, limits and messages included; the plugin package's `card-ref-agreement.test.ts`\n// checks that against the published protocol, so a link one accepts the other accepts.\n\nexport const CARD_REF_SCHEME = \"ref\";\n\nexport const CARD_REF_LIMITS = Object.freeze({\n /** The whole link, in UTF-16 code units. */\n length: 512,\n /** The target (the card's id). */\n target: 128,\n /** Distinct param names. */\n names: 16,\n /** Values of one param name (`key=a&key=b`). */\n values: 32,\n /** One param name. */\n name: 32,\n /** One decoded value, in UTF-16 code units. */\n value: 256,\n});\n\n/** A parsed reference. A repeated param is a list in order; values are decoded once, never split on commas. */\nexport interface CardRef {\n /** The `id` of the card this points into. */\n target: string;\n params: Record<string, string[]>;\n}\n\n/** What the reader did with the link: pointed at it, left it, or chose it (click, Enter, tap). */\nexport type CardRefEvent = \"enter\" | \"leave\" | \"activate\";\n\n/** What a card answers. `ok: false` lets the host show a stale reference as plain text, with the reason. */\nexport type CardRefResult = { ok: true; label?: string } | { ok: false; code: string; reason: string };\n\nexport type CardRefParse = { ok: true; ref: CardRef } | { ok: false; error: string };\n\n/** A host's side of references: hands one on to the card it points into. `null` clears everything shown. */\nexport interface CardRefHost {\n ref(ref: CardRef | null, event: CardRefEvent): CardRefResult;\n}\n\nconst TARGET = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;\nconst NAME = /^[a-z][A-Za-z0-9_-]{0,31}$/;\nconst RAW_VALUE = /^(?:[A-Za-z0-9._~-]|%[0-9A-Fa-f]{2})+$/;\n\nconst hasOwn = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k);\n\nfunction decodeValue(raw: string): string | null {\n const bytes: number[] = [];\n for (let i = 0; i < raw.length; i++) {\n if (raw[i] === \"%\") {\n bytes.push(parseInt(raw.slice(i + 1, i + 3), 16));\n i += 2;\n } else bytes.push(raw.charCodeAt(i));\n }\n try {\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(Uint8Array.from(bytes));\n } catch {\n return null;\n }\n}\n\n/** Reads a `ref:` link. */\nexport function parseCardRef(href: unknown): CardRefParse {\n const fail = (error: string): CardRefParse => ({ ok: false, error });\n if (typeof href !== \"string\") return fail(\"a ref must be a string.\");\n if (href.length > CARD_REF_LIMITS.length) return fail(`a ref is at most ${CARD_REF_LIMITS.length} characters.`);\n if (!href.startsWith(`${CARD_REF_SCHEME}:`)) return fail(`a ref starts with \"${CARD_REF_SCHEME}:\".`);\n const rest = href.slice(CARD_REF_SCHEME.length + 1);\n if (rest.includes(\"#\")) return fail(\"a ref has no fragment.\");\n const q = rest.indexOf(\"?\");\n const target = q < 0 ? rest : rest.slice(0, q);\n if (!TARGET.test(target)) return fail(\"a ref target is 1 to 128 letters, digits, dot, underscore, colon or dash, starting with a letter or digit.\");\n const params: Record<string, string[]> = {};\n if (q >= 0) {\n const query = rest.slice(q + 1);\n if (query === \"\") return fail(\"a ref query is empty.\");\n for (const part of query.split(\"&\")) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) return fail(\"each ref param is name=value.\");\n const name = part.slice(0, eq);\n const raw = part.slice(eq + 1);\n if (!NAME.test(name)) return fail(\"a ref param name is 1 to 32 letters, digits, dash or underscore, starting with a lowercase letter.\");\n if (!RAW_VALUE.test(raw)) return fail(\"a ref param value is not empty and uses letters, digits, dot, dash, underscore, tilde or %XX only.\");\n const value = decodeValue(raw);\n if (value === null) return fail(\"a ref param value must be valid UTF-8.\");\n if (value.length > CARD_REF_LIMITS.value) return fail(`a ref param value is at most ${CARD_REF_LIMITS.value} characters.`);\n if (!hasOwn(params, name)) {\n if (Object.keys(params).length >= CARD_REF_LIMITS.names) return fail(`a ref has at most ${CARD_REF_LIMITS.names} param names.`);\n params[name] = [];\n }\n if (params[name]!.length >= CARD_REF_LIMITS.values) return fail(`a ref param has at most ${CARD_REF_LIMITS.values} values.`);\n params[name]!.push(value);\n }\n }\n return { ok: true, ref: { target, params } };\n}\n","// The built-in card catalogue — the agent's default visual vocabulary.\n//\n// Chosen to span the presentations an agent actually needs, not to be\n// exhaustive: comparison (table), magnitude (stats), shape-over-time (chart),\n// sequence (timeline), detail (keyvalue), long work (progress), rich text\n// (markdown/code/diff), media, and the three interactive ones that let the agent\n// ASK rather than assume (choice, form, confirm).\n//\n// Validators are permissive about extra fields and strict about the fields the\n// renderer indexes. A card that renders with a missing optional is fine; a card\n// whose `rows` is a string is a crash, so that is what we reject.\n\nimport { estimateJsonTokens } from \"../tokens/estimate.js\";\nimport { check, failed, isObj, type CardKindDefinition, type CardValidation } from \"./registry.js\";\nimport type { CardSpec } from \"./types.js\";\n\nconst ok: CardValidation = { ok: true };\n\n/**\n * The entries of `spec[field]` that are already renderable. The last entry of\n * a streaming array is usually half-written; `ready` decides whether it can be\n * shown yet (a row with one cell can, a checklist item with no status cannot).\n */\nconst arrived = (spec: Record<string, unknown>, field: string, ready: (item: Record<string, unknown>) => boolean) => {\n const value = spec[field];\n return Array.isArray(value) ? value.filter((item): item is Record<string, unknown> => isObj(item) && ready(item)) : [];\n};\nconst isScalar = (v: unknown) => typeof v === \"string\" || typeof v === \"number\";\n\nconst tokensOf = (spec: CardSpec) => estimateJsonTokens(spec);\n\nconst FORMATS = [\"text\", \"number\", \"currency\", \"percent\", \"bytes\", \"duration\", \"datetime\", \"code\"];\n\nexport const tableCard: CardKindDefinition = {\n kind: \"table\",\n summary: \"Many items sharing the same fields. Search results, inventories, case lists, line items, survey rows.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"columns\", \"rows\"],\n properties: {\n kind: { const: \"table\" },\n title: { type: \"string\" },\n caption: { type: \"string\" },\n columns: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"key\", \"label\"],\n properties: {\n key: { type: \"string\", description: \"Matches a key in each row object.\" },\n label: { type: \"string\" },\n format: { type: \"string\", enum: FORMATS },\n align: { type: \"string\", enum: [\"left\", \"right\", \"center\"] },\n pill: { type: \"boolean\", description: \"Render the cell as a status pill.\" },\n },\n },\n },\n rows: { type: \"array\", items: { type: \"object\" }, description: \"Objects keyed by column.key.\" },\n sortBy: { type: \"string\" },\n sortDir: { type: \"string\", enum: [\"asc\", \"desc\"] },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"table\");\n if (failed(s)) return s;\n const cols = check.arrayField(s as Record<string, unknown>, \"columns\", \"table\");\n if (failed(cols)) return cols;\n const rows = check.arrayField(s as Record<string, unknown>, \"rows\", \"table\", 0);\n if (failed(rows)) return rows;\n for (const c of cols as unknown[]) {\n if (!isObj(c) || typeof c[\"key\"] !== \"string\" || typeof c[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each table column needs a string `key` and `label`.\", expected: '{ key, label }' };\n }\n }\n return ok;\n },\n partial(spec) {\n const columns = arrived(spec, \"columns\", (c) => typeof c[\"key\"] === \"string\" && typeof c[\"label\"] === \"string\");\n if (!columns.length) return undefined;\n // A row shows from its first cell, so the table fills cell by cell. Sorting\n // waits for the whole card: rows land in arrival order rather than each new\n // one shuffling the ones already on screen.\n const rows = arrived(spec, \"rows\", (r) => Object.keys(r).length > 0);\n const { sortBy: _sortBy, sortDir: _sortDir, ...rest } = spec;\n return { ...rest, kind: \"table\", columns, rows } as CardSpec;\n },\n};\n\nexport const statsCard: CardKindDefinition = {\n kind: \"stats\",\n summary: \"A row of headline numbers, optionally with change vs a prior period. Totals, counts, rates, before/after.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"stats\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: {\n label: { type: \"string\" },\n value: { type: [\"string\", \"number\"] },\n format: { type: \"string\", enum: FORMATS },\n delta: { type: \"number\", description: \"Signed change; drives arrow and colour.\" },\n deltaFormat: { type: \"string\", enum: FORMATS },\n hint: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"stats\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"stats\");\n if (failed(items)) return items;\n for (const i of items as unknown[]) {\n if (!isObj(i) || typeof i[\"label\"] !== \"string\" || i[\"value\"] === undefined) {\n return { ok: false, error: \"Each stat needs a `label` and a `value`.\", expected: \"{ label, value }\" };\n }\n }\n return ok;\n },\n partial(spec) {\n const items = arrived(spec, \"items\", (i) => typeof i[\"label\"] === \"string\" && isScalar(i[\"value\"]));\n return items.length ? ({ ...spec, kind: \"stats\", items } as CardSpec) : undefined;\n },\n};\n\nexport const chartCard: CardKindDefinition = {\n kind: \"chart\",\n summary:\n \"Plot shape over time or across categories. `variant:\\\"series\\\"` with `series[]` for line/area/bar/scatter; `variant:\\\"candlestick\\\"` with `candles[]` for OHLC.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\"],\n properties: {\n kind: { const: \"chart\" },\n title: { type: \"string\" },\n variant: { type: \"string\", enum: [\"series\", \"candlestick\"] },\n xLabel: { type: \"string\" },\n yLabel: { type: \"string\" },\n xType: { type: \"string\", enum: [\"time\", \"number\", \"category\"] },\n stacked: { type: \"boolean\" },\n series: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"name\", \"points\"],\n properties: {\n name: { type: \"string\" },\n type: { type: \"string\", enum: [\"line\", \"area\", \"bar\", \"scatter\"] },\n color: { type: \"string\" },\n axis: { type: \"string\", enum: [\"left\", \"right\"] },\n points: {\n type: \"array\",\n description: \"[x, y] pairs. x may be a timestamp, number or category label.\",\n items: { type: \"array\", items: [{ type: [\"string\", \"number\"] }, { type: \"number\" }] },\n },\n },\n },\n },\n candles: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"t\", \"o\", \"h\", \"l\", \"c\"],\n properties: {\n t: { type: [\"string\", \"number\"] },\n o: { type: \"number\" },\n h: { type: \"number\" },\n l: { type: \"number\" },\n c: { type: \"number\" },\n v: { type: \"number\" },\n },\n },\n },\n annotations: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"type\", \"value\"],\n properties: {\n type: { type: \"string\", enum: [\"hline\", \"vline\", \"band\", \"marker\"] },\n value: { type: [\"string\", \"number\"] },\n to: { type: [\"string\", \"number\"] },\n label: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"chart\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n const variant = o[\"variant\"] ?? \"series\";\n if (variant === \"candlestick\") {\n const candles = check.arrayField(o, \"candles\", \"chart\");\n if (failed(candles)) return candles;\n for (const c of candles as unknown[]) {\n if (!isObj(c) || [\"o\", \"h\", \"l\", \"c\"].some((k) => typeof c[k] !== \"number\")) {\n return { ok: false, error: \"Each candle needs numeric o, h, l, c.\", expected: \"{ t, o, h, l, c, v? }\" };\n }\n }\n return ok;\n }\n const series = check.arrayField(o, \"series\", \"chart\");\n if (failed(series)) return series;\n for (const sr of series as unknown[]) {\n if (!isObj(sr) || typeof sr[\"name\"] !== \"string\" || !Array.isArray(sr[\"points\"])) {\n return { ok: false, error: \"Each series needs a `name` and a `points` array.\", expected: '{ name, points: [[x,y],…] }' };\n }\n // Catch the common mistake of `points: [1,2,3]` instead of `[[x,y],…]`.\n const first = (sr[\"points\"] as unknown[])[0];\n if (first !== undefined && !Array.isArray(first)) {\n return { ok: false, error: \"`points` must be [x, y] pairs, not bare values.\", expected: \"points: [[0, 12], [1, 15]]\" };\n }\n }\n return ok;\n },\n};\n\nexport const timelineCard: CardKindDefinition = {\n kind: \"timeline\",\n summary: \"An ordered sequence of events with times and status. Best for history, schedules, execution traces.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"events\"],\n properties: {\n kind: { const: \"timeline\" },\n title: { type: \"string\" },\n events: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"at\", \"label\"],\n properties: {\n at: { type: [\"string\", \"number\"] },\n label: { type: \"string\" },\n detail: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"timeline\");\n if (failed(s)) return s;\n const events = check.arrayField(s as Record<string, unknown>, \"events\", \"timeline\");\n return failed(events) ? events : ok;\n },\n partial(spec) {\n const events = arrived(spec, \"events\", (e) => typeof e[\"label\"] === \"string\" && isScalar(e[\"at\"]));\n return events.length ? ({ ...spec, kind: \"timeline\", events } as CardSpec) : undefined;\n },\n};\n\nexport const keyValueCard: CardKindDefinition = {\n kind: \"keyvalue\",\n summary: \"Labelled detail rows describing ONE thing. A record, a contract's key terms, a config, a profile.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"keyvalue\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: {\n label: { type: \"string\" },\n value: { type: [\"string\", \"number\"] },\n format: { type: \"string\", enum: FORMATS },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n mono: { type: \"boolean\", description: \"Monospace — use for hashes, ids, addresses.\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"keyvalue\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"keyvalue\");\n return failed(items) ? items : ok;\n },\n};\n\nexport const progressCard: CardKindDefinition = {\n kind: \"progress\",\n summary: \"Multi-step work with per-step status. Best for long or background operations the user is waiting on.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"steps\"],\n properties: {\n kind: { const: \"progress\" },\n title: { type: \"string\" },\n fraction: { type: \"number\", minimum: 0, maximum: 1 },\n steps: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"status\"],\n properties: {\n label: { type: \"string\" },\n status: { type: \"string\", enum: [\"pending\", \"active\", \"done\", \"failed\", \"skipped\"] },\n detail: { type: \"string\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"progress\");\n if (failed(s)) return s;\n const steps = check.arrayField(s as Record<string, unknown>, \"steps\", \"progress\");\n if (failed(steps)) return steps;\n const valid = new Set([\"pending\", \"active\", \"done\", \"failed\", \"skipped\"]);\n for (const st of steps as unknown[]) {\n if (!isObj(st) || !valid.has(String(st[\"status\"]))) {\n return { ok: false, error: \"Each step needs a status of pending|active|done|failed|skipped.\" };\n }\n }\n return ok;\n },\n};\n\nexport const mediaCard: CardKindDefinition = {\n kind: \"media\",\n summary: \"Images, audio, or video with captions.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"media\" },\n title: { type: \"string\" },\n layout: { type: \"string\", enum: [\"grid\", \"single\"] },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"url\"],\n properties: {\n url: { type: \"string\" },\n alt: { type: \"string\" },\n caption: { type: \"string\" },\n mediaType: { type: \"string\" },\n width: { type: \"number\" },\n height: { type: \"number\" },\n durationMs: { type: \"number\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"media\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"media\");\n return failed(items) ? items : ok;\n },\n};\n\nexport const markdownCard: CardKindDefinition = {\n kind: \"markdown\",\n summary: \"Formatted long-form text. Use only when structure genuinely needs headings/lists — plain replies do not need a card.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"body\"],\n properties: { kind: { const: \"markdown\" }, title: { type: \"string\" }, body: { type: \"string\" } },\n },\n validate(spec) {\n const s = check.object(spec, \"markdown\");\n if (failed(s)) return s;\n return typeof (s as Record<string, unknown>)[\"body\"] === \"string\"\n ? ok\n : { ok: false, error: \"markdown.body must be a string.\" };\n },\n partial(spec) {\n const body = typeof spec[\"body\"] === \"string\" ? spec[\"body\"] : \"\";\n if (!body && typeof spec[\"title\"] !== \"string\") return undefined;\n return { ...spec, kind: \"markdown\", body } as CardSpec;\n },\n};\n\nexport const documentCard: CardKindDefinition = {\n kind: \"document\",\n // Written for the model, and deliberately about SIZE and REUSE rather than\n // about formatting: the distinction the model has to get right is \"this is a\n // thing we will keep working on\" versus \"this is a long answer\".\n summary:\n \"A document the user will keep, read in a previewer and come back to. Use for something worth revising — a draft, a report, a set of notes — not for a long reply. Returns an id later turns use to re-read or edit it.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"docId\", \"title\", \"markdown\", \"revision\"],\n properties: {\n kind: { const: \"document\" },\n docId: { type: \"string\" },\n title: { type: \"string\" },\n markdown: { type: \"string\" },\n revision: { type: \"number\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"document\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"docId\"] !== \"string\" || !o[\"docId\"]) {\n return { ok: false, error: \"document.docId must be a non-empty string.\" };\n }\n if (typeof o[\"title\"] !== \"string\") return { ok: false, error: \"document.title must be a string.\" };\n if (typeof o[\"markdown\"] !== \"string\") return { ok: false, error: \"document.markdown must be a string.\" };\n // A missing revision would let a stale edit through as revision 0, which is\n // exactly the failure the token exists to prevent — so it is required, not\n // defaulted.\n return typeof o[\"revision\"] === \"number\"\n ? ok\n : { ok: false, error: \"document.revision must be a number.\" };\n },\n};\n\nexport const editReviewCard: CardKindDefinition = {\n kind: \"editreview\",\n interactive: true,\n summary:\n \"Propose changes to a document and let the user accept them hunk by hunk. The only way to change a document — nothing is written until this is answered.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"docId\", \"title\", \"revision\", \"hunks\"],\n properties: {\n kind: { const: \"editreview\" },\n docId: { type: \"string\" },\n title: { type: \"string\" },\n revision: { type: \"number\" },\n summary: { type: \"string\" },\n hunks: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"index\", \"block\", \"removed\", \"added\"],\n properties: {\n index: { type: \"number\" },\n block: { type: \"number\" },\n removed: { type: \"array\", items: { type: \"string\" } },\n added: { type: \"array\", items: { type: \"string\" } },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"editreview\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"docId\"] !== \"string\" || !o[\"docId\"]) {\n return { ok: false, error: \"editreview.docId must be a non-empty string.\" };\n }\n if (typeof o[\"revision\"] !== \"number\") {\n return { ok: false, error: \"editreview.revision must be a number.\" };\n }\n const hunks = o[\"hunks\"];\n if (!Array.isArray(hunks) || hunks.length === 0) {\n // An empty review would render as an approval prompt for nothing, and a\n // user who clicks Apply on it has approved a no-op they cannot see.\n return { ok: false, error: \"editreview.hunks must be a non-empty array.\" };\n }\n return ok;\n },\n};\n\nexport const emailCard: CardKindDefinition = {\n kind: \"email\",\n // NOT interactive, despite being editable. \"Interactive\" here means the run\n // suspends until the user answers, and nothing waits on this: the draft is a\n // deliverable the user takes away, not a question the model asked. Marking it\n // interactive would serialise it against real decisions for no reason.\n summary:\n \"A drafted message for the user to send themselves. Use when the outcome of the work is something that has to reach someone.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"to\", \"subject\", \"body\"],\n properties: {\n kind: { const: \"email\" },\n to: { type: \"array\", items: { type: \"string\" } },\n cc: { type: \"array\", items: { type: \"string\" } },\n bcc: { type: \"array\", items: { type: \"string\" } },\n subject: { type: \"string\" },\n body: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"email\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (!Array.isArray(o[\"to\"])) return { ok: false, error: \"email.to must be an array.\" };\n if (typeof o[\"subject\"] !== \"string\") return { ok: false, error: \"email.subject must be a string.\" };\n return typeof o[\"body\"] === \"string\" ? ok : { ok: false, error: \"email.body must be a string.\" };\n },\n};\n\nexport const codeCard: CardKindDefinition = {\n kind: \"code\",\n summary: \"A code block with language and optional filename.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"code\"],\n properties: {\n kind: { const: \"code\" },\n title: { type: \"string\" },\n language: { type: \"string\" },\n filename: { type: \"string\" },\n code: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"code\");\n if (failed(s)) return s;\n return typeof (s as Record<string, unknown>)[\"code\"] === \"string\" ? ok : { ok: false, error: \"code.code must be a string.\" };\n },\n};\n\nexport const diffCard: CardKindDefinition = {\n kind: \"diff\",\n summary: \"Before/after comparison of two texts.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"before\", \"after\"],\n properties: {\n kind: { const: \"diff\" },\n title: { type: \"string\" },\n language: { type: \"string\" },\n before: { type: \"string\" },\n after: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"diff\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n return typeof o[\"before\"] === \"string\" && typeof o[\"after\"] === \"string\"\n ? ok\n : { ok: false, error: \"diff needs string `before` and `after`.\" };\n },\n};\n\nexport const comparisonCard: CardKindDefinition = {\n kind: \"comparison\",\n summary:\n \"A matrix of options against criteria. Reach for this whenever the user is CHOOSING between things — vendors, clauses, plans, candidates, approaches. Boolean values render as ✓/✗.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"options\", \"criteria\"],\n properties: {\n kind: { const: \"comparison\" },\n title: { type: \"string\" },\n options: {\n type: \"array\",\n description: \"The things being compared. These become columns.\",\n items: {\n type: \"object\",\n required: [\"id\", \"label\"],\n properties: {\n id: { type: \"string\" },\n label: { type: \"string\" },\n note: { type: \"string\" },\n highlight: { type: \"boolean\", description: \"Mark a recommended option.\" },\n },\n },\n },\n criteria: {\n type: \"array\",\n description: \"The dimensions compared on. These become rows.\",\n items: {\n type: \"object\",\n required: [\"label\", \"values\"],\n properties: {\n label: { type: \"string\" },\n detail: { type: \"string\" },\n weight: { type: \"string\", enum: [\"low\", \"normal\", \"high\"] },\n values: {\n type: \"object\",\n description: \"Keyed by option id. true/false render as ✓/✗; null renders as —.\",\n additionalProperties: true,\n },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"comparison\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n const options = check.arrayField(o, \"options\", \"comparison\");\n if (failed(options)) return options;\n const criteria = check.arrayField(o, \"criteria\", \"comparison\");\n if (failed(criteria)) return criteria;\n\n const ids = new Set<string>();\n for (const opt of options as unknown[]) {\n if (!isObj(opt) || typeof opt[\"id\"] !== \"string\" || typeof opt[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each comparison option needs a string `id` and `label`.\" };\n }\n if (ids.has(opt[\"id\"])) return { ok: false, error: `Duplicate comparison option id \"${opt[\"id\"]}\".` };\n ids.add(opt[\"id\"]);\n }\n for (const c of criteria as unknown[]) {\n if (!isObj(c) || typeof c[\"label\"] !== \"string\" || !isObj(c[\"values\"])) {\n return { ok: false, error: \"Each criterion needs a `label` and a `values` object keyed by option id.\", expected: '{ label, values: { optionId: … } }' };\n }\n }\n return ok;\n },\n};\n\nconst CHECK_STATUSES = new Set([\"done\", \"todo\", \"blocked\", \"na\"]);\n\nexport const checklistCard: CardKindDefinition = {\n kind: \"checklist\",\n summary:\n \"Items with a state. Compliance reviews, launch readiness, document requirements, audit findings, QA passes. Use `group` to section a long list.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"checklist\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"status\"],\n properties: {\n label: { type: \"string\" },\n status: { type: \"string\", enum: [\"done\", \"todo\", \"blocked\", \"na\"] },\n detail: { type: \"string\" },\n group: { type: \"string\", description: \"Heading to group consecutive items under.\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"checklist\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"checklist\");\n if (failed(items)) return items;\n for (const i of items as unknown[]) {\n if (!isObj(i) || typeof i[\"label\"] !== \"string\" || !CHECK_STATUSES.has(String(i[\"status\"]))) {\n return { ok: false, error: \"Each checklist item needs a `label` and a status of done|todo|blocked|na.\" };\n }\n }\n return ok;\n },\n partial(spec) {\n // An item waits for its status: showing \"todo\" for one that is about to\n // say \"blocked\" would be a claim the model never made.\n const items = arrived(spec, \"items\", (i) => typeof i[\"label\"] === \"string\" && CHECK_STATUSES.has(String(i[\"status\"])));\n return items.length ? ({ ...spec, kind: \"checklist\", items } as CardSpec) : undefined;\n },\n};\n\nexport const calloutCard: CardKindDefinition = {\n kind: \"callout\",\n summary:\n \"One short highlighted note. Disclaimers, caveats, prerequisites, limits on what you checked. Use `danger` for anything the reader would regret missing.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"tone\", \"body\"],\n properties: {\n kind: { const: \"callout\" },\n tone: { type: \"string\", enum: [\"info\", \"warning\", \"danger\", \"success\", \"note\"] },\n title: { type: \"string\" },\n body: { type: \"string\" },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"callout\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"body\"] !== \"string\") return { ok: false, error: \"callout.body must be a string.\" };\n if (![\"info\", \"warning\", \"danger\", \"success\", \"note\"].includes(String(o[\"tone\"]))) {\n return { ok: false, error: \"callout.tone must be info|warning|danger|success|note.\" };\n }\n return ok;\n },\n};\n\nexport const citationsCard: CardKindDefinition = {\n kind: \"citations\",\n summary:\n \"The sources behind what you just said. Use whenever a claim rests on specific documents — case law, statutes, papers, filings, articles, internal docs. Quote the passage relied on in `snippet`.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"items\"],\n properties: {\n kind: { const: \"citations\" },\n title: { type: \"string\" },\n items: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"title\"],\n properties: {\n title: { type: \"string\" },\n source: { type: \"string\", description: \"Publication, court, statute, dataset, site.\" },\n url: { type: \"string\" },\n date: { type: [\"string\", \"number\"] },\n snippet: { type: \"string\", description: \"The specific passage relied on.\" },\n locator: { type: \"string\", description: \"Page, section, paragraph, or clause.\" },\n relevance: { type: \"string\", enum: [\"high\", \"medium\", \"low\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"citations\");\n if (failed(s)) return s;\n const items = check.arrayField(s as Record<string, unknown>, \"items\", \"citations\");\n if (failed(items)) return items;\n for (const i of items as unknown[]) {\n if (!isObj(i) || typeof i[\"title\"] !== \"string\") {\n return { ok: false, error: \"Each citation needs a `title`.\" };\n }\n }\n return ok;\n },\n};\n\nexport const funnelCard: CardKindDefinition = {\n kind: \"funnel\",\n summary:\n \"Staged drop-off, in order. Conversion funnels, hiring pipelines, application intake, case attrition. Stages must be ordered widest to narrowest.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"stages\"],\n properties: {\n kind: { const: \"funnel\" },\n title: { type: \"string\" },\n format: { type: \"string\", enum: FORMATS },\n stages: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: { label: { type: \"string\" }, value: { type: \"number\" }, note: { type: \"string\" } },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"funnel\");\n if (failed(s)) return s;\n const stages = check.arrayField(s as Record<string, unknown>, \"stages\", \"funnel\", 2);\n if (failed(stages)) return stages;\n for (const st of stages as unknown[]) {\n if (!isObj(st) || typeof st[\"label\"] !== \"string\" || typeof st[\"value\"] !== \"number\") {\n return { ok: false, error: \"Each funnel stage needs a string `label` and a numeric `value`.\" };\n }\n }\n return ok;\n },\n};\n\nexport const gaugeCard: CardKindDefinition = {\n kind: \"gauge\",\n summary:\n \"One value on a scale, with optional named bands. Risk levels, readiness scores, sentiment, confidence, utilisation. Label the bands so the number means something.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"value\"],\n properties: {\n kind: { const: \"gauge\" },\n title: { type: \"string\" },\n value: { type: \"number\" },\n min: { type: \"number\", description: \"Default 0.\" },\n max: { type: \"number\", description: \"Default 100.\" },\n label: { type: \"string\", description: \"What the current value means in words.\" },\n format: { type: \"string\", enum: FORMATS },\n bands: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"from\", \"to\", \"label\"],\n properties: {\n from: { type: \"number\" },\n to: { type: \"number\" },\n label: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"gauge\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"value\"] !== \"number\") return { ok: false, error: \"gauge.value must be a number.\" };\n const min = typeof o[\"min\"] === \"number\" ? o[\"min\"] : 0;\n const max = typeof o[\"max\"] === \"number\" ? o[\"max\"] : 100;\n if (max <= min) return { ok: false, error: \"gauge.max must be greater than gauge.min.\" };\n return ok;\n },\n};\n\nexport const treeCard: CardKindDefinition = {\n kind: \"tree\",\n summary:\n \"Nested structure. Document outlines, org charts, taxonomies, decision trees, dependency chains, file layouts.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"nodes\"],\n properties: {\n kind: { const: \"tree\" },\n title: { type: \"string\" },\n nodes: {\n type: \"array\",\n description: \"Each node is { label, detail?, tone?, children?: [ …same shape… ] }.\",\n items: {\n type: \"object\",\n required: [\"label\"],\n properties: {\n label: { type: \"string\" },\n detail: { type: \"string\" },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n children: { type: \"array\", items: { type: \"object\" } },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"tree\");\n if (failed(s)) return s;\n const nodes = check.arrayField(s as Record<string, unknown>, \"nodes\", \"tree\");\n if (failed(nodes)) return nodes;\n\n // Depth-limited walk: a cyclic or absurdly deep tree would hang the renderer.\n const walk = (list: unknown[], depth: number): CardValidation => {\n if (depth > 8) return { ok: false, error: \"tree nesting is limited to 8 levels.\" };\n for (const n of list) {\n if (!isObj(n) || typeof n[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each tree node needs a string `label`.\" };\n }\n const kids = n[\"children\"];\n if (kids !== undefined) {\n if (!Array.isArray(kids)) return { ok: false, error: \"tree node `children` must be an array.\" };\n const inner = walk(kids, depth + 1);\n if (!inner.ok) return inner;\n }\n }\n return ok;\n };\n return walk(nodes as unknown[], 1);\n },\n};\n\n// ── Interactive ─────────────────────────────────────────────────────────────\n\nexport const choiceCard: CardKindDefinition = {\n kind: \"choice\",\n interactive: true,\n summary:\n \"Ask the user to pick from options. Use instead of guessing when several candidates fit. Each option may carry `meta` facts shown on its row.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"options\"],\n properties: {\n kind: { const: \"choice\" },\n title: { type: \"string\" },\n prompt: { type: \"string\" },\n multiple: { type: \"boolean\" },\n options: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"id\", \"label\"],\n properties: {\n id: { type: \"string\" },\n label: { type: \"string\" },\n description: { type: \"string\" },\n imageUrl: { type: \"string\" },\n disabled: { type: \"boolean\" },\n disabledReason: { type: \"string\" },\n meta: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: { label: { type: \"string\" }, value: { type: [\"string\", \"number\"] }, format: { type: \"string\", enum: FORMATS } },\n },\n },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"choice\");\n if (failed(s)) return s;\n const options = check.arrayField(s as Record<string, unknown>, \"options\", \"choice\");\n if (failed(options)) return options;\n const ids = new Set<string>();\n for (const o of options as unknown[]) {\n if (!isObj(o) || typeof o[\"id\"] !== \"string\" || typeof o[\"label\"] !== \"string\") {\n return { ok: false, error: \"Each choice option needs a string `id` and `label`.\" };\n }\n // Duplicate ids make the selection ambiguous when it comes back.\n if (ids.has(o[\"id\"])) return { ok: false, error: `Duplicate choice option id \"${o[\"id\"]}\".` };\n ids.add(o[\"id\"]);\n }\n return ok;\n },\n};\n\nexport const formCard: CardKindDefinition = {\n kind: \"form\",\n interactive: true,\n summary: \"Collect structured input. Use when you need several values at once rather than a back-and-forth.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"fields\"],\n properties: {\n kind: { const: \"form\" },\n title: { type: \"string\" },\n description: { type: \"string\" },\n submitLabel: { type: \"string\" },\n fields: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"name\", \"label\", \"type\"],\n properties: {\n name: { type: \"string\" },\n label: { type: \"string\" },\n type: { type: \"string\", enum: [\"text\", \"textarea\", \"number\", \"select\", \"boolean\"] },\n placeholder: { type: \"string\" },\n required: { type: \"boolean\" },\n min: { type: \"number\" },\n max: { type: \"number\" },\n step: { type: \"number\" },\n suffix: { type: \"string\" },\n options: {\n type: \"array\",\n items: { type: \"object\", required: [\"value\", \"label\"], properties: { value: { type: \"string\" }, label: { type: \"string\" } } },\n },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"form\");\n if (failed(s)) return s;\n const fields = check.arrayField(s as Record<string, unknown>, \"fields\", \"form\");\n if (failed(fields)) return fields;\n const types = new Set([\"text\", \"textarea\", \"number\", \"select\", \"boolean\"]);\n for (const f of fields as unknown[]) {\n if (!isObj(f) || typeof f[\"name\"] !== \"string\" || !types.has(String(f[\"type\"]))) {\n return { ok: false, error: \"Each field needs a `name` and a type of text|textarea|number|select|boolean.\" };\n }\n if (f[\"type\"] === \"select\" && !Array.isArray(f[\"options\"])) {\n return { ok: false, error: `Select field \"${String(f[\"name\"])}\" needs an \\`options\\` array.` };\n }\n }\n return ok;\n },\n};\n\nexport const confirmCard: CardKindDefinition = {\n kind: \"confirm\",\n interactive: true,\n summary:\n \"Get explicit approval before a consequential action. `description` says what will happen in plain words, `summary` lists exact amounts, targets, and anything irreversible, and `title` is the one question the buttons answer.\",\n estimateTokens: tokensOf,\n schema: {\n type: \"object\",\n required: [\"kind\", \"title\", \"summary\"],\n properties: {\n kind: { const: \"confirm\" },\n title: { type: \"string\" },\n description: { type: \"string\" },\n confirmLabel: { type: \"string\" },\n cancelLabel: { type: \"string\" },\n danger: { type: \"boolean\" },\n summary: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"label\", \"value\"],\n properties: {\n label: { type: \"string\" },\n value: { type: [\"string\", \"number\"] },\n tone: { type: \"string\", enum: [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"] },\n mono: { type: \"boolean\" },\n },\n },\n },\n },\n },\n validate(spec) {\n const s = check.object(spec, \"confirm\");\n if (failed(s)) return s;\n const o = s as Record<string, unknown>;\n if (typeof o[\"title\"] !== \"string\") return { ok: false, error: \"confirm.title is required.\" };\n // A card whose sentence already says everything needs no detail rows; one with no sentence needs at least one.\n const hasDescription = typeof o[\"description\"] === \"string\" && o[\"description\"].trim() !== \"\";\n const summary = check.arrayField(o, \"summary\", \"confirm\", hasDescription ? 0 : 1);\n if (failed(summary)) return summary;\n return ok;\n },\n};\n\nexport const BUILTIN_CARDS: CardKindDefinition[] = [\n // structured data\n tableCard,\n statsCard,\n comparisonCard,\n keyValueCard,\n treeCard,\n // quantitative shape\n chartCard,\n funnelCard,\n gaugeCard,\n // sequence and state\n timelineCard,\n progressCard,\n checklistCard,\n // prose and evidence\n markdownCard,\n documentCard,\n calloutCard,\n citationsCard,\n codeCard,\n diffCard,\n mediaCard,\n // interactive — these ask the user and pause the run\n choiceCard,\n formCard,\n confirmCard,\n editReviewCard,\n emailCard,\n];\n","// Surfaces: an interface the agent assembles, instead of one card it picks.\n//\n// A card answers \"which presentation fits this result\". A surface answers \"what\n// does the person need in order to work with this\": a filter next to the chart\n// it filters, a total that follows both, a button that asks the agent to look\n// again. Cards stay what they were and become blocks inside it.\n//\n// The format has four properties, each there for a reason:\n//\n// 1. FLAT. Components are a list that reference each other by id, so a surface\n// can stream one complete entry at a time and be patched without resending\n// the tree. (The same shape A2UI and json-render arrived at.)\n//\n// 2. DATA, NOT CODE. Everything the model writes is JSON from a closed\n// vocabulary. There is no expression language, no script, no HTML and no\n// CSS. `$query` filters and groups rows declaratively, and that is as far as\n// computation goes.\n//\n// 3. LOCAL BY DEFAULT. Each surface owns a data model. Controls write to it and\n// neighbours read from it, so narrowing a filter costs no model call.\n//\n// 4. CLOSED ACTIONS. A button can change local state, call a tool the current\n// presets already allow, or send the agent an event. Nothing else exists to\n// be asked for.\n\nimport type { CardAction } from \"../cards/types.js\";\n\nexport const SURFACE_CARD_KIND = \"surface\" as const;\nexport const SURFACE_FORMAT_VERSION = 1 as const;\n\n/** Hard ceilings. A model that exceeds one receives a correction, never a frozen tab. */\nexport const SURFACE_LIMITS = {\n components: 200,\n depth: 16,\n dataChars: 64_000,\n specChars: 200_000,\n surfaces: 24,\n listItems: 200,\n queryRows: 2_000,\n actionUpdates: 8,\n tabs: 12,\n} as const;\n\n/** Read a value from the data model by JSON Pointer: `{ \"$path\": \"/filters/region\" }`. */\nexport type SurfacePathBinding = { $path: string };\n/** Inside a `List` template, read a field of the current row. `\"\"` is the row itself. */\nexport type SurfaceItemBinding = { $item: string };\n/** Interpolate values into a string: `{ \"$template\": \"Spend in {/region}\" }`, `{.name}` for a row field. */\nexport type SurfaceTemplateBinding = { $template: string };\n/** Filter, group and aggregate an array in the data model. */\nexport type SurfaceQueryBinding = { $query: SurfaceQuery };\n\nexport type SurfaceBinding =\n | SurfacePathBinding\n | SurfaceItemBinding\n | SurfaceTemplateBinding\n | SurfaceQueryBinding;\n\nexport type SurfaceWhereOp = \"eq\" | \"ne\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\" | \"contains\";\n\nexport type SurfaceWhere = {\n field: string;\n op?: SurfaceWhereOp;\n value: unknown;\n /** Skip this clause when the value equals this, so an \"All\" option needs no special case. */\n ignore?: string | number | boolean;\n};\n\nexport type SurfaceAggregateOp = \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n\nexport type SurfaceQuery = {\n /** JSON Pointer to an array of rows. */\n from: string;\n where?: SurfaceWhere[];\n groupBy?: string;\n aggregate?: { op: SurfaceAggregateOp; field?: string };\n /** A row field; after `groupBy`, `key` or `value`. */\n sortBy?: string;\n sortDir?: \"asc\" | \"desc\";\n limit?: number;\n /** Return one field of each row instead of the row. */\n select?: string;\n /** Grouped results: `[key, value]` pairs (default, chart-ready) or `{ key, value }` rows. */\n shape?: \"points\" | \"rows\";\n};\n\nexport type SurfaceConditionOp = \"truthy\" | \"falsy\" | \"eq\" | \"ne\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\";\n\n/** A declarative test over the data model, for `visibleWhen` and `disabledWhen`. */\nexport type SurfaceCondition = {\n path: string;\n op?: SurfaceConditionOp;\n value?: unknown;\n};\n\n/** The whole action vocabulary. Adding a member here is a security decision. */\nexport type SurfaceAction =\n | { type: \"set\"; updates: { path: string; value: unknown }[] }\n | { type: \"tool\"; tool: string; args?: Record<string, unknown>; resultPath?: string }\n | { type: \"event\"; name: string; context?: Record<string, unknown> };\n\nexport type SurfaceComponent = {\n id: string;\n component: string;\n visibleWhen?: SurfaceCondition;\n [prop: string]: unknown;\n};\n\nexport type SurfaceIssueCode =\n | \"invalid-shape\"\n | \"duplicate-id\"\n | \"unknown-component\"\n | \"invalid-prop\"\n | \"invalid-binding\"\n | \"invalid-action\"\n | \"tool-not-allowed\"\n | \"unsafe-content\"\n | \"invalid-card\"\n | \"invalid-data\"\n | \"missing-root\"\n | \"missing-child\"\n | \"cycle\"\n | \"too-deep\"\n | \"limit-exceeded\"\n | \"not-found\"\n | \"expired\"\n | \"stale-revision\";\n\n/** One thing wrong, written for the model that has to fix it. */\nexport type SurfaceIssue = {\n code: SurfaceIssueCode;\n message: string;\n /** What to send instead. */\n fix: string;\n componentId?: string;\n path?: string;\n};\n\n/**\n * The current state of a surface. Travels as a card spec, which is how it uses\n * the thread, history-shedding and renderer seams cards already have.\n */\nexport type SurfaceSpec = {\n kind: typeof SURFACE_CARD_KIND;\n version: typeof SURFACE_FORMAT_VERSION;\n surfaceId: string;\n title?: string;\n root: string;\n components: SurfaceComponent[];\n data: Record<string, unknown>;\n /** Bumped by every agent update and every local edit. */\n revision: number;\n /** The call that created it: where it lives in the transcript. */\n originCallId?: string;\n /** Parts that could not be accepted. The person sees a fallback in their place. */\n issues?: SurfaceIssue[];\n /** Removed by the agent. */\n deleted?: boolean;\n /** The payload was shed from saved history. */\n expired?: boolean;\n /**\n * Only on a streaming preview: the part the model is still writing. Every part\n * listed before it is complete. A renderer holds its place until it lands.\n */\n pending?: SurfacePendingPart;\n};\n\n/** The part of a streaming surface that is still arriving, as far as it has arrived. */\nexport type SurfacePendingPart = { id: string; component?: string; kind?: string };\n\n/** Patches for an existing surface, applied in order and validated before rendering. */\nexport type SurfaceOperation =\n | { op: \"upsertComponents\"; components: unknown[] }\n | { op: \"removeComponents\"; ids: string[] }\n | { op: \"setRoot\"; root: string }\n | { op: \"setTitle\"; title: string }\n | { op: \"setData\"; path: string; value: unknown }\n | { op: \"removeData\"; path: string };\n\nexport type SurfaceActivityState = \"queued\" | \"running\" | \"done\" | \"failed\" | \"refused\" | \"cancelled\";\n\n/** What became of the last thing the person pressed. A press with no visible result reads as broken. */\nexport type SurfaceActivity = {\n componentId: string;\n state: SurfaceActivityState;\n message?: string;\n at: number;\n};\n\n/** Recorded on the user message an action produces, so the transcript can show it as an action. */\nexport type SurfaceEventRecord = {\n surfaceId: string;\n componentId: string;\n title?: string;\n label?: string;\n type: \"event\" | \"tool\";\n name: string;\n context?: Record<string, unknown>;\n};\n\nexport const SURFACE_EVENT_METADATA_KEY = \"surfaceEvent\" as const;\n\n/** How an interactive card answered inside a surface. Stored at the card's `bind` path. */\nexport type SurfaceCardAnswer = Pick<CardAction, \"type\" | \"value\" | \"at\">;\n","// JSON Pointer (RFC 6901) over a surface's data model.\n//\n// Paths come from a model, so this is also a security boundary. Walking\n// `__proto__` or `constructor` would let a spec write to Object.prototype for\n// the whole page; such a pointer does not parse. Writes are structural: the\n// previous state is never mutated, which is what lets a renderer compare by\n// identity.\n\nimport { SURFACE_LIMITS } from \"./types.js\";\n\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\nexport const isForbiddenKey = (key: string): boolean => FORBIDDEN_SEGMENTS.has(key);\n\n/** Segments of a pointer, or `undefined` when it is malformed or unsafe. `\"\"` and `\"/\"` are the root. */\nexport function parsePointer(pointer: unknown): string[] | undefined {\n if (typeof pointer !== \"string\") return undefined;\n if (pointer === \"\" || pointer === \"/\") return [];\n if (!pointer.startsWith(\"/\")) return undefined;\n const segments = pointer\n .slice(1)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n if (segments.length > SURFACE_LIMITS.depth) return undefined;\n if (segments.some((s) => s === \"\" || FORBIDDEN_SEGMENTS.has(s))) return undefined;\n return segments;\n}\n\nconst isContainer = (v: unknown): v is Record<string, unknown> | unknown[] => typeof v === \"object\" && v !== null;\nconst isIndex = (s: string) => /^(0|[1-9]\\d*)$/.test(s);\n\n/** Own properties only: a binding must never read something off a prototype. */\nfunction child(value: unknown, key: string): unknown {\n if (Array.isArray(value)) return isIndex(key) ? value[Number(key)] : undefined;\n if (!isContainer(value)) return undefined;\n return Object.prototype.hasOwnProperty.call(value, key) ? (value as Record<string, unknown>)[key] : undefined;\n}\n\nexport function getAt(data: unknown, pointer: string): unknown {\n const segments = parsePointer(pointer);\n if (!segments) return undefined;\n let current = data;\n for (const segment of segments) current = child(current, segment);\n return current;\n}\n\nfunction writeAt(node: unknown, segments: string[], index: number, value: unknown): unknown {\n if (index === segments.length) return value;\n const key = segments[index]!;\n if (Array.isArray(node)) {\n const at = key === \"-\" ? node.length : isIndex(key) ? Number(key) : -1;\n if (at < 0 || at > node.length) throw new RangeError(key);\n const next = [...node];\n next[at] = writeAt(node[at], segments, index + 1, value);\n return next;\n }\n const base = isContainer(node) ? (node as Record<string, unknown>) : {};\n return { ...base, [key]: writeAt(child(base, key), segments, index + 1, value) };\n}\n\n/** A new data model with `value` at `pointer`, or `undefined` when the pointer cannot be written. */\nexport function setAt(data: Record<string, unknown>, pointer: string, value: unknown): Record<string, unknown> | undefined {\n const segments = parsePointer(pointer);\n if (!segments) return undefined;\n if (!segments.length) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n }\n try {\n return writeAt(data, segments, 0, value) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** A new data model without the value at `pointer`. Removing what is not there changes nothing. */\nexport function removeAt(data: Record<string, unknown>, pointer: string): Record<string, unknown> | undefined {\n const segments = parsePointer(pointer);\n if (!segments?.length) return undefined;\n const parentPath = segments.slice(0, -1);\n const key = segments[segments.length - 1]!;\n let parent: unknown = data;\n for (const segment of parentPath) parent = child(parent, segment);\n if (!isContainer(parent)) return data;\n const without: unknown = Array.isArray(parent)\n ? parent.filter((_, i) => String(i) !== key)\n : Object.fromEntries(Object.entries(parent).filter(([k]) => k !== key));\n if (!parentPath.length) return without as Record<string, unknown>;\n return writeAt(data, parentPath, 0, without) as Record<string, unknown>;\n}\n","// What a spec may never carry, whichever component it is attached to.\n//\n// Rendering is already safe by construction (props are enumerated, text is\n// escaped, nothing reaches innerHTML). This is the second wall, and it exists so\n// the refusal happens where the model can read it: a spec carrying a script URL\n// is corrected at the tool call instead of being quietly neutralised later.\n\nimport { isForbiddenKey } from \"./pointer.js\";\n\nconst DANGEROUS_KEYS = new Set([\"dangerouslysetinnerhtml\", \"innerhtml\", \"outerhtml\", \"srcdoc\"]);\nconst SCRIPT_SCHEMES = /^(javascript|vbscript|livescript|data:text\\/html|data:application\\/xhtml|data:image\\/svg)/;\nconst MARKUP = /<\\s*\\/?\\s*[a-z][a-z0-9-]*(\\s[^<>]*)?\\/?>|<\\s*(script|iframe|object|embed|style|svg|math)\\b/i;\n\n/** Browsers ignore whitespace and control characters inside a scheme, so `java\\tscript:` is one too. */\nconst compact = (s: string) =>\n // eslint-disable-next-line no-control-regex\n s.replace(/[\\u0000-\\u0020\\u007f-\\u009f\\u200b-\\u200f\\u2028\\u2029\\ufeff]/g, \"\").toLowerCase();\n\nexport const isScriptUrl = (s: string): boolean => {\n const c = compact(s.slice(0, 256));\n return SCRIPT_SCHEMES.test(c) && (c.startsWith(\"data:\") || /^[a-z]+:/.test(c));\n};\n\nexport type UnsafeFinding = { path: string; reason: string };\n\n/**\n * First unsafe thing in `value`. `markup` also refuses HTML in strings: right for\n * a primitive's props, wrong for a code card, whose whole job is to show source.\n */\nexport function findUnsafe(value: unknown, opts: { markup?: boolean; path?: string } = {}): UnsafeFinding | undefined {\n const markup = opts.markup === true;\n let visited = 0;\n\n const walk = (node: unknown, path: string, depth: number): UnsafeFinding | undefined => {\n visited += 1;\n if (visited > 50_000 || depth > 32) return { path, reason: \"is nested too deeply to inspect\" };\n if (typeof node === \"string\") {\n if (isScriptUrl(node)) return { path, reason: \"is a URL that runs script\" };\n if (markup && MARKUP.test(node)) return { path, reason: \"contains HTML\" };\n return undefined;\n }\n if (typeof node === \"function\") return { path, reason: \"is executable\" };\n if (typeof node !== \"object\" || node === null) return undefined;\n if (Array.isArray(node)) {\n for (let i = 0; i < node.length; i += 1) {\n const found = walk(node[i], `${path}/${i}`, depth + 1);\n if (found) return found;\n }\n return undefined;\n }\n for (const key of Object.keys(node)) {\n if (isForbiddenKey(key) || DANGEROUS_KEYS.has(key.toLowerCase())) {\n return { path: `${path}/${key}`, reason: \"is not an allowed key\" };\n }\n const found = walk((node as Record<string, unknown>)[key], `${path}/${key}`, depth + 1);\n if (found) return found;\n }\n return undefined;\n };\n\n return walk(value, opts.path ?? \"\", 0);\n}\n\n/** A URL a surface may load or link to: http(s), plus inline raster images for `image`. */\nexport function safeSurfaceUrl(url: unknown, use: \"link\" | \"image\"): string | undefined {\n if (typeof url !== \"string\") return undefined;\n const trimmed = url.trim();\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(trimmed)) return undefined;\n if (/^https?:\\/\\/[^\\s]+$/i.test(trimmed)) return trimmed;\n if (use === \"image\" && /^data:image\\/(png|jpeg|jpg|gif|webp);base64,[a-z0-9+/=]+$/i.test(trimmed)) return trimmed;\n return undefined;\n}\n","// A small JSON Schema checker, for the subset the surface catalogue uses.\n//\n// Core carries no validation dependency (see providers/types.ts), and what a\n// surface needs from one is modest: walk a schema, and say what was wrong in a\n// sentence a model can act on.\n\nimport type { JSONSchema } from \"../providers/types.js\";\n\nexport type SchemaProblem = { path: string; message: string; expected?: string };\n\nexport type SchemaCheckOptions = {\n /** A value this returns true for is checked elsewhere, unless its schema is `x-static`. */\n isDynamic?: (value: unknown) => boolean;\n maxProblems?: number;\n};\n\nconst typeOf = (v: unknown): string => {\n if (v === null) return \"null\";\n if (Array.isArray(v)) return \"array\";\n return typeof v;\n};\n\nconst matchesType = (value: unknown, type: string): boolean => {\n if (type === \"integer\") return typeof value === \"number\" && Number.isInteger(value);\n if (type === \"number\") return typeof value === \"number\" && Number.isFinite(value);\n return typeOf(value) === type;\n};\n\nconst quote = (values: readonly unknown[]) => values.map((v) => JSON.stringify(v)).join(\", \");\n\nexport function checkSchema(schema: JSONSchema, value: unknown, path = \"\", opts: SchemaCheckOptions = {}): SchemaProblem[] {\n const out: SchemaProblem[] = [];\n const max = opts.maxProblems ?? 6;\n\n const walk = (s: JSONSchema, v: unknown, at: string): void => {\n if (out.length >= max) return;\n if (opts.isDynamic?.(v) && s[\"x-static\"] !== true) return;\n const label = at || \"value\";\n\n const anyOf = s[\"anyOf\"];\n if (Array.isArray(anyOf)) {\n const passes = (anyOf as JSONSchema[]).some((option) => checkSchema(option, v, at, opts).length === 0);\n if (!passes) out.push({ path: at, message: `${label} does not match any allowed form.`, expected: s.description });\n return;\n }\n if (s.const !== undefined && v !== s.const) {\n out.push({ path: at, message: `${label} must be ${JSON.stringify(s.const)}.` });\n return;\n }\n if (s.enum && !s.enum.includes(v)) {\n out.push({ path: at, message: `${label} is ${JSON.stringify(v)}.`, expected: `One of: ${quote(s.enum)}` });\n return;\n }\n if (s.type !== undefined) {\n const types = Array.isArray(s.type) ? s.type : [s.type];\n if (!types.some((t) => matchesType(v, t))) {\n out.push({ path: at, message: `${label} must be ${types.join(\" or \")}, got ${typeOf(v)}.` });\n return;\n }\n }\n if (typeof v === \"number\") {\n if (s.minimum != null && v < s.minimum) out.push({ path: at, message: `${label} must be at least ${s.minimum}.` });\n if (s.maximum != null && v > s.maximum) out.push({ path: at, message: `${label} must be at most ${s.maximum}.` });\n }\n if (typeof v === \"string\") {\n const min = s[\"minLength\"];\n const maxLength = s[\"maxLength\"];\n if (typeof min === \"number\" && v.length < min) out.push({ path: at, message: `${label} must not be empty.` });\n if (typeof maxLength === \"number\" && v.length > maxLength) {\n out.push({ path: at, message: `${label} is longer than ${maxLength} characters.` });\n }\n }\n if (Array.isArray(v)) {\n const minItems = s[\"minItems\"];\n const maxItems = s[\"maxItems\"];\n if (typeof minItems === \"number\" && v.length < minItems) out.push({ path: at, message: `${label} needs at least ${minItems} item(s).` });\n if (typeof maxItems === \"number\" && v.length > maxItems) out.push({ path: at, message: `${label} allows at most ${maxItems} item(s).` });\n if (s.items && !Array.isArray(s.items)) {\n const items = s.items;\n v.forEach((item, i) => walk(items, item, `${at}/${i}`));\n }\n }\n if (typeOf(v) === \"object\") {\n const record = v as Record<string, unknown>;\n for (const key of s.required ?? []) {\n if (record[key] === undefined) out.push({ path: `${at}/${key}`, message: `${at ? `${at}/` : \"\"}${key} is required.` });\n }\n const properties = s.properties ?? {};\n for (const [key, item] of Object.entries(record)) {\n const propSchema = properties[key];\n if (propSchema) walk(propSchema, item, `${at}/${key}`);\n else if (s.additionalProperties === false) {\n out.push({\n path: `${at}/${key}`,\n message: `Unknown prop \"${key}\".`,\n expected: `Allowed: ${Object.keys(properties).join(\", \") || \"(none)\"}`,\n });\n } else if (typeof s.additionalProperties === \"object\") walk(s.additionalProperties, item, `${at}/${key}`);\n }\n }\n };\n\n walk(schema, value, path);\n return out.slice(0, max);\n}\n","// Bindings: how a prop reads the data model.\n//\n// Every form here is data and every evaluation is bounded. Resolution walks the\n// SPEC once and never the values it reads, so a row that happens to contain\n// `{ \"$path\": \"/secret\" }` stays a row. Data cannot promote itself into a binding.\n\nimport { getAt, parsePointer } from \"./pointer.js\";\nimport {\n SURFACE_LIMITS,\n type SurfaceAction,\n type SurfaceBinding,\n type SurfaceCondition,\n type SurfaceQuery,\n type SurfaceWhere,\n} from \"./types.js\";\n\nexport type BindingScope = {\n data: unknown;\n /** The current row, inside a `List` template. */\n item?: unknown;\n index?: number;\n};\n\nconst BINDING_KEYS = [\"$path\", \"$item\", \"$template\", \"$query\"] as const;\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/** Exactly one `$` key and nothing else: anything looser would swallow ordinary objects. */\nexport function isSurfaceBinding(value: unknown): value is SurfaceBinding {\n if (!isPlainObject(value)) return false;\n const keys = Object.keys(value);\n return keys.length === 1 && (BINDING_KEYS as readonly string[]).includes(keys[0]!);\n}\n\n/** True when any binding of the given form appears anywhere inside `value`. */\nexport function usesBinding(value: unknown, key: (typeof BINDING_KEYS)[number]): boolean {\n if (Array.isArray(value)) return value.some((v) => usesBinding(v, key));\n if (!isPlainObject(value)) return false;\n if (isSurfaceBinding(value)) {\n if (key in value) return true;\n if (\"$query\" in value) return usesBinding(value.$query.where?.map((w) => w?.value), key);\n return key === \"$item\" && \"$template\" in value && /\\{\\.[^{}]*\\}/.test(String(value.$template));\n }\n return Object.values(value).some((v) => usesBinding(v, key));\n}\n\nconst TEMPLATE_TOKEN = /\\{(\\/[^{}]*|\\.[^{}]*)\\}/g;\n\nconst itemField = (item: unknown, field: string): unknown => {\n if (!field) return item;\n return getAt(item, field.startsWith(\"/\") ? field : `/${field.replace(/\\./g, \"/\")}`);\n};\n\nconst printable = (v: unknown): string =>\n typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\" ? String(v) : \"\";\n\nexport function formatTemplate(template: string, scope: BindingScope): string {\n return template.replace(TEMPLATE_TOKEN, (_, token: string) =>\n printable(token.startsWith(\".\") ? itemField(scope.item, token.slice(1)) : getAt(scope.data, token)),\n );\n}\n\nconst asNumber = (v: unknown): number | undefined => {\n if (typeof v === \"number\") return Number.isFinite(v) ? v : undefined;\n if (typeof v === \"string\" && v.trim() !== \"\") {\n const n = Number(v);\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n};\n\nconst sameValue = (a: unknown, b: unknown) => a === b || (a != null && b != null && String(a) === String(b));\n\nfunction compare(left: unknown, op: string, right: unknown): boolean {\n switch (op) {\n case \"eq\":\n return sameValue(left, right);\n case \"ne\":\n return !sameValue(left, right);\n case \"in\":\n return Array.isArray(right) && right.some((r) => sameValue(left, r));\n case \"contains\":\n return String(left ?? \"\").toLowerCase().includes(String(right ?? \"\").toLowerCase());\n default: {\n const a = asNumber(left);\n const b = asNumber(right);\n if (a === undefined || b === undefined) return false;\n return op === \"gt\" ? a > b : op === \"gte\" ? a >= b : op === \"lt\" ? a < b : op === \"lte\" ? a <= b : false;\n }\n }\n}\n\nfunction rowField(row: unknown, field: string): unknown {\n return isPlainObject(row) && Object.prototype.hasOwnProperty.call(row, field) ? row[field] : undefined;\n}\n\nconst clauseApplies = (clause: SurfaceWhere, value: unknown) => {\n if (value === undefined || value === null || value === \"\") return false;\n if (Array.isArray(value) && value.length === 0) return false;\n return clause.ignore === undefined || !sameValue(value, clause.ignore);\n};\n\nconst tidy = (n: number) => Math.round(n * 1e6) / 1e6;\n\nfunction aggregate(rows: readonly unknown[], spec: NonNullable<SurfaceQuery[\"aggregate\"]>): number {\n if (spec.op === \"count\") return rows.length;\n const values = rows.map((r) => asNumber(rowField(r, spec.field ?? \"\"))).filter((n): n is number => n !== undefined);\n if (!values.length) return 0;\n switch (spec.op) {\n case \"sum\":\n return tidy(values.reduce((a, b) => a + b, 0));\n case \"avg\":\n return tidy(values.reduce((a, b) => a + b, 0) / values.length);\n case \"min\":\n return values.reduce((a, b) => Math.min(a, b));\n case \"max\":\n return values.reduce((a, b) => Math.max(a, b));\n }\n}\n\nconst order = (a: unknown, b: unknown): number => {\n const x = asNumber(a);\n const y = asNumber(b);\n if (x !== undefined && y !== undefined) return x - y;\n return String(a ?? \"\").localeCompare(String(b ?? \"\"));\n};\n\n/** Run a declarative query. Bad input yields an empty result, never a throw in a render. */\nexport function runSurfaceQuery(query: SurfaceQuery, scope: BindingScope): unknown {\n const source = getAt(scope.data, query.from);\n let rows: unknown[] = Array.isArray(source) ? source.slice(0, SURFACE_LIMITS.queryRows) : [];\n\n for (const clause of query.where ?? []) {\n const value = resolveSurfaceValue(clause.value, scope);\n if (!clauseApplies(clause, value)) continue;\n rows = rows.filter((row) => compare(rowField(row, clause.field), clause.op ?? \"eq\", value));\n }\n\n const direction = query.sortDir === \"desc\" ? -1 : 1;\n const limit = (list: unknown[]) => (typeof query.limit === \"number\" && query.limit >= 0 ? list.slice(0, query.limit) : list);\n\n if (query.groupBy) {\n const groups = new Map<string, unknown[]>();\n for (const row of rows) {\n const key = printable(rowField(row, query.groupBy));\n const bucket = groups.get(key);\n if (bucket) bucket.push(row);\n else groups.set(key, [row]);\n }\n let pairs = [...groups].map(([key, bucket]) => ({ key, value: aggregate(bucket, query.aggregate ?? { op: \"count\" }) }));\n if (query.sortBy === \"key\" || query.sortBy === \"value\") {\n const by = query.sortBy;\n pairs = [...pairs].sort((a, b) => order(a[by], b[by]) * direction);\n }\n const limited = limit(pairs) as typeof pairs;\n return query.shape === \"rows\" ? limited : limited.map((p) => [p.key, p.value]);\n }\n\n if (query.aggregate) return aggregate(rows, query.aggregate);\n\n if (query.sortBy) {\n const by = query.sortBy;\n rows = [...rows].sort((a, b) => order(rowField(a, by), rowField(b, by)) * direction);\n }\n rows = limit(rows);\n return query.select ? rows.map((r) => rowField(r, query.select!)) : rows;\n}\n\n/** Replace every binding inside a spec value with what it currently reads. */\nexport function resolveSurfaceValue(value: unknown, scope: BindingScope, depth = 0): unknown {\n if (depth > SURFACE_LIMITS.depth * 2) return undefined;\n if (Array.isArray(value)) return value.map((v) => resolveSurfaceValue(v, scope, depth + 1));\n if (!isPlainObject(value)) return value;\n if (isSurfaceBinding(value)) {\n if (\"$path\" in value) return getAt(scope.data, value.$path);\n if (\"$item\" in value) return itemField(scope.item, value.$item);\n if (\"$template\" in value) return formatTemplate(value.$template, scope);\n return runSurfaceQuery(value.$query, scope);\n }\n const out: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) out[key] = resolveSurfaceValue(item, scope, depth + 1);\n return out;\n}\n\nexport function evaluateSurfaceCondition(condition: SurfaceCondition | undefined, scope: BindingScope): boolean {\n if (!condition) return true;\n const current = getAt(scope.data, condition.path);\n const op = condition.op ?? (condition.value === undefined ? \"truthy\" : \"eq\");\n if (op === \"truthy\") return Boolean(current) && !(Array.isArray(current) && current.length === 0);\n if (op === \"falsy\") return !current || (Array.isArray(current) && current.length === 0);\n return compare(current, op, condition.value);\n}\n\n/** An action with its bindings read at the moment the person pressed. */\nexport function resolveSurfaceAction(action: SurfaceAction, scope: BindingScope): SurfaceAction {\n switch (action.type) {\n case \"set\":\n return { type: \"set\", updates: action.updates.map((u) => ({ path: u.path, value: resolveSurfaceValue(u.value, scope) })) };\n case \"tool\":\n return { ...action, args: resolveSurfaceValue(action.args ?? {}, scope) as Record<string, unknown> };\n case \"event\":\n return { ...action, context: resolveSurfaceValue(action.context ?? {}, scope) as Record<string, unknown> };\n }\n}\n\n/** Problems with one binding, as sentences. Empty means it is usable. */\nexport function bindingProblems(binding: SurfaceBinding): string[] {\n if (\"$path\" in binding) {\n return parsePointer(binding.$path) ? [] : [`$path ${JSON.stringify(binding.$path)} is not a JSON Pointer such as \"/filters/region\".`];\n }\n if (\"$item\" in binding) {\n return typeof binding.$item === \"string\" ? [] : [\"$item must be a field name of the current row.\"];\n }\n if (\"$template\" in binding) return typeof binding.$template === \"string\" ? [] : [\"$template must be a string.\"];\n\n const query = binding.$query as SurfaceQuery | undefined;\n if (!isPlainObject(query)) return [\"$query must be an object with a `from` pointer.\"];\n const out: string[] = [];\n if (!parsePointer(query.from)) out.push(`$query.from ${JSON.stringify(query.from)} is not a JSON Pointer to an array.`);\n const allowed = new Set([\"from\", \"where\", \"groupBy\", \"aggregate\", \"sortBy\", \"sortDir\", \"limit\", \"select\", \"shape\"]);\n for (const key of Object.keys(query)) if (!allowed.has(key)) out.push(`$query has no \"${key}\". Allowed: ${[...allowed].join(\", \")}.`);\n if (query.where !== undefined && !Array.isArray(query.where)) out.push(\"$query.where must be an array of { field, op, value }.\");\n for (const clause of Array.isArray(query.where) ? query.where : []) {\n if (!isPlainObject(clause) || typeof clause.field !== \"string\") out.push(\"Each $query.where clause needs a string `field`.\");\n else if (clause.op !== undefined && ![\"eq\", \"ne\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\", \"contains\"].includes(clause.op)) {\n out.push(`$query.where op \"${String(clause.op)}\" is not one of eq, ne, gt, gte, lt, lte, in, contains.`);\n }\n }\n if (query.aggregate !== undefined) {\n const ops = [\"count\", \"sum\", \"avg\", \"min\", \"max\"];\n if (!isPlainObject(query.aggregate) || !ops.includes(String(query.aggregate.op))) out.push(`$query.aggregate.op must be one of ${ops.join(\", \")}.`);\n else if (query.aggregate.op !== \"count\" && typeof query.aggregate.field !== \"string\") out.push(`$query.aggregate \"${query.aggregate.op}\" needs a \\`field\\`.`);\n }\n if (query.sortDir !== undefined && query.sortDir !== \"asc\" && query.sortDir !== \"desc\") out.push('$query.sortDir must be \"asc\" or \"desc\".');\n if (query.shape !== undefined && query.shape !== \"points\" && query.shape !== \"rows\") out.push('$query.shape must be \"points\" or \"rows\".');\n return out;\n}\n","// The built-in surface vocabulary: layout, display, input and one action control.\n//\n// Names follow A2UI's basic catalogue where a counterpart exists. Every prop is\n// enumerated and `additionalProperties` is false, which is what makes \"no style,\n// no className, no onClick\" a property of the format rather than a filter on it.\n\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { SurfaceComponentDefinition } from \"./catalogue.js\";\n\nconst TONES = [\"neutral\", \"positive\", \"negative\", \"warning\", \"info\"];\nconst FORMATS = [\"text\", \"number\", \"currency\", \"percent\", \"bytes\", \"duration\", \"datetime\", \"code\"];\nconst GAPS = [\"none\", \"xs\", \"sm\", \"md\", \"lg\"];\n\n/** Structural props are never bindings: the graph must be knowable before any data arrives. */\nconst fixed = (schema: JSONSchema): JSONSchema => ({ ...schema, \"x-static\": true });\nconst childIds: JSONSchema = fixed({ type: \"array\", items: { type: \"string\" }, description: \"Component ids, in display order.\" });\nconst childId = (description: string): JSONSchema => fixed({ type: \"string\", description });\n\n/** A control's value must be a `$path`: it has to know where to write. */\nconst boundValue: JSONSchema = {\n type: \"object\",\n required: [\"$path\"],\n properties: { $path: { type: \"string\" } },\n additionalProperties: false,\n description: 'Two-way binding, e.g. { \"$path\": \"/filters/region\" }.',\n \"x-static\": true,\n};\n\nexport const CONDITION_SCHEMA: JSONSchema = fixed({\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\" },\n op: { type: \"string\", enum: [\"truthy\", \"falsy\", \"eq\", \"ne\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"] },\n value: {},\n },\n additionalProperties: false,\n});\n\nexport const ACTION_SCHEMA: JSONSchema = fixed({\n type: \"object\",\n required: [\"type\"],\n description:\n 'One of { \"type\": \"set\", \"updates\": [{ \"path\", \"value\" }] }, { \"type\": \"tool\", \"tool\", \"args\", \"resultPath\" }, { \"type\": \"event\", \"name\", \"context\" }.',\n});\n\nconst props = (properties: Record<string, JSONSchema>, required: string[] = []): JSONSchema => ({\n type: \"object\",\n properties,\n required,\n additionalProperties: false,\n});\n\nconst text = (description?: string): JSONSchema => ({ type: \"string\", ...(description ? { description } : {}) });\n\nexport const SURFACE_PRIMITIVES: SurfaceComponentDefinition[] = [\n {\n name: \"Stack\",\n category: \"layout\",\n summary: \"Arrange children in a column or a row.\",\n props: props(\n {\n children: childIds,\n direction: { type: \"string\", enum: [\"vertical\", \"horizontal\"] },\n gap: { type: \"string\", enum: GAPS },\n align: { type: \"string\", enum: [\"start\", \"center\", \"end\", \"stretch\"] },\n justify: { type: \"string\", enum: [\"start\", \"center\", \"end\", \"between\"] },\n wrap: { type: \"boolean\" },\n },\n [\"children\"],\n ),\n slots: (p) => (p[\"children\"] as string[]) ?? [],\n },\n {\n name: \"Grid\",\n category: \"layout\",\n summary: \"Equal columns that collapse on narrow containers.\",\n props: props(\n {\n children: childIds,\n columns: { type: \"integer\", minimum: 1, maximum: 4 },\n gap: { type: \"string\", enum: GAPS },\n },\n [\"children\"],\n ),\n slots: (p) => (p[\"children\"] as string[]) ?? [],\n },\n {\n name: \"Section\",\n category: \"layout\",\n summary: \"A titled group of children.\",\n props: props(\n {\n title: text(),\n description: text(),\n tone: { type: \"string\", enum: TONES },\n children: childIds,\n },\n [\"children\"],\n ),\n slots: (p) => (p[\"children\"] as string[]) ?? [],\n },\n {\n name: \"Tabs\",\n category: \"layout\",\n summary: \"Switch between named panels. Keyboard accessible.\",\n props: props(\n {\n label: text(\"Names the tab list for screen readers.\"),\n value: { ...boundValue, description: \"Optional binding for the selected tab id.\" },\n tabs: fixed({\n type: \"array\",\n minItems: 1,\n maxItems: 12,\n items: {\n type: \"object\",\n required: [\"id\", \"label\", \"child\"],\n properties: { id: { type: \"string\" }, label: { type: \"string\" }, child: { type: \"string\" } },\n additionalProperties: false,\n },\n }),\n },\n [\"tabs\"],\n ),\n slots: (p) => ((p[\"tabs\"] as { child: string }[]) ?? []).map((t) => t.child),\n },\n {\n name: \"List\",\n category: \"layout\",\n summary: \"Repeat one template for each row of an array; the template reads rows with $item.\",\n props: props(\n {\n items: { type: \"array\", description: \"A $path or $query that yields an array.\" },\n child: childId(\"The template component rendered once per row.\"),\n emptyText: text(\"Shown when there are no rows.\"),\n gap: { type: \"string\", enum: GAPS },\n },\n [\"items\", \"child\"],\n ),\n slots: (p) => (typeof p[\"child\"] === \"string\" ? [p[\"child\"]] : []),\n templateSlots: (p) => (typeof p[\"child\"] === \"string\" ? [p[\"child\"]] : []),\n },\n { name: \"Divider\", category: \"layout\", summary: \"A horizontal rule between groups.\", props: props({}) },\n {\n name: \"Text\",\n category: \"display\",\n summary: \"Plain text. Never parsed as HTML or Markdown.\",\n props: props(\n {\n text: { type: [\"string\", \"number\"] },\n variant: { type: \"string\", enum: [\"title\", \"heading\", \"body\", \"caption\", \"label\", \"code\"] },\n tone: { type: \"string\", enum: TONES },\n },\n [\"text\"],\n ),\n },\n {\n name: \"Metric\",\n category: \"display\",\n summary: \"One headline number with a label and optional change.\",\n props: props(\n {\n label: text(),\n value: { type: [\"string\", \"number\", \"null\"] },\n format: { type: \"string\", enum: FORMATS },\n delta: { type: \"number\" },\n deltaFormat: { type: \"string\", enum: FORMATS },\n hint: text(),\n tone: { type: \"string\", enum: TONES },\n },\n [\"label\", \"value\"],\n ),\n },\n {\n name: \"Badge\",\n category: \"display\",\n summary: \"A short status label.\",\n props: props({ text: { type: [\"string\", \"number\"] }, tone: { type: \"string\", enum: TONES } }, [\"text\"]),\n },\n {\n name: \"Image\",\n category: \"display\",\n summary: \"An http(s) image with required alt text.\",\n props: props({ src: text(), alt: text(), caption: text() }, [\"src\", \"alt\"]),\n },\n {\n name: \"Link\",\n category: \"display\",\n summary: \"An http(s) link that opens in a new tab.\",\n props: props({ text: text(), href: text() }, [\"text\", \"href\"]),\n },\n {\n name: \"Field\",\n category: \"input\",\n summary: \"Text, number, date or multi-line input bound to the data model.\",\n props: props(\n {\n label: text(),\n value: boundValue,\n type: { type: \"string\", enum: [\"text\", \"number\", \"date\", \"textarea\"] },\n placeholder: text(),\n helper: text(),\n min: { type: \"number\" },\n max: { type: \"number\" },\n step: { type: \"number\" },\n },\n [\"label\", \"value\"],\n ),\n },\n {\n name: \"Select\",\n category: \"input\",\n summary: \"Choose one option; writes its value to the data model.\",\n props: props(\n {\n label: text(),\n value: boundValue,\n options: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"value\", \"label\"],\n properties: { value: { type: [\"string\", \"number\", \"boolean\"] }, label: { type: \"string\" } },\n additionalProperties: false,\n },\n },\n helper: text(),\n },\n [\"label\", \"value\", \"options\"],\n ),\n },\n {\n name: \"Toggle\",\n category: \"input\",\n summary: \"An on/off switch bound to a boolean.\",\n props: props({ label: text(), value: boundValue, helper: text() }, [\"label\", \"value\"]),\n },\n {\n name: \"Slider\",\n category: \"input\",\n summary: \"Pick a number in a range.\",\n props: props(\n {\n label: text(),\n value: boundValue,\n min: { type: \"number\" },\n max: { type: \"number\" },\n step: { type: \"number\" },\n format: { type: \"string\", enum: FORMATS },\n },\n [\"label\", \"value\", \"min\", \"max\"],\n ),\n },\n {\n name: \"Button\",\n category: \"action\",\n summary: \"Runs one action when pressed: set local state, call an allowed tool, or send the agent an event.\",\n props: props(\n {\n label: text(),\n action: ACTION_SCHEMA,\n variant: { type: \"string\", enum: [\"primary\", \"secondary\", \"ghost\", \"danger\"] },\n disabledWhen: CONDITION_SCHEMA,\n },\n [\"label\", \"action\"],\n ),\n },\n];\n","// The catalogue: everything a surface may be built from, in one place.\n//\n// Three sources, one lookup: the built-in primitives, every kind in the card\n// registry (read live, so a plugin installed after startup is available\n// immediately), and components a host registers with its own renderer.\n//\n// The index is one line per component and the schemas are fetched on request.\n// That split is the progressive disclosure: forty schemas in every prompt would\n// cost more than most of the surfaces they describe.\n\nimport type { CardRegistry } from \"../cards/registry.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\nimport { ACTION_SCHEMA, SURFACE_PRIMITIVES } from \"./primitives.js\";\nimport { SURFACE_CARD_KIND } from \"./types.js\";\n\nexport type SurfaceComponentCategory = \"layout\" | \"display\" | \"input\" | \"action\" | \"card\" | \"custom\";\n\nexport type SurfaceComponentDefinition = {\n name: string;\n category: SurfaceComponentCategory;\n /** One line for the index. Keep domain nouns out of it: this steers the model. */\n summary: string;\n /** Schema for the component's props, excluding `id`, `component` and `visibleWhen`. */\n props: JSONSchema;\n /** Ids of the components this one renders. */\n slots?: (props: Record<string, unknown>) => string[];\n /** The subset of `slots` rendered once per row, where `$item` is in scope. */\n templateSlots?: (props: Record<string, unknown>) => string[];\n};\n\n/** The prefix that addresses one card kind in the index, as in `Card:chart`. */\nexport const CARD_ENTRY_PREFIX = \"Card:\";\n\nexport const CARD_COMPONENT: SurfaceComponentDefinition = {\n name: \"Card\",\n category: \"card\",\n summary: \"Embed any card kind. `spec` may contain bindings.\",\n props: {\n type: \"object\",\n required: [\"kind\", \"spec\"],\n additionalProperties: false,\n properties: {\n kind: { type: \"string\", description: \"A registered card kind.\", \"x-static\": true },\n spec: { type: \"object\", description: \"The card body, without `kind`.\", \"x-static\": true },\n bind: { type: \"string\", description: \"Interactive kinds only: JSON Pointer that stores the answer.\", \"x-static\": true },\n action: ACTION_SCHEMA,\n },\n },\n};\n\nexport type SurfaceCatalogueOptions = {\n cards?: CardRegistry;\n /** Host components. Each needs a renderer under the same name in the UI layer. */\n components?: readonly SurfaceComponentDefinition[];\n};\n\nexport class SurfaceCatalogue {\n readonly cards: CardRegistry | undefined;\n private readonly definitions = new Map<string, SurfaceComponentDefinition>();\n\n constructor(options: SurfaceCatalogueOptions = {}) {\n this.cards = options.cards;\n for (const def of SURFACE_PRIMITIVES) this.definitions.set(def.name, def);\n this.definitions.set(CARD_COMPONENT.name, CARD_COMPONENT);\n for (const def of options.components ?? []) this.register(def);\n }\n\n /** Add a host component. A built-in name cannot be replaced: its meaning is part of the format. */\n register(def: SurfaceComponentDefinition): this {\n const existing = this.definitions.get(def.name);\n if (existing && existing.category !== \"custom\") throw new Error(`Surface component \"${def.name}\" is built in and cannot be replaced.`);\n if (def.name.startsWith(CARD_ENTRY_PREFIX)) throw new Error(`Surface component names cannot start with \"${CARD_ENTRY_PREFIX}\".`);\n this.definitions.set(def.name, { ...def, category: \"custom\" });\n return this;\n }\n\n get(name: string): SurfaceComponentDefinition | undefined {\n return this.definitions.get(name);\n }\n\n has(name: string): boolean {\n return this.definitions.has(name);\n }\n\n /** Card kinds usable inside a surface. A surface cannot contain a surface. */\n cardKinds() {\n return (this.cards?.list() ?? []).filter((k) => k.kind !== SURFACE_CARD_KIND);\n }\n\n /** Every addressable entry: components by name, cards as `Card:<kind>`. */\n names(): string[] {\n return [...this.definitions.keys(), ...this.cardKinds().map((k) => `${CARD_ENTRY_PREFIX}${k.kind}`)];\n }\n\n /** One line per entry. Cheap enough to hand over whenever the model asks what exists. */\n index(): string {\n const lines = [...this.definitions.values()].map((d) => `- ${d.name} (${d.category}): ${d.summary}`);\n for (const k of this.cardKinds()) {\n lines.push(`- ${CARD_ENTRY_PREFIX}${k.kind}${k.interactive ? \" (interactive, needs `bind`)\" : \"\"}: ${k.summary}`);\n }\n return lines.join(\"\\n\");\n }\n\n /** The full schema of one entry, or `undefined` for a name that does not exist. */\n schemaOf(name: string): { name: string; summary: string; props: JSONSchema; interactive?: boolean } | undefined {\n if (name.startsWith(CARD_ENTRY_PREFIX)) {\n const kind = name.slice(CARD_ENTRY_PREFIX.length);\n const def = this.cardKinds().find((k) => k.kind === kind);\n if (!def) return undefined;\n return { name, summary: def.summary, props: def.schema, ...(def.interactive ? { interactive: true } : {}) };\n }\n const def = this.definitions.get(name);\n return def ? { name: def.name, summary: def.summary, props: def.props } : undefined;\n }\n}\n","// Validation: the only road from model output to a rendered component.\n//\n// Every failure is reported per component, in words the model can act on, and the\n// rest of the surface survives it. One bad chart should cost one correction, not\n// the whole interface.\n\nimport { checkSchema } from \"./schema-check.js\";\nimport { bindingProblems, isSurfaceBinding, resolveSurfaceValue, usesBinding } from \"./bindings.js\";\nimport type { SurfaceCatalogue, SurfaceComponentDefinition } from \"./catalogue.js\";\nimport { parsePointer } from \"./pointer.js\";\nimport { findUnsafe } from \"./safety.js\";\nimport {\n SURFACE_CARD_KIND,\n SURFACE_LIMITS,\n type SurfaceAction,\n type SurfaceBinding,\n type SurfaceComponent,\n type SurfaceIssue,\n} from \"./types.js\";\n\nexport type SurfaceValidationContext = {\n catalogue: SurfaceCatalogue;\n data: Record<string, unknown>;\n /** Tools an action may call. Omitted means \"checked at dispatch only\". */\n actionTools?: readonly string[];\n /** Leave cards whose spec has bindings to the render that resolves them. */\n deferBoundCards?: boolean;\n};\n\nconst ID = /^[A-Za-z0-9_.:-]{1,64}$/;\nexport const isSurfaceId = (value: unknown): value is string => typeof value === \"string\" && ID.test(value);\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst RESERVED = new Set([\"id\", \"component\", \"visibleWhen\"]);\n\nfunction collectBindings(value: unknown, out: SurfaceBinding[] = []): SurfaceBinding[] {\n if (Array.isArray(value)) for (const v of value) collectBindings(v, out);\n else if (isSurfaceBinding(value)) {\n out.push(value);\n if (\"$query\" in value && isObject(value.$query) && Array.isArray(value.$query.where)) {\n for (const clause of value.$query.where) collectBindings(isObject(clause) ? clause[\"value\"] : undefined, out);\n }\n } else if (isObject(value)) for (const v of Object.values(value)) collectBindings(v, out);\n return out;\n}\n\nfunction bindingIssues(value: unknown, componentId: string): SurfaceIssue[] {\n return collectBindings(value).flatMap((binding) =>\n bindingProblems(binding).map((message) => ({\n code: \"invalid-binding\" as const,\n componentId,\n message,\n fix: 'Use { \"$path\": \"/a/b\" }, { \"$template\": \"Text {/a}\" }, { \"$query\": { \"from\": \"/rows\" } }, or { \"$item\": \"field\" } inside a List.',\n })),\n );\n}\n\nexport function validateSurfaceAction(action: unknown, componentId: string, ctx: SurfaceValidationContext): SurfaceIssue[] {\n const bad = (message: string, fix: string, code: SurfaceIssue[\"code\"] = \"invalid-action\"): SurfaceIssue[] => [\n { code, componentId, path: \"/action\", message, fix },\n ];\n const closed = 'Use { \"type\": \"set\", \"updates\": [...] }, { \"type\": \"tool\", \"tool\": \"name\", \"args\": {} } or { \"type\": \"event\", \"name\": \"name\" }.';\n if (!isObject(action)) return bad(\"action must be an object.\", closed);\n\n const onlyKeys = (allowed: string[]) => {\n const extra = Object.keys(action).filter((k) => !allowed.includes(k));\n return extra.length ? bad(`action has no \"${extra[0]}\". Actions cannot carry code or URLs.`, `Allowed keys: ${allowed.join(\", \")}.`) : [];\n };\n\n const typed = action as SurfaceAction;\n switch (typed.type) {\n case \"set\": {\n const extra = onlyKeys([\"type\", \"updates\"]);\n if (extra.length) return extra;\n if (!Array.isArray(typed.updates) || !typed.updates.length || typed.updates.length > SURFACE_LIMITS.actionUpdates) {\n return bad(`set needs 1 to ${SURFACE_LIMITS.actionUpdates} updates.`, 'Send \"updates\": [{ \"path\": \"/a\", \"value\": 1 }].');\n }\n for (const update of typed.updates) {\n if (!isObject(update) || !parsePointer(update.path)) return bad(\"Each update needs a JSON Pointer `path`.\", 'Send { \"path\": \"/a\", \"value\": 1 }.');\n }\n return bindingIssues(typed.updates, componentId);\n }\n case \"tool\": {\n const extra = onlyKeys([\"type\", \"tool\", \"args\", \"resultPath\"]);\n if (extra.length) return extra;\n if (typeof typed.tool !== \"string\" || !typed.tool) return bad(\"A tool action needs a `tool` name.\", 'Send { \"type\": \"tool\", \"tool\": \"name\" }.');\n if (typed.args !== undefined && !isObject(typed.args)) return bad(\"Tool `args` must be an object.\", \"Send args as an object of literals or bindings.\");\n if (typed.resultPath !== undefined && !parsePointer(typed.resultPath)) return bad(\"`resultPath` must be a JSON Pointer.\", 'Send \"resultPath\": \"/result\".');\n if (ctx.actionTools && !ctx.actionTools.includes(typed.tool)) {\n return bad(\n `Tool \"${typed.tool}\" is not available to this surface.`,\n ctx.actionTools.length ? `Available: ${ctx.actionTools.slice(0, 24).join(\", \")}.` : 'No tools are available; use an \"event\" action instead.',\n \"tool-not-allowed\",\n );\n }\n return bindingIssues(typed.args, componentId);\n }\n case \"event\": {\n const extra = onlyKeys([\"type\", \"name\", \"context\"]);\n if (extra.length) return extra;\n if (!isSurfaceId(typed.name)) return bad(\"An event needs a short `name`.\", 'Send { \"type\": \"event\", \"name\": \"apply\" }.');\n if (typed.context !== undefined && !isObject(typed.context)) return bad(\"Event `context` must be an object.\", \"Send context as an object of literals or bindings.\");\n return bindingIssues(typed.context, componentId);\n }\n default:\n return bad(`Unknown action type ${JSON.stringify((action as { type?: unknown }).type)}.`, closed);\n }\n}\n\nfunction validateCard(raw: SurfaceComponent, ctx: SurfaceValidationContext): SurfaceIssue[] {\n const id = raw.id;\n const kind = raw[\"kind\"];\n const registry = ctx.catalogue.cards;\n const available = ctx.catalogue.cardKinds().map((k) => k.kind);\n if (typeof kind !== \"string\" || kind === SURFACE_CARD_KIND || !registry?.has(kind)) {\n return [{ code: \"invalid-card\", componentId: id, path: \"/kind\", message: `Unknown card kind ${JSON.stringify(kind)}.`, fix: `One of: ${available.join(\", \") || \"(no card registry)\"}.` }];\n }\n const spec = raw[\"spec\"];\n if (!isObject(spec)) return [{ code: \"invalid-card\", componentId: id, path: \"/spec\", message: \"Card `spec` must be an object.\", fix: \"Send the card body as `spec`.\" }];\n\n const issues = bindingIssues(spec, id);\n if (registry.isInteractive(kind) && !parsePointer(raw[\"bind\"])) {\n issues.push({\n code: \"invalid-card\",\n componentId: id,\n path: \"/bind\",\n message: `Interactive card \"${kind}\" needs \\`bind\\`, the place its answer is stored.`,\n fix: 'Add \"bind\": \"/answers/decision\".',\n });\n }\n if (raw[\"action\"] !== undefined) issues.push(...validateSurfaceAction(raw[\"action\"], id, ctx));\n if (issues.length) return issues;\n\n // Rows from a List do not exist yet, so a template card is checked when it renders.\n if (usesBinding(spec, \"$item\")) return [];\n if (ctx.deferBoundCards && (usesBinding(spec, \"$path\") || usesBinding(spec, \"$query\") || usesBinding(spec, \"$template\"))) return [];\n const verdict = registry.validate({ ...(resolveSurfaceValue(spec, { data: ctx.data }) as Record<string, unknown>), kind });\n return verdict.ok\n ? []\n : [{ code: \"invalid-card\", componentId: id, path: \"/spec\", message: verdict.error, fix: verdict.expected ?? `Call describeSurfaceComponents for ${\"`\"}Card:${kind}${\"`\"}.` }];\n}\n\n/** Everything wrong with one component, judged alone. */\nexport function validateSurfaceComponent(raw: unknown, ctx: SurfaceValidationContext): SurfaceIssue[] {\n if (!isObject(raw)) return [{ code: \"invalid-shape\", message: \"Each component must be an object.\", fix: 'Send { \"id\": \"a\", \"component\": \"Text\", \"text\": \"Hello\" }.' }];\n const id = raw[\"id\"];\n if (!isSurfaceId(id)) return [{ code: \"invalid-shape\", message: `Component id ${JSON.stringify(id)} is invalid.`, fix: \"Use 1 to 64 letters, digits, or . _ : -\" }];\n const component = raw as SurfaceComponent;\n const name = component.component;\n const def: SurfaceComponentDefinition | undefined = typeof name === \"string\" ? ctx.catalogue.get(name) : undefined;\n if (!def) {\n return [{\n code: \"unknown-component\",\n componentId: id,\n path: \"/component\",\n message: `Unknown component ${JSON.stringify(name)}.`,\n fix: `One of: ${ctx.catalogue.names().filter((n) => !n.startsWith(\"Card:\")).join(\", \")}. Cards use \"component\": \"Card\" with a \"kind\".`,\n }];\n }\n\n const isCard = def.name === \"Card\";\n const unsafe = findUnsafe(raw, { markup: !isCard && def.category !== \"custom\" });\n if (unsafe) {\n return [{ code: \"unsafe-content\", componentId: id, path: unsafe.path, message: `${unsafe.path || \"The component\"} ${unsafe.reason}.`, fix: \"Send plain text and http(s) URLs only. Surfaces cannot carry script, HTML or CSS.\" }];\n }\n\n const props = Object.fromEntries(Object.entries(raw).filter(([k]) => !RESERVED.has(k)));\n const issues: SurfaceIssue[] = checkSchema(def.props, props, \"\", { isDynamic: isSurfaceBinding }).map((p) => ({\n code: \"invalid-prop\" as const,\n componentId: id,\n path: p.path,\n message: `${def.name}: ${p.message}`,\n fix: p.expected ?? `Call describeSurfaceComponents for ${def.name}.`,\n }));\n\n if (raw[\"visibleWhen\"] !== undefined) {\n const condition = raw[\"visibleWhen\"];\n if (!isObject(condition) || !parsePointer(condition[\"path\"])) {\n issues.push({ code: \"invalid-binding\", componentId: id, path: \"/visibleWhen\", message: \"visibleWhen needs a JSON Pointer `path`.\", fix: 'Send { \"path\": \"/showDetails\" }.' });\n }\n }\n if (issues.length) return issues;\n\n if (isCard) return validateCard(component, ctx);\n\n const out = bindingIssues(props, id);\n for (const key of [\"value\"] as const) {\n const bound = props[key];\n if (def.category === \"input\" && isObject(bound) && !parsePointer(bound[\"$path\"])) {\n out.push({ code: \"invalid-binding\", componentId: id, path: `/${key}`, message: `${def.name}.value must be a writable $path.`, fix: 'Send \"value\": { \"$path\": \"/filters/region\" }.' });\n }\n }\n if (props[\"action\"] !== undefined) out.push(...validateSurfaceAction(props[\"action\"], id, ctx));\n if (props[\"disabledWhen\"] !== undefined && !parsePointer((props[\"disabledWhen\"] as { path?: unknown }).path)) {\n out.push({ code: \"invalid-binding\", componentId: id, path: \"/disabledWhen\", message: \"disabledWhen needs a JSON Pointer `path`.\", fix: 'Send { \"path\": \"/busy\" }.' });\n }\n return out;\n}\n\n/** Split a component list into what may render and what must be corrected. */\nexport function validateSurfaceComponents(raw: readonly unknown[], ctx: SurfaceValidationContext): { components: SurfaceComponent[]; issues: SurfaceIssue[] } {\n const components: SurfaceComponent[] = [];\n const issues: SurfaceIssue[] = [];\n const seen = new Set<string>();\n for (const entry of raw) {\n const found = validateSurfaceComponent(entry, ctx);\n if (found.length) {\n issues.push(...found);\n continue;\n }\n const component = entry as SurfaceComponent;\n if (seen.has(component.id)) {\n issues.push({ code: \"duplicate-id\", componentId: component.id, message: `Component id \"${component.id}\" is used twice.`, fix: \"Give every component its own id.\" });\n continue;\n }\n seen.add(component.id);\n components.push(component);\n }\n return { components, issues };\n}\n\n/**\n * Whole-graph checks: a root that exists, children that exist, no cycles, bounded\n * depth, and `$item` only where a row is in scope.\n */\nexport function validateSurfaceGraph(\n root: string,\n components: readonly SurfaceComponent[],\n catalogue: SurfaceCatalogue,\n rejected: ReadonlySet<string> = new Set(),\n): SurfaceIssue[] {\n const byId = new Map(components.map((c) => [c.id, c]));\n const issues: SurfaceIssue[] = [];\n if (!byId.has(root)) {\n if (!rejected.has(root)) issues.push({ code: \"missing-root\", componentId: root, message: `Root \"${root}\" is not in the component list.`, fix: \"Add a component with that id, or set `root` to one that exists.\" });\n return issues;\n }\n\n const slotsOf = (c: SurfaceComponent) => {\n try {\n return catalogue.get(c.component)?.slots?.(c) ?? [];\n } catch {\n return [];\n }\n };\n const templatesOf = (c: SurfaceComponent) => {\n try {\n return catalogue.get(c.component)?.templateSlots?.(c) ?? [];\n } catch {\n return [];\n }\n };\n\n const reported = new Set<string>();\n const once = (key: string, issue: SurfaceIssue) => {\n if (reported.has(key)) return;\n reported.add(key);\n issues.push(issue);\n };\n\n const visit = (id: string, trail: string[], inTemplate: boolean): void => {\n const component = byId.get(id);\n if (!component) return;\n if (trail.includes(id)) {\n once(`cycle:${id}`, { code: \"cycle\", componentId: id, message: `Component \"${id}\" contains itself.`, fix: \"Remove the reference that loops back.\" });\n return;\n }\n if (trail.length >= SURFACE_LIMITS.depth) {\n once(`depth:${id}`, { code: \"too-deep\", componentId: id, message: `Nesting is deeper than ${SURFACE_LIMITS.depth} levels.`, fix: \"Flatten the layout.\" });\n return;\n }\n if (!inTemplate && usesBinding(component, \"$item\")) {\n once(`item:${id}`, { code: \"invalid-binding\", componentId: id, message: `\"${id}\" reads $item outside a List template.`, fix: \"Use $path here, or move it under a List's `child`.\" });\n }\n const templates = templatesOf(component);\n for (const child of slotsOf(component)) {\n if (!byId.has(child)) {\n if (!rejected.has(child)) once(`missing:${child}`, { code: \"missing-child\", componentId: id, message: `\"${id}\" references \"${child}\", which does not exist.`, fix: `Add a component with id \"${child}\" or remove the reference.` });\n continue;\n }\n visit(child, [...trail, id], inTemplate || templates.includes(child));\n }\n };\n\n visit(root, [], false);\n return issues;\n}\n","// Building and patching surfaces. Pure functions: spec in, spec and corrections out.\n\nimport type { SurfaceCatalogue } from \"./catalogue.js\";\nimport { removeAt, setAt } from \"./pointer.js\";\nimport { findUnsafe } from \"./safety.js\";\nimport {\n SURFACE_CARD_KIND,\n SURFACE_FORMAT_VERSION,\n SURFACE_LIMITS,\n type SurfaceComponent,\n type SurfaceIssue,\n type SurfaceOperation,\n type SurfaceSpec,\n} from \"./types.js\";\nimport {\n isSurfaceId,\n validateSurfaceComponent,\n validateSurfaceComponents,\n validateSurfaceGraph,\n type SurfaceValidationContext,\n} from \"./validate.js\";\n\nexport type SurfaceBuildContext = {\n catalogue: SurfaceCatalogue;\n actionTools?: readonly string[];\n};\n\n/** `spec` is absent when nothing could be rendered at all. `issues` is what the model must correct. */\nexport type SurfaceBuildResult = { spec?: SurfaceSpec; issues: SurfaceIssue[] };\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst fatal = (issue: SurfaceIssue): SurfaceBuildResult => ({ issues: [issue] });\n\nfunction dataIssue(data: unknown): SurfaceIssue | undefined {\n const unsafe = findUnsafe(data);\n if (unsafe) {\n return { code: \"unsafe-content\", path: unsafe.path, message: `data${unsafe.path} ${unsafe.reason}.`, fix: \"Store plain values and http(s) URLs only.\" };\n }\n if (JSON.stringify(data).length > SURFACE_LIMITS.dataChars) {\n return { code: \"limit-exceeded\", path: \"/data\", message: `data is larger than ${SURFACE_LIMITS.dataChars} characters.`, fix: \"Send a summary or fewer rows.\" };\n }\n return undefined;\n}\n\nconst tooMany = (count: number): SurfaceIssue => ({\n code: \"limit-exceeded\",\n message: `A surface may hold ${SURFACE_LIMITS.components} components; this has ${count}.`,\n fix: \"Use a List template instead of repeating components.\",\n});\n\n/** Issues that belong in the spec: parts the person sees a fallback for. */\nfunction persistentIssues(components: readonly SurfaceComponent[], issues: readonly SurfaceIssue[]): SurfaceIssue[] {\n const present = new Set(components.map((c) => c.id));\n return issues.filter((i) => !i.componentId || !present.has(i.componentId) || i.code === \"missing-child\" || i.code === \"cycle\" || i.code === \"too-deep\" || i.code === \"invalid-binding\");\n}\n\n/** Validate a complete surface from `createSurface` arguments. */\nexport function buildSurface(\n input: unknown,\n ctx: SurfaceBuildContext,\n opts: { revision?: number; originCallId?: string } = {},\n): SurfaceBuildResult {\n if (!isObject(input)) return fatal({ code: \"invalid-shape\", message: \"Surface must be an object.\", fix: \"Send surfaceId, root and components.\" });\n const { surfaceId, root, components, data, title } = input;\n if (!isSurfaceId(surfaceId)) return fatal({ code: \"invalid-shape\", path: \"/surfaceId\", message: \"surfaceId is missing or invalid.\", fix: 'Send a short id such as \"overview\".' });\n if (!isSurfaceId(root)) return fatal({ code: \"missing-root\", path: \"/root\", message: \"root must be the id of a component.\", fix: 'Send \"root\": \"main\" and a component with that id.' });\n if (!Array.isArray(components) || !components.length) return fatal({ code: \"invalid-shape\", path: \"/components\", message: \"components must be a non-empty array.\", fix: 'Send [{ \"id\": \"main\", \"component\": \"Stack\", \"children\": [] }].' });\n if (components.length > SURFACE_LIMITS.components) return fatal(tooMany(components.length));\n if (data !== undefined && !isObject(data)) return fatal({ code: \"invalid-data\", path: \"/data\", message: \"data must be an object.\", fix: 'Send \"data\": { \"filters\": {} }.' });\n const model = (data ?? {}) as Record<string, unknown>;\n const bad = dataIssue(model);\n if (bad) return fatal(bad);\n if (JSON.stringify(components).length > SURFACE_LIMITS.specChars) {\n return fatal({ code: \"limit-exceeded\", path: \"/components\", message: `components exceed ${SURFACE_LIMITS.specChars} characters.`, fix: \"Move repeated content into data and use a List.\" });\n }\n\n const validation: SurfaceValidationContext = { catalogue: ctx.catalogue, data: model, actionTools: ctx.actionTools };\n const checked = validateSurfaceComponents(components, validation);\n const rejected = new Set(checked.issues.flatMap((i) => (i.componentId ? [i.componentId] : [])));\n const graph = validateSurfaceGraph(root, checked.components, ctx.catalogue, rejected);\n const issues = [...checked.issues, ...graph];\n const kept = persistentIssues(checked.components, issues);\n\n return {\n issues,\n spec: {\n kind: SURFACE_CARD_KIND,\n version: SURFACE_FORMAT_VERSION,\n surfaceId,\n ...(typeof title === \"string\" && title ? { title } : {}),\n root,\n components: checked.components,\n data: model,\n revision: opts.revision ?? 1,\n ...(opts.originCallId ? { originCallId: opts.originCallId } : {}),\n ...(kept.length ? { issues: kept } : {}),\n },\n };\n}\n\n/**\n * Apply patches to a surface.\n *\n * Data operations land first, whatever order they were sent in: a component is\n * validated against the data it binds to, and a model naturally writes the new\n * chart before the rows it reads. A rejected upsert keeps the previous version\n * of that component on screen.\n */\nexport function applySurfaceOperations(spec: SurfaceSpec, operations: unknown, ctx: SurfaceBuildContext): SurfaceBuildResult {\n if (!Array.isArray(operations) || !operations.length) {\n return fatal({ code: \"invalid-shape\", path: \"/operations\", message: \"operations must be a non-empty array.\", fix: 'Send [{ \"op\": \"setData\", \"path\": \"/a\", \"value\": 1 }].' });\n }\n\n const issues: SurfaceIssue[] = [];\n let data = spec.data;\n const ops = operations as SurfaceOperation[];\n\n for (const op of ops) {\n if (!isObject(op)) continue;\n if (op.op === \"setData\") {\n const unsafe = findUnsafe(op.value);\n const next = unsafe ? undefined : setAt(data, op.path, op.value);\n if (next) data = next;\n else issues.push({ code: unsafe ? \"unsafe-content\" : \"invalid-data\", path: op.path, message: unsafe ? `The value ${unsafe.path} ${unsafe.reason}.` : `Cannot write to ${JSON.stringify(op.path)}.`, fix: 'Use a JSON Pointer such as \"/filters/region\" with a plain value.' });\n } else if (op.op === \"removeData\") {\n const next = removeAt(data, op.path);\n if (next) data = next;\n else issues.push({ code: \"invalid-data\", path: op.path, message: `Cannot remove ${JSON.stringify(op.path)}.`, fix: 'Use a JSON Pointer such as \"/filters/region\".' });\n }\n }\n const bad = dataIssue(data);\n if (bad) return fatal(bad);\n\n const validation: SurfaceValidationContext = { catalogue: ctx.catalogue, data, actionTools: ctx.actionTools };\n const byId = new Map(spec.components.map((c) => [c.id, c]));\n const rejected = new Set((spec.issues ?? []).flatMap((i) => (i.componentId && !byId.has(i.componentId) ? [i.componentId] : [])));\n const carried = new Map<string, SurfaceIssue[]>();\n for (const issue of spec.issues ?? []) {\n if (issue.componentId && rejected.has(issue.componentId)) carried.set(issue.componentId, [...(carried.get(issue.componentId) ?? []), issue]);\n }\n let root = spec.root;\n let title = spec.title;\n\n for (const op of ops) {\n if (!isObject(op)) {\n issues.push({ code: \"invalid-shape\", message: \"Each operation must be an object.\", fix: \"Send { op, ... }.\" });\n continue;\n }\n switch (op.op) {\n case \"setData\":\n case \"removeData\":\n break;\n case \"upsertComponents\": {\n if (!Array.isArray(op.components)) {\n issues.push({ code: \"invalid-shape\", path: \"/components\", message: \"upsertComponents needs a `components` array.\", fix: \"Send the changed components in full.\" });\n break;\n }\n for (const raw of op.components) {\n const found = validateSurfaceComponent(raw, validation);\n const id = isObject(raw) && typeof raw[\"id\"] === \"string\" ? raw[\"id\"] : undefined;\n if (found.length) {\n issues.push(...found);\n if (id && !byId.has(id)) {\n rejected.add(id);\n carried.set(id, found);\n }\n continue;\n }\n const component = raw as SurfaceComponent;\n byId.set(component.id, component);\n rejected.delete(component.id);\n carried.delete(component.id);\n }\n break;\n }\n case \"removeComponents\": {\n const ids = new Set(Array.isArray(op.ids) ? op.ids : []);\n for (const id of ids) {\n byId.delete(id);\n rejected.delete(id);\n carried.delete(id);\n }\n // Dropping a child from its parent's list is unambiguous, so it is done\n // here rather than bounced back as a dangling reference.\n for (const [id, component] of byId) {\n const children = component[\"children\"];\n if (Array.isArray(children) && children.some((c) => ids.has(c as string))) {\n byId.set(id, { ...component, children: children.filter((c) => !ids.has(c as string)) });\n }\n }\n break;\n }\n case \"setRoot\":\n if (isSurfaceId(op.root)) root = op.root;\n else issues.push({ code: \"missing-root\", path: \"/root\", message: \"setRoot needs a component id.\", fix: 'Send { \"op\": \"setRoot\", \"root\": \"main\" }.' });\n break;\n case \"setTitle\":\n if (typeof op.title === \"string\") title = op.title;\n else issues.push({ code: \"invalid-shape\", path: \"/title\", message: \"setTitle needs a string `title`.\", fix: 'Send { \"op\": \"setTitle\", \"title\": \"Overview\" }.' });\n break;\n default:\n issues.push({\n code: \"invalid-shape\",\n message: `Unknown operation ${JSON.stringify((op as { op?: unknown }).op)}.`,\n fix: \"Use upsertComponents, removeComponents, setRoot, setTitle, setData or removeData.\",\n });\n }\n }\n\n const components = [...byId.values()];\n if (components.length > SURFACE_LIMITS.components) return fatal(tooMany(components.length));\n\n const graph = validateSurfaceGraph(root, components, ctx.catalogue, rejected);\n issues.push(...graph);\n const kept = [...[...carried.values()].flat(), ...graph];\n const { issues: _previous, title: _title, ...rest } = spec;\n\n return {\n issues,\n spec: {\n ...rest,\n ...(title ? { title } : {}),\n root,\n components,\n data,\n revision: spec.revision + 1,\n ...(kept.length ? { issues: kept } : {}),\n },\n };\n}\n\n/**\n * A surface from arguments still streaming in: every complete, valid component so\n * far. The last entry is usually half-written, so a failure here is not an error,\n * only something that has not arrived.\n */\nexport function previewSurface(partial: unknown, catalogue: SurfaceCatalogue): SurfaceSpec | undefined {\n if (!isObject(partial)) return undefined;\n const { surfaceId, root, components, data, title } = partial;\n if (!isSurfaceId(surfaceId) || !isSurfaceId(root) || !Array.isArray(components)) return undefined;\n const model = isObject(data) && !findUnsafe(data) ? data : {};\n const validation: SurfaceValidationContext = { catalogue, data: model };\n const seen = new Set<string>();\n const valid: SurfaceComponent[] = [];\n for (const raw of components.slice(0, SURFACE_LIMITS.components)) {\n if (validateSurfaceComponent(raw, validation).length) continue;\n const component = raw as SurfaceComponent;\n if (seen.has(component.id)) continue;\n seen.add(component.id);\n valid.push(component);\n }\n if (!valid.length) return undefined;\n // The last part listed is the one still being written, whether or not it is valid yet.\n const last: unknown = components.at(-1);\n const pending =\n isObject(last) && typeof last[\"id\"] === \"string\"\n ? {\n id: last[\"id\"],\n ...(typeof last[\"component\"] === \"string\" ? { component: last[\"component\"] } : {}),\n ...(typeof last[\"kind\"] === \"string\" ? { kind: last[\"kind\"] } : {}),\n }\n : undefined;\n return {\n kind: SURFACE_CARD_KIND,\n version: SURFACE_FORMAT_VERSION,\n surfaceId,\n ...(typeof title === \"string\" && title ? { title } : {}),\n root,\n components: valid,\n data: model,\n revision: 0,\n ...(pending ? { pending } : {}),\n };\n}\n\n/**\n * Re-validate a spec at the renderer. A thread can be edited in storage and a\n * catalogue can shrink between sessions, so what was valid when written is not\n * trusted when read. Whether a bound card is valid depends on the data of the\n * moment, so that one check is left to the render that resolves it.\n */\nexport function sanitizeSurfaceSpec(spec: SurfaceSpec, catalogue: SurfaceCatalogue): SurfaceSpec {\n const components = Array.isArray(spec.components) ? spec.components.slice(0, SURFACE_LIMITS.components) : [];\n const data = isObject(spec.data) && !findUnsafe(spec.data) ? spec.data : {};\n const checked = validateSurfaceComponents(components, { catalogue, data, deferBoundCards: true });\n const rejected = new Set(checked.issues.flatMap((i) => (i.componentId ? [i.componentId] : [])));\n const root = typeof spec.root === \"string\" ? spec.root : \"\";\n const graph = validateSurfaceGraph(root, checked.components, catalogue, rejected);\n const previous = (spec.issues ?? []).filter((i) => i?.componentId && !checked.components.some((c) => c.id === i.componentId));\n const issues = [...checked.issues, ...graph, ...previous];\n const { issues: _old, ...rest } = spec;\n return { ...rest, root, components: checked.components, data, ...(issues.length ? { issues } : {}) };\n}\n","// Where surfaces live between tool calls.\n//\n// A surface's state is DERIVED from the active branch: the newest snapshot of it\n// on the path from root to head. Nothing is stored beside the thread, so switching\n// branch, regenerating and reloading all give the right answer for free, and a\n// branch that never updated a surface shows it as that branch left it.\n\nimport type { Message } from \"../content/types.js\";\nimport { SURFACE_CARD_KIND, SURFACE_FORMAT_VERSION, type SurfaceSpec } from \"./types.js\";\n\nconst CARD_ID_PREFIX = \"surface:\";\nexport const SURFACE_ARTIFACT_KIND = `card:${SURFACE_CARD_KIND}`;\n\n/** One card id per surface, so a later snapshot replaces the earlier one in a run. */\nexport const surfaceCardId = (surfaceId: string): string => `${CARD_ID_PREFIX}${surfaceId}`;\n\nexport function isSurfaceSpec(value: unknown): value is SurfaceSpec {\n return typeof value === \"object\" && value !== null && (value as { kind?: unknown }).kind === SURFACE_CARD_KIND && typeof (value as { surfaceId?: unknown }).surfaceId === \"string\";\n}\n\nfunction expiredStub(surfaceId: string): SurfaceSpec {\n return { kind: SURFACE_CARD_KIND, version: SURFACE_FORMAT_VERSION, surfaceId, root: \"\", components: [], data: {}, revision: 0, expired: true };\n}\n\n/** The current state of every surface on a message path. Later snapshots win. */\nexport function foldSurfaces(messages: readonly Message[]): Record<string, SurfaceSpec> {\n const out: Record<string, SurfaceSpec> = {};\n for (const message of messages) {\n for (const part of message.parts) {\n if (part.type !== \"artifact\" || part.kind !== SURFACE_ARTIFACT_KIND) continue;\n const data = part.data as { expired?: boolean } | null;\n if (data?.expired === true && part.id.startsWith(CARD_ID_PREFIX)) {\n const surfaceId = part.id.slice(CARD_ID_PREFIX.length);\n out[surfaceId] = expiredStub(surfaceId);\n } else if (isSurfaceSpec(part.data)) {\n out[part.data.surfaceId] = part.data;\n }\n }\n }\n return out;\n}\n\n/** The working copy a run reads and writes, so two calls in one step see each other. */\nexport class SurfaceLedger {\n private readonly surfaces = new Map<string, SurfaceSpec>();\n\n constructor(initial: Record<string, SurfaceSpec> = {}) {\n for (const [id, spec] of Object.entries(initial)) this.surfaces.set(id, spec);\n }\n\n get(surfaceId: string): SurfaceSpec | undefined {\n return this.surfaces.get(surfaceId);\n }\n\n put(spec: SurfaceSpec): void {\n this.surfaces.set(spec.surfaceId, spec);\n }\n\n list(): SurfaceSpec[] {\n return [...this.surfaces.values()];\n }\n\n /** Surfaces still on screen. */\n live(): SurfaceSpec[] {\n return this.list().filter((s) => !s.deleted && !s.expired);\n }\n}\n","// The agent's handle on surfaces: create, patch, delete, read, and look up schemas.\n//\n// Descriptions stay short on purpose. These definitions ride in every request, so\n// they carry the shape of the format and point at `describeSurfaceComponents` for\n// the rest.\n\nimport { packByPriority } from \"../tokens/budget.js\";\nimport { estimateJsonTokens } from \"../tokens/estimate.js\";\nimport type { ToolDefinition, ToolExecutionContext } from \"../tools/types.js\";\nimport type { SurfaceCatalogue } from \"./catalogue.js\";\nimport { SurfaceLedger, surfaceCardId } from \"./ledger.js\";\nimport { applySurfaceOperations, buildSurface, previewSurface } from \"./operations.js\";\nimport { getAt } from \"./pointer.js\";\nimport { SURFACE_CARD_KIND, SURFACE_FORMAT_VERSION, SURFACE_LIMITS, type SurfaceIssue, type SurfaceSpec } from \"./types.js\";\n\nexport const SURFACE_TOOL_NAMES = [\"createSurface\", \"updateSurface\", \"deleteSurface\", \"readSurface\", \"describeSurfaceComponents\"] as const;\n\nexport const SURFACE_GUIDE = [\n \"A surface is an interface you assemble from a flat list of components that reference each other by id.\",\n \"\",\n 'Shape: { \"surfaceId\": \"overview\", \"title\": \"Overview\", \"data\": { \"region\": \"all\", \"rows\": [] }, \"root\": \"main\", \"components\": [',\n ' { \"id\": \"main\", \"component\": \"Stack\", \"children\": [\"region\", \"total\"] },',\n ' { \"id\": \"region\", \"component\": \"Select\", \"label\": \"Region\", \"value\": { \"$path\": \"/region\" }, \"options\": [{ \"value\": \"all\", \"label\": \"All\" }] },',\n ' { \"id\": \"total\", \"component\": \"Metric\", \"label\": \"Total\", \"format\": \"number\", \"value\": { \"$query\": { \"from\": \"/rows\", \"where\": [{ \"field\": \"region\", \"value\": { \"$path\": \"/region\" }, \"ignore\": \"all\" }], \"aggregate\": { \"op\": \"sum\", \"field\": \"amount\" } } } }',\n \"] }\",\n \"\",\n \"Send `data` first, then `root`, then components parents before children, so the interface can draw as it streams.\",\n \"\",\n \"Bindings work in any prop: $path reads the data model, $template interpolates ({/path}, {.rowField}), $query filters, groups and aggregates rows, and $item reads the current row inside a List.\",\n \"Controls write to their `value` $path, so neighbours update with no call to you. Use `visibleWhen` to show parts conditionally.\",\n 'Cards are blocks: { \"id\": \"trend\", \"component\": \"Card\", \"kind\": \"chart\", \"spec\": { ... } }. Interactive card kinds also need `bind`.',\n \"\",\n \"Button actions are exactly: set (local state), tool (a tool you may already call; it follows the same approval rules) and event (returns to you as a new message).\",\n \"Never send code, HTML, CSS or script URLs. Change an existing surface with updateSurface rather than creating another. Call readSurface before acting on what the person has chosen.\",\n].join(\"\\n\");\n\nconst toCorrections = (issues: readonly SurfaceIssue[]) => issues.slice(0, 12);\n\nfunction outcome(spec: SurfaceSpec, issues: readonly SurfaceIssue[]) {\n const card = { card: spec, cardId: surfaceCardId(spec.surfaceId) };\n const facts = { surfaceId: spec.surfaceId, revision: spec.revision, components: spec.components.length };\n if (!issues.length) return { output: { ok: true, ...facts }, ...card };\n return {\n output: { ok: false, partial: true, ...facts, corrections: toCorrections(issues), next: \"The valid parts are on screen. Send the corrected parts with updateSurface.\" },\n failure: \"invalid-input\" as const,\n ...card,\n };\n}\n\nconst refused = (issues: readonly SurfaceIssue[]) => ({\n output: { ok: false, rendered: false, corrections: toCorrections(issues) },\n failure: \"invalid-input\" as const,\n});\n\nconst unavailable = (surfaceId: unknown, ledger: SurfaceLedger) => {\n const spec = typeof surfaceId === \"string\" ? ledger.get(surfaceId) : undefined;\n return {\n output: {\n ok: false,\n error: spec?.expired\n ? `Surface \"${String(surfaceId)}\" expired from saved history. Call createSurface to rebuild it.`\n : `No surface \"${String(surfaceId)}\".`,\n available: ledger.live().map((s) => s.surfaceId),\n },\n failure: \"not-found\" as const,\n };\n};\n\nexport type SurfaceToolsOptions = { catalogue: SurfaceCatalogue };\n\nexport function createSurfaceTools(options: SurfaceToolsOptions): ToolDefinition[] {\n const { catalogue } = options;\n // Used only when a tool runs outside runAgent, which supplies the real ledger.\n const standalone = new SurfaceLedger();\n const ledgerOf = (ctx: ToolExecutionContext) => ctx.surfaces ?? standalone;\n\n const createSurface: ToolDefinition = {\n name: \"createSurface\",\n side: \"read\",\n description:\n \"Assemble an interactive interface from a flat component list: layout, text, metrics, inputs, buttons and any card. \" +\n \"Use it when the person will explore, filter, compare or act, rather than just read. \" +\n \"Call describeSurfaceComponents first for the format and each component's props.\",\n inputSchema: {\n type: \"object\",\n required: [\"surfaceId\", \"root\", \"components\"],\n properties: {\n surfaceId: { type: \"string\", description: \"Stable id for later updates.\" },\n title: { type: \"string\" },\n data: { type: \"object\", description: \"Initial state that components bind to.\", additionalProperties: true },\n root: { type: \"string\", description: \"Id of the top component.\" },\n components: {\n type: \"array\",\n items: { type: \"object\", required: [\"id\", \"component\"], additionalProperties: true },\n },\n },\n additionalProperties: false,\n },\n loading: { kind: \"generic\", label: \"Building the interface\" },\n partialCard: (input) => previewSurface(input, catalogue),\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const surfaceId = (input as { surfaceId?: unknown } | null)?.surfaceId;\n const prior = typeof surfaceId === \"string\" ? ledger.get(surfaceId) : undefined;\n const replacing = prior && !prior.deleted && !prior.expired ? prior : undefined;\n if (!replacing && ledger.live().length >= SURFACE_LIMITS.surfaces) {\n return refused([{ code: \"limit-exceeded\", message: `A thread may hold ${SURFACE_LIMITS.surfaces} surfaces.`, fix: \"Update or delete an existing surface.\" }]);\n }\n const built = buildSurface(input, { catalogue, actionTools: ctx.surfaceActionTools }, {\n revision: (prior?.revision ?? 0) + 1,\n originCallId: replacing?.originCallId ?? ctx.callId,\n });\n if (!built.spec) return refused(built.issues);\n ledger.put(built.spec);\n return outcome(built.spec, built.issues);\n },\n };\n\n const updateSurface: ToolDefinition = {\n name: \"updateSurface\",\n side: \"read\",\n description:\n \"Patch a surface in place. Operations: upsertComponents { components }, removeComponents { ids }, setRoot { root }, setTitle { title }, setData { path, value }, removeData { path }.\",\n inputSchema: {\n type: \"object\",\n required: [\"surfaceId\", \"operations\"],\n properties: {\n surfaceId: { type: \"string\" },\n operations: { type: \"array\", items: { type: \"object\", required: [\"op\"], additionalProperties: true } },\n expectedRevision: { type: \"number\", description: \"Refuse the patch if the surface has changed since this revision.\" },\n },\n additionalProperties: false,\n },\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const { surfaceId, operations, expectedRevision } = (input ?? {}) as { surfaceId?: string; operations?: unknown; expectedRevision?: number };\n const current = surfaceId ? ledger.get(surfaceId) : undefined;\n if (!current || current.deleted || current.expired) return unavailable(surfaceId, ledger);\n if (expectedRevision != null && expectedRevision !== current.revision) {\n return refused([{\n code: \"stale-revision\",\n message: `The surface is at revision ${current.revision}, not ${expectedRevision}. The person may have changed it.`,\n fix: \"Call readSurface, then patch against the current revision.\",\n }]);\n }\n const built = applySurfaceOperations(current, operations, { catalogue, actionTools: ctx.surfaceActionTools });\n if (!built.spec) return refused(built.issues);\n ledger.put(built.spec);\n return outcome(built.spec, built.issues);\n },\n };\n\n const deleteSurface: ToolDefinition = {\n name: \"deleteSurface\",\n side: \"read\",\n description: \"Remove a surface from the conversation.\",\n inputSchema: {\n type: \"object\",\n required: [\"surfaceId\"],\n properties: { surfaceId: { type: \"string\" } },\n additionalProperties: false,\n },\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const { surfaceId } = (input ?? {}) as { surfaceId?: string };\n const current = surfaceId ? ledger.get(surfaceId) : undefined;\n if (!current || current.deleted) return unavailable(surfaceId, ledger);\n const tombstone: SurfaceSpec = {\n kind: SURFACE_CARD_KIND,\n version: SURFACE_FORMAT_VERSION,\n surfaceId: current.surfaceId,\n ...(current.title ? { title: current.title } : {}),\n root: \"\",\n components: [],\n data: {},\n revision: current.revision + 1,\n ...(current.originCallId ? { originCallId: current.originCallId } : {}),\n deleted: true,\n };\n ledger.put(tombstone);\n return { output: { ok: true, surfaceId: current.surfaceId, deleted: true }, card: tombstone, cardId: surfaceCardId(current.surfaceId) };\n },\n };\n\n const readSurface: ToolDefinition = {\n name: \"readSurface\",\n side: \"read\",\n description: \"Read a surface's current state, including what the person has changed. Omit surfaceId to list surfaces.\",\n inputSchema: {\n type: \"object\",\n properties: {\n surfaceId: { type: \"string\" },\n paths: { type: \"array\", items: { type: \"string\" }, description: \"JSON Pointers to read instead of the whole data model.\" },\n },\n additionalProperties: false,\n },\n execute(input, ctx) {\n const ledger = ledgerOf(ctx);\n const { surfaceId, paths } = (input ?? {}) as { surfaceId?: string; paths?: string[] };\n if (!surfaceId) {\n return { output: { ok: true, surfaces: ledger.live().map((s) => ({ surfaceId: s.surfaceId, title: s.title, revision: s.revision })) } };\n }\n const spec = ledger.get(surfaceId);\n if (!spec || spec.deleted || spec.expired) return unavailable(surfaceId, ledger);\n return {\n output: {\n ok: true,\n surfaceId,\n ...(spec.title ? { title: spec.title } : {}),\n revision: spec.revision,\n root: spec.root,\n components: spec.components.map((c) => ({ id: c.id, component: c.component })),\n ...(Array.isArray(paths) ? { values: Object.fromEntries(paths.map((p) => [p, getAt(spec.data, p)])) } : { data: spec.data }),\n ...(spec.issues?.length ? { issues: toCorrections(spec.issues) } : {}),\n },\n };\n },\n };\n\n const describeSurfaceComponents: ToolDefinition = {\n name: \"describeSurfaceComponents\",\n side: \"read\",\n description: \"Look up the surface format. No arguments returns the guide and component index; `components` returns those schemas, such as [\\\"Select\\\", \\\"Card:chart\\\"].\",\n inputSchema: {\n type: \"object\",\n properties: {\n components: { type: \"array\", items: { type: \"string\" } },\n maxTokens: { type: \"number\", description: \"Budget for the returned schemas. Default 1500.\" },\n },\n additionalProperties: false,\n },\n execute(input) {\n const { components, maxTokens } = (input ?? {}) as { components?: string[]; maxTokens?: number };\n if (!Array.isArray(components) || !components.length) {\n return { output: { ok: true, guide: SURFACE_GUIDE, index: catalogue.index() } };\n }\n const known = components.flatMap((name) => {\n const schema = catalogue.schemaOf(name);\n return schema ? [schema] : [];\n });\n const unknown = components.filter((name) => !catalogue.schemaOf(name));\n const budget = Math.max(200, Math.min(maxTokens ?? 1_500, 6_000));\n const packed = packByPriority(known, budget, estimateJsonTokens);\n return {\n output: {\n ok: true,\n schemas: packed.included,\n ...(packed.dropped.length ? { omitted: packed.dropped.map((d) => d.item.name), next: \"Request the omitted components in another call.\" } : {}),\n ...(unknown.length ? { unknown, available: catalogue.names() } : {}),\n },\n };\n },\n };\n\n return [createSurface, updateSurface, deleteSurface, readSurface, describeSurfaceComponents];\n}\n","// Progressive disclosure, through the seams the framework already has.\n//\n// The skill index carries one line. `loadSkill` pays for the guide when the model\n// decides to build something. The context source keeps surfaces discoverable after\n// compaction has trimmed the calls that created them.\n\nimport type { ContextSource } from \"../context/types.js\";\nimport type { Skill } from \"../skills/types.js\";\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { SurfaceCatalogue } from \"./catalogue.js\";\nimport { foldSurfaces } from \"./ledger.js\";\nimport { SURFACE_GUIDE } from \"./tools.js\";\n\nexport const SURFACE_SKILL_ID = \"surface-authoring\";\n\n/** A `manual` skill: one line in the index until the model loads it. */\nexport function createSurfaceSkill(catalogue: SurfaceCatalogue): Skill {\n return {\n id: SURFACE_SKILL_ID,\n name: \"Building interfaces\",\n description: \"How to assemble an interactive surface from components, bindings and actions.\",\n mode: \"manual\",\n aliases: [\"surface\", \"interface\", \"dashboard\", \"filter\", \"form\"],\n tools: [\"createSurface\", \"updateSurface\", \"deleteSurface\", \"readSurface\", \"describeSurfaceComponents\"],\n body: () => [SURFACE_GUIDE, \"\", \"Components:\", catalogue.index()].join(\"\\n\"),\n };\n}\n\n/**\n * One line per surface on the active path. Data stays out: the model asks for it\n * with `readSurface` when it needs it, so an idle dashboard costs a line a turn.\n */\nexport function createSurfaceContextSource(): ContextSource {\n return {\n id: \"surfaces\",\n run({ messages }) {\n const live = Object.values(foldSurfaces(messages)).filter((s) => !s.deleted && !s.expired);\n if (!live.length) return {};\n const text = [\n \"Surfaces on screen. Call readSurface for their current state before relying on it:\",\n ...live.map((s) => `- ${s.surfaceId}${s.title ? ` (${s.title})` : \"\"}, revision ${s.revision}`),\n ].join(\"\\n\");\n return { layers: [{ id: \"surfaces\", kind: \"custom\", text, tokens: estimateTokens(text), priority: 400 }] };\n },\n };\n}\n","// An async event channel: push from a callback, consume as an async iterable.\n//\n// Needed because tool execution is a plain `await`, not a generator, yet some\n// events MUST reach the UI while a tool is still running:\n//\n// • `awaiting-user` — a card asking for a decision. Buffering this until the\n// tool resolves deadlocks: the tool waits for the user, the user waits for\n// the card, and the card waits for the tool.\n// • `card` — progress updates from a long-running tool.\n// • `tool-result` — each call as it finishes, so a fast lookup is not held\n// back until the slowest call in the same step is done.\n//\n// Collecting events into an array and yielding them afterwards looks equivalent\n// and is not. This is the fix.\n\nexport class EventChannel<T> {\n private queue: T[] = [];\n private waiting: ((result: IteratorResult<T>) => void)[] = [];\n private closed = false;\n\n /** Enqueue an event, handing it straight to a waiting consumer if there is one. */\n push(value: T): void {\n if (this.closed) return;\n const resolve = this.waiting.shift();\n if (resolve) resolve({ value, done: false });\n else this.queue.push(value);\n }\n\n /** No more events. Consumers drain what is buffered, then finish. */\n close(): void {\n if (this.closed) return;\n this.closed = true;\n for (const resolve of this.waiting) resolve({ value: undefined as never, done: true });\n this.waiting = [];\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return {\n next: (): Promise<IteratorResult<T>> => {\n // Buffered events drain first, even after close, so nothing pushed\n // immediately before close() is lost.\n if (this.queue.length) return Promise.resolve({ value: this.queue.shift()!, done: false });\n if (this.closed) return Promise.resolve({ value: undefined as never, done: true });\n return new Promise((resolve) => this.waiting.push(resolve));\n },\n };\n }\n}\n","// The card a person sees before a `side: \"confirm\"` tool runs.\n//\n// It is written for the person approving the action, not for the model or a\n// developer: no tool names, package names or raw JSON. Those stay in the run\n// trace, where a developer can still find them.\n\nimport type { CardSpec } from \"../cards/types.js\";\nimport type { ToolApproval, ToolDefinition } from \"./types.js\";\n\nconst MAX_FIELDS = 6;\nconst MAX_VALUE_CHARS = 160;\nconst MAX_DESCRIPTION_CHARS = 240;\n\nconst clip = (text: string, max: number): string => (text.length > max ? `${text.slice(0, max - 1)}…` : text);\n\n/** \"documentId\" → \"Document\", \"max_retry_count\" → \"Max retry count\". */\nexport function humanizeFieldName(key: string): string {\n const words = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .split(/[\\s_\\-.]+/)\n .filter(Boolean)\n .map((word) => word.toLowerCase());\n if (words.length > 1 && (words[words.length - 1] === \"id\" || words[words.length - 1] === \"ids\")) words.pop();\n const text = words.join(\" \");\n return text ? text.charAt(0).toUpperCase() + text.slice(1) : key;\n}\n\n/** A value as plain text, or `undefined` when it has no short plain form. */\nfunction plainValue(value: unknown): string | undefined {\n if (typeof value === \"string\") return value.trim() ? clip(value.trim(), MAX_VALUE_CHARS) : undefined;\n if (typeof value === \"number\" || typeof value === \"bigint\") return String(value);\n if (typeof value === \"boolean\") return value ? \"Yes\" : \"No\";\n if (Array.isArray(value)) {\n const items = value.map(plainValue);\n if (value.length && items.every((item) => item !== undefined)) return clip(items.join(\", \"), MAX_VALUE_CHARS);\n return value.length === 1 ? \"1 item\" : `${value.length} items`;\n }\n return undefined;\n}\n\n/** The first sentence of a tool description: the part that says what it does. */\nfunction firstSentence(description: string): string {\n const text = description.trim().replace(/\\s+/g, \" \");\n const end = text.search(/[.!?](\\s|$)/);\n return clip(end === -1 ? text : text.slice(0, end + 1), MAX_DESCRIPTION_CHARS);\n}\n\nfunction fieldsOf(input: unknown): { label: string; value: string }[] {\n if (input === undefined || input === null) return [];\n if (typeof input !== \"object\" || Array.isArray(input)) {\n const value = plainValue(input);\n return value === undefined ? [] : [{ label: \"Details\", value }];\n }\n const fields: { label: string; value: string }[] = [];\n for (const [key, raw] of Object.entries(input)) {\n const value = plainValue(raw);\n if (value !== undefined) fields.push({ label: humanizeFieldName(key), value });\n if (fields.length === MAX_FIELDS) break;\n }\n return fields;\n}\n\nconst MAX_TITLE_CHARS = 120;\nconst MAX_LABEL_CHARS = 40;\n\nconst textOr = (value: unknown, max: number): string | undefined =>\n typeof value === \"string\" && value.trim() ? clip(value.trim().replace(/\\s+/g, \" \"), max) : undefined;\n\n/**\n * The tool's own wording, kept to plain text of sane length. A plugin's hook is code\n * the host does not control, so anything that is not a string is dropped.\n */\nfunction customApproval(tool: Pick<ToolDefinition, \"approval\">, input: unknown): ToolApproval | undefined {\n if (typeof tool.approval !== \"function\") return undefined;\n let raw: unknown;\n try {\n raw = tool.approval(input);\n } catch {\n // A broken copy hook must not block the approval itself.\n return undefined;\n }\n if (typeof raw !== \"object\" || raw === null) return undefined;\n const r = raw as Record<string, unknown>;\n const title = textOr(r[\"title\"], MAX_TITLE_CHARS);\n const description = textOr(r[\"description\"], MAX_DESCRIPTION_CHARS);\n const confirmLabel = textOr(r[\"confirmLabel\"], MAX_LABEL_CHARS);\n const cancelLabel = textOr(r[\"cancelLabel\"], MAX_LABEL_CHARS);\n const summary = Array.isArray(r[\"summary\"])\n ? r[\"summary\"].flatMap((row: unknown) => {\n const label = textOr((row as { label?: unknown } | null)?.label, MAX_LABEL_CHARS);\n const value = textOr((row as { value?: unknown } | null)?.value, MAX_VALUE_CHARS);\n return label && value ? [{ label, value }] : [];\n }).slice(0, MAX_FIELDS)\n : undefined;\n // Wording with neither a question nor a sentence says nothing; use the generic card.\n if (!title && !description) return undefined;\n return {\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n ...(summary ? { summary } : {}),\n ...(confirmLabel ? { confirmLabel } : {}),\n ...(cancelLabel ? { cancelLabel } : {}),\n ...(typeof r[\"danger\"] === \"boolean\" ? { danger: r[\"danger\"] } : {}),\n };\n}\n\n/**\n * The approval card for a tool call. A tool's own `approval` wording wins; without it\n * the card uses the first sentence of the description and the input's plain fields.\n */\nexport function approvalCard(\n tool: Pick<ToolDefinition, \"description\" | \"approval\">,\n input: unknown,\n options: { danger?: boolean } = {},\n): CardSpec {\n const custom = customApproval(tool, input);\n let description: string | undefined = custom?.description ?? firstSentence(tool.description);\n // A tool that words its own approval decides which details to list; without wording, the input's plain fields.\n let summary = custom ? (custom.summary ?? []) : fieldsOf(input);\n // With neither a sentence nor details there is nothing to approve but the bare act, so name it.\n if (!summary.length && !description) summary = [{ label: \"Action\", value: \"Run a tool\" }];\n description ||= undefined;\n const danger = custom?.danger ?? options.danger;\n return {\n kind: \"confirm\",\n title: custom?.title ?? \"Allow this?\",\n ...(description ? { description } : {}),\n summary,\n confirmLabel: custom?.confirmLabel ?? \"Allow\",\n cancelLabel: custom?.cancelLabel ?? \"Not now\",\n ...(danger ? { danger: true } : {}),\n };\n}\n","// Tool execution.\n//\n// Two rules that matter more than they look:\n//\n// 1. A tool that throws returns `{ error }` to the model, not an exception to\n// the caller. A model that reads \"no pool found for SUI/FOO\" picks a\n// different pool; a stack trace that kills the run teaches it nothing and\n// costs the user their turn.\n//\n// 2. Errors are COMPACTED. A raw error can be a 40KB stack that then rides in\n// history for the rest of the conversation, crowding out the actual work.\n//\n// 3. `side: \"confirm\"` is enforced HERE, on the one path every tool call takes,\n// whether a model or a button started it. No approval means no execution.\n\nimport { AgentError, toAgentError } from \"../errors.js\";\nimport { makeCard } from \"../cards/registry.js\";\nimport { CARD_KEY, isCardCarrier, withCard, type Card, type CardSpec } from \"../cards/types.js\";\nimport type { SurfaceLedger } from \"../surfaces/ledger.js\";\nimport { approvalCard } from \"../tools/approval.js\";\nimport type { ToolDefinition, ToolExecutionContext, ToolResult } from \"../tools/types.js\";\n\nexport type ToolCallRequest = { callId: string; name: string; input: unknown };\n\nexport type ToolCallOutcome = {\n callId: string;\n name: string;\n output: unknown;\n card?: Card;\n failure?: string;\n /** Tool names this outcome unlocked for the rest of the run (loadSkill). */\n unlockTools?: string[];\n ms: number;\n};\n\nconst MAX_ERROR_CHARS = 400;\n\n/**\n * What the model reads when the person says no to an approval. The same words\n * go into the `{ error }` of the denied result and into the `reason` of the\n * answer a tool that asks for itself receives, so `userDeclined` (stop.ts) can\n * tell a person's \"no\" from a host that cannot ask.\n */\nexport const USER_DECLINED = \"The user declined.\";\n\n/** Shrink an error to something worth carrying in history. */\nexport function compactError(e: unknown): { error: string; kind?: string } {\n if (e instanceof AgentError) {\n return { error: e.message.slice(0, MAX_ERROR_CHARS), kind: e.kind };\n }\n const message = e instanceof Error ? e.message : String(e);\n return { error: message.slice(0, MAX_ERROR_CHARS) || \"Tool failed with no message.\" };\n}\n\n\n/**\n * Why a `side: \"confirm\"` tool may not start, or `undefined` when it may. Anything\n * short of an explicit yes is a no: a host that cannot ask, a dismissed card, a\n * stopped run, an answer this code does not recognise.\n */\nasync function confirmationRefusal(tool: ToolDefinition, call: ToolCallRequest, opts: ExecuteToolOptions): Promise<string | undefined> {\n if (!opts.requestCard) return `\"${tool.name}\" needs the user's approval and this host cannot ask for it.`;\n if (tool.confirmation === \"tool\") return undefined;\n const answer = await opts.requestCard(call.callId, approvalCard(tool, call.input));\n if (opts.signal?.aborted) return \"The run was stopped before this was approved.\";\n return (answer as { confirmed?: unknown } | null | undefined)?.confirmed === true ? undefined : USER_DECLINED;\n}\n\nconst isToolResult = (v: unknown): v is ToolResult =>\n typeof v === \"object\" &&\n v !== null &&\n \"output\" in v &&\n Object.keys(v).every((k) => [\"output\", \"card\", \"failure\", \"cardId\", \"unlockTools\", \"placement\"].includes(k));\n\nexport type ExecuteToolOptions = {\n tools: readonly ToolDefinition[];\n vars: Record<string, unknown>;\n signal?: AbortSignal;\n timeoutMs?: number;\n onCard?: (card: Card) => void;\n /** Suspend and ask the user. Supplied by the runtime; resolves on a CardAction. */\n requestCard?: (callId: string, spec: CardSpec) => Promise<unknown>;\n /** Host-executed tools (no `execute`) are delegated here. */\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /**\n * `executeToolCalls` only: fires as each call settles, in COMPLETION order,\n * exactly once per call — failures and timeouts included. This is how a\n * fast result reaches the UI without waiting on the slowest call in the step.\n */\n onOutcome?: (outcome: ToolCallOutcome) => void;\n /**\n * Precomputed name→tool index. `executeToolCalls` builds this once per\n * batch and reuses it here instead of a linear `tools.find` per call; a\n * standalone `executeToolCall` caller can leave it unset and pay the scan.\n */\n toolIndex?: ReadonlyMap<string, ToolDefinition>;\n surfaces?: SurfaceLedger;\n surfaceActionTools?: readonly string[];\n};\n\nexport async function executeToolCall(call: ToolCallRequest, opts: ExecuteToolOptions): Promise<ToolCallOutcome> {\n const started = Date.now();\n const tool = opts.toolIndex ? opts.toolIndex.get(call.name) : opts.tools.find((t) => t.name === call.name);\n\n if (!tool) {\n // Name the tools that DO exist — a model that hallucinated a name recovers\n // from a list, and loops forever without one.\n return {\n callId: call.callId,\n name: call.name,\n output: {\n error: `Unknown tool \"${call.name}\".`,\n availableTools: opts.tools.map((t) => t.name),\n },\n failure: \"not-found\",\n ms: Date.now() - started,\n };\n }\n\n let emittedCard: Card | undefined;\n // A timed-out tool keeps running in the background. Once its outcome is\n // decided, anything it surfaces would land AFTER its own tool-result — a\n // progress card for a finished call, or a dialog nobody is waiting on.\n let settled = false;\n const ctx: ToolExecutionContext = {\n vars: opts.vars,\n signal: opts.signal,\n callId: call.callId,\n ...(opts.surfaces ? { surfaces: opts.surfaces } : {}),\n ...(opts.surfaceActionTools ? { surfaceActionTools: opts.surfaceActionTools } : {}),\n emitCard: (spec) => {\n if (settled) return;\n const card = makeCard(spec, call.callId);\n emittedCard = card;\n opts.onCard?.(card);\n },\n ...(opts.requestCard\n ? {\n requestCard: (spec: CardSpec) =>\n settled\n ? Promise.reject(new AgentError(\"cancelled\", `Tool \"${call.name}\" already finished.`))\n : opts.requestCard!(call.callId, spec),\n }\n : {}),\n };\n\n try {\n // Before the timeout starts: a person deciding is not a tool running slowly.\n if (tool.side === \"confirm\") {\n const refusal = await confirmationRefusal(tool, call, opts);\n if (refusal) return { callId: call.callId, name: call.name, output: { error: refusal }, failure: \"denied\", ms: Date.now() - started };\n }\n\n const raw = tool.execute\n ? await withTimeout(Promise.resolve(tool.execute(call.input, ctx)), opts.timeoutMs, call.name)\n : opts.onHostTool\n ? await withTimeout(opts.onHostTool(call), opts.timeoutMs, call.name)\n : (() => {\n throw new AgentError(\"not-supported\", `Tool \"${call.name}\" has no executor and no host handler.`);\n })();\n\n const result: ToolResult = isToolResult(raw) ? raw : { output: raw };\n\n // A tool may attach a card three ways, and all three must work — a tool\n // author should not have to know which one the runtime happens to check:\n // 1. `ctx.emitCard(spec)` mid-execution (progress on a long tool)\n // 2. `{ output, card: spec }` the explicit result field\n // 3. `withCard(output, spec)` embedded in the output under $card\n // Whichever is used, the card ends up BOTH surfaced to the UI and carried\n // inside the output — the latter so it survives persistence, since the\n // ContextBuilder strips it again before the next provider call.\n let card = emittedCard;\n let output = result.output;\n\n if (result.card) {\n card = makeCard(result.card, call.callId, result.cardId, result.placement === \"panel\" ? \"panel\" : undefined);\n output = withCard(asRecord(result.output), card.spec, card.id, card.placement);\n opts.onCard?.(card);\n } else if (isCardCarrier(result.output)) {\n const embedded = result.output[CARD_KEY];\n card = { ...embedded, callId: call.callId };\n opts.onCard?.(card);\n }\n\n return {\n callId: call.callId,\n name: call.name,\n output: explainMissingInput(tool, call.input, output, result.failure),\n ...(card ? { card } : {}),\n ...(result.failure ? { failure: result.failure } : {}),\n ...(result.unlockTools?.length ? { unlockTools: result.unlockTools } : {}),\n ms: Date.now() - started,\n };\n } catch (e) {\n const err = toAgentError(e);\n return {\n callId: call.callId,\n name: call.name,\n output: explainMissingInput(tool, call.input, compactError(err), err.kind === \"cancelled\" ? \"denied\" : err.kind === \"timeout\" ? \"timeout\" : \"execution-error\"),\n failure: err.kind === \"cancelled\" ? \"denied\" : \"execution-error\",\n ms: Date.now() - started,\n };\n } finally {\n settled = true;\n }\n}\n\nconst NOT_ABOUT_INPUT = new Set([\"denied\", \"timeout\", \"not-found\"]);\nconst MAX_DESCRIBED = 200;\n\n/**\n * A failed call that never named what the tool requires gets told exactly that.\n *\n * Models sometimes send a call with no arguments (`{}`) for a tool whose schema\n * lists required ones. The tool's own error then says something short and\n * tool-specific (\"No symbol given.\"), and a model that does not see why often\n * sends the identical call again. When the call failed AND a top-level\n * `required` key is absent from its input, this adds `missing` (the names) and\n * `expected` (each one's type, enum and description from the tool's own\n * schema) next to whatever the tool said, so the retry has something to fill.\n *\n * Additive on purpose: only failed outputs, never a rewrite of the tool's own\n * error, and nothing is checked on a call that succeeded — a tool may fall\n * back to a default for a required key (the chart in view) and that stays its\n * decision.\n */\nexport function explainMissingInput(tool: ToolDefinition, input: unknown, output: unknown, failure?: string): unknown {\n if (failure && NOT_ABOUT_INPUT.has(failure)) return output;\n if (typeof output !== \"object\" || output === null || Array.isArray(output)) return output;\n const out = output as Record<string, unknown>;\n const failed = failure !== undefined || (typeof out.error === \"string\" && out.ok !== true);\n if (!failed || \"missing\" in out || \"expected\" in out) return output;\n\n const schema = tool.inputSchema as { required?: unknown; properties?: unknown } | undefined;\n const required = Array.isArray(schema?.required) ? schema.required.filter((k): k is string => typeof k === \"string\") : [];\n if (!required.length) return output;\n const given = typeof input === \"object\" && input !== null && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n const missing = required.filter((k) => given[k] === undefined || given[k] === null);\n if (!missing.length) return output;\n\n const props = (typeof schema?.properties === \"object\" && schema.properties !== null ? schema.properties : {}) as Record<string, unknown>;\n const expected: Record<string, unknown> = {};\n for (const key of missing) expected[key] = describeProperty(props[key]);\n return { ...out, missing, expected };\n}\n\nfunction describeProperty(raw: unknown): Record<string, unknown> {\n if (typeof raw !== \"object\" || raw === null) return {};\n const p = raw as Record<string, unknown>;\n const d: Record<string, unknown> = {};\n for (const k of [\"type\", \"enum\", \"minimum\", \"maximum\"] as const) if (p[k] !== undefined) d[k] = p[k];\n if (typeof p.description === \"string\") {\n d.description = p.description.length > MAX_DESCRIBED ? `${p.description.slice(0, MAX_DESCRIBED)}…` : p.description;\n }\n return d;\n}\n\n/**\n * Execute a step's calls concurrently.\n *\n * Parallel because models emit independent calls in one step and running them\n * serially triples the latency of a three-lookup turn. Two orders, on purpose:\n * `onOutcome` reports each call as it FINISHES, so a 50ms lookup is not held\n * hostage by a 900ms one; the returned array is in CALL order, since that is\n * what gets written back to history and humans read the transcript top to\n * bottom.\n */\nexport async function executeToolCalls(\n calls: readonly ToolCallRequest[],\n opts: ExecuteToolOptions,\n): Promise<ToolCallOutcome[]> {\n // Built once for the whole batch and reused for both the interactive filter\n // below and every executeToolCall — a linear tools.find() per call, twice\n // over, is wasted work once the tool list is more than a handful long.\n const toolIndex = opts.toolIndex ?? new Map(opts.tools.map((t) => [t.name, t] as const));\n const callOpts: ExecuteToolOptions = opts.toolIndex ? opts : { ...opts, toolIndex };\n\n // Interactive tools must NOT run in parallel — two confirm dialogs racing for\n // the same user is not a thing a user can answer.\n const interactive = calls.filter((c) => toolIndex.get(c.name)?.side === \"confirm\");\n const concurrent = calls.filter((c) => !interactive.includes(c));\n\n // executeToolCall never rejects — every failure is already an outcome — so\n // this reports each call exactly once.\n const settle = async (c: ToolCallRequest) => {\n const outcome = await executeToolCall(c, callOpts);\n opts.onOutcome?.(outcome);\n return outcome;\n };\n\n const concurrentResults = await Promise.all(concurrent.map(settle));\n const serialResults: ToolCallOutcome[] = [];\n for (const c of interactive) serialResults.push(await settle(c));\n\n const byId = new Map([...concurrentResults, ...serialResults].map((r) => [r.callId, r]));\n return calls.map((c) => byId.get(c.callId)!).filter(Boolean);\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) return value as Record<string, unknown>;\n return { result: value };\n}\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number | undefined, name: string): Promise<T> {\n if (!ms) return promise;\n return Promise.race([\n promise,\n new Promise<never>((_, reject) =>\n setTimeout(() => reject(new AgentError(\"timeout\", `Tool \"${name}\" timed out after ${ms}ms.`)), ms),\n ),\n ]);\n}\n","import type { FinishReason, Usage } from \"../content/types.js\";\nimport type { AgentErrorKind } from \"../errors.js\";\nimport type { RunMode } from \"./events.js\";\n\n/**\n * Where the numbers in a metering record came from.\n *\n * Core currently only emits `provider` or `unavailable`. `estimated` and\n * `mixed` are reserved so hosts can enrich records without replacing this\n * contract when a provider omits usage.\n */\nexport type MeteringSource = \"provider\" | \"estimated\" | \"mixed\" | \"unavailable\";\n\n/** Terminal outcome of a provider step or the containing run. */\nexport type MeteringStatus = \"completed\" | \"failed\" | \"cancelled\";\n\nexport type MeteringError = {\n kind: AgentErrorKind;\n message: string;\n};\n\ntype MeteringBase = {\n /** Stable within a run; suitable as an idempotency key in a host ledger. */\n id: string;\n runId: string;\n provider: string;\n requestedModel: string;\n mode: RunMode;\n status: MeteringStatus;\n usage: Usage;\n source: MeteringSource;\n startedAt: number;\n finishedAt: number;\n durationMs: number;\n /** Host-owned dimensions. Core never interprets or sends these upstream. */\n metadata?: Readonly<Record<string, string>>;\n error?: MeteringError;\n};\n\n/** Exactly one terminal record is emitted for every attempted provider call. */\nexport type StepMeteringRecord = MeteringBase & {\n scope: \"step\";\n step: number;\n /** The provider's actual model, when it reports one. */\n reportedModel?: string;\n responseId?: string;\n finishReason?: FinishReason;\n};\n\n/** Exactly one summary record is emitted when a run terminates. */\nexport type RunMeteringRecord = MeteringBase & {\n scope: \"run\";\n steps: number;\n finishReason: FinishReason;\n /** Unique actual model ids observed across completed steps. */\n reportedModels?: string[];\n};\n\nexport type MeteringRecord = StepMeteringRecord | RunMeteringRecord;\n\n/**\n * Optional delivery target in addition to the public `metering` RunEvent.\n *\n * Delivery is awaited to preserve ordering. A sink failure is fail-open: it\n * is reported to `onError`, when supplied, but never changes the agent run.\n * Durable storage, retries and pricing remain host responsibilities.\n */\nexport type MeterSink = {\n record(record: MeteringRecord): void | Promise<void>;\n onError?(error: unknown, record: MeteringRecord): void | Promise<void>;\n};\n\nexport function usageSource(usage: Usage): MeteringSource {\n return Object.values(usage).some((value) => typeof value === \"number\") ? \"provider\" : \"unavailable\";\n}\n\nexport function combineMeteringSources(sources: readonly MeteringSource[]): MeteringSource {\n if (!sources.length) return \"unavailable\";\n const unique = new Set(sources);\n return unique.size === 1 ? sources[0]! : \"mixed\";\n}\n\nexport async function deliverMetering(sink: MeterSink | undefined, record: MeteringRecord): Promise<void> {\n if (!sink) return;\n try {\n await sink.record(record);\n } catch (error) {\n try {\n await sink.onError?.(error, record);\n } catch {\n // Observability must not change the run it observes.\n }\n }\n}\n","// A tool call that a person started by pressing a button.\n//\n// It goes through `executeToolCall`, the function a model's call goes through, and\n// emits the same run events. So a `confirm` tool asks with the same card, a card it\n// returns lands in the transcript, and the next model turn can read what happened.\n// There is deliberately no second, lighter path for \"the user clicked it\": the spec\n// that put the button there was written by a model.\n\nimport { nextId } from \"../content/parts.js\";\nimport type { FinishReason } from \"../content/types.js\";\nimport { makeCard } from \"../cards/registry.js\";\nimport type { Card, CardAction, CardSpec } from \"../cards/types.js\";\nimport { EventChannel } from \"../runtime/channel.js\";\nimport type { RunEvent } from \"../runtime/events.js\";\nimport { executeToolCall, type ToolCallRequest } from \"../runtime/execute-tools.js\";\nimport { deliverMetering, type MeterSink, type MeteringRecord } from \"../runtime/metering.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\nimport type { ToolDefinition, ToolResolution } from \"../tools/types.js\";\nimport { checkSchema } from \"./schema-check.js\";\nimport { SURFACE_TOOL_NAMES } from \"./tools.js\";\n\n/** Tools about the conversation itself. A button has no business calling these. */\nconst NOT_ACTIONABLE = new Set<string>([...SURFACE_TOOL_NAMES, \"visualize\", \"updateCard\", \"loadSkill\"]);\n\n/**\n * What a surface action may call right now: the presets' grant, with deny applied.\n * `allow` is left out on purpose. A skill grants relevance for a turn, not authority\n * that outlives it on a button.\n */\nexport function surfaceActionTools(tools: ToolRegistry, resolution: ToolResolution): ToolDefinition[] {\n return tools\n .resolve({ presets: resolution.presets, ...(resolution.deny ? { deny: resolution.deny } : {}) })\n .filter((t) => !NOT_ACTIONABLE.has(t.name));\n}\n\nexport type SurfaceToolAuthorization = { ok: true; tool: ToolDefinition } | { ok: false; reason: string };\n\n/** Decided at the moment of the press. What was allowed when the surface was drawn may not be now. */\nexport function authorizeSurfaceTool(name: string, args: unknown, tools: ToolRegistry, resolution: ToolResolution): SurfaceToolAuthorization {\n const tool = surfaceActionTools(tools, resolution).find((t) => t.name === name);\n if (!tool) return { ok: false, reason: `\"${name}\" is not permitted here.` };\n const problems = checkSchema(tool.inputSchema, args ?? {});\n if (problems.length) return { ok: false, reason: `\"${name}\" received invalid input: ${problems[0]!.message}` };\n return { ok: true, tool };\n}\n\nexport type SurfaceToolRunConfig = {\n tool: ToolDefinition;\n args: Record<string, unknown>;\n surfaceId: string;\n componentId: string;\n provider: string;\n model: string;\n vars?: Record<string, unknown>;\n signal?: AbortSignal;\n toolTimeoutMs?: number;\n meter?: MeterSink;\n meteringMetadata?: Readonly<Record<string, string>>;\n onUserDecision?: (callId: string, card: Card) => Promise<CardAction>;\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n};\n\nexport async function* runSurfaceToolAction(config: SurfaceToolRunConfig): AsyncGenerator<RunEvent, void, unknown> {\n const runId = nextId(\"run\");\n const callId = nextId(\"call_surface\");\n const startedAt = Date.now();\n yield { type: \"run-start\", runId, mode: \"sync\" };\n yield { type: \"step-start\", step: 0 };\n yield { type: \"tool-call\", callId, name: config.tool.name, input: config.args };\n\n const channel = new EventChannel<RunEvent>();\n const onUserDecision = config.onUserDecision;\n const running = executeToolCall(\n { callId, name: config.tool.name, input: config.args },\n {\n tools: [config.tool],\n vars: config.vars ?? {},\n signal: config.signal,\n timeoutMs: config.toolTimeoutMs,\n onCard: (card) => channel.push({ type: \"card\", card }),\n onHostTool: config.onHostTool,\n requestCard: onUserDecision\n ? async (id, spec: CardSpec) => {\n const card = makeCard(spec, id);\n channel.push({ type: \"awaiting-user\", callId: id, card });\n const action = await onUserDecision(id, card);\n channel.push({ type: \"user-responded\", callId: id, action });\n return action.type === \"cancel\" || action.type === \"dismiss\"\n ? { cancelled: true, reason: \"The user declined.\" }\n : (action.value ?? { confirmed: true });\n }\n : undefined,\n },\n ).then((outcome) => {\n channel.push({\n type: \"tool-result\",\n callId: outcome.callId,\n name: outcome.name,\n output: outcome.output,\n ...(outcome.failure ? { failure: outcome.failure } : {}),\n ms: outcome.ms,\n });\n return outcome;\n }).finally(() => channel.close());\n\n for await (const event of channel) yield event;\n const outcome = await running;\n\n // A tool action spends no tokens, but it is still an act a host may need to\n // account for, so it produces the same terminal record as any other run.\n const finishedAt = Date.now();\n const finishReason: FinishReason = outcome.failure === \"denied\" && config.signal?.aborted ? \"cancelled\" : \"stop\";\n const record: MeteringRecord = {\n scope: \"run\",\n id: `${runId}:run`,\n runId,\n provider: config.provider,\n requestedModel: config.model,\n mode: \"sync\",\n status: finishReason === \"cancelled\" ? \"cancelled\" : outcome.failure ? \"failed\" : \"completed\",\n usage: {},\n source: \"unavailable\",\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n steps: 0,\n finishReason,\n metadata: { ...config.meteringMetadata, trigger: \"surface-action\", surfaceId: config.surfaceId, componentId: config.componentId, tool: config.tool.name },\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"run-finish\", runId, finishReason, usage: {}, steps: 0 };\n}\n","// One-way export to A2UI v0.9.1 messages (a2ui.org), with no runtime dependency.\n//\n// The formats share their structure: a flat list, ids for children, JSON Pointers\n// for data. Components with a basic-catalogue counterpart are renamed to it; the\n// rest keep their names and rely on this catalogue id, as A2UI's custom catalogues\n// allow. `$query`, `set` and `tool` have no A2UI equivalent and travel as namespaced\n// function calls and events that a receiving client would have to implement.\n\nimport { isSurfaceBinding } from \"./bindings.js\";\nimport type { SurfaceAction, SurfaceComponent, SurfaceSpec } from \"./types.js\";\n\nexport const A2UI_VERSION = \"v0.9.1\" as const;\nexport const SURFACE_A2UI_CATALOG_ID = \"urn:supersolutions:super-chat:surface-catalog:v1\" as const;\n\nexport type A2uiMessage =\n | { version: typeof A2UI_VERSION; createSurface: { surfaceId: string; catalogId: string; sendDataModel: boolean } }\n | { version: typeof A2UI_VERSION; updateComponents: { surfaceId: string; components: Record<string, unknown>[] } }\n | { version: typeof A2UI_VERSION; updateDataModel: { surfaceId: string; path: string; value: unknown } }\n | { version: typeof A2UI_VERSION; deleteSurface: { surfaceId: string } };\n\nconst toDynamic = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(toDynamic);\n if (typeof value !== \"object\" || value === null) return value;\n if (isSurfaceBinding(value)) {\n if (\"$path\" in value) return { path: value.$path };\n if (\"$item\" in value) return { path: value.$item };\n if (\"$template\" in value) {\n return { call: \"formatString\", args: { value: value.$template.replace(/\\{(\\/[^{}]*)\\}/g, \"$${$1}\").replace(/\\{\\.([^{}]*)\\}/g, \"$${$1}\") } };\n }\n return { call: \"superchat.query\", args: toDynamic(value.$query) };\n }\n return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, toDynamic(v)]));\n};\n\nconst toAction = (action: SurfaceAction): unknown => {\n switch (action.type) {\n case \"event\":\n return { event: { name: action.name, ...(action.context ? { context: toDynamic(action.context) } : {}) } };\n case \"set\":\n return { functionCall: { call: \"superchat.set\", args: { updates: toDynamic(action.updates) } } };\n case \"tool\":\n return { event: { name: \"superchat.tool\", context: toDynamic({ tool: action.tool, args: action.args ?? {}, resultPath: action.resultPath }) } };\n }\n};\n\nconst TEXT_VARIANTS: Record<string, string> = { title: \"h2\", heading: \"h4\", body: \"body\", caption: \"caption\", label: \"caption\", code: \"body\" };\n\nfunction toComponents(component: SurfaceComponent, rename: (id: string) => string): Record<string, unknown>[] {\n const { id, component: name, visibleWhen: _visibleWhen, ...rest } = component;\n const base = { id: rename(id) };\n const props = toDynamic(rest) as Record<string, unknown>;\n const children = Array.isArray(rest[\"children\"]) ? (rest[\"children\"] as string[]).map(rename) : undefined;\n\n switch (name) {\n case \"Stack\":\n return [{ ...base, component: rest[\"direction\"] === \"horizontal\" ? \"Row\" : \"Column\", children, ...(rest[\"justify\"] ? { justify: rest[\"justify\"] === \"between\" ? \"spaceBetween\" : rest[\"justify\"] } : {}), ...(rest[\"align\"] ? { align: rest[\"align\"] } : {}) }];\n case \"Text\":\n return [{ ...base, component: \"Text\", text: props[\"text\"], ...(typeof rest[\"variant\"] === \"string\" ? { variant: TEXT_VARIANTS[rest[\"variant\"]] } : {}) }];\n case \"Image\":\n return [{ ...base, component: \"Image\", url: props[\"src\"] }];\n case \"Divider\":\n return [{ ...base, component: \"Divider\" }];\n case \"Tabs\":\n return [{ ...base, component: \"Tabs\", tabs: (rest[\"tabs\"] as { label: string; child: string }[]).map((t) => ({ title: t.label, child: rename(t.child) })) }];\n case \"List\": {\n const items = rest[\"items\"];\n const path = isSurfaceBinding(items) && \"$path\" in items ? items.$path : undefined;\n return path\n ? [{ ...base, component: \"List\", children: { path, componentId: rename(rest[\"child\"] as string) } }]\n : [{ ...base, component: name, ...props, child: rename(rest[\"child\"] as string) }];\n }\n case \"Field\":\n return [{ ...base, component: rest[\"type\"] === \"date\" ? \"DateTimeInput\" : \"TextField\", label: props[\"label\"], value: props[\"value\"] }];\n case \"Select\":\n return [{ ...base, component: \"ChoicePicker\", label: props[\"label\"], value: props[\"value\"], options: props[\"options\"], variant: \"mutuallyExclusive\" }];\n case \"Toggle\":\n return [{ ...base, component: \"CheckBox\", label: props[\"label\"], value: props[\"value\"] }];\n case \"Slider\":\n return [{ ...base, component: \"Slider\", label: props[\"label\"], value: props[\"value\"], min: props[\"min\"], max: props[\"max\"] }];\n case \"Button\": {\n const labelId = rename(`${id}__label`);\n return [\n { ...base, component: \"Button\", child: labelId, variant: rest[\"variant\"] === \"primary\" ? \"primary\" : \"borderless\", action: toAction(rest[\"action\"] as SurfaceAction) },\n { id: labelId, component: \"Text\", text: props[\"label\"] },\n ];\n }\n default:\n return [{ ...base, component: name, ...props, ...(children ? { children } : {}) }];\n }\n}\n\n/** The messages that would recreate this surface in an A2UI client. */\nexport function toA2uiMessages(spec: SurfaceSpec): A2uiMessage[] {\n const { surfaceId } = spec;\n if (spec.deleted) return [{ version: A2UI_VERSION, deleteSurface: { surfaceId } }];\n // A2UI requires the top component to be called \"root\".\n const rename = (id: string) => (id === spec.root ? \"root\" : id === \"root\" ? `${spec.root}__swapped` : id);\n return [\n { version: A2UI_VERSION, createSurface: { surfaceId, catalogId: SURFACE_A2UI_CATALOG_ID, sendDataModel: true } },\n { version: A2UI_VERSION, updateComponents: { surfaceId, components: spec.components.flatMap((c) => toComponents(c, rename)) } },\n { version: A2UI_VERSION, updateDataModel: { surfaceId, path: \"/\", value: spec.data } },\n ];\n}\n","// Tool definitions and capability presets.\n//\n// Presets are EXPLICIT ALLOWLISTS, not blocklists. A newly registered tool is\n// invisible until someone puts it in a preset. The inverse (everything exposed\n// unless denied) means the day you add `deleteEverything` it is already live on\n// every API key you ever minted.\n//\n// Three preset tiers cover most agent products, and they map to genuinely\n// different trust levels rather than arbitrary groupings:\n// observer — pure reads. Safe to hand to anyone.\n// draft — produces something the USER must approve/sign. No side effects.\n// executor — acts on the user's behalf. Needs explicit, scoped authorization.\n// Hosts can define their own tiers; these are just the defaults.\n\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { Card, CardSpec } from \"../cards/types.js\";\nimport type { SurfaceLedger } from \"../surfaces/ledger.js\";\n\nexport type ToolSide = \"read\" | \"write\" | \"confirm\";\n\n/**\n * A truthful preview of the output geometry while a tool is still running.\n *\n * This is host-only metadata: providers never see it. A function is useful for\n * tools such as image generation where count and aspect ratio come from the\n * call input rather than from the tool definition alone.\n */\nexport type ToolLoadingHint = {\n kind: \"media\" | \"chart\" | \"table\" | \"document\" | \"generic\";\n label: string;\n count?: number;\n /** CSS-compatible ratio, for example `1024 / 1536`. */\n aspectRatio?: string;\n};\n\nexport type ToolLoading = ToolLoadingHint | ((input: unknown) => ToolLoadingHint | undefined);\n\nexport type ToolExecutionContext = {\n /** Host-supplied per-run values: user id, session, network, locale. */\n vars: Record<string, unknown>;\n signal?: AbortSignal;\n /** The tool call's id, for correlating a card back to it. */\n callId: string;\n /** Emit a card mid-execution (progress updates on a long tool). */\n emitCard?: (spec: CardSpec) => void;\n /** Ask the user something and await the answer. Absent when this host cannot ask. */\n requestCard?: (spec: CardSpec) => Promise<unknown>;\n /** The surfaces on this conversation's active path, as this run sees them. */\n surfaces?: SurfaceLedger;\n /** Tools a surface button may call in this run. */\n surfaceActionTools?: readonly string[];\n};\n\nexport type ToolResultExtras = {\n /**\n * Where the card should be shown: `inline` (the default) or `panel`, the host's side panel.\n * Ignored without a card; an interactive card stays inline whatever is asked.\n */\n placement?: \"inline\" | \"panel\";\n /**\n * Update an EXISTING card instead of minting a new one: the runtime reuses\n * this id, and the reducer's upsert replaces the old card in place.\n */\n cardId?: string;\n /**\n * Tool names this result unlocks for the REST of the run (`loadSkill`'s pull\n * half). The runtime re-resolves the active set and re-declares specs to the\n * provider from the next step on.\n */\n unlockTools?: string[];\n};\n\nexport type ToolResult = ToolResultExtras & {\n /** What the model sees. Keep it small — this is re-sent every subsequent step. */\n output: unknown;\n /** What the user sees. Not sent to the model. */\n card?: CardSpec;\n failure?: \"execution-error\" | \"denied\" | \"invalid-input\" | \"timeout\" | \"not-found\";\n};\n\n/**\n * How an approval card reads, in the words of the person approving. The card shows\n * `description`, then any `summary` rows, then `title` as the question above the buttons.\n */\nexport type ToolApproval = {\n /** The one question the buttons answer, such as \"Rename the report?\". */\n title?: string;\n /** What will happen, in a sentence or two, such as \"Your report will be titled “Q3 review”.\". */\n description?: string;\n /** Exact details worth checking: amounts, targets, anything irreversible. Omit when the sentence says it all. */\n summary?: { label: string; value: string }[];\n /** The verb on the approve button, such as \"Rename\". Defaults to \"Allow\". */\n confirmLabel?: string;\n /** Defaults to \"Not now\". */\n cancelLabel?: string;\n /** Marks an action that is hard to undo. */\n danger?: boolean;\n};\n\nexport type ToolDefinition = {\n name: string;\n description: string;\n inputSchema: JSONSchema;\n /**\n * Absent `execute` means the HOST runs this tool (browser-side: read the DOM,\n * open a wallet, use a local file). The runtime emits a `tool-call` event and\n * suspends until the host supplies a result.\n */\n execute?: (input: unknown, ctx: ToolExecutionContext) => Promise<ToolResult | unknown> | ToolResult | unknown;\n /**\n * `confirm` suspends the run and shows an approval card before executing.\n * The distinction from `write` is intent: `write` acts, `confirm` asks first.\n * The runtime enforces this: with no approval, and no way to get one, the tool\n * does not run.\n */\n side?: ToolSide;\n /**\n * Who asks, for a `side: \"confirm\"` tool. `\"runtime\"` (the default) shows a\n * generic approval card before the tool starts. `\"tool\"` is for a tool whose\n * approval needs something only it can compute, such as a diff: it must call\n * `ctx.requestCard` itself before acting. A tool that asks for itself without\n * saying so is asked about twice, which is the safe way for that to go wrong.\n */\n confirmation?: \"runtime\" | \"tool\";\n /**\n * The approval card's wording, written for the person approving the action. Without\n * it the card shows the first sentence of `description` and the input's plain fields.\n * Never shown to the model.\n */\n approval?: (input: unknown) => ToolApproval | undefined;\n /** Ask the provider to enforce the schema (OpenAI strict mode). */\n strict?: boolean;\n /** Default card renderer key when the result carries no explicit card. */\n render?: string;\n /** Rough token cost of a typical result, for budgeting. */\n costHint?: number;\n /** Live-only output placeholder. Omit when the result's shape is unknown. */\n loading?: ToolLoading;\n /**\n * For a tool whose ARGUMENTS are a card (`visualize` is the built-in one):\n * a preview of that card from arguments that are still streaming. Called\n * with each tolerant parse of the partial JSON; return `undefined` until\n * there is something worth drawing. Route it through\n * `CardRegistry.partial` so interactive kinds and specs that fail\n * validation never preview. Live-only — the validated card from `execute`\n * replaces it, and it is never written to history.\n *\n * A tool whose card is computed BY `execute` has nothing to preview here:\n * the arguments are a query, not the answer.\n */\n partialCard?: (partialInput: unknown) => CardSpec | undefined;\n};\n\n/** Resolve a tool's streaming card preview; a throwing hook means \"no preview\", never a failed call. */\nexport function resolvePartialCard(tool: ToolDefinition | undefined, partialInput: unknown): CardSpec | undefined {\n if (!tool?.partialCard) return undefined;\n try {\n return tool.partialCard(partialInput);\n } catch {\n return undefined;\n }\n}\n\n/** Resolve a static or input-derived loading hint without leaking a function into run events. */\nexport function resolveToolLoading(loading: ToolLoading | undefined, input: unknown): ToolLoadingHint | undefined {\n try {\n return typeof loading === \"function\" ? loading(input) : loading;\n } catch {\n // Presentation metadata must never be able to fail the tool call itself.\n return undefined;\n }\n}\n\nexport type PresetName = string;\n\nexport type ToolResolution = {\n /** Preset names enabled for this run. */\n presets: readonly PresetName[];\n /** Extra tools unlocked beyond the presets (skills unlock their own tools). */\n allow?: readonly string[];\n /** Removed even if a preset grants them. Applied last. */\n deny?: readonly string[];\n};\n\nexport const DEFAULT_PRESETS = [\"observer\", \"draft\", \"executor\"] as const;\n","import type { ToolSpec } from \"../providers/types.js\";\nimport { normalizeToolName } from \"./repair.js\";\nimport type { PresetName, ToolDefinition, ToolResolution } from \"./types.js\";\n\n/**\n * The tool registry. Holds definitions, maps preset → allowlist, and renders the\n * provider-facing `ToolSpec[]`.\n *\n * `resolve()` is the only way to get a tool set, and it always applies deny\n * last — so a host-level kill switch cannot be re-granted by a preset or by a\n * skill unlocking a tool.\n */\nexport class ToolRegistry {\n private tools = new Map<string, ToolDefinition>();\n private presets = new Map<PresetName, Set<string>>();\n private listeners = new Set<() => void>();\n private version = 0;\n // Reverse of `presets`: tool name → presets that grant it. Lazily rebuilt —\n // `touch()` just nulls it out, so a burst of register()/addToPreset() calls\n // pays for one rebuild on the next presetsFor()/resolve(), not one per call.\n private reversePresetIndex: Map<string, PresetName[]> | null = null;\n\n constructor(tools: readonly ToolDefinition[] = []) {\n for (const t of tools) this.register(t);\n }\n\n register(tool: ToolDefinition, presets: readonly PresetName[] = []): this {\n this.tools.set(tool.name, tool);\n for (const p of presets) this.addToPreset(p, tool.name);\n this.touch();\n return this;\n }\n\n /** Register several tools into the same preset — the common bulk case. */\n registerAll(tools: readonly ToolDefinition[], presets: readonly PresetName[] = []): this {\n for (const t of tools) this.register(t, presets);\n return this;\n }\n\n addToPreset(preset: PresetName, ...names: string[]): this {\n const set = this.presets.get(preset) ?? new Set<string>();\n for (const n of names) set.add(n);\n this.presets.set(preset, set);\n this.touch();\n return this;\n }\n\n /**\n * Change notification, so a UI (or an inspector hook) re-reads after a LATE\n * registration — tools imported from an MCP server arrive long after mount,\n * and a registry nobody can observe leaves them invisible until reload.\n */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Monotonic change counter — a stable snapshot value for useSyncExternalStore. */\n getVersion(): number {\n return this.version;\n }\n\n private touch(): void {\n this.version += 1;\n this.reversePresetIndex = null;\n for (const l of this.listeners) l();\n }\n\n get(name: string): ToolDefinition | undefined {\n // Tolerate router-namespaced names (\"functions.getPrice\") so a call from a\n // provider that rewrites names still dispatches.\n return this.tools.get(name) ?? this.tools.get(normalizeToolName(name));\n }\n\n has(name: string): boolean {\n return this.get(name) !== undefined;\n }\n\n list(): ToolDefinition[] {\n return [...this.tools.values()];\n }\n\n presetNames(): PresetName[] {\n return [...this.presets.keys()];\n }\n\n /** Tool names in a preset that are actually registered. */\n namesInPreset(preset: PresetName): string[] {\n return [...(this.presets.get(preset) ?? [])].filter((n) => this.tools.has(n)).sort();\n }\n\n /** Which presets grant `name`. Used by the UI to explain why a tool is available. */\n presetsFor(name: string): PresetName[] {\n return this.reverseIndex().get(name) ?? [];\n }\n\n /** Tool name → presets that grant it, rebuilt on demand after the last mutation. */\n private reverseIndex(): Map<string, PresetName[]> {\n if (this.reversePresetIndex) return this.reversePresetIndex;\n const index = new Map<string, PresetName[]>();\n for (const [preset, names] of this.presets) {\n for (const name of names) {\n const grants = index.get(name);\n if (grants) grants.push(preset);\n else index.set(name, [preset]);\n }\n }\n this.reversePresetIndex = index;\n return index;\n }\n\n /**\n * Resolve the tool set for a run.\n *\n * Two distinct grants, and keeping them separate is a security property:\n *\n * PRESETS grant AUTHORITY. Whether the caller may act at all.\n * `allow` grants RELEVANCE. Usually a matched skill saying \"these are the\n * tools my instructions describe\".\n *\n * A skill must therefore never be able to escalate past the capability tier.\n * So `allow` can surface a tool that belongs to NO preset (private by\n * default, unlocked by the skill that documents it), but a tool that IS in a\n * preset still requires that preset to be enabled. Otherwise any skill could\n * hand out the executor tier just by naming a tool.\n *\n * A name listed in a preset but never registered is skipped rather than\n * throwing — presets are configuration and often outlive the tools they name.\n */\n resolve(resolution: ToolResolution): ToolDefinition[] {\n const allowed = new Set<string>();\n for (const preset of resolution.presets) {\n for (const name of this.presets.get(preset) ?? []) allowed.add(name);\n }\n for (const name of resolution.allow ?? []) {\n const grants = this.presetsFor(name);\n const skillGated = grants.length === 0;\n const withinTier = grants.some((g) => resolution.presets.includes(g));\n if (skillGated || withinTier) allowed.add(name);\n }\n for (const name of resolution.deny ?? []) allowed.delete(name);\n\n return [...allowed]\n .map((n) => this.tools.get(n))\n .filter((t): t is ToolDefinition => t !== undefined)\n .sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /** Provider-facing specs. The adapter turns these into its own wire shape. */\n toSpecs(tools: readonly ToolDefinition[]): ToolSpec[] {\n return tools.map((t) => ({\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict ? { strict: true } : {}),\n }));\n }\n\n /** Tools whose execution happens on the host, not here. */\n hostExecuted(tools: readonly ToolDefinition[]): string[] {\n return tools.filter((t) => typeof t.execute !== \"function\").map((t) => t.name);\n }\n}\n","// Tolerant, incremental JSON for tool arguments that are still streaming.\n//\n// A provider streams a tool call's arguments as raw JSON fragments, and the\n// only thing a UI can do with `{\"kind\":\"table\",\"spec\":{\"columns\":[{\"key\":\"na`\n// is wait — unless something can read it as \"a table spec whose columns have\n// started\". This is that something.\n//\n// What it promises, and what it does not:\n// • Every snapshot is a value `JSON.parse` could have produced from SOME\n// prefix-completion of the input: open containers are closed, an open\n// string VALUE shows the characters received so far.\n// • An open KEY is never shown — `{\"ti` is `{}`, not `{ ti: undefined }`.\n// • An unterminated NUMBER is never shown either. `12` may be the start of\n// `1200`, and a magnitude that is wrong by a factor of a hundred is worse\n// than one that is late. A truncated string reads as truncated; a\n// truncated number reads as a different number.\n// • Literals (`true`/`false`/`null`) appear only once complete.\n// • A half-received escape (`\\`, `\\u00`) and a lone high surrogate are held\n// back until the rest arrives, so a snapshot never contains a broken char.\n// • Prose or a ``` fence before the first `{`/`[` is skipped. Anything else\n// malformed FREEZES the parser at its last good snapshot rather than\n// guessing — the authoritative, repaired and validated value still arrives\n// with the provider's `tool-call-end`. This is a preview, never a source of\n// truth.\n//\n// Incremental rather than re-parse-per-delta because a long spec arrives in\n// thousands of fragments: re-reading the whole accumulated string each time is\n// quadratic over the call. Here each character is read once, and a snapshot\n// copies only the chain of containers that are still open — every finished\n// object or array is frozen and SHARED between snapshots, so a table that has\n// received 200 rows hands the UI the same 199 row objects it saw last time.\n\ntype ObjectFrame = {\n type: \"object\";\n value: Record<string, unknown>;\n /** The key whose value is being read, once its closing quote has arrived. */\n key: string | undefined;\n expect: \"key\" | \"colon\" | \"value\" | \"comma\";\n};\ntype ArrayFrame = { type: \"array\"; value: unknown[]; expect: \"value\" | \"comma\" };\ntype Frame = ObjectFrame | ArrayFrame;\n\ntype Token =\n | { type: \"string\"; isKey: boolean; text: string; escape: \"\" | \"\\\\\" | \"u\"; hex: string }\n | { type: \"number\"; text: string }\n | { type: \"literal\"; text: string };\n\nconst QUOTE = 0x22;\nconst BACKSLASH = 0x5c;\nconst ESCAPES: Record<string, string> = { '\"': '\"', \"\\\\\": \"\\\\\", \"/\": \"/\", b: \"\\b\", f: \"\\f\", n: \"\\n\", r: \"\\r\", t: \"\\t\" };\nconst LITERALS: Record<string, unknown> = { true: true, false: false, null: null };\nconst NUMBER = /^-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\nconst HEX = /^[0-9a-fA-F]$/;\nconst isSpace = (c: string) => c === \" \" || c === \"\\n\" || c === \"\\r\" || c === \"\\t\";\nconst isNumberChar = (c: string) => (c >= \"0\" && c <= \"9\") || c === \"-\" || c === \"+\" || c === \".\" || c === \"e\" || c === \"E\";\n\n/** JSON.parse semantics for an own `__proto__` key: a data property, not a prototype swap. */\nfunction setOwn(target: Record<string, unknown>, key: string, value: unknown): void {\n if (key === \"__proto__\") Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n else target[key] = value;\n}\n\n/** Drop a trailing high surrogate whose low half has not arrived yet. */\nfunction visible(text: string): string {\n const last = text.charCodeAt(text.length - 1);\n return last >= 0xd800 && last <= 0xdbff ? text.slice(0, -1) : text;\n}\n\nexport class PartialJsonParser {\n private stack: Frame[] = [];\n private token: Token | null = null;\n private root: unknown = undefined;\n private started = false;\n private done = false;\n private broken = false;\n private changes = 0;\n private cache: { at: number; value: unknown } | null = null;\n\n /** True once the top-level value has closed. Input after it is ignored. */\n get complete(): boolean {\n return this.done;\n }\n\n /** True once the input stopped being JSON. The parser keeps its last good snapshot. */\n get failed(): boolean {\n return this.broken;\n }\n\n /**\n * Bumped whenever the snapshot would differ. Compare against the value you\n * last rendered to skip deltas that changed nothing visible — whitespace, a\n * key's characters, the digits of an unfinished number.\n */\n get version(): number {\n return this.changes;\n }\n\n push(chunk: string): void {\n let i = 0;\n const len = chunk.length;\n while (i < len && !this.done && !this.broken) {\n const token = this.token;\n if (token?.type === \"string\") {\n i = this.readString(token, chunk, i);\n continue;\n }\n const c = chunk[i]!;\n if (token?.type === \"number\") {\n if (isNumberChar(c)) {\n token.text += c;\n i += 1;\n continue;\n }\n this.token = null;\n if (!NUMBER.test(token.text)) {\n this.broken = true;\n return;\n }\n this.assign(Number(token.text));\n continue; // `c` still needs reading: it is what ended the number\n }\n if (token?.type === \"literal\") {\n token.text += c;\n i += 1;\n if (Object.hasOwn(LITERALS, token.text)) {\n this.token = null;\n this.assign(LITERALS[token.text]);\n } else if (!Object.keys(LITERALS).some((l) => l.startsWith(token.text))) {\n this.broken = true;\n }\n continue;\n }\n i += 1;\n if (isSpace(c)) continue;\n this.structural(c);\n }\n }\n\n /**\n * The value as far as it has arrived, or `undefined` before the top-level\n * container opens. Stable by reference until `version` changes.\n */\n snapshot(): unknown {\n if (this.done) return this.root;\n if (this.cache?.at === this.changes) return this.cache.value;\n let child: unknown = undefined;\n let hasChild = false;\n if (this.token?.type === \"string\" && !this.token.isKey) {\n child = visible(this.token.text);\n hasChild = true;\n }\n for (let i = this.stack.length - 1; i >= 0; i -= 1) {\n const frame = this.stack[i]!;\n if (frame.type === \"object\") {\n const copy = { ...frame.value };\n if (hasChild && frame.key !== undefined) setOwn(copy, frame.key, child);\n child = copy;\n } else {\n const copy = frame.value.slice();\n if (hasChild) copy.push(child);\n child = copy;\n }\n hasChild = true;\n }\n this.cache = { at: this.changes, value: child };\n return child;\n }\n\n private structural(c: string): void {\n const frame = this.stack[this.stack.length - 1];\n if (!frame) {\n // Before the root: tolerate whatever a model wraps JSON in. After it,\n // `done` has already stopped the loop.\n if (c === \"{\" || c === \"[\") {\n this.started = true;\n this.open(c);\n }\n return;\n }\n if (frame.type === \"object\") {\n switch (frame.expect) {\n case \"key\":\n if (c === '\"') this.token = { type: \"string\", isKey: true, text: \"\", escape: \"\", hex: \"\" };\n else if (c === \"}\") this.close(); // `{}`, or a trailing comma\n else this.broken = true;\n return;\n case \"colon\":\n if (c === \":\") frame.expect = \"value\";\n else this.broken = true;\n return;\n case \"value\":\n this.startValue(c);\n return;\n case \"comma\":\n if (c === \",\") frame.expect = \"key\";\n else if (c === \"}\") this.close();\n else this.broken = true;\n return;\n }\n }\n if (frame.expect === \"value\") {\n if (c === \"]\") this.close(); // `[]`, or a trailing comma\n else this.startValue(c);\n } else if (c === \",\") frame.expect = \"value\";\n else if (c === \"]\") this.close();\n else this.broken = true;\n }\n\n private startValue(c: string): void {\n if (c === '\"') {\n this.token = { type: \"string\", isKey: false, text: \"\", escape: \"\", hex: \"\" };\n this.changes += 1; // the key now shows, with an empty value\n } else if (c === \"{\" || c === \"[\") this.open(c);\n else if (c === \"-\" || (c >= \"0\" && c <= \"9\")) this.token = { type: \"number\", text: c };\n else if (c === \"t\" || c === \"f\" || c === \"n\") this.token = { type: \"literal\", text: c };\n else this.broken = true;\n }\n\n private open(c: \"{\" | \"[\"): void {\n this.stack.push(c === \"{\" ? { type: \"object\", value: {}, key: undefined, expect: \"key\" } : { type: \"array\", value: [], expect: \"value\" });\n this.changes += 1;\n }\n\n private close(): void {\n const frame = this.stack.pop()!;\n this.assign(frame.value);\n }\n\n /** A value finished: hand it to the container it belongs to, or finish the root. */\n private assign(value: unknown): void {\n this.changes += 1;\n const parent = this.stack[this.stack.length - 1];\n if (!parent) {\n this.root = value;\n this.done = this.started;\n return;\n }\n if (parent.type === \"object\") {\n setOwn(parent.value, parent.key!, value);\n parent.key = undefined;\n } else {\n parent.value.push(value);\n }\n parent.expect = \"comma\";\n }\n\n /** Consume string characters from `i`; returns where reading stopped. */\n private readString(token: Extract<Token, { type: \"string\" }>, chunk: string, i: number): number {\n const len = chunk.length;\n while (i < len) {\n if (token.escape === \"u\") {\n const c = chunk[i]!;\n if (!HEX.test(c)) {\n this.broken = true;\n return len;\n }\n token.hex += c;\n i += 1;\n if (token.hex.length === 4) {\n token.text += String.fromCharCode(parseInt(token.hex, 16));\n token.escape = \"\";\n token.hex = \"\";\n if (!token.isKey) this.changes += 1;\n }\n continue;\n }\n if (token.escape === \"\\\\\") {\n const c = chunk[i]!;\n i += 1;\n if (c === \"u\") {\n token.escape = \"u\";\n continue;\n }\n // An unknown escape keeps its character: lenient, and lossless enough\n // for a preview that the validated value will replace anyway.\n token.text += ESCAPES[c] ?? c;\n token.escape = \"\";\n if (!token.isKey) this.changes += 1;\n continue;\n }\n // Copy the plain run up to the next quote or backslash in one slice.\n let j = i;\n while (j < len) {\n const code = chunk.charCodeAt(j);\n if (code === QUOTE || code === BACKSLASH) break;\n j += 1;\n }\n if (j > i) {\n token.text += chunk.slice(i, j);\n if (!token.isKey) this.changes += 1;\n i = j;\n }\n if (i >= len) return i;\n if (chunk.charCodeAt(i) === BACKSLASH) {\n token.escape = \"\\\\\";\n i += 1;\n continue;\n }\n // Closing quote.\n this.token = null;\n if (token.isKey) {\n const frame = this.stack[this.stack.length - 1] as ObjectFrame;\n frame.key = token.text;\n frame.expect = \"colon\";\n } else {\n this.assign(token.text);\n }\n return i + 1;\n }\n return i;\n }\n}\n\n/** One-shot form: the best value `text` supports so far, and whether it is whole. */\nexport function parsePartialJson(text: string): { value: unknown; complete: boolean } {\n const parser = new PartialJsonParser();\n parser.push(text);\n return { value: parser.snapshot(), complete: parser.complete };\n}\n","// Built-in tools: the agent's own capabilities, as opposed to the host's domain\n// tools.\n//\n// `visualize` is the important one. Without it an agent can only show what some\n// engineer pre-built a card for; with it the agent CHOOSES a presentation for\n// whatever it is holding — a comparison becomes a table, a trend becomes a\n// chart, an ambiguous match becomes a choice card instead of a guess. That is\n// the difference between an agent that talks about data and one that shows it.\n\nimport { CardRegistry, isObj } from \"../cards/registry.js\";\nimport type { CardSpec } from \"../cards/types.js\";\nimport type { SkillRegistry } from \"../skills/registry.js\";\nimport type { SurfaceCatalogue } from \"../surfaces/catalogue.js\";\nimport { createSurfaceTools } from \"../surfaces/tools.js\";\nimport type { ToolDefinition } from \"./types.js\";\n\n/** Where `visualize` may put a card. `document` is not the agent's to choose from a chat. */\nexport type VisualizePlacement = \"inline\" | \"panel\";\n\nexport type VisualizeToolOptions = {\n cards: CardRegistry;\n /** Restrict which kinds the agent may emit (a read-only chat may want no `confirm`). */\n kinds?: string[];\n /**\n * Where the agent may put a card. Default `[\"inline\"]`: the tool is exactly as before. Add\n * `\"panel\"` when the host shows a side panel (super-chat-ui's `ChatPanel`): the agent can then open\n * a card beside the conversation, for a chart or a document worth room of its own.\n */\n placements?: readonly VisualizePlacement[];\n};\n\n/**\n * The generic visualization tool.\n *\n * The description carries the whole catalogue because model card-choice quality\n * tracks how well the options are described far more than it tracks schema\n * strictness — and a `oneOf` union across 13 shapes both bloats the request and\n * degrades tool-call accuracy on most models. We take a loose schema plus a\n * precise description, then validate and hand back a correction the model can\n * act on.\n */\nexport function createVisualizeTool(opts: VisualizeToolOptions): ToolDefinition {\n const { cards } = opts;\n const available = opts.kinds ? cards.list().filter((k) => opts.kinds!.includes(k.kind)) : cards.list();\n const panel = (opts.placements ?? [\"inline\"]).includes(\"panel\");\n const catalogue = available\n .map((k) => `- ${k.kind}${k.interactive ? \" (interactive — the user replies)\" : \"\"}: ${k.summary}`)\n .join(\"\\n\");\n\n return {\n name: \"visualize\",\n side: \"read\",\n description: [\n \"Render a visual card for the user. Use this whenever a result is easier to SEE than to read:\",\n \"comparisons, trends, sequences, multi-field records, long operations, or a decision the user must make.\",\n \"\",\n \"Available kinds:\",\n catalogue,\n \"\",\n \"Rules:\",\n \"- Put the data IN the card. Do not also repeat every row in your prose — say what it means instead.\",\n \"- Interactive kinds (choice, form, confirm) pause for the user's answer, which is returned to you as this tool's result. Use them instead of guessing.\",\n \"- Use `confirm` before anything consequential or irreversible.\",\n \"- One card per distinct idea. Do not wrap a one-line answer in a card.\",\n ...(panel\n ? [\n '- `placement: \"panel\"` opens the card in the side panel beside the chat, with room to explore: use it for a chart the user will work with or a long document. Keep small results (a few figures, a short table) inline, the default.',\n \"- Interactive kinds are always inline.\",\n ]\n : []),\n ].join(\"\\n\"),\n inputSchema: {\n type: \"object\",\n required: [\"kind\", \"spec\"],\n properties: {\n kind: { type: \"string\", enum: available.map((k) => k.kind), description: \"Which card to render.\" },\n // Before `spec`, so it streams first: a panel card is not previewed in the chat.\n ...(panel\n ? { placement: { type: \"string\", enum: [\"inline\", \"panel\"], description: \"Where to show the card: in the chat (inline, default) or in the side panel.\" } }\n : {}),\n spec: {\n type: \"object\",\n description: \"The card body. Must match the schema for `kind`, and must include `kind` itself.\",\n additionalProperties: true,\n },\n },\n additionalProperties: false,\n },\n loading: (input) => {\n const { kind, spec } = (input ?? {}) as { kind?: string; spec?: Record<string, unknown> };\n if (!kind || cards.get(kind)?.interactive) return undefined;\n const outputKind = kind === \"media\"\n ? \"media\"\n : [\"chart\", \"funnel\", \"gauge\"].includes(kind)\n ? \"chart\"\n : [\"table\", \"comparison\"].includes(kind)\n ? \"table\"\n : [\"document\", \"markdown\", \"code\", \"diff\", \"email\"].includes(kind)\n ? \"document\"\n : \"generic\";\n const mediaItems = kind === \"media\" && Array.isArray(spec?.[\"items\"])\n ? spec[\"items\"] as Record<string, unknown>[]\n : [];\n const first = mediaItems[0];\n const width = typeof first?.[\"width\"] === \"number\" ? first[\"width\"] : undefined;\n const height = typeof first?.[\"height\"] === \"number\" ? first[\"height\"] : undefined;\n return {\n kind: outputKind,\n label: `Preparing ${kind} card`,\n ...(mediaItems.length ? { count: mediaItems.length } : {}),\n ...(width && height ? { aspectRatio: `${width} / ${height}` } : {}),\n };\n },\n // The card IS this tool's arguments, so it can be drawn while they stream.\n // `cards.partial` refuses interactive kinds and anything its own validator\n // rejects; `execute` below stays the only path to a real card.\n partialCard: (input) => {\n const { kind, spec, placement } = (input ?? {}) as { kind?: unknown; spec?: unknown; placement?: unknown };\n if (typeof kind !== \"string\" || !isObj(spec)) return undefined;\n // A card bound for the side panel is drawn there once it is whole, not previewed in the chat.\n if (placement === \"panel\") return undefined;\n if (opts.kinds && !opts.kinds.includes(kind)) return undefined;\n return cards.partial({ ...spec, kind });\n },\n async execute(input, ctx) {\n const { kind, spec, placement } = (input ?? {}) as { kind?: string; spec?: Record<string, unknown>; placement?: unknown };\n if (!kind) return { output: { ok: false, error: \"`kind` is required.\" }, failure: \"invalid-input\" as const };\n if (placement !== undefined && placement !== \"inline\" && !(panel && placement === \"panel\")) {\n const allowed = panel ? '\"inline\" or \"panel\"' : '\"inline\" (this chat has no side panel)';\n return { output: { ok: false, error: `placement must be ${allowed}.` }, failure: \"invalid-input\" as const };\n }\n\n // Models routinely omit `kind` inside `spec` since they already passed it\n // at the top level. Filling it in is unambiguous, so do it rather than\n // bouncing the call.\n const full = { ...(spec ?? {}), kind } as CardSpec;\n\n const verdict = cards.validate(full);\n if (!verdict.ok) {\n // A refusal that names the wrong field but not the right shape (\"symbol must be an object\") costs the model a\n // guess per step. When the kind gave no `expected` of its own, send the kind's own summary: how to build it.\n const shape = verdict.expected ?? cards.get(kind)?.summary;\n return {\n // Returned as data, not thrown: the model reads the correction and\n // retries with a valid spec on the next step.\n output: { ok: false, error: verdict.error, ...(shape ? { expected: shape } : {}) },\n failure: \"invalid-input\" as const,\n };\n }\n\n const def = cards.get(kind);\n if (placement === \"panel\" && def?.interactive) {\n return { output: { ok: false, error: `${kind} asks the user something, so it is shown in the chat: send it without placement.` }, failure: \"invalid-input\" as const };\n }\n if (def?.interactive && ctx.requestCard) {\n // Suspend for the user's answer. The runtime resolves this when the UI\n // reports a CardAction.\n //\n // No `card` in the result: requestCard already surfaced this card and\n // the user has answered it on screen. Returning it again mints a second\n // card with a new id, and the thread renders the same question twice.\n const answer = await ctx.requestCard(full);\n return { output: { ok: true, kind, response: answer } };\n }\n\n if (placement === \"panel\") return { output: { ok: true, kind, rendered: true, placement: \"panel\" }, card: full, placement: \"panel\" as const };\n return { output: { ok: true, kind, rendered: true }, card: full };\n },\n };\n}\n\n/**\n * `loadSkill` — the pull half of progressive disclosure.\n *\n * Paired with `SkillRegistry.manualIndex()` in the system prompt: the model sees\n * a one-line menu every turn and pays for a skill's body only when it decides it\n * needs one.\n */\nexport function createLoadSkillTool(skills: SkillRegistry): ToolDefinition {\n return {\n name: \"loadSkill\",\n side: \"read\",\n description:\n \"Load a skill's full instructions before acting in its area. Skill ids are listed in your instructions. \" +\n \"Loading a skill may also unlock tools specific to it.\",\n inputSchema: {\n type: \"object\",\n required: [\"id\"],\n properties: {\n id: { type: \"string\", description: \"The skill id to load.\" },\n topic: { type: \"string\", description: \"Optional sub-topic, to load only the relevant section.\" },\n },\n additionalProperties: false,\n },\n async execute(input, ctx) {\n const { id, topic } = (input ?? {}) as { id?: string; topic?: string };\n if (!id) return { output: { ok: false, error: \"`id` is required.\" }, failure: \"invalid-input\" as const };\n\n const loaded = await skills.load(id, { query: topic ?? \"\", vars: ctx.vars });\n if (!loaded.found) return { output: { ok: false, error: loaded.text }, failure: \"not-found\" as const };\n\n return {\n output: {\n ok: true,\n id,\n instructions: loaded.text,\n ...(loaded.tools.length ? { unlockedTools: loaded.tools } : {}),\n },\n // The runtime half of the promise: re-resolve the active set so the\n // names announced in `unlockedTools` are actually callable next step.\n ...(loaded.tools.length ? { unlockTools: loaded.tools } : {}),\n };\n },\n };\n}\n\n/**\n * `updateCard` — let the agent revise a card it already emitted.\n *\n * Without this, a long-running operation can only append new progress cards, and\n * the thread fills with near-identical snapshots.\n */\nexport function createUpdateCardTool(cards: CardRegistry): ToolDefinition {\n return {\n name: \"updateCard\",\n side: \"read\",\n description:\n \"Replace a card you previously rendered, by its id. Use for progress updates instead of emitting a new card each time.\",\n inputSchema: {\n type: \"object\",\n required: [\"cardId\", \"spec\"],\n properties: {\n cardId: { type: \"string\" },\n spec: { type: \"object\", additionalProperties: true },\n },\n additionalProperties: false,\n },\n execute(input) {\n const { cardId, spec } = (input ?? {}) as { cardId?: string; spec?: Record<string, unknown> };\n if (!cardId || !spec) {\n return { output: { ok: false, error: \"`cardId` and `spec` are required.\" }, failure: \"invalid-input\" as const };\n }\n const verdict = cards.validate(spec);\n if (!verdict.ok) {\n return { output: { ok: false, error: verdict.error, expected: verdict.expected }, failure: \"invalid-input\" as const };\n }\n // `cardId` makes the runtime REUSE the id, so the reducer's upsert\n // replaces the original card instead of appending a near-identical twin.\n return { output: { ok: true, cardId }, card: spec as CardSpec, cardId };\n },\n };\n}\n\n/** The default built-in set, wired to the given registries. */\nexport function createBuiltinTools(opts: { cards: CardRegistry; skills?: SkillRegistry; surfaces?: SurfaceCatalogue; placements?: readonly VisualizePlacement[] }): ToolDefinition[] {\n const tools = [createVisualizeTool({ cards: opts.cards, ...(opts.placements ? { placements: opts.placements } : {}) }), createUpdateCardTool(opts.cards)];\n // Opt-in: a host that has not asked for surfaces sees the same tool list as before.\n if (opts.surfaces) tools.push(...createSurfaceTools({ catalogue: opts.surfaces }));\n if (opts.skills && opts.skills.list().some((s) => s.mode === \"manual\")) {\n tools.push(createLoadSkillTool(opts.skills));\n }\n return tools;\n}\n","// The event stream a run emits. This is the framework's public runtime surface:\n// React state, server logs, and any host UI are all just reducers over it.\n//\n// Modelled as events rather than a promise because the interesting parts of an\n// agent turn happen BEFORE it finishes — the context trace, the tool calls, the\n// card that needs an answer. A promise-shaped API hides all of it.\n//\n// Ordering guarantees for a step's tools (correlate by `callId`, never by\n// position):\n// 1. Every `tool-call` of the step is emitted before any tool runs.\n// 2. Per callId: `tool-call` → its `card` / `awaiting-user` /\n// `user-responded` → exactly one `tool-result`, failures, timeouts and\n// aborts included.\n// 3. `tool-result`s arrive in COMPLETION order, not call order. `confirm`\n// tools still run one at a time after the parallel ones, so their results\n// come last.\n// 4. All of a step's `tool-result`s arrive before the next `step-start`.\n// 5. The `role: \"tool\"` message runAgent writes back to history keeps CALL\n// order.\n//\n// `tool-call-input-delta` comes earlier still: in stream mode, while the model\n// is WRITING a call's arguments, before the step ends and before `tool-call`.\n// It is a preview — a tolerant parse of the JSON so far, and the card it\n// implies when the tool can say (`ToolDefinition.partialCard`). `tool-call`\n// remains the authoritative, repaired input, and only the tool's own execute\n// path validates and emits a real `card`. Nothing a delta carries is ever\n// written to history.\n\nimport type { Card, CardAction, CardSpec } from \"../cards/types.js\";\nimport type { ContentPart, FinishReason, Usage } from \"../content/types.js\";\nimport type { ContextTrace } from \"../context/types.js\";\nimport type { JobHandle, JobStatus } from \"../providers/types.js\";\nimport type { MeteringRecord } from \"./metering.js\";\nimport type { ToolLoadingHint } from \"../tools/types.js\";\n\nexport type RunEvent =\n | { type: \"run-start\"; runId: string; mode: RunMode }\n /**\n * Everything the run has produced so far, replacing what the consumer holds.\n *\n * For a consumer that joins a run part-way, or lost part of its stream: a\n * turn that runs on a server, followed over a connection that dropped, where\n * replaying every event is not possible. `runAgent` never emits it. The run\n * is live after it — a card still waiting on the person is announced again\n * with `awaiting-user`.\n */\n | { type: \"run-snapshot\"; parts: ContentPart[]; cards: Card[]; usage?: Usage; steps?: number }\n /** Emitted before the first provider call — the whole \"why did it send that\" answer. */\n | { type: \"context-built\"; trace: ContextTrace; system: string; toolNames: string[] }\n | { type: \"step-start\"; step: number }\n | { type: \"text-delta\"; delta: string }\n | { type: \"reasoning-delta\"; delta: string }\n /**\n * Live-only: a tool call's arguments as far as they have streamed. Stream\n * mode only; never sent for a kind that is interactive. `partialCard` is a\n * VALID but incomplete card, present only when the tool previews one.\n */\n | {\n type: \"tool-call-input-delta\";\n callId: string;\n name: string;\n partialInput: unknown;\n partialCard?: CardSpec;\n loading?: ToolLoadingHint;\n }\n | { type: \"tool-call\"; callId: string; name: string; input: unknown; repaired?: boolean; loading?: ToolLoadingHint }\n /** A `confirm`-side tool, or an interactive card, is waiting on the user. */\n | { type: \"awaiting-user\"; callId: string; card: Card }\n | { type: \"user-responded\"; callId: string; action: CardAction }\n | { type: \"tool-result\"; callId: string; name: string; output: unknown; failure?: string; ms: number }\n /** A card was produced — by a tool result, or mid-execution by a long tool. */\n | { type: \"card\"; card: Card }\n | { type: \"card-updated\"; cardId: string; spec: CardSpec }\n | { type: \"step-finish\"; step: number; finishReason: FinishReason; usage?: Usage }\n /** Background mode: the provider accepted the job and we are now polling. */\n | { type: \"job-started\"; handle: JobHandle }\n | { type: \"job-status\"; handle: JobHandle; status: JobStatus }\n | { type: \"message\"; parts: ContentPart[] }\n /** Canonical, idempotent per-step and per-run usage observation. */\n | { type: \"metering\"; record: MeteringRecord }\n | { type: \"usage\"; usage: Usage }\n | { type: \"run-finish\"; runId: string; finishReason: FinishReason; usage: Usage; steps: number }\n | { type: \"error\"; error: unknown; recoverable: boolean };\n\nexport type RunMode = \"stream\" | \"sync\" | \"background\";\n\n/** Accumulated state a host can rebuild from the event stream. */\nexport type RunState = {\n runId: string;\n mode: RunMode;\n status: \"idle\" | \"running\" | \"awaiting-user\" | \"done\" | \"error\";\n parts: ContentPart[];\n cards: Card[];\n usage: Usage;\n steps: number;\n /** Live tool output slots, removed as their correlated result arrives. */\n pendingTools: Record<string, { callId: string; name: string; loading?: ToolLoadingHint }>;\n /**\n * Calls whose arguments are streaming or have streamed, keyed by callId:\n * the latest `tool-call-input-delta` for each. Kept past `tool-call` so a\n * card preview holds its place until the validated card replaces it, and\n * removed with the call's `tool-result`. Live-only — never committed.\n */\n partialTools?: Record<string, PartialToolCall>;\n trace?: ContextTrace;\n /**\n * Tool names actually exposed to the model this run — the base presets PLUS\n * anything a matched skill unlocked. Distinct from what the registry would\n * return for the presets alone, which is why it is recorded rather than\n * recomputed by the UI.\n */\n toolNames?: string[];\n job?: { handle: JobHandle; status: JobStatus };\n pendingCard?: Card;\n error?: unknown;\n finishReason?: FinishReason;\n};\n\nexport type PartialToolCall = {\n callId: string;\n name: string;\n partialInput: unknown;\n partialCard?: CardSpec;\n loading?: ToolLoadingHint;\n};\n\nexport function initialRunState(runId: string, mode: RunMode): RunState {\n return { runId, mode, status: \"idle\", parts: [], cards: [], usage: {}, steps: 0, pendingTools: {}, partialTools: {} };\n}\n\nfunction mergeUsage(a: Usage, b?: Usage): Usage {\n if (!b) return a;\n const add = (x?: number, y?: number) => (x == null && y == null ? undefined : (x ?? 0) + (y ?? 0));\n return {\n inputTokens: add(a.inputTokens, b.inputTokens),\n outputTokens: add(a.outputTokens, b.outputTokens),\n totalTokens: add(a.totalTokens, b.totalTokens),\n cachedInputTokens: add(a.cachedInputTokens, b.cachedInputTokens),\n reasoningTokens: add(a.reasoningTokens, b.reasoningTokens),\n };\n}\n\n/**\n * The canonical reducer. React, a CLI renderer and a server-side recorder all\n * use this one function, so they can never disagree about what a run looked like.\n */\nexport function reduceRunEvent(state: RunState, event: RunEvent): RunState {\n switch (event.type) {\n case \"run-start\":\n return { ...state, runId: event.runId, mode: event.mode, status: \"running\" };\n case \"run-snapshot\":\n // REPLACE, not merge: the sender cannot know what this consumer missed,\n // so anything kept from before could be shown twice. What is live-only\n // (argument previews, a card's wait) is dropped; the stream re-announces\n // whatever still applies.\n return {\n ...state,\n status: \"running\",\n parts: event.parts,\n cards: event.cards,\n pendingCard: undefined,\n pendingTools: Object.fromEntries(\n event.parts.flatMap((p) =>\n p.type === \"tool-call\" && p.status === \"running\" ? [[p.callId, { callId: p.callId, name: p.name }]] : [],\n ),\n ),\n partialTools: {},\n ...(event.usage ? { usage: event.usage } : {}),\n ...(event.steps != null ? { steps: event.steps } : {}),\n };\n case \"context-built\":\n return { ...state, trace: event.trace, toolNames: event.toolNames };\n case \"step-start\":\n return { ...state, steps: event.step + 1 };\n case \"text-delta\": {\n const last = state.parts[state.parts.length - 1];\n const parts =\n last && last.type === \"text\"\n ? [...state.parts.slice(0, -1), { ...last, text: last.text + event.delta }]\n : [...state.parts, { type: \"text\" as const, text: event.delta }];\n return { ...state, parts };\n }\n case \"reasoning-delta\": {\n const last = state.parts[state.parts.length - 1];\n const parts =\n last && last.type === \"reasoning\"\n ? [...state.parts.slice(0, -1), { ...last, text: last.text + event.delta }]\n : [...state.parts, { type: \"reasoning\" as const, text: event.delta }];\n return { ...state, parts };\n }\n case \"tool-call-input-delta\":\n return {\n ...state,\n partialTools: {\n ...state.partialTools,\n [event.callId]: {\n callId: event.callId,\n name: event.name,\n partialInput: event.partialInput,\n ...(event.partialCard ? { partialCard: event.partialCard } : {}),\n ...(event.loading ? { loading: event.loading } : {}),\n },\n },\n };\n case \"tool-call\":\n return {\n ...state,\n pendingTools: {\n ...state.pendingTools,\n [event.callId]: {\n callId: event.callId,\n name: event.name,\n ...(event.loading ? { loading: event.loading } : {}),\n },\n },\n parts: [\n ...state.parts,\n { type: \"tool-call\", callId: event.callId, name: event.name, input: event.input, status: \"running\", ...(event.repaired ? { repaired: true } : {}) },\n ],\n };\n case \"awaiting-user\":\n return { ...state, status: \"awaiting-user\", pendingCard: event.card, cards: upsertCard(state.cards, event.card) };\n case \"user-responded\":\n // Record the answer ON the card. It is the only copy that outlives the\n // run: the renderer's local state dies when the turn commits and the card\n // re-mounts from history.\n return {\n ...state,\n status: \"running\",\n pendingCard: undefined,\n cards: state.cards.map((c) => (c.callId === event.callId ? { ...c, action: event.action } : c)),\n };\n case \"tool-result\": {\n const pendingTools = { ...state.pendingTools };\n delete pendingTools[event.callId];\n return {\n ...state,\n pendingTools,\n ...(state.partialTools?.[event.callId] ? { partialTools: without(state.partialTools, event.callId) } : {}),\n parts: [\n ...markCallDone(state.parts, event.callId, event.failure ? \"error\" : \"done\"),\n {\n type: \"tool-result\",\n callId: event.callId,\n name: event.name,\n output: event.output,\n ms: event.ms,\n ...(event.failure ? { failure: event.failure as never } : {}),\n },\n ],\n };\n }\n case \"card\":\n return { ...state, cards: upsertCard(state.cards, event.card) };\n case \"card-updated\":\n return {\n ...state,\n cards: state.cards.map((c) => (c.id === event.cardId ? { ...c, spec: event.spec } : c)),\n };\n case \"job-started\":\n return { ...state, job: { handle: event.handle, status: \"queued\" } };\n case \"job-status\":\n return { ...state, job: { handle: event.handle, status: event.status } };\n case \"message\":\n return { ...state, parts: [...state.parts, ...event.parts] };\n case \"metering\":\n // Metering is an observation event. The legacy `usage` event remains the\n // sole live accumulator so adding this event is backwards compatible and\n // cannot double-count a turn.\n return state;\n // ── usage: exactly one event accumulates ──────────────────────────────\n // runAgent reports a step's cost three times: `usage` (live), `step-finish`\n // (the same numbers again, for consumers that only watch step boundaries)\n // and `run-finish` (the running total). Adding all three counted every\n // turn 3×, which is not a rounding error — it read as context overflow on\n // a model whose window it had not come close to.\n case \"usage\":\n return { ...state, usage: mergeUsage(state.usage, event.usage) };\n case \"step-finish\":\n // Deliberately does NOT touch usage: the `usage` event above already\n // added this step. `steps` is owned by step-start.\n return state;\n case \"run-finish\":\n // A failed run stays failed: runAgent yields error → run-finish, and an\n // unconditional \"done\" here would mask the error from every consumer.\n // Cancellation maps to \"done\" — a user abort is an outcome, not a fault.\n return {\n ...state,\n status: event.finishReason === \"error\" ? \"error\" : \"done\",\n pendingTools: {},\n partialTools: {},\n finishReason: event.finishReason,\n // REPLACE, not merge. This is runAgent's own total across every step,\n // so it is the authoritative figure — and taking it wholesale also\n // repairs any drift for a consumer that fed the reducer a step-finish\n // without its paired usage event.\n usage: event.usage,\n steps: event.steps,\n };\n case \"error\":\n return {\n ...state,\n status: event.recoverable ? state.status : \"error\",\n ...(event.recoverable ? {} : { pendingTools: {}, partialTools: {} }),\n error: event.error,\n };\n default:\n return state;\n }\n}\n\nfunction without<T>(record: Record<string, T>, key: string): Record<string, T> {\n const next = { ...record };\n delete next[key];\n return next;\n}\n\nfunction upsertCard(cards: Card[], card: Card): Card[] {\n const i = cards.findIndex((c) => c.id === card.id);\n if (i === -1) return [...cards, card];\n const next = [...cards];\n // A revision replaces the content, not the place: the card stays in the slot\n // of the call that first drew it.\n // Nor its placement: an update that names none keeps the panel the card was opened in.\n const prev = cards[i]!;\n const home = prev.callId;\n const placement = card.placement ?? prev.placement;\n next[i] = { ...card, ...(home ? { callId: home } : {}), ...(placement ? { placement } : {}) };\n return next;\n}\n\nfunction markCallDone(parts: ContentPart[], callId: string, status: \"done\" | \"error\"): ContentPart[] {\n return parts.map((p) => (p.type === \"tool-call\" && p.callId === callId ? { ...p, status } : p));\n}\n","// Stop conditions.\n//\n// `maxSteps` alone is a blunt instrument: it either cuts a task short or lets a\n// looping agent burn eight steps re-reading the same file. These are the\n// composable predicates that let a host say what \"done\" actually means for its\n// domain.\n\nimport type { FinishReason, Usage } from \"../content/types.js\";\nimport { USER_DECLINED, type ToolCallOutcome } from \"./execute-tools.js\";\n\nexport type StopContext = {\n step: number;\n finishReason: FinishReason;\n outcomes: readonly ToolCallOutcome[];\n usage: Usage;\n};\n\nexport type StopCondition = (ctx: StopContext) => boolean;\n\nexport const stepCountIs = (n: number): StopCondition => (ctx) => ctx.step >= n;\n\n/** Stop as soon as a specific tool has run — the \"one action then report\" shape. */\nexport const afterTool = (...names: string[]): StopCondition => (ctx) =>\n ctx.outcomes.some((o) => names.includes(o.name) && !o.failure);\n\n/** Stop when the model produced prose with no tool calls. The natural end. */\nexport const noToolCalls: StopCondition = (ctx) => ctx.finishReason !== \"tool-calls\" && ctx.outcomes.length === 0;\n\nexport const tokenBudgetExceeded = (maxTotal: number): StopCondition => (ctx) =>\n (ctx.usage.totalTokens ?? (ctx.usage.inputTokens ?? 0) + (ctx.usage.outputTokens ?? 0)) >= maxTotal;\n\n/**\n * Stop after `n` consecutive failing steps.\n *\n * The failure mode this catches: a tool that errors identically every time\n * (bad credential, missing config). The model will happily retry it until the\n * step cap, producing nothing but latency and spend.\n */\nexport const consecutiveFailures = (n: number): StopCondition => {\n let streak = 0;\n return (ctx) => {\n const allFailed = ctx.outcomes.length > 0 && ctx.outcomes.every((o) => o.failure);\n streak = allFailed ? streak + 1 : 0;\n return streak >= n;\n };\n};\n\n/**\n * Whether an outcome is the person saying no, as opposed to a tool failing or a\n * host that cannot ask. Three shapes carry it:\n *\n * - an approval the runtime asked for (`side: \"confirm\"`): `failure: \"denied\"`\n * and the error is `USER_DECLINED`;\n * - a tool that asks for itself (`confirmation: \"tool\"`) and returns the\n * answer it was given: `{ cancelled: true }`;\n * - an interactive card from `visualize`: `{ response: { cancelled: true } }`.\n */\nexport function isUserDecline(outcome: ToolCallOutcome): boolean {\n const output = outcome.output;\n if (typeof output !== \"object\" || output === null) return false;\n const o = output as { error?: unknown; cancelled?: unknown; response?: unknown };\n if (outcome.failure === \"denied\" && o.error === USER_DECLINED) return true;\n if (o.cancelled === true) return true;\n return typeof o.response === \"object\" && o.response !== null && (o.response as { cancelled?: unknown }).cancelled === true;\n}\n\n/**\n * Stop the run as soon as the person has declined something.\n *\n * Opt-in. By default a decline is only a result the model reads (\"The user\n * declined.\"): the run goes on, and the model decides what to do, usually to say\n * what was left undone and ask. Use this when your product treats a \"no\" as the\n * end of the turn. It is not in `DEFAULT_STOP_CONDITIONS`.\n */\nexport const userDeclined: StopCondition = (ctx) => ctx.outcomes.some(isUserDecline);\n\nexport function shouldStop(conditions: readonly StopCondition[] | undefined, ctx: StopContext): boolean {\n if (!conditions?.length) return false;\n return conditions.some((c) => c(ctx));\n}\n\n/**\n * A sane default set for an interactive chat agent. A person's \"no\" is not here:\n * it is told to the model and the run continues (see `userDeclined`).\n */\nexport const DEFAULT_STOP_CONDITIONS: StopCondition[] = [consecutiveFailures(3)];\n","// The agent loop.\n//\n// One async generator drives all three modes (stream / sync / background) so\n// there is exactly one place where \"call model → run tools → loop\" lives. The\n// modes differ only in HOW a step's result is obtained:\n//\n// stream — SSE, deltas surface immediately\n// sync — one request/response\n// background — provider-side job + polling; survives a closed tab\n//\n// Everything after that — tool dispatch, card suspension, stop conditions,\n// history append — is identical, which is the point.\n\nimport { assistantMessage, nextId } from \"../content/parts.js\";\nimport type { ContentPart, FinishReason, Message, Usage } from \"../content/types.js\";\nimport { stripCardPayload, type Card, type CardAction, type CardSpec } from \"../cards/types.js\";\nimport { makeCard } from \"../cards/registry.js\";\nimport type { ContextBuilder } from \"../context/builder.js\";\nimport { AgentError, toAgentError } from \"../errors.js\";\nimport type { GenerateResult, NormalizedRequest, Provider, StreamEvent } from \"../providers/types.js\";\nimport type { ToolRegistry } from \"../tools/registry.js\";\nimport { resolvePartialCard, resolveToolLoading, type ToolDefinition, type ToolResolution } from \"../tools/types.js\";\nimport { PartialJsonParser } from \"../tools/partial-json.js\";\nimport { awaitJob } from \"./jobs.js\";\nimport { executeToolCalls, USER_DECLINED, type ToolCallRequest } from \"./execute-tools.js\";\nimport { EventChannel } from \"./channel.js\";\nimport type { RunEvent, RunMode } from \"./events.js\";\nimport {\n combineMeteringSources,\n deliverMetering,\n usageSource,\n type MeterSink,\n type MeteringRecord,\n type MeteringSource,\n} from \"./metering.js\";\nimport { shouldStop, type StopCondition } from \"./stop.js\";\nimport { foldSurfaces, SurfaceLedger } from \"../surfaces/ledger.js\";\nimport { surfaceActionTools } from \"../surfaces/action-run.js\";\n\nexport type RunConfig = {\n provider: Provider;\n model: string;\n contextBuilder: ContextBuilder;\n tools: ToolRegistry;\n toolResolution: ToolResolution;\n mode?: RunMode;\n maxSteps?: number;\n stopWhen?: StopCondition[];\n vars?: Record<string, unknown>;\n temperature?: number;\n maxOutputTokens?: number;\n reasoning?: NormalizedRequest[\"reasoning\"];\n // Pass-throughs to NormalizedRequest — the adapter implements all of these;\n // without this block no runAgent caller could ever set them.\n toolChoice?: NormalizedRequest[\"toolChoice\"];\n /** Provider-hosted tools (web search, code interpreter), keyed by provider id. */\n providerTools?: NormalizedRequest[\"providerTools\"];\n responseFormat?: NormalizedRequest[\"responseFormat\"];\n topP?: number;\n stopSequences?: string[];\n /** Provider-side conversation storage opt-out (OpenAI `store`). */\n store?: boolean;\n metadata?: Record<string, string>;\n /** Usage delivery target. Pricing and persistence belong to the host. */\n meter?: MeterSink;\n /** Host-only dimensions copied onto metering records, never sent upstream. */\n meteringMetadata?: Readonly<Record<string, string>>;\n /** The per-provider escape hatch, keyed by provider id. */\n providerOptions?: NormalizedRequest[\"providerOptions\"];\n toolTimeoutMs?: number;\n signal?: AbortSignal;\n /**\n * Resolve an interactive card. The host shows it and returns the user's\n * answer. Absent means interactive cards auto-decline rather than hang.\n */\n onUserDecision?: (callId: string, card: Card) => Promise<CardAction>;\n /** Execute a tool that has no `execute` (browser-side capabilities). */\n onHostTool?: (call: ToolCallRequest) => Promise<unknown>;\n /** Persist a background job handle so a reload can resume it. */\n onJobHandle?: (handle: NonNullable<GenerateResult[\"responseId\"]> extends string ? unknown : never) => void;\n /** Skills the user pinned in the UI. */\n forceSkillIds?: string[];\n /**\n * Chain via the provider's stored response instead of resending history.\n * Only used when the provider supports it; cuts input tokens dramatically on\n * long tool loops.\n */\n useServerHistory?: boolean;\n /**\n * The working copy of this conversation's surfaces. A client passes one so\n * edits the person makes mid-run are visible to `readSurface`; without it the\n * run derives its own from `messages`.\n */\n surfaces?: SurfaceLedger;\n};\n\nexport async function* runAgent(\n messages: readonly Message[],\n config: RunConfig,\n): AsyncGenerator<RunEvent, void, unknown> {\n const runId = nextId(\"run\");\n const mode = config.mode ?? \"stream\";\n const maxSteps = config.maxSteps ?? 8;\n const vars = config.vars ?? {};\n const runStartedAt = Date.now();\n const surfaces = config.surfaces ?? new SurfaceLedger(foldSurfaces(messages));\n\n yield { type: \"run-start\", runId, mode };\n\n // Mutable accumulators: `.push()`, not `[...arr, x]` — this loop runs once\n // per step of a potentially long tool-calling turn, and re-copying the\n // whole array every step is wasted work on a long thread. Neither array is\n // returned or exposed outside this generator (see the yields below), so\n // there is no reference-equality contract to preserve.\n const history: Message[] = [...messages];\n let totalUsage: Usage = {};\n let finishReason: FinishReason = \"unknown\";\n let step = 0;\n let attemptedSteps = 0;\n let previousResponseId: string | undefined;\n const meteringSources: MeteringSource[] = [];\n const reportedModels = new Set<string>();\n\n try {\n // ── context, built once per run ────────────────────────────────────────\n // Rebuilding per step would let skills flap in and out mid-turn and would\n // break the cacheable prompt prefix. Tool RESULTS extend history within the\n // loop; the instruction block stays fixed.\n const baseTools = config.tools.resolve(config.toolResolution);\n const context = await config.contextBuilder.build({\n messages: history,\n vars,\n forceSkillIds: config.forceSkillIds,\n baseTools: baseTools.map((t) => t.name),\n signal: config.signal,\n });\n\n yield { type: \"context-built\", trace: context.trace, system: context.system, toolNames: context.toolNames };\n\n // Skills may have unlocked tools beyond the base presets. `let`, not\n // `const`: a loadSkill outcome can unlock more mid-run (see below).\n let unlockedNames = [...context.toolNames];\n let activeTools = config.tools.resolve({ ...config.toolResolution, allow: unlockedNames });\n let specs = config.tools.toSpecs(activeTools);\n\n const working: Message[] = [...context.messages];\n\n while (step < maxSteps) {\n if (config.signal?.aborted) throw new AgentError(\"cancelled\", \"Run was cancelled.\");\n yield { type: \"step-start\", step };\n attemptedSteps += 1;\n const stepStartedAt = Date.now();\n\n const request: NormalizedRequest = {\n model: config.model,\n system: context.system,\n messages: working,\n ...(specs.length ? { tools: specs } : {}),\n ...(config.providerTools ? { providerTools: config.providerTools } : {}),\n ...(config.toolChoice ? { toolChoice: config.toolChoice } : {}),\n ...(config.temperature != null ? { temperature: config.temperature } : {}),\n ...(config.topP != null ? { topP: config.topP } : {}),\n ...(config.maxOutputTokens != null ? { maxOutputTokens: config.maxOutputTokens } : {}),\n ...(config.stopSequences?.length ? { stopSequences: config.stopSequences } : {}),\n ...(config.responseFormat ? { responseFormat: config.responseFormat } : {}),\n ...(config.store != null ? { store: config.store } : {}),\n ...(config.metadata ? { metadata: config.metadata } : {}),\n ...(config.providerOptions ? { providerOptions: config.providerOptions } : {}),\n ...(config.reasoning ? { reasoning: config.reasoning } : {}),\n ...(config.useServerHistory && previousResponseId && config.provider.capabilities.serverSideHistory\n ? { previousResponseId }\n : {}),\n };\n\n // ── obtain this step's result ────────────────────────────────────────\n let parts: ContentPart[] = [];\n let stepFinish: FinishReason = \"unknown\";\n let stepUsage: Usage | undefined;\n let responseId: string | undefined;\n let reportedModel: string | undefined;\n let streamSnapshot: (() => GenerateResult) | undefined;\n\n try {\n if (mode === \"stream\" && config.provider.capabilities.streaming) {\n const collected = collectStream(config.provider.stream(request, { signal: config.signal }));\n streamSnapshot = collected.result;\n // Arguments still being written, per call. Parsed incrementally, and\n // forwarded only when the parse visibly changed: whitespace, a key's\n // characters or an unfinished number are not worth a re-render.\n const writing = new Map<string, { name: string; tool?: ToolDefinition; parser: PartialJsonParser; seen: number }>();\n for await (const event of collected.events()) {\n if (event.type === \"text-delta\") yield { type: \"text-delta\", delta: event.delta };\n else if (event.type === \"reasoning-delta\") yield { type: \"reasoning-delta\", delta: event.delta };\n else if (event.type === \"tool-call-start\") {\n const tool = activeTools.find((t) => t.name === event.name);\n writing.set(event.callId, { name: event.name, tool, parser: new PartialJsonParser(), seen: 0 });\n } else if (event.type === \"tool-call-delta\") {\n const call = writing.get(event.callId);\n if (!call) continue;\n call.parser.push(event.argsDelta);\n if (call.parser.version === call.seen) continue;\n call.seen = call.parser.version;\n const partialInput = call.parser.snapshot();\n if (partialInput === undefined) continue;\n const partialCard = resolvePartialCard(call.tool, partialInput);\n const loading = resolveToolLoading(call.tool?.loading, partialInput);\n yield {\n type: \"tool-call-input-delta\",\n callId: event.callId,\n name: call.name,\n partialInput,\n ...(partialCard ? { partialCard } : {}),\n ...(loading ? { loading } : {}),\n };\n } else if (event.type === \"error\") throw toAgentError(event.error, config.provider.id);\n }\n const done = collected.result();\n parts = done.parts;\n stepFinish = done.finishReason;\n stepUsage = done.usage;\n responseId = done.responseId;\n reportedModel = done.modelId || undefined;\n } else if (mode === \"background\") {\n if (!config.provider.startJob || !config.provider.capabilities.backgroundJobs) {\n throw new AgentError(\n \"not-supported\",\n `Provider \"${config.provider.id}\" has no background mode. Use mode \"stream\" or \"sync\".`,\n );\n }\n const handle = await config.provider.startJob({ ...request, background: true }, { signal: config.signal });\n reportedModel = handle.model || undefined;\n responseId = handle.id;\n yield { type: \"job-started\", handle };\n\n // Polling, not streaming: the entire value of background mode is that it\n // survives a dropped connection, and a stream does not.\n const snapshot = await awaitJob(config.provider, handle, { signal: config.signal });\n yield { type: \"job-status\", handle, status: snapshot.status };\n\n if (snapshot.status === \"cancelled\") {\n throw new AgentError(\"cancelled\", snapshot.error?.message ?? \"Background job was cancelled.\", {\n provider: config.provider.id,\n });\n }\n if (snapshot.status === \"failed\" || !snapshot.result) {\n throw new AgentError(\"unknown\", snapshot.error?.message ?? `Background job ended as ${snapshot.status}.`, {\n provider: config.provider.id,\n });\n }\n parts = snapshot.result.parts;\n stepFinish = snapshot.result.finishReason;\n stepUsage = snapshot.result.usage;\n responseId = snapshot.result.responseId ?? responseId;\n reportedModel = snapshot.result.modelId || reportedModel;\n // Deltas never streamed, so surface the text as one block.\n const textParts = parts.filter((p) => p.type === \"text\");\n if (textParts.length) yield { type: \"message\", parts: textParts };\n } else {\n const result = await config.provider.generate(request, { signal: config.signal });\n parts = result.parts;\n stepFinish = result.finishReason;\n stepUsage = result.usage;\n responseId = result.responseId;\n reportedModel = result.modelId || undefined;\n const textParts = parts.filter((p) => p.type === \"text\");\n if (textParts.length) yield { type: \"message\", parts: textParts };\n }\n } catch (cause) {\n const error = toAgentError(cause, config.provider.id);\n const partial = streamSnapshot?.();\n stepUsage = partial?.usage ?? stepUsage ?? {};\n responseId = partial?.responseId ?? responseId;\n reportedModel = partial?.modelId || reportedModel;\n const source = usageSource(stepUsage);\n meteringSources.push(source);\n if (reportedModel) reportedModels.add(reportedModel);\n if (source !== \"unavailable\") {\n totalUsage = addUsage(totalUsage, stepUsage);\n yield { type: \"usage\", usage: stepUsage };\n }\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"step\",\n id: `${runId}:step:${step}`,\n runId,\n step,\n provider: config.provider.id,\n requestedModel: config.model,\n ...(reportedModel ? { reportedModel } : {}),\n mode,\n status: error.kind === \"cancelled\" ? \"cancelled\" : \"failed\",\n usage: stepUsage,\n source,\n startedAt: stepStartedAt,\n finishedAt,\n durationMs: finishedAt - stepStartedAt,\n ...(responseId ? { responseId } : {}),\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n error: { kind: error.kind, message: error.message },\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n throw error;\n }\n\n previousResponseId = responseId;\n if (stepUsage) {\n totalUsage = addUsage(totalUsage, stepUsage);\n yield { type: \"usage\", usage: stepUsage };\n }\n const source = usageSource(stepUsage ?? {});\n meteringSources.push(source);\n if (reportedModel) reportedModels.add(reportedModel);\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"step\",\n id: `${runId}:step:${step}`,\n runId,\n step,\n provider: config.provider.id,\n requestedModel: config.model,\n ...(reportedModel ? { reportedModel } : {}),\n mode,\n status: meteringStatus(stepFinish),\n usage: stepUsage ?? {},\n source,\n startedAt: stepStartedAt,\n finishedAt,\n durationMs: finishedAt - stepStartedAt,\n ...(responseId ? { responseId } : {}),\n finishReason: stepFinish,\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"step-finish\", step, finishReason: stepFinish, ...(stepUsage ? { usage: stepUsage } : {}) };\n\n const assistant = assistantMessage(parts);\n working.push(assistant);\n history.push(assistant);\n\n const calls: ToolCallRequest[] = parts\n .filter((p): p is Extract<ContentPart, { type: \"tool-call\" }> => p.type === \"tool-call\")\n .map((p) => ({ callId: p.callId, name: p.name, input: p.input }));\n\n if (!calls.length) {\n finishReason = stepFinish;\n break;\n }\n\n for (const call of calls) {\n const source = parts.find((p) => p.type === \"tool-call\" && p.callId === call.callId) as\n | Extract<ContentPart, { type: \"tool-call\" }>\n | undefined;\n const loading = resolveToolLoading(config.tools.get(call.name)?.loading, call.input);\n yield {\n type: \"tool-call\",\n callId: call.callId,\n name: call.name,\n input: call.input,\n ...(source?.repaired ? { repaired: true } : {}),\n ...(loading ? { loading } : {}),\n };\n }\n\n // ── run tools ────────────────────────────────────────────────────────\n // Tool execution is a plain async call and cannot yield into this loop, so\n // it pushes into a channel that we drain CONCURRENTLY. Draining afterwards\n // would deadlock the human-in-the-loop path: the tool waits on the user,\n // the user waits to see the card, and the card waits on the tool.\n //\n // Results go through the same channel, in COMPLETION order: yielding them\n // after `await running` made every result in a step land together, when\n // the slowest tool finished. History below stays in CALL order.\n const channel = new EventChannel<RunEvent>();\n const running = executeToolCalls(calls, {\n tools: activeTools,\n vars,\n signal: config.signal,\n timeoutMs: config.toolTimeoutMs,\n surfaces,\n surfaceActionTools: surfaceActionTools(config.tools, config.toolResolution).map((t) => t.name),\n onCard: (card) => channel.push({ type: \"card\", card }),\n onOutcome: (outcome) =>\n channel.push({\n type: \"tool-result\",\n callId: outcome.callId,\n name: outcome.name,\n output: outcome.output,\n ...(outcome.failure ? { failure: outcome.failure } : {}),\n ms: outcome.ms,\n }),\n onHostTool: config.onHostTool,\n requestCard: config.onUserDecision\n ? async (callId, spec: CardSpec) => {\n const card = makeCard(spec, callId);\n channel.push({ type: \"awaiting-user\", callId, card });\n const action = await config.onUserDecision!(callId, card);\n channel.push({ type: \"user-responded\", callId, action });\n return action.type === \"cancel\" || action.type === \"dismiss\"\n ? { cancelled: true, reason: USER_DECLINED }\n : (action.value ?? { confirmed: true });\n }\n : undefined,\n }).finally(() => channel.close());\n\n for await (const event of channel) yield event;\n const outcomes = await running;\n\n // Two versions of each tool result, deliberately:\n // • the EVENT (already sent via `onOutcome`) carries the full output,\n // card payload included, so the UI can render it and the host can\n // persist it;\n // • the message fed back to the provider has the card stripped. The\n // model already read the surrounding data, and re-sending a chart\n // spec on every subsequent step of the same turn is pure waste.\n // No events here: every card and every result already went out through\n // the channel. Re-yielding would double-count in any host recording the\n // stream.\n const providerParts: ContentPart[] = [];\n const persistedParts: ContentPart[] = [];\n for (const outcome of outcomes) {\n const base = {\n type: \"tool-result\" as const,\n callId: outcome.callId,\n name: outcome.name,\n ...(outcome.failure ? { failure: outcome.failure as never } : {}),\n };\n providerParts.push({ ...base, output: stripCardPayload(outcome.output) });\n persistedParts.push({ ...base, output: outcome.output });\n }\n\n const createdAt = Date.now();\n const toolId = nextId(\"tool\");\n working.push({ id: toolId, role: \"tool\", parts: providerParts, createdAt });\n history.push({ id: toolId, role: \"tool\", parts: persistedParts, createdAt });\n\n // loadSkill's pull half: an outcome that unlocked tools re-resolves the\n // active set so the names it announced are callable from the NEXT step.\n // This does change the declared tool block mid-run — accepted: a cache\n // miss on the remaining steps beats advertising tools that 404.\n const unlocked = outcomes.flatMap((o) => o.unlockTools ?? []).filter((n) => !unlockedNames.includes(n));\n if (unlocked.length) {\n unlockedNames = [...unlockedNames, ...unlocked];\n activeTools = config.tools.resolve({ ...config.toolResolution, allow: unlockedNames });\n specs = config.tools.toSpecs(activeTools);\n }\n\n step += 1;\n finishReason = stepFinish;\n\n const stop = shouldStop(config.stopWhen, { step, finishReason: stepFinish, outcomes, usage: totalUsage });\n if (stop) {\n finishReason = \"stop\";\n break;\n }\n }\n\n // Hitting the cap with the model still wanting to act means the answer is\n // truncated. Saying so is better than presenting half a task as finished.\n if (step >= maxSteps && finishReason === \"tool-calls\") {\n yield {\n type: \"message\",\n parts: [\n {\n type: \"text\",\n text: `\\n\\n_(Reached the ${maxSteps}-step limit while still working — this may be incomplete. Ask me to continue.)_`,\n },\n ],\n };\n }\n\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"run\",\n id: `${runId}:run`,\n runId,\n provider: config.provider.id,\n requestedModel: config.model,\n mode,\n status: meteringStatus(finishReason),\n usage: totalUsage,\n source: combineMeteringSources(meteringSources),\n startedAt: runStartedAt,\n finishedAt,\n durationMs: finishedAt - runStartedAt,\n steps: attemptedSteps,\n finishReason,\n ...(reportedModels.size ? { reportedModels: [...reportedModels] } : {}),\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"run-finish\", runId, finishReason, usage: totalUsage, steps: attemptedSteps };\n } catch (e) {\n const error = toAgentError(e, config.provider.id);\n yield { type: \"error\", error, recoverable: false };\n const terminalReason: FinishReason = error.kind === \"cancelled\" ? \"cancelled\" : \"error\";\n const finishedAt = Date.now();\n const record: MeteringRecord = {\n scope: \"run\",\n id: `${runId}:run`,\n runId,\n provider: config.provider.id,\n requestedModel: config.model,\n mode,\n status: error.kind === \"cancelled\" ? \"cancelled\" : \"failed\",\n usage: totalUsage,\n source: combineMeteringSources(meteringSources),\n startedAt: runStartedAt,\n finishedAt,\n durationMs: finishedAt - runStartedAt,\n steps: attemptedSteps,\n finishReason: terminalReason,\n ...(reportedModels.size ? { reportedModels: [...reportedModels] } : {}),\n ...(config.meteringMetadata ? { metadata: config.meteringMetadata } : {}),\n error: { kind: error.kind, message: error.message },\n };\n await deliverMetering(config.meter, record);\n yield { type: \"metering\", record };\n yield { type: \"run-finish\", runId, finishReason: terminalReason, usage: totalUsage, steps: attemptedSteps };\n }\n}\n\n/**\n * Tee a provider stream: forward deltas for live rendering while accumulating\n * the parts that become the assistant message.\n *\n * Necessary because the loop needs BOTH — the UI wants tokens as they arrive,\n * and the next step needs a complete, well-formed message.\n */\nfunction collectStream(stream: AsyncIterable<StreamEvent>) {\n const parts: ContentPart[] = [];\n let finishReason: FinishReason = \"unknown\";\n let usage: Usage | undefined;\n let responseId: string | undefined;\n let modelId = \"\";\n\n async function* events(): AsyncGenerator<StreamEvent> {\n for await (const event of stream) {\n switch (event.type) {\n case \"start\":\n responseId = event.responseId;\n modelId = event.modelId;\n break;\n case \"text-delta\": {\n const last = parts[parts.length - 1];\n if (last?.type === \"text\") last.text += event.delta;\n else parts.push({ type: \"text\", text: event.delta });\n break;\n }\n case \"reasoning-delta\": {\n const last = parts[parts.length - 1];\n if (last?.type === \"reasoning\") {\n last.text += event.delta;\n // Anthropic's replay token (signature_delta) arrives at the END of\n // a thinking block — stamp it onto the accumulated part, or replay\n // never works in stream mode.\n if (event.signature) last.signature = event.signature;\n } else {\n parts.push({ type: \"reasoning\", text: event.delta, ...(event.signature ? { signature: event.signature } : {}) });\n }\n break;\n }\n case \"tool-call-end\":\n parts.push({\n type: \"tool-call\",\n callId: event.callId,\n name: event.name,\n input: event.input,\n status: \"pending\",\n ...(event.repaired ? { repaired: true } : {}),\n });\n break;\n case \"usage\":\n usage = event.usage;\n break;\n case \"finish\":\n finishReason = event.finishReason;\n if (event.usage) usage = event.usage;\n if (event.responseId) responseId = event.responseId;\n break;\n default:\n break;\n }\n yield event;\n }\n }\n\n return {\n events,\n result: (): GenerateResult => ({\n parts,\n finishReason,\n usage: usage ?? {},\n modelId,\n ...(responseId ? { responseId } : {}),\n }),\n };\n}\n\nfunction addUsage(a: Usage, b: Usage): Usage {\n const add = (x?: number, y?: number) => (x == null && y == null ? undefined : (x ?? 0) + (y ?? 0));\n return {\n inputTokens: add(a.inputTokens, b.inputTokens),\n outputTokens: add(a.outputTokens, b.outputTokens),\n totalTokens: add(a.totalTokens, b.totalTokens),\n cachedInputTokens: add(a.cachedInputTokens, b.cachedInputTokens),\n reasoningTokens: add(a.reasoningTokens, b.reasoningTokens),\n };\n}\n\nfunction meteringStatus(reason: FinishReason): \"completed\" | \"failed\" | \"cancelled\" {\n if (reason === \"cancelled\") return \"cancelled\";\n if (reason === \"error\") return \"failed\";\n return \"completed\";\n}\n","// Uploaded-file persistence.\n//\n// A providerFile id is only worth minting if it OUTLIVES the page — the whole\n// point of uploading once is not re-encoding the same bytes as base64 on every\n// turn. Messages that reference a file persist through the ThreadStore; this\n// store is the cross-thread registry that answers \"what have I already\n// uploaded\", so a host can offer re-attach instead of re-upload.\n//\n// Mirrors JobStore deliberately: same shape, same defensiveness. A corrupted\n// entry degrades to \"upload again\", never a crash.\n\nimport type { ProviderFileRef } from \"../providers/types.js\";\n\nexport type StoredFile = {\n ref: ProviderFileRef;\n filename: string;\n mediaType?: string;\n sizeBytes?: number;\n /** Thread the file was first attached in, if any. */\n threadId?: string;\n createdAt: number;\n};\n\nexport type FileStore = {\n list(): Promise<StoredFile[]>;\n /** Keyed by `ref.id`. */\n get(id: string): Promise<StoredFile | undefined>;\n put(file: StoredFile): Promise<void>;\n remove(id: string): Promise<void>;\n};\n\nexport function createMemoryFileStore(): FileStore {\n const files = new Map<string, StoredFile>();\n return {\n async list() {\n return [...files.values()].sort((a, b) => b.createdAt - a.createdAt);\n },\n async get(id) {\n return files.get(id);\n },\n async put(file) {\n files.set(file.ref.id, file);\n },\n async remove(id) {\n files.delete(id);\n },\n };\n}\n\n/** localStorage-backed store. Every read is defensive — see JobStore. */\nexport function createLocalFileStore(key = \"superchat:files\"): FileStore {\n const read = (): Record<string, StoredFile> => {\n try {\n const raw = globalThis.localStorage?.getItem(key) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : {};\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, StoredFile>) : {};\n } catch {\n return {};\n }\n };\n const write = (all: Record<string, StoredFile>) => {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(all));\n } catch {\n // Quota or private mode — a lost ref degrades to \"upload again\", not a crash.\n }\n };\n\n return {\n async list() {\n return Object.values(read()).sort((a, b) => b.createdAt - a.createdAt);\n },\n async get(id) {\n return read()[id];\n },\n async put(file) {\n const all = read();\n all[file.ref.id] = file;\n write(all);\n },\n async remove(id) {\n const all = read();\n delete all[id];\n write(all);\n },\n };\n}\n","// Thread persistence.\n//\n// Snapshot-per-thread, not event sourcing: the client folds a finished run into\n// messages at exactly one point, which makes \"after that fold\" a natural save\n// point, and a snapshot needs no replay machinery to load. Hosts that want an\n// event log can record `RunEvent`s through `reduceRunEvent` themselves — the\n// seam exists; this module just doesn't require it.\n//\n// What is deliberately NOT persisted: compaction summaries and any other\n// derived context. Context is derived, never accumulated — persisting it would\n// freeze one turn's derivation into every later turn.\n//\n// Three implementations ship: memory, localStorage, and REST\n// (`createRestThreadStore`) — the last one so \"bring your own backend\" is a\n// config line rather than an exercise, and so the interface is proven against\n// something that isn't synchronous key-value storage.\n\nimport { linkLinear } from \"../content/branching.js\";\nimport type { Message } from \"../content/types.js\";\n\nexport type ThreadMeta = {\n id: string;\n /** Derived at save time from the first user message; never model-generated. */\n title?: string;\n createdAt: number;\n updatedAt: number;\n messageCount: number;\n};\n\nexport const THREAD_SCHEMA_VERSION = 2 as const;\n\nexport type StoredThread = {\n version: typeof THREAD_SCHEMA_VERSION;\n meta: ThreadMeta;\n /** The full message TREE (flat, parentId pointers) — abandoned branches included. */\n messages: Message[];\n /** Leaf of the active branch. Absent → the last message (v1-era linearity). */\n headId?: string | null;\n};\n\n/**\n * v1 stored threads (linear, no parent pointers) migrate on read: the list is\n * linked into a chain and the head is the last message. Never thrown away —\n * a stored conversation outliving a schema bump is the whole point of the\n * version field.\n */\nfunction migrate(parsed: { version?: number; meta?: ThreadMeta; messages?: Message[]; headId?: string | null }): StoredThread | undefined {\n if (!parsed || !Array.isArray(parsed.messages) || !parsed.meta) return undefined;\n if (parsed.version === THREAD_SCHEMA_VERSION) return parsed as StoredThread;\n if (parsed.version === 1) {\n const messages = linkLinear(parsed.messages);\n return {\n version: THREAD_SCHEMA_VERSION,\n meta: parsed.meta,\n messages,\n headId: messages.at(-1)?.id ?? null,\n };\n }\n return undefined; // a FUTURE version reads as absent, never a crash\n}\n\nexport type ThreadStore = {\n /** Metadata only — a thread picker must not load every message ever sent. */\n list(): Promise<ThreadMeta[]>;\n load(id: string): Promise<StoredThread | undefined>;\n save(thread: StoredThread): Promise<void>;\n remove(id: string): Promise<void>;\n};\n\nconst TITLE_MAX = 64;\n\nfunction deriveTitle(messages: readonly Message[]): string | undefined {\n for (const m of messages) {\n if (m.role !== \"user\") continue;\n for (const p of m.parts) {\n if (p.type === \"text\" && p.text.trim()) {\n const line = p.text.trim().split(\"\\n\", 1)[0]!;\n return line.length > TITLE_MAX ? `${line.slice(0, TITLE_MAX - 1)}…` : line;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Deep-clone through JSON, per message.\n *\n * Tool inputs/outputs and artifact data are `unknown` — a host's execute can\n * return a Date, a Map, or something circular. The round-trip normalizes what\n * JSON can carry and a per-message fallback replaces what it can't, because\n * persistence must never take down a run.\n */\nfunction safeCloneMessages(messages: readonly Message[]): Message[] {\n try {\n return JSON.parse(JSON.stringify(messages)) as Message[];\n } catch {\n return messages.map((m) => {\n try {\n return JSON.parse(JSON.stringify(m)) as Message;\n } catch {\n return {\n id: m.id,\n role: m.role,\n parts: [{ type: \"text\", text: \"[unserializable message dropped]\" }],\n ...(m.createdAt != null ? { createdAt: m.createdAt } : {}),\n };\n }\n });\n }\n}\n\n/** Build a JSON-safe snapshot: safe-clone, derive title, stamp meta. */\nexport function threadSnapshot(\n id: string,\n messages: readonly Message[],\n prior?: ThreadMeta,\n headId?: string | null,\n): StoredThread {\n const cloned = safeCloneMessages(messages);\n const title = deriveTitle(cloned) ?? prior?.title;\n return {\n version: THREAD_SCHEMA_VERSION,\n meta: {\n id,\n ...(title ? { title } : {}),\n createdAt: prior?.createdAt ?? Date.now(),\n updatedAt: Date.now(),\n messageCount: cloned.length,\n },\n messages: cloned,\n headId: headId !== undefined ? headId : (cloned.at(-1)?.id ?? null),\n };\n}\n\nexport function createMemoryThreadStore(): ThreadStore {\n const threads = new Map<string, StoredThread>();\n return {\n async list() {\n return [...threads.values()].map((t) => t.meta).sort((a, b) => b.updatedAt - a.updatedAt);\n },\n async load(id) {\n const t = threads.get(id);\n return t ? migrate(t) : undefined;\n },\n async save(thread) {\n threads.set(thread.meta.id, thread);\n },\n async remove(id) {\n threads.delete(id);\n },\n };\n}\n\n/**\n * localStorage-backed store, key per thread: `{prefix}:index` holds the meta\n * list, `{prefix}:{id}` holds one thread. One growing thread must not rewrite\n * every other thread on each save (the job store's single-blob layout is fine\n * for handles; it is wrong for conversations).\n *\n * Every read is defensive — a corrupted entry reads as absent, never a throw.\n * A version other than the current one also reads as absent: v2 migrates\n * deliberately, it does not crash v1 readers.\n */\nexport function createLocalThreadStore(prefix = \"superchat:threads\"): ThreadStore {\n const indexKey = `${prefix}:index`;\n const threadKey = (id: string) => `${prefix}:${id}`;\n\n const readIndex = (): ThreadMeta[] => {\n try {\n const raw = globalThis.localStorage?.getItem(indexKey) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : [];\n return Array.isArray(parsed) ? (parsed as ThreadMeta[]).filter((m) => typeof m?.id === \"string\") : [];\n } catch {\n return [];\n }\n };\n const writeIndex = (metas: ThreadMeta[]): void => {\n try {\n globalThis.localStorage?.setItem(indexKey, JSON.stringify(metas));\n } catch {\n // Quota or private mode — the thread entries themselves may still exist;\n // a stale index degrades to an incomplete picker, not a crash.\n }\n };\n\n return {\n async list() {\n return readIndex().sort((a, b) => b.updatedAt - a.updatedAt);\n },\n\n async load(id) {\n try {\n const raw = globalThis.localStorage?.getItem(threadKey(id)) ?? null;\n if (!raw) return undefined;\n return migrate(JSON.parse(raw) as StoredThread);\n } catch {\n return undefined;\n }\n },\n\n async save(thread) {\n const store = globalThis.localStorage;\n if (!store) return;\n const key = threadKey(thread.meta.id);\n let payload = thread;\n try {\n store.setItem(key, JSON.stringify(payload));\n } catch {\n // Quota. Shed the heaviest cargo — artifact payloads (card specs,\n // chart data) — and mark them expired so the UI says \"this result\n // expired, ask again\" instead of rendering an empty shell. One retry;\n // if that also fails, the previous snapshot stays.\n payload = { ...thread, messages: expireArtifacts(thread.messages) };\n try {\n store.setItem(key, JSON.stringify(payload));\n } catch {\n return;\n }\n }\n const index = readIndex().filter((m) => m.id !== thread.meta.id);\n index.push(payload.meta);\n writeIndex(index);\n },\n\n async remove(id) {\n try {\n globalThis.localStorage?.removeItem(threadKey(id));\n } catch {\n // removeItem does not throw for quota; being defensive costs nothing.\n }\n writeIndex(readIndex().filter((m) => m.id !== id));\n },\n };\n}\n\nexport type RestThreadStoreConfig = {\n /** Base path of your thread API, e.g. \"/api/threads\". */\n url: string;\n /** Extra headers (auth, CSRF). A function is called per request. */\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);\n credentials?: RequestCredentials;\n fetchImpl?: typeof fetch;\n /**\n * Called when a request fails. Default: swallow. Persistence is\n * fire-and-forget at the call site, so a thrown error would surface as an\n * unhandled rejection rather than anything a user can act on — but a host\n * that wants telemetry needs the hook.\n */\n onError?: (error: unknown, op: \"list\" | \"load\" | \"save\" | \"remove\") => void;\n};\n\n/**\n * REST-backed store — the \"bring your own backend\" implementation.\n *\n * The wire contract, four calls:\n * GET {url} → ThreadMeta[]\n * GET {url}/{id} → StoredThread (404 = absent, not an error)\n * PUT {url}/{id} ← StoredThread\n * DELETE {url}/{id}\n *\n * Reads stay defensive in the same way the localStorage store is: a failed or\n * malformed response degrades to \"not found\" / \"empty list\" rather than\n * throwing into a render or a run. Records still go through `migrate`, so a\n * server that stored v1 payloads keeps working.\n */\nexport function createRestThreadStore(config: RestThreadStoreConfig): ThreadStore {\n const doFetch = config.fetchImpl ?? globalThis.fetch;\n const base = config.url.replace(/\\/$/, \"\");\n const path = (id: string) => `${base}/${encodeURIComponent(id)}`;\n\n const headers = async (): Promise<Record<string, string>> =>\n typeof config.headers === \"function\" ? await config.headers() : (config.headers ?? {});\n\n const request = async (input: string, init: RequestInit, op: \"list\" | \"load\" | \"save\" | \"remove\"): Promise<Response | undefined> => {\n try {\n const res = await doFetch(input, {\n ...init,\n headers: { ...(init.body ? { \"content-type\": \"application/json\" } : {}), ...(await headers()), ...init.headers },\n credentials: config.credentials ?? \"same-origin\",\n });\n // 404 on load is a legitimate \"no such thread\", not a failure.\n if (!res.ok && !(op === \"load\" && res.status === 404)) {\n config.onError?.(new Error(`Thread store ${op} failed: ${res.status}`), op);\n return undefined;\n }\n return res;\n } catch (e) {\n config.onError?.(e, op);\n return undefined;\n }\n };\n\n return {\n async list() {\n const res = await request(base, { method: \"GET\" }, \"list\");\n if (!res) return [];\n try {\n const parsed = (await res.json()) as unknown;\n return Array.isArray(parsed)\n ? (parsed as ThreadMeta[]).filter((m) => typeof m?.id === \"string\").sort((a, b) => b.updatedAt - a.updatedAt)\n : [];\n } catch (e) {\n config.onError?.(e, \"list\");\n return [];\n }\n },\n\n async load(id) {\n const res = await request(path(id), { method: \"GET\" }, \"load\");\n if (!res || res.status === 404) return undefined;\n try {\n return migrate((await res.json()) as StoredThread);\n } catch (e) {\n config.onError?.(e, \"load\");\n return undefined;\n }\n },\n\n async save(thread) {\n await request(path(thread.meta.id), { method: \"PUT\", body: JSON.stringify(thread) }, \"save\");\n },\n\n async remove(id) {\n await request(path(id), { method: \"DELETE\" }, \"remove\");\n },\n };\n}\n\n/** Replace every artifact part's data with an expired stub. */\nfunction expireArtifacts(messages: readonly Message[]): Message[] {\n return messages.map((m) => ({\n ...m,\n parts: m.parts.map((p) =>\n p.type === \"artifact\"\n ? { ...p, data: { kind: (p.data as { kind?: string } | null)?.kind ?? p.kind, expired: true } }\n : p,\n ),\n }));\n}\n","// Persistent cross-thread memory.\n//\n// The seam, not a database: `MemoryStore` is four async methods a host backs\n// with anything (localStorage here, a row per user in production), and the two\n// halves that plug it into the machinery that already exists —\n//\n// READ → `createMemorySource()` a ContextSource injecting remembered facts\n// as a \"memory\" layer, under the same token budget and trace as\n// every other layer (\"why does the model know that\" stays answerable);\n// WRITE → `createRememberTool()` a tool the model calls to save, update or\n// forget a fact — memory the USER can see forming, not a hidden\n// profile.\n//\n// Deliberately NOT persisted: conversation history (that is the ThreadStore's\n// job) or derived context. Memory is small, structured, and cross-thread:\n// preferences, standing facts, corrections.\n\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { ContextSource } from \"../context/types.js\";\nimport type { ToolDefinition } from \"../tools/types.js\";\n\nexport type MemoryEntry = {\n /** Stable slug (\"preferred-language\"), so a fact updates instead of duplicating. */\n key: string;\n value: string;\n updatedAt: number;\n};\n\nexport type MemoryStore = {\n /** `vars` carries host scoping (user id, workspace) — the store decides what it means. */\n list(vars?: Record<string, unknown>): Promise<MemoryEntry[]>;\n set(key: string, value: string, vars?: Record<string, unknown>): Promise<void>;\n remove(key: string, vars?: Record<string, unknown>): Promise<void>;\n};\n\n/**\n * Total facts a store keeps before it starts evicting. Distinct from\n * `MemorySourceOptions.maxEntries` (below), which caps how many of the\n * stored facts are injected into a single turn's context — this cap bounds\n * the store itself so it doesn't grow forever.\n */\nconst DEFAULT_STORE_CAP = 500;\n\n/** Most-recently-updated first, so a cap-and-slice keeps the freshest facts. */\nfunction byRecency(a: MemoryEntry, b: MemoryEntry): number {\n return b.updatedAt - a.updatedAt;\n}\n\nexport function createMemoryMemoryStore(opts: { maxEntries?: number } = {}): MemoryStore {\n const cap = opts.maxEntries ?? DEFAULT_STORE_CAP;\n const entries = new Map<string, MemoryEntry>();\n return {\n async list() {\n return [...entries.values()].sort(byRecency);\n },\n async set(key, value) {\n entries.set(key, { key, value, updatedAt: Date.now() });\n if (entries.size > cap) {\n // Evict oldest-by-updatedAt beyond the cap, at write time — a store\n // that only trims at read time never actually shrinks.\n const overflow = [...entries.values()].sort(byRecency).slice(cap);\n for (const e of overflow) entries.delete(e.key);\n }\n },\n async remove(key) {\n entries.delete(key);\n },\n };\n}\n\n/** localStorage-backed store — same defensiveness as the job/file stores. */\nexport function createLocalMemoryStore(storageKey = \"superchat:memory\", opts: { maxEntries?: number } = {}): MemoryStore {\n const cap = opts.maxEntries ?? DEFAULT_STORE_CAP;\n const read = (): Record<string, MemoryEntry> => {\n try {\n const raw = globalThis.localStorage?.getItem(storageKey) ?? null;\n const parsed = raw ? (JSON.parse(raw) as unknown) : {};\n return typeof parsed === \"object\" && parsed !== null ? (parsed as Record<string, MemoryEntry>) : {};\n } catch {\n return {};\n }\n };\n const write = (all: Record<string, MemoryEntry>) => {\n try {\n globalThis.localStorage?.setItem(storageKey, JSON.stringify(all));\n } catch {\n // Quota/private mode — a lost memory degrades to \"not remembered\".\n }\n };\n return {\n async list() {\n return Object.values(read()).sort(byRecency);\n },\n async set(key, value) {\n const all = read();\n all[key] = { key, value, updatedAt: Date.now() };\n const keys = Object.keys(all);\n if (keys.length > cap) {\n const overflow = keys.map((k) => all[k]!).sort(byRecency).slice(cap);\n for (const e of overflow) delete all[e.key];\n }\n write(all);\n },\n async remove(key) {\n const all = read();\n delete all[key];\n write(all);\n },\n };\n}\n\nexport type MemorySourceOptions = {\n id?: string;\n /** Budget-pressure priority; identity is 1000, skills ~800. */\n priority?: number;\n /** Cap on injected entries — memory must not crowd out the conversation. */\n maxEntries?: number;\n};\n\n/** The read half: remembered facts as a context layer, every turn. */\nexport function createMemorySource(store: MemoryStore, opts: MemorySourceOptions = {}): ContextSource {\n return {\n id: opts.id ?? \"memory\",\n async run({ vars }) {\n const entries = (await store.list(vars)).slice(0, opts.maxEntries ?? 50);\n if (!entries.length) return {};\n const text = [\n \"Things you remember about this user, from earlier conversations:\",\n ...entries.map((e) => `- ${e.key}: ${e.value}`),\n \"Apply them without re-asking. Update them with the `remember` tool when they change.\",\n ].join(\"\\n\");\n return {\n layers: [\n {\n id: opts.id ?? \"memory\",\n kind: \"memory\",\n text,\n tokens: estimateTokens(text),\n priority: opts.priority ?? 500,\n },\n ],\n };\n },\n };\n}\n\n/** The write half: the model saves/updates/forgets a fact, visibly. */\nexport function createRememberTool(store: MemoryStore): ToolDefinition {\n return {\n name: \"remember\",\n side: \"write\",\n description:\n \"Save a durable fact about the user for future conversations — a preference, a standing constraint, a correction. \" +\n \"Use a stable key so updating a fact replaces it instead of duplicating it. \" +\n \"Pass value: null to forget a fact. Do NOT store conversation history or anything the user would not expect to be remembered.\",\n inputSchema: {\n type: \"object\",\n required: [\"key\"],\n properties: {\n key: { type: \"string\", description: 'Stable slug, e.g. \"preferred-language\".' },\n value: { type: [\"string\", \"null\"], description: \"The fact to remember, or null to forget the key.\" },\n },\n additionalProperties: false,\n },\n async execute(input, ctx) {\n const { key, value } = (input ?? {}) as { key?: string; value?: string | null };\n if (!key) return { output: { ok: false, error: \"`key` is required.\" }, failure: \"invalid-input\" as const };\n if (value == null || value === \"\") {\n await store.remove(key, ctx.vars);\n return { output: { ok: true, forgot: key } };\n }\n await store.set(key, value, ctx.vars);\n return { output: { ok: true, remembered: { key, value } } };\n },\n };\n}\n","// Retrieval seam.\n//\n// The framework's position: retrieval is a CONTEXT SOURCE, not a vector\n// database. `Retriever` is one method a host backs with whatever it already\n// runs (pgvector, Elasticsearch, a SaaS RAG API); `createRetrievalSource()`\n// runs it against the turn's query and injects the hits as a numbered\n// evidence layer — under the same token budget, recorded in the same trace,\n// with reference markers the model can cite via the `citations` card. That\n// closes the loop the card system left open: a citations renderer with no way\n// to produce citations.\n//\n// `createKeywordRetriever()` is the zero-dependency reference implementation —\n// honest lexical overlap scoring for demos and tests, not a semantic index.\n\nimport { tokenize } from \"../skills/match.js\";\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { ContextSource } from \"../context/types.js\";\n\nexport type RetrievedChunk = {\n id: string;\n text: string;\n /** Where this came from — shown to the user in citations. */\n source?: string;\n title?: string;\n uri?: string;\n /** Higher is better; used only for ordering, scale is the retriever's. */\n score?: number;\n};\n\nexport type Retriever = {\n retrieve(query: string, opts?: { limit?: number; signal?: AbortSignal; vars?: Record<string, unknown> }): Promise<RetrievedChunk[]>;\n};\n\nexport type RetrievalSourceOptions = {\n id?: string;\n /** Max chunks injected per turn. */\n limit?: number;\n /** Budget-pressure priority; memory is 500. */\n priority?: number;\n /** Skip retrieval entirely for queries shorter than this (greetings). */\n minQueryLength?: number;\n};\n\n/** Plug a retriever into context assembly as a cited-evidence layer. */\nexport function createRetrievalSource(retriever: Retriever, opts: RetrievalSourceOptions = {}): ContextSource {\n return {\n id: opts.id ?? \"retrieval\",\n async run({ query, vars, signal }) {\n if (query.trim().length < (opts.minQueryLength ?? 8)) return {};\n const chunks = (await retriever.retrieve(query, { limit: opts.limit ?? 5, signal, vars })).slice(\n 0,\n opts.limit ?? 5,\n );\n if (!chunks.length) return {};\n\n const text = [\n \"Reference material retrieved for this question. Ground your answer in it when relevant:\",\n ...chunks.map(\n (c, i) =>\n `[${i + 1}] ${c.title ?? c.id}${c.source ? ` (${c.source})` : \"\"}\\n${c.text.trim()}`,\n ),\n \"When your answer draws on a reference, cite it — use the `citations` card via the visualize tool, quoting the passage you relied on, so the reader can check the work.\",\n ].join(\"\\n\\n\");\n\n return {\n layers: [\n {\n id: opts.id ?? \"retrieval\",\n kind: \"custom\",\n text,\n tokens: estimateTokens(text),\n priority: opts.priority ?? 400,\n },\n ],\n };\n },\n };\n}\n\nexport type RetrievalDoc = { id: string; text: string; title?: string; source?: string; uri?: string };\n\n/**\n * Zero-dependency lexical retriever: paragraphs scored by token overlap with\n * the query (CJK-safe via the skills tokenizer). The reference implementation\n * a host swaps for a real index — and enough for a playground to demonstrate\n * the whole retrieve → inject → cite loop honestly.\n */\nexport function createKeywordRetriever(docs: readonly RetrievalDoc[]): Retriever {\n type Chunk = RetrievedChunk & { terms: Set<string>; idx: number };\n const chunks: Chunk[] = docs\n .flatMap((doc) =>\n doc.text\n .split(/\\n\\s*\\n/)\n .map((p) => p.trim())\n .filter((p) => p.length > 0)\n .map((paragraph, i) => ({\n id: `${doc.id}#${i}`,\n text: paragraph,\n ...(doc.title ? { title: doc.title } : {}),\n ...(doc.source ? { source: doc.source } : {}),\n ...(doc.uri ? { uri: doc.uri } : {}),\n terms: new Set(tokenize(paragraph)),\n })),\n )\n // `idx` records original corpus order so candidate gathering below (which\n // visits chunks per query term, not in corpus order) can restore it before\n // scoring — ties must break the same way the old full scan did.\n .map((c, idx) => ({ ...c, idx }));\n\n // term → chunks containing it, built once so a query only touches chunks\n // sharing at least one query term instead of rescanning the whole corpus.\n const invertedIndex = new Map<string, Chunk[]>();\n for (const chunk of chunks) {\n for (const term of chunk.terms) {\n const bucket = invertedIndex.get(term);\n if (bucket) bucket.push(chunk);\n else invertedIndex.set(term, [chunk]);\n }\n }\n\n return {\n async retrieve(query, opts = {}) {\n const queryTerms = tokenize(query);\n if (!queryTerms.length) return [];\n\n const seen = new Set<Chunk>();\n const candidates: Chunk[] = [];\n for (const term of queryTerms) {\n for (const chunk of invertedIndex.get(term) ?? []) {\n if (!seen.has(chunk)) {\n seen.add(chunk);\n candidates.push(chunk);\n }\n }\n }\n candidates.sort((a, b) => a.idx - b.idx);\n\n const scored = candidates\n .map((c) => {\n const hits = queryTerms.filter((t) => c.terms.has(t)).length;\n return { chunk: c, score: hits / Math.sqrt(c.terms.size || 1) };\n })\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, opts.limit ?? 5);\n return scored.map(({ chunk, score }) => {\n const { terms: _terms, idx: _idx, ...rest } = chunk;\n return { ...rest, score };\n });\n },\n };\n}\n","// The app-state seam — the agent reading and operating the HOST APPLICATION,\n// not just the transcript.\n//\n// This is the piece that makes \"an agent surface inside your own product\"\n// literal. Without it an agent can only talk about the product; with it the\n// agent sees what the user sees (a form's current values, the selected rows,\n// the open document) and can act on it (fill the field, apply the filter,\n// navigate) — while the UI stays the source of truth and re-renders normally.\n//\n// Two halves, both built on machinery that already exists:\n//\n// READ → `createAppStateSource()` is a ContextSource. State enters context\n// the same way memory and retrieval do: budgeted, traced, derived\n// fresh every turn — never accumulated, so a stale snapshot from\n// three turns ago can't contradict the screen.\n// WRITE → `createAppActionTools()` are ordinary ToolDefinitions, which means\n// they inherit the whole security model for free: preset allowlists,\n// `side: \"confirm\"` suspension, deny-last. An action that mutates a\n// user's document belongs in `executor`, and the framework already\n// knows what that means.\n//\n// The deliberate non-goal: no diffing, no CRDT, no bidirectional sync\n// protocol. The host owns its state and already has a way to render it; this\n// reads a snapshot and calls a handler. Anything more would be a state\n// manager competing with the one the host already uses.\n\nimport { estimateTokens } from \"../tokens/estimate.js\";\nimport type { ContextSource } from \"../context/types.js\";\nimport type { JSONSchema } from \"../providers/types.js\";\nimport type { ToolDefinition, ToolSide } from \"../tools/types.js\";\n\nexport type AppStateBinding<T = unknown> = {\n /** Stable id — also the context layer id and the trace entry name. */\n id: string;\n /**\n * What this state IS, in the model's vocabulary. This is the description the\n * model reasons about, so write it for the model: \"the checkout form the\n * user is filling in\", not \"checkoutFormState\".\n */\n description: string;\n /** Read the CURRENT value. Called fresh every turn — never cached. */\n read(): T | Promise<T>;\n /**\n * Serialize for the prompt. Default is pretty JSON; override to summarize a\n * large store down to what the model actually needs.\n */\n serialize?(value: T): string;\n /** Skip injection entirely (a closed dialog's state is noise). */\n when?(value: T): boolean;\n};\n\nexport type AppAction<I = Record<string, unknown>> = {\n /** Tool name the model calls — verb-shaped: `applyFilter`, `openDocument`. */\n name: string;\n description: string;\n inputSchema: JSONSchema;\n /**\n * Perform it against the host app. The return value is what the model reads\n * back, so return the RESULT (\"filter applied, 12 rows match\"), not `void` —\n * an action whose outcome the model can't observe is an action it will\n * repeat.\n */\n run(input: I): unknown | Promise<unknown>;\n /**\n * `confirm` suspends the run behind an interactive card before executing —\n * the right default for anything the user would want to see first.\n */\n side?: ToolSide;\n};\n\nexport type AppStateSourceOptions = {\n id?: string;\n /** Budget-pressure priority. Memory is 500, retrieval 400. */\n priority?: number;\n};\n\nconst defaultSerialize = (value: unknown): string => {\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n return \"[unserializable state]\";\n }\n};\n\n/**\n * The read half: host application state as a context layer, refreshed every\n * turn. Bindings that throw are skipped rather than failing the turn — a\n * component unmounting mid-run must cost context, not the conversation.\n */\nexport function createAppStateSource(\n // Bindings are heterogeneous by nature — a form's values and a selection's\n // ids have nothing in common — so the array is typed at the erased boundary\n // and each binding keeps its own type at its definition site.\n bindings: readonly AppStateBinding<any>[],\n opts: AppStateSourceOptions = {},\n): ContextSource {\n return {\n id: opts.id ?? \"app-state\",\n async run() {\n const blocks: string[] = [];\n for (const binding of bindings) {\n try {\n const value = await binding.read();\n if (binding.when && !binding.when(value)) continue;\n const body = (binding.serialize ?? defaultSerialize)(value);\n if (!body?.trim()) continue;\n blocks.push(`### ${binding.id} — ${binding.description}\\n${body}`);\n } catch {\n // A binding that throws is a component that went away. Skip it.\n }\n }\n if (!blocks.length) return {};\n\n const text = [\n \"Current state of the application the user is looking at. This is live — it reflects the screen right now, not the conversation:\",\n ...blocks,\n \"Refer to it directly rather than asking the user to repeat what is already on screen.\",\n ].join(\"\\n\\n\");\n\n return {\n layers: [\n {\n id: opts.id ?? \"app-state\",\n kind: \"environment\",\n text,\n tokens: estimateTokens(text),\n priority: opts.priority ?? 600,\n },\n ],\n };\n },\n };\n}\n\n/**\n * The write half: host actions as ordinary tools.\n *\n * Returned, not registered — the host calls `registry.registerAll(...)` with\n * the preset it decides these deserve. That is the same rule MCP imports\n * follow, and for the same reason: a tool that can mutate the user's document\n * must get its authority explicitly, never by virtue of being wired up.\n */\nexport function createAppActionTools(actions: readonly AppAction<any>[]): ToolDefinition[] {\n return actions.map((action) => ({\n name: action.name,\n description: action.description,\n inputSchema: action.inputSchema,\n side: action.side ?? \"write\",\n execute: async (input) => {\n const result = await action.run((input ?? {}) as Record<string, unknown>);\n // A bare undefined reads as failure to a model; say it worked.\n return { output: result === undefined ? { ok: true } : result };\n },\n }));\n}\n","// A minimal MCP client — Streamable HTTP only, deliberately.\n//\n// This is a FRONTEND framework: the MCP servers it can reach are remote HTTP\n// ones. stdio transport means spawning a process, which a browser cannot do —\n// hosts that want stdio servers put them behind an HTTP gateway.\n//\n// The client rides the same `Transport` seam the LLM adapters use, and for the\n// same reason: credentials. An MCP server whose token must stay server-side is\n// one more entry in `createProxyHandler`'s provider map ({ baseUrl: the MCP\n// server, apiKey: its token, allowPaths: [\"POST /mcp\"] }) and this client runs\n// over the same proxy transport, no new machinery. For unauthenticated or\n// local servers, `createHttpTransport` below talks straight HTTP.\n\nimport { AgentError } from \"../errors.js\";\nimport { errorFromResponse } from \"../transport/retry.js\";\nimport { parseSSEJson } from \"../transport/sse.js\";\nimport type { Transport, TransportRequest } from \"../transport/types.js\";\nimport type {\n JsonRpcRequest,\n JsonRpcResponse,\n McpCallResult,\n McpElicitHandler,\n McpElicitRequest,\n McpServerInfo,\n McpTool,\n} from \"./types.js\";\n\nexport type McpClientConfig = {\n transport: Transport;\n /** Routing id in the proxy's provider map. Default \"mcp\". */\n provider?: string;\n /** Server-relative path of the MCP endpoint. Default \"/\". */\n path?: string;\n protocolVersion?: string;\n clientInfo?: { name: string; version: string };\n /**\n * Answer `elicitation/create` — the server asking the USER for structured\n * input mid-call. Without a handler, elicitations are declined (never hung).\n * `importMcpTools` bridges this onto the interactive-card suspension, so an\n * eliciting server gets the same form-card UX as a local `confirm` tool.\n */\n onElicit?: McpElicitHandler;\n};\n\nconst DEFAULT_PROTOCOL = \"2025-06-18\";\n\n/** Bounds every request when the caller supplies no signal of its own — a hung MCP server must not block forever. */\nconst DEFAULT_RPC_TIMEOUT_MS = 30_000;\n\n/**\n * Combine signals so any one of them can abort the request. Prefers the\n * platform `AbortSignal.any` where available; falls back to a manual\n * listener-based combine for runtimes that lack it.\n */\nfunction combineSignals(signals: readonly (AbortSignal | undefined)[]): AbortSignal {\n const present = signals.filter((s): s is AbortSignal => s != null);\n if (present.length === 0) return new AbortController().signal; // never aborts\n if (present.length === 1) return present[0]!;\n if (typeof AbortSignal.any === \"function\") return AbortSignal.any(present);\n\n const controller = new AbortController();\n for (const s of present) {\n if (s.aborted) {\n controller.abort(s.reason);\n break;\n }\n s.addEventListener(\"abort\", () => controller.abort(s.reason), { once: true });\n }\n return controller.signal;\n}\n\n/** Thrown for protocol-level JSON-RPC errors (unknown method, bad params). */\nexport class McpRpcError extends Error {\n readonly code: number;\n readonly data?: unknown;\n constructor(code: number, message: string, data?: unknown) {\n super(message);\n this.name = \"McpRpcError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/** More pages than any real server has; past this, pagination is treated as a loop. */\nconst MAX_TOOL_PAGES = 1000;\n\nexport class McpClient {\n private readonly transport: Transport;\n private readonly provider: string;\n private readonly path: string;\n private readonly protocolVersion: string;\n private readonly clientInfo: { name: string; version: string };\n private readonly onElicit: McpElicitHandler | undefined;\n private rpcId = 0;\n private sessionId: string | undefined;\n private handshake: { serverInfo: McpServerInfo; protocolVersion: string } | undefined;\n /** The in-flight `connect()` call, if any — concurrent callers await this instead of starting their own `initialize` round trip. */\n private connecting: Promise<{ serverInfo: McpServerInfo; protocolVersion: string }> | undefined;\n\n constructor(config: McpClientConfig) {\n this.transport = config.transport;\n this.provider = config.provider ?? \"mcp\";\n this.path = config.path ?? \"/\";\n this.protocolVersion = config.protocolVersion ?? DEFAULT_PROTOCOL;\n this.clientInfo = config.clientInfo ?? { name: \"superchat\", version: \"0.1.0\" };\n this.onElicit = config.onElicit;\n }\n\n /**\n * Idempotent: a second call returns the cached handshake. Concurrent calls\n * while the first is still in flight share that same call rather than each\n * firing their own `initialize` round trip.\n */\n async connect(): Promise<{ serverInfo: McpServerInfo; protocolVersion: string }> {\n if (this.handshake) return this.handshake;\n if (this.connecting) return this.connecting;\n this.connecting = this.doConnect().finally(() => {\n this.connecting = undefined;\n });\n return this.connecting;\n }\n\n private async doConnect(): Promise<{ serverInfo: McpServerInfo; protocolVersion: string }> {\n const result = (await this.rpc(\"initialize\", {\n protocolVersion: this.protocolVersion,\n // Declaring elicitation is what permits the server to ask; without a\n // handler we keep the capability undeclared and decline defensively.\n capabilities: this.onElicit ? { elicitation: {} } : {},\n clientInfo: this.clientInfo,\n })) as { protocolVersion?: string; serverInfo?: McpServerInfo };\n\n // Fire the initialized notification; a server may 202 it with no body.\n await this.post({ jsonrpc: \"2.0\", method: \"notifications/initialized\" });\n\n this.handshake = {\n serverInfo: result.serverInfo ?? { name: \"unknown\" },\n protocolVersion: result.protocolVersion ?? this.protocolVersion,\n };\n return this.handshake;\n }\n\n /** All tools, following `nextCursor` pagination to exhaustion. */\n async listTools(opts: { signal?: AbortSignal } = {}): Promise<McpTool[]> {\n await this.ensureConnected();\n const tools: McpTool[] = [];\n // A server that keeps handing back the same cursor (or never stops paginating) would otherwise\n // loop here for ever, growing `tools` without bound.\n const seen = new Set<string>();\n let cursor: string | undefined;\n do {\n const page = (await this.rpc(\"tools/list\", cursor ? { cursor } : {}, opts)) as {\n tools?: McpTool[];\n nextCursor?: string;\n };\n if (Array.isArray(page.tools)) tools.push(...page.tools);\n cursor = typeof page.nextCursor === \"string\" && page.nextCursor !== \"\" ? page.nextCursor : undefined;\n if (cursor !== undefined) {\n if (seen.has(cursor) || seen.size >= MAX_TOOL_PAGES) {\n throw new McpRpcError(-32603, \"tools/list pagination does not terminate (repeated cursor or too many pages)\");\n }\n seen.add(cursor);\n }\n } while (cursor);\n return tools;\n }\n\n /**\n * Call a tool. A JSON-RPC error comes back as a failed `McpCallResult`\n * rather than a throw — tool errors are for the model to read, and an\n * exception here would abort the whole agent turn instead of one step.\n */\n async callTool(\n name: string,\n args: unknown,\n opts: { signal?: AbortSignal; onElicit?: McpElicitHandler } = {},\n ): Promise<McpCallResult> {\n await this.ensureConnected();\n try {\n const result = (await this.rpc(\"tools/call\", { name, arguments: args ?? {} }, opts)) as McpCallResult;\n return { ...result, content: result.content ?? [] };\n } catch (e) {\n if (e instanceof McpRpcError) {\n return { content: [{ type: \"text\", text: e.message }], isError: true };\n }\n throw e;\n }\n }\n\n /** Best-effort session teardown; servers may not support DELETE. */\n async close(): Promise<void> {\n if (!this.sessionId) return;\n try {\n await this.transport.fetch(this.request(\"DELETE\"));\n } catch {\n // The session expires server-side regardless.\n }\n this.sessionId = undefined;\n this.handshake = undefined;\n }\n\n private async ensureConnected(): Promise<void> {\n if (!this.handshake) await this.connect();\n }\n\n private request(method: TransportRequest[\"method\"], body?: unknown): TransportRequest {\n return {\n provider: this.provider,\n path: this.path,\n method,\n ...(body !== undefined ? { body } : {}),\n headers: {\n // Streamable HTTP: a POST response may be JSON or an SSE stream.\n accept: \"application/json, text/event-stream\",\n ...(this.sessionId ? { \"mcp-session-id\": this.sessionId } : {}),\n },\n };\n }\n\n private async post(body: JsonRpcRequest, signal?: AbortSignal): Promise<Response> {\n // Every call gets bounded by DEFAULT_RPC_TIMEOUT_MS, even when the caller\n // supplies its own signal — a caller's signal is typically for run-level\n // cancellation, not a guarantee the server will ever respond.\n const combined = combineSignals([signal, AbortSignal.timeout(DEFAULT_RPC_TIMEOUT_MS)]);\n const res = await this.transport.fetch({ ...this.request(\"POST\", body), signal: combined });\n const sid = res.headers.get(\"mcp-session-id\");\n if (sid) this.sessionId = sid;\n if (!res.ok) throw await errorFromResponse(res, this.provider);\n return res;\n }\n\n private async rpc(\n method: string,\n params: unknown,\n opts: { signal?: AbortSignal; onElicit?: McpElicitHandler } = {},\n ): Promise<unknown> {\n this.rpcId += 1;\n const id = this.rpcId;\n const res = await this.post({ jsonrpc: \"2.0\", id, method, params }, opts.signal);\n\n const contentType = res.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"text/event-stream\")) {\n if (!res.body) throw new AgentError(\"network\", \"MCP response had no body to stream.\", { provider: this.provider });\n // The stream carries our response, server notifications, AND possibly\n // server-initiated REQUESTS (elicitation). Answer those inline — the\n // final tool result cannot arrive until the elicitation is settled, so\n // awaiting here is the correct ordering, not a stall.\n for await (const frame of parseSSEJson<JsonRpcResponse & JsonRpcRequest>(res.body)) {\n const msg = frame.data;\n if (!msg) continue;\n if (typeof msg.method === \"string\" && msg.id != null) {\n await this.answerServerRequest(msg as JsonRpcRequest & { id: number | string }, opts.onElicit, opts.signal);\n continue;\n }\n if (msg.id === id) return this.settle(msg as JsonRpcResponse);\n }\n throw new AgentError(\"network\", `MCP stream ended without a response to \"${method}\".`, { provider: this.provider });\n }\n\n return this.settle((await res.json()) as JsonRpcResponse);\n }\n\n /** Answer a server-initiated request (elicitation); unknown methods get a JSON-RPC error. */\n private async answerServerRequest(\n request: JsonRpcRequest & { id: number | string },\n override: McpElicitHandler | undefined,\n signal?: AbortSignal,\n ): Promise<void> {\n if (request.method === \"elicitation/create\") {\n const handler = override ?? this.onElicit;\n let result: unknown;\n try {\n result = handler ? await handler((request.params ?? { message: \"\" }) as McpElicitRequest) : { action: \"decline\" };\n } catch {\n result = { action: \"cancel\" }; // the user's card was dismissed / the run aborted\n }\n await this.post({ jsonrpc: \"2.0\", id: request.id, result } as unknown as JsonRpcRequest, signal).catch(() => {});\n return;\n }\n await this.post(\n {\n jsonrpc: \"2.0\",\n id: request.id,\n error: { code: -32601, message: `Method not supported: ${request.method}` },\n } as unknown as JsonRpcRequest,\n signal,\n ).catch(() => {});\n }\n\n private settle(response: JsonRpcResponse): unknown {\n if (response.error) throw new McpRpcError(response.error.code, response.error.message, response.error.data);\n return response.result;\n }\n}\n\n/**\n * Credential-free direct HTTP transport for MCP servers that need no key (a\n * local dev server, the playground's mock route). Anything with a token that\n * must stay secret belongs behind `createProxyHandler` instead.\n */\nexport function createHttpTransport(opts: {\n baseUrl: string;\n headers?: Record<string, string>;\n fetchImpl?: typeof fetch;\n}): Transport {\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const isBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\n return {\n kind: \"custom\",\n credentialSafe: !isBrowser || !opts.headers,\n async fetch(req: TransportRequest): Promise<Response> {\n // `baseUrl` may be relative (\"/api/mcp\") in a browser host.\n const full = `${opts.baseUrl.replace(/\\/$/, \"\")}${req.path === \"/\" ? \"\" : req.path}` || opts.baseUrl;\n const url = new URL(full, isBrowser ? window.location.origin : undefined);\n for (const [k, v] of Object.entries(req.query ?? {})) {\n if (v !== undefined && v !== null) url.searchParams.set(k, String(v));\n }\n return doFetch(url.toString(), {\n method: req.method,\n headers: {\n ...(req.body !== undefined ? { \"content-type\": \"application/json\" } : {}),\n ...opts.headers,\n ...req.headers,\n },\n body: req.body === undefined ? undefined : JSON.stringify(req.body),\n signal: req.signal,\n });\n },\n };\n}\n","// MCP tools → ToolDefinitions.\n//\n// Import grants EXISTENCE, never authority. `importMcpTools` returns\n// definitions; registering them is the host's move, and registering with no\n// preset makes them skill-gated — private until a skill (or an explicit\n// `allow`) surfaces them, exactly like any locally defined domain tool. An MCP\n// server must not be able to walk its tools into the executor tier by being\n// connected.\n\nimport type { CardSpec, FormField } from \"../cards/types.js\";\nimport type { Skill } from \"../skills/types.js\";\nimport type { ToolDefinition, ToolResult, ToolSide } from \"../tools/types.js\";\nimport type { McpClient } from \"./client.js\";\nimport type { McpCallResult, McpContent, McpElicitHandler, McpElicitRequest } from \"./types.js\";\n\nexport type McpImportOptions = {\n /**\n * Prefix for imported tool names (\"namespace_toolName\"), so two servers with\n * a `search` tool can coexist. Defaults to the server's sanitized name.\n */\n namespace?: string;\n /** Defaults to \"read\": a remote server's tools are reads until the host says otherwise. */\n side?: ToolSide;\n costHint?: number;\n /** Override the result mapping per server. */\n mapResult?: (result: McpCallResult) => ToolResult;\n};\n\n/** `normalizeToolName` strips a leading \"mcp_\", so that namespace would break dispatch. */\nconst RESERVED_NAMESPACE = \"mcp\";\n\nfunction sanitizeNamespace(raw: string | undefined): string {\n const cleaned = (raw ?? \"\").replace(/[^a-zA-Z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\");\n if (!cleaned || cleaned.toLowerCase() === RESERVED_NAMESPACE) return \"srv\";\n return cleaned;\n}\n\n/**\n * Fetch the server's tool list and wrap each tool in a `ToolDefinition` whose\n * executor calls back through the client. Throws when two tools collide after\n * namespacing — a silent overwrite would drop a tool with no trace.\n */\nexport async function importMcpTools(client: McpClient, opts: McpImportOptions = {}): Promise<ToolDefinition[]> {\n const { serverInfo } = await client.connect();\n const namespace = sanitizeNamespace(opts.namespace ?? serverInfo.name);\n const mapResult = opts.mapResult ?? mapMcpResult;\n\n const tools = await client.listTools();\n const out: ToolDefinition[] = [];\n const seen = new Set<string>();\n\n for (const tool of tools) {\n const name = `${namespace}_${tool.name}`;\n if (seen.has(name)) {\n throw new Error(`MCP import: two tools map to \"${name}\". Give the servers distinct namespaces.`);\n }\n seen.add(name);\n\n out.push({\n name,\n description: tool.description ?? `Tool \"${tool.name}\" from the ${namespace} MCP server.`,\n inputSchema: tool.inputSchema ?? { type: \"object\" },\n side: opts.side ?? \"read\",\n ...(opts.costHint != null ? { costHint: opts.costHint } : {}),\n execute: async (input, ctx) => {\n // The model calls the namespaced name; the server knows the original.\n // If the server elicits mid-call, the ask surfaces as an interactive\n // form card — the same suspension a local `confirm` tool gets.\n const result = await client.callTool(tool.name, input, {\n signal: ctx.signal,\n ...(ctx.requestCard ? { onElicit: elicitViaCard(ctx.requestCard) } : {}),\n });\n return mapResult(result);\n },\n });\n }\n\n return out;\n}\n\n/**\n * Default MCP result → ToolResult mapping.\n *\n * The model reads `output`; a UI-worthy image rides as a card. Kept small on\n * purpose — the output is billed on every later turn of the thread.\n */\nexport function mapMcpResult(result: McpCallResult): ToolResult {\n if (result.isError) {\n return { output: { error: textOf(result.content) || \"MCP tool failed.\" }, failure: \"execution-error\" };\n }\n if (result.structuredContent !== undefined) {\n return { output: result.structuredContent };\n }\n\n const texts = result.content.filter((c): c is Extract<McpContent, { type: \"text\" }> => c.type === \"text\");\n const resources = result.content.filter((c): c is Extract<McpContent, { type: \"resource\" }> => c.type === \"resource\");\n const image = result.content.find((c): c is Extract<McpContent, { type: \"image\" }> => c.type === \"image\");\n\n let output: unknown;\n if (texts.length === 1) {\n // A single text that parses as JSON becomes the parsed value — models do\n // better with structure than with a string of escaped braces.\n output = parseMaybeJson(texts[0]!.text);\n } else if (texts.length > 1) {\n output = texts.map((t) => t.text).join(\"\\n\");\n }\n\n if (resources.length) {\n const refs = resources.map((r) => ({ uri: r.resource.uri, ...(r.resource.text ? { text: r.resource.text } : {}) }));\n output = output === undefined ? { resources: refs } : { text: output, resources: refs };\n }\n if (output === undefined) output = image ? \"(image result)\" : null;\n\n return {\n output,\n ...(image\n ? {\n card: {\n kind: \"media\",\n items: [{ url: `data:${image.mimeType};base64,${image.data}`, mediaType: image.mimeType }],\n layout: \"single\",\n },\n }\n : {}),\n };\n}\n\n/**\n * The relevance half of the composition: a `matched` skill that names the\n * imported tools, so they surface when the conversation is about them —\n * exactly how a locally defined domain tool becomes visible. Registering the\n * tools makes them EXIST; registering this skill makes them REACHABLE. The\n * authority tier still comes from presets, which this never touches.\n */\nexport function createMcpSkill(\n serverName: string,\n defs: readonly ToolDefinition[],\n opts: { id?: string; priority?: number } = {},\n): Skill {\n // \"utils_word_count\" → alias \"word count\"; the original tool vocabulary is\n // what a user's request will actually contain.\n const bare = (name: string) => name.slice(name.indexOf(\"_\") + 1);\n const aliases = [...new Set(defs.flatMap((d) => [bare(d.name).replace(/_/g, \" \"), bare(d.name)]))];\n\n return {\n id: opts.id ?? `mcp-${serverName.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\")}`,\n name: `MCP: ${serverName}`,\n description: `Tools provided by the ${serverName} MCP server.`,\n mode: \"matched\",\n aliases,\n ...(opts.priority != null ? { priority: opts.priority } : {}),\n body: [\n `The ${serverName} MCP server provides these tools:`,\n ...defs.map((d) => `- ${d.name}: ${d.description.split(\"\\n\")[0]}`),\n \"Call them like any other tool.\",\n ].join(\"\\n\"),\n tools: defs.map((d) => d.name),\n };\n}\n\n/**\n * MCP elicitation → interactive form card. The server's `requestedSchema`\n * becomes form fields; the user's submission becomes the `accept` content, a\n * dismissal becomes `decline`. This is the bridge that makes an eliciting MCP\n * server feel like a first-class interactive tool instead of a hang.\n */\nexport function elicitViaCard(requestCard: (spec: CardSpec) => Promise<unknown>): McpElicitHandler {\n return async (params: McpElicitRequest) => {\n const props = params.requestedSchema?.properties ?? {};\n const required = new Set(params.requestedSchema?.required ?? []);\n const fields: FormField[] = Object.entries(props).map(([name, p]) => {\n const label = p.title ?? name;\n if (Array.isArray(p.enum) && p.enum.length) {\n return {\n name,\n label,\n type: \"select\",\n options: p.enum.map((v) => ({ value: String(v), label: String(v) })),\n ...(required.has(name) ? { required: true } : {}),\n };\n }\n if (p.type === \"boolean\") return { name, label, type: \"boolean\", ...(p.default != null ? { value: Boolean(p.default) } : {}) };\n if (p.type === \"number\" || p.type === \"integer\") {\n return { name, label, type: \"number\", ...(required.has(name) ? { required: true } : {}) };\n }\n return {\n name,\n label,\n type: \"text\",\n ...(p.description ? { placeholder: p.description } : {}),\n ...(required.has(name) ? { required: true } : {}),\n };\n });\n\n const answer = await requestCard({\n kind: \"form\",\n title: \"This tool needs your input\",\n description: params.message,\n fields: fields.length ? fields : [{ name: \"response\", label: params.message || \"Response\", type: \"text\" }],\n submitLabel: \"Send\",\n });\n\n if (answer && typeof answer === \"object\" && (answer as { cancelled?: boolean }).cancelled) {\n return { action: \"decline\" };\n }\n const content =\n answer && typeof answer === \"object\" && !Array.isArray(answer) ? (answer as Record<string, unknown>) : { response: answer };\n return { action: \"accept\", content };\n };\n}\n\nconst textOf = (content: McpContent[]): string =>\n content\n .filter((c): c is Extract<McpContent, { type: \"text\" }> => c.type === \"text\")\n .map((c) => c.text)\n .join(\"\\n\");\n\nfunction parseMaybeJson(text: string): unknown {\n const trimmed = text.trim();\n if (!trimmed.startsWith(\"{\") && !trimmed.startsWith(\"[\")) return text;\n try {\n return JSON.parse(trimmed);\n } catch {\n return text;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAI,UAAU;AAOP,SAAS,OAAO,SAAS,OAAe;AAC7C,aAAW;AACX,SAAO,GAAG,MAAM,IAAI,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,GAAG,QAAQ,SAAS,EAAE,CAAC;AACpE;AAEO,IAAM,OAAO,CAAC,WAAgC,EAAE,MAAM,QAAQ,MAAM,MAAM;AAE1E,IAAM,QAAQ,CACnB,QACA,OAAiE,CAAC,OACjD,EAAE,MAAM,SAAS,QAAQ,GAAG,KAAK;AAE7C,IAAM,OAAO,CAAC,QAAqB,WAAmB,cAAoC;AAAA,EAC/F,MAAM;AAAA,EACN;AAAA,EACA;AAAA,EACA,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AACjC;AAEO,IAAM,WAAW,CACtB,QACA,MACA,OACA,OAAwD,CAAC,OACxC,EAAE,MAAM,aAAa,QAAQ,MAAM,OAAO,QAAQ,KAAK,UAAU,WAAW,GAAG,KAAK;AAEhG,IAAM,aAAa,CACxB,QACA,MACA,QACA,OAAuD,CAAC,OACvC,EAAE,MAAM,eAAe,QAAQ,MAAM,QAAQ,GAAG,KAAK;AAEjE,SAAS,QAAQ,MAAmB,OAA+B,IAAsB;AAC9F,SAAO;AAAA,IACL,IAAI,MAAM,OAAO,SAAS,cAAc,SAAS,IAAI;AAAA,IACrD;AAAA,IACA,OAAO,OAAO,UAAU,WAAW,CAAC,KAAK,KAAK,CAAC,IAAI;AAAA,IACnD,WAAW,KAAK,IAAI;AAAA,EACtB;AACF;AAEO,IAAM,cAAc,CAAC,OAA+B,OAAgB,QAAQ,QAAQ,OAAO,EAAE;AAC7F,IAAM,mBAAmB,CAAC,OAA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,aAAO,EAAE,QAAQ,UAAU;AAAA,IAC7B;AACA,UAAM,UACJ,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IAAK,SAAqC,EAAE,UAAU,OAAO;AAC5H,WAAO,EAAE,QAAQ,UAAU,QAAQ;AAAA,EACrC;AACF;AAEA,IAAM,SAAS,CAAC,YACd,QACG,OAAO,CAAC,MAAkD,EAAE,SAAS,MAAM,EAC3E,IAAI,CAAC,MAAM,EAAE,IAAI,EACjB,KAAK,IAAI;AAEd,SAAS,eAAeC,OAAuB;AAC7C,QAAM,UAAUA,MAAK,KAAK;AAC1B,MAAI,CAAC,QAAQ,WAAW,GAAG,KAAK,CAAC,QAAQ,WAAW,GAAG,EAAG,QAAOA;AACjE,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAOA;AAAA,EACT;AACF;","names":["text","j","last","quote","text","text","counter","text","counter","messages","text","counter","text","counter","text","printable","without","FORMATS","text","def","message","props","child","isObject","message","text","text","message","failed","props","outcome","outcome","props","QUOTE","text","child","outcome","source","finishedAt","record","outcome","file","byRecency","text","text","text","message","isBrowser","image","props","text"]}
|