@supersolutions/super-chat-core 0.1.0 → 0.2.1

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 CHANGED
@@ -1,7 +1,7 @@
1
- import { C as ContentPart, M as Message, a as MediaSource, b as MessageRole, T as ToolCallStatus, c as ToolFailureKind, d as TransportRequest, e as Transport, R as RetryPolicy, f as ModelInfo, P as ProviderCapabilities, g as Provider, h as CallOptions, J as JSONSchema, i as ToolSpec, U as Usage, F as FinishReason, j as JobHandle, k as JobStatus, N as NormalizedRequest, G as GenerateResult, l as ProviderFileRef } from './types-C3VavKYX.js';
2
- export { D as DEFAULT_RETRY, m as FileUploadRequest, n as JobSnapshot, o as MultipartBody, p as ReasoningOptions, q as ResponseFormat, S as StreamEvent, r as ToolChoice, s as isMultipartBody } from './types-C3VavKYX.js';
3
- export { J as JobStore, O as OpenAIDialect, a as OpenAIProviderConfig, R as ResumeResult, S as StoredJob, b as awaitJob, c as buildChatRequest, d as buildResponsesRequest, e as createLocalJobStore, f as createMemoryJobStore, g as createOpenAIProvider, i as isTerminal, r as reap, h as resumeJobs } from './map-in-B1lLaNxO.js';
4
- export { A as AnthropicProviderConfig, b as buildAnthropicRequest, c as createAnthropicProvider } from './map-in-ByQRBLJ2.js';
1
+ import { C as ContentPart, M as Message, a as MediaSource, b as MessageRole, T as ToolCallStatus, c as ToolFailureKind, d as TransportRequest, e as Transport, R as RetryPolicy, f as ModelInfo, P as ProviderCapabilities, g as Provider, h as CallOptions, J as JSONSchema, U as Usage, F as FinishReason, i as JobHandle, j as JobStatus, k as ToolSpec, N as NormalizedRequest, G as GenerateResult, l as ProviderFileRef } from './types-y3SK7HwA.js';
2
+ export { D as DEFAULT_RETRY, m as FileUploadRequest, n as JobSnapshot, o as MultipartBody, p as ReasoningOptions, q as ResponseFormat, S as StreamEvent, r as ToolChoice, s as isMultipartBody } from './types-y3SK7HwA.js';
3
+ export { J as JobStore, O as OpenAIDialect, a as OpenAIProviderConfig, R as ResumeResult, S as StoredJob, b as awaitJob, c as buildChatRequest, d as buildResponsesRequest, e as createLocalJobStore, f as createMemoryJobStore, g as createOpenAIProvider, i as isTerminal, r as reap, h as resumeJobs } from './map-in-CXwWaHl2.js';
4
+ export { A as AnthropicProviderConfig, b as buildAnthropicRequest, c as createAnthropicProvider } from './map-in-C5lFV2DR.js';
5
5
 
6
6
  /**
7
7
  * Monotonic id. Deliberately not `crypto.randomUUID()` — ids show up in test
@@ -98,908 +98,1118 @@ type MarkdownBlock = {
98
98
  */
99
99
  declare function splitBlocks(src: string): MarkdownBlock[];
100
100
 
101
- type DocumentSnapshot = {
102
- id: string;
103
- title: string;
104
- markdown: string;
105
- /**
106
- * Optimistic-concurrency token, bumped on every accepted write.
107
- *
108
- * The user can change a document between the model reading it and proposing
109
- * an edit — in another tab, or by accepting a different edit first. Without
110
- * this the second edit would apply its find/replace to text that has moved.
111
- * It is cheap now and impossible to retrofit, so it is required from the
112
- * first version rather than added when someone hits the bug.
113
- */
114
- revision: number;
115
- /**
116
- * Set when this revision is an undo: the revision whose body it checked out,
117
- * resolved to the original rather than to another undo.
118
- *
119
- * Undo mints a new revision instead of rolling the number back, so without
120
- * this the store cannot tell "v4, which is v2 restored" from "v4, a fresh
121
- * edit" — and the next undo would step back one from v4, i.e. to v3, which is
122
- * the body the user just undid. Walking back from here instead is what makes
123
- * the second undo an undo rather than a redo.
124
- */
125
- restoredFrom?: number;
126
- createdAt: number;
127
- updatedAt: number;
101
+ type CardTone = "neutral" | "positive" | "negative" | "warning" | "info";
102
+ type CardValueFormat = "text" | "number" | "currency" | "percent" | "bytes" | "duration" | "datetime" | "code";
103
+ type TableColumn = {
104
+ key: string;
105
+ label: string;
106
+ format?: CardValueFormat;
107
+ align?: "left" | "right" | "center";
108
+ /** Render this column's cell as an emphasis/status pill. */
109
+ pill?: boolean;
128
110
  };
129
- /**
130
- * Host-owned persistence. Mirrors ThreadStore/FileStore deliberately: same
131
- * shape, same defensiveness, so a host that has implemented one has implemented
132
- * this.
133
- */
134
- type DocumentStore = {
135
- list(): Promise<DocumentSnapshot[]>;
136
- get(id: string): Promise<DocumentSnapshot | undefined>;
137
- create(input: {
138
- title: string;
139
- markdown: string;
140
- id?: string;
141
- }): Promise<DocumentSnapshot>;
142
- /**
143
- * Write a new body. Rejects when `expectedRevision` is not the current one —
144
- * the store is where the check belongs, because it is the only place that
145
- * sees concurrent writers.
146
- *
147
- * `restoredFrom` marks the write as an undo and must be persisted on the new
148
- * snapshot (and cleared by any write without it). A store that drops it
149
- * still undoes once; the second undo then walks forward instead of back.
150
- */
151
- update(id: string, markdown: string, expectedRevision: number, opts?: {
152
- restoredFrom?: number;
153
- }): Promise<DocumentSnapshot>;
154
- remove(id: string): Promise<void>;
155
- /** Prior revisions, newest first. Undo is a checkout, never an inverse edit. */
156
- history(id: string): Promise<DocumentSnapshot[]>;
111
+ type TableCard = {
112
+ kind: "table";
113
+ title?: string;
114
+ caption?: string;
115
+ columns: TableColumn[];
116
+ rows: Record<string, unknown>[];
117
+ /** Column key to sort by on first render. */
118
+ sortBy?: string;
119
+ sortDir?: "asc" | "desc";
157
120
  };
158
- /** One navigable entry in a document's outline. */
159
- type DocumentOutlineEntry = {
160
- block: number;
161
- kind: MarkdownBlockKind;
162
- /** 1–6 for a heading block; absent otherwise. */
163
- level?: number;
164
- /** First line, trimmed — enough to steer by without paying for the body. */
165
- preview: string;
166
- chars: number;
121
+ type StatItem = {
122
+ label: string;
123
+ value: string | number;
124
+ format?: CardValueFormat;
125
+ /** Signed change vs a prior period; drives colour and arrow. */
126
+ delta?: number;
127
+ deltaFormat?: CardValueFormat;
128
+ hint?: string;
129
+ tone?: CardTone;
130
+ };
131
+ type StatsCard = {
132
+ kind: "stats";
133
+ title?: string;
134
+ items: StatItem[];
135
+ };
136
+ type ChartSeries = {
137
+ name: string;
138
+ /** `[x, y]` pairs; x is a number, a timestamp, or a category label. */
139
+ points: [string | number, number][];
140
+ type?: "line" | "area" | "bar" | "scatter";
141
+ color?: string;
142
+ /** Plot against a secondary axis — volume under price, for instance. */
143
+ axis?: "left" | "right";
144
+ };
145
+ type ChartAnnotation = {
146
+ type: "hline" | "vline" | "band" | "marker";
147
+ value: string | number;
148
+ /** Second bound, for `band`. */
149
+ to?: string | number;
150
+ label?: string;
151
+ tone?: CardTone;
152
+ };
153
+ type ChartCard = {
154
+ kind: "chart";
155
+ title?: string;
156
+ /** OHLC candles are their own shape; series charts use `series`. */
157
+ variant?: "series" | "candlestick";
158
+ xLabel?: string;
159
+ yLabel?: string;
160
+ xType?: "time" | "number" | "category";
161
+ series?: ChartSeries[];
162
+ candles?: {
163
+ t: string | number;
164
+ o: number;
165
+ h: number;
166
+ l: number;
167
+ c: number;
168
+ v?: number;
169
+ }[];
170
+ annotations?: ChartAnnotation[];
171
+ stacked?: boolean;
172
+ };
173
+ type TimelineCard = {
174
+ kind: "timeline";
175
+ title?: string;
176
+ events: {
177
+ at: string | number;
178
+ label: string;
179
+ detail?: string;
180
+ tone?: CardTone;
181
+ }[];
182
+ };
183
+ type KeyValueCard = {
184
+ kind: "keyvalue";
185
+ title?: string;
186
+ items: {
187
+ label: string;
188
+ value: string | number;
189
+ format?: CardValueFormat;
190
+ tone?: CardTone;
191
+ mono?: boolean;
192
+ }[];
193
+ };
194
+ type ProgressStep = {
195
+ label: string;
196
+ status: "pending" | "active" | "done" | "failed" | "skipped";
197
+ detail?: string;
198
+ };
199
+ type ProgressCard = {
200
+ kind: "progress";
201
+ title?: string;
202
+ steps: ProgressStep[];
203
+ /** 0–1. Omit for indeterminate. */
204
+ fraction?: number;
205
+ };
206
+ type MediaCard = {
207
+ kind: "media";
208
+ title?: string;
209
+ items: {
210
+ url: string;
211
+ alt?: string;
212
+ caption?: string;
213
+ mediaType?: string;
214
+ /** Known intrinsic geometry keeps generated media from shifting on decode. */
215
+ width?: number;
216
+ height?: number;
217
+ durationMs?: number;
218
+ }[];
219
+ layout?: "grid" | "single";
220
+ };
221
+ type MarkdownCard = {
222
+ kind: "markdown";
223
+ title?: string;
224
+ body: string;
167
225
  };
168
226
  /**
169
- * One proposed change: find this exact text, put that in its place.
227
+ * A document artifact — long-form Markdown the agent authored and the user
228
+ * reads in a previewer rather than inline in the transcript.
170
229
  *
171
- * Not a line range, which the previous edit in the same batch would invalidate,
172
- * and not a whole-document rewrite, which costs tokens proportional to size ×
173
- * edits, silently revises paragraphs nobody asked about, and — worst — leaves
174
- * nothing meaningful to approve, because everything appears changed.
230
+ * `docId` is the stable handle every later turn addresses: the body here is for
231
+ * display only, and stripCardPayload removes it from what the model sees after
232
+ * the turn that produced it. A model that wants to re-read the document calls
233
+ * the read tool with this id — which is the point, because a document large
234
+ * enough to deserve a previewer is too large to re-send every turn.
175
235
  *
176
- * `block` narrows the search to one block. Optional, but the model should send
177
- * it whenever it read the text through an outline or a quote, because a short
178
- * `find` that is unique within a block is often ambiguous across a document.
236
+ * `revision` is the optimistic-concurrency token. An edit carrying a stale one
237
+ * is refused rather than applied to text that has since moved.
179
238
  */
180
- type DocumentEdit = {
181
- block?: number;
182
- find: string;
183
- replace: string;
184
- };
185
- /** Why a proposed edit could not be applied. Each maps to a different retry. */
186
- type EditRejection =
187
- /** No occurrence — the model is quoting text that is not there. Re-read. */
188
- "not-found"
189
- /** Several occurrences — the anchor is too short. Widen it or name a block. */
190
- | "ambiguous"
191
- /** The document moved underneath. Re-read and re-propose. */
192
- | "stale-revision"
193
- /** The named block does not exist. */
194
- | "no-such-block";
195
- type EditResult = {
196
- ok: true;
197
- markdown: string;
198
- applied: AppliedEdit[];
199
- } | {
200
- ok: false;
201
- reason: EditRejection;
202
- message: string;
203
- edit?: DocumentEdit;
204
- };
205
- /** An edit resolved against the source — enough to render and to reverse. */
206
- type AppliedEdit = {
207
- edit: DocumentEdit;
208
- /** Where the match landed in the ORIGINAL source. */
209
- start: number;
210
- end: number;
211
- block: number;
212
- };
213
-
214
- /** A span of a document artifact, resolved to source offsets. */
215
- type DocumentQuoteRef = {
239
+ type DocumentCard = {
240
+ kind: "document";
216
241
  docId: string;
217
242
  title: string;
218
- /** Revision the span was taken from — compared at send time; see `drift`. */
243
+ markdown: string;
219
244
  revision: number;
220
- /** Inclusive block index range. */
221
- blocks: [number, number];
222
- start: number;
223
- end: number;
224
- /** SOURCE markdown, not rendered text. */
225
- text: string;
226
- /**
227
- * How the document had moved past `revision` when the message was sent.
228
- * Absent when it had not, or when nothing checked — see `checkQuoteDrift`.
229
- */
230
- drift?: QuoteDrift;
231
245
  };
232
246
  /**
233
- * What a quote's document did between the quoted revision and the send.
247
+ * A matrix of options against criteria.
234
248
  *
235
- * The quoted revision can be old the moment it is taken — a document card
236
- * further up the thread still shows the body it was created with — and the
237
- * model cannot tell from the text alone. Told, it re-reads; not told, it
238
- * proposes an edit against text that may no longer be there, or answers about
239
- * a paragraph the user has since rewritten.
249
+ * The most domain-portable card there is: legal clause-vs-clause, vendor
250
+ * selection, pricing tiers, candidate evaluation, feature comparison. Boolean
251
+ * values render as ✓/✗, so "does it have X" tables need no encoding by the model.
240
252
  */
241
- type QuoteDrift =
242
- /** Past the quoted revision. `intact`: the quoted text still appears verbatim. */
243
- {
244
- status: "moved";
245
- revision: number;
246
- intact: boolean;
247
- }
248
- /** The document no longer exists. */
249
- | {
250
- status: "removed";
253
+ type ComparisonCard = {
254
+ kind: "comparison";
255
+ title?: string;
256
+ /** The things being compared — these become columns. */
257
+ options: {
258
+ id: string;
259
+ label: string;
260
+ note?: string;
261
+ highlight?: boolean;
262
+ }[];
263
+ /** The dimensions they are compared on — these become rows. */
264
+ criteria: {
265
+ label: string;
266
+ /** Keyed by option id. `true`/`false` render as ✓/✗; `null` renders as “—”. */
267
+ values: Record<string, string | number | boolean | null>;
268
+ detail?: string;
269
+ weight?: "low" | "normal" | "high";
270
+ }[];
271
+ };
272
+ /** Items with a state. Compliance reviews, launch readiness, QA passes, audits. */
273
+ type ChecklistCard = {
274
+ kind: "checklist";
275
+ title?: string;
276
+ items: {
277
+ label: string;
278
+ status: "done" | "todo" | "blocked" | "na";
279
+ detail?: string;
280
+ /** Optional heading to group consecutive items under. */
281
+ group?: string;
282
+ }[];
283
+ };
284
+ /** A single highlighted note. Disclaimers, caveats, prerequisites, warnings. */
285
+ type CalloutCard = {
286
+ kind: "callout";
287
+ tone: "info" | "warning" | "danger" | "success" | "note";
288
+ title?: string;
289
+ body: string;
251
290
  };
252
291
  /**
253
- * Compare a quote against the document as it is now. `undefined` when the
254
- * quote is current.
292
+ * Sources behind a claim.
255
293
  *
256
- * Any revision other than the quoted one counts — a lower one means the id now
257
- * names a different document, which is drift too.
294
+ * Domain-agnostic and unusually important for agents specifically: it is the
295
+ * card that lets a reader check the work rather than trust the summary.
258
296
  */
259
- declare function quoteDrift(quote: DocumentQuoteRef, current: Pick<DocumentSnapshot, "revision" | "markdown"> | undefined): QuoteDrift | undefined;
297
+ type CitationsCard = {
298
+ kind: "citations";
299
+ title?: string;
300
+ items: {
301
+ title: string;
302
+ /** Publication, court, statute, dataset, site — whatever the source is. */
303
+ source?: string;
304
+ url?: string;
305
+ date?: string | number;
306
+ /** The specific passage relied on. */
307
+ snippet?: string;
308
+ locator?: string;
309
+ relevance?: "high" | "medium" | "low";
310
+ }[];
311
+ };
312
+ /** Staged drop-off. Conversion funnels, hiring pipelines, case attrition, intake flows. */
313
+ type FunnelCard = {
314
+ kind: "funnel";
315
+ title?: string;
316
+ stages: {
317
+ label: string;
318
+ value: number;
319
+ note?: string;
320
+ }[];
321
+ format?: CardValueFormat;
322
+ };
323
+ /** One value against a scale, with optional named bands. Scores, risk levels, sentiment. */
324
+ type GaugeCard = {
325
+ kind: "gauge";
326
+ title?: string;
327
+ value: number;
328
+ min?: number;
329
+ max?: number;
330
+ label?: string;
331
+ bands?: {
332
+ from: number;
333
+ to: number;
334
+ label: string;
335
+ tone?: CardTone;
336
+ }[];
337
+ format?: CardValueFormat;
338
+ };
339
+ type TreeNode = {
340
+ label: string;
341
+ detail?: string;
342
+ tone?: CardTone;
343
+ children?: TreeNode[];
344
+ };
345
+ /** Nested structure. Document outlines, org charts, taxonomies, decision trees. */
346
+ type TreeCard = {
347
+ kind: "tree";
348
+ title?: string;
349
+ nodes: TreeNode[];
350
+ };
351
+ type CodeCard = {
352
+ kind: "code";
353
+ title?: string;
354
+ language?: string;
355
+ code: string;
356
+ filename?: string;
357
+ };
358
+ type DiffCard = {
359
+ kind: "diff";
360
+ title?: string;
361
+ before: string;
362
+ after: string;
363
+ language?: string;
364
+ };
365
+ type ChoiceCard = {
366
+ kind: "choice";
367
+ title?: string;
368
+ prompt?: string;
369
+ multiple?: boolean;
370
+ options: {
371
+ id: string;
372
+ label: string;
373
+ description?: string;
374
+ /** Small facts shown on the option row: APR, TVL, price. */
375
+ meta?: {
376
+ label: string;
377
+ value: string | number;
378
+ format?: CardValueFormat;
379
+ }[];
380
+ imageUrl?: string;
381
+ disabled?: boolean;
382
+ disabledReason?: string;
383
+ }[];
384
+ };
385
+ type FormField = {
386
+ name: string;
387
+ label: string;
388
+ type: "text" | "textarea";
389
+ placeholder?: string;
390
+ required?: boolean;
391
+ value?: string;
392
+ } | {
393
+ name: string;
394
+ label: string;
395
+ type: "number";
396
+ min?: number;
397
+ max?: number;
398
+ step?: number;
399
+ required?: boolean;
400
+ value?: number;
401
+ suffix?: string;
402
+ } | {
403
+ name: string;
404
+ label: string;
405
+ type: "select";
406
+ options: {
407
+ value: string;
408
+ label: string;
409
+ }[];
410
+ required?: boolean;
411
+ value?: string;
412
+ } | {
413
+ name: string;
414
+ label: string;
415
+ type: "boolean";
416
+ value?: boolean;
417
+ };
418
+ type FormCard = {
419
+ kind: "form";
420
+ title?: string;
421
+ description?: string;
422
+ fields: FormField[];
423
+ submitLabel?: string;
424
+ };
425
+ type ConfirmCard = {
426
+ kind: "confirm";
427
+ title: string;
428
+ /** The consequential summary — what will actually happen. */
429
+ summary: {
430
+ label: string;
431
+ value: string | number;
432
+ tone?: CardTone;
433
+ mono?: boolean;
434
+ }[];
435
+ description?: string;
436
+ confirmLabel?: string;
437
+ cancelLabel?: string;
438
+ /** Renders the confirm control as destructive. */
439
+ danger?: boolean;
440
+ };
441
+ type BuiltinCard = TableCard | StatsCard | ChartCard | TimelineCard | KeyValueCard | ProgressCard | MediaCard | MarkdownCard | DocumentCard | EditReviewCard | EmailCard | CodeCard | DiffCard | ComparisonCard | ChecklistCard | CalloutCard | CitationsCard | FunnelCard | GaugeCard | TreeCard | ChoiceCard | FormCard | ConfirmCard;
442
+ type BuiltinCardKind = BuiltinCard["kind"];
260
443
  /**
261
- * Stamp each quote with its drift against the store, ready to send.
444
+ * The approval surface for a proposed document edit.
262
445
  *
263
- * A lookup that throws leaves that quote unstamped rather than failing the
264
- * send: the user's message matters more than the annotation, the quote still
265
- * names its revision, and an edit made from it is still checked against the
266
- * current one.
446
+ * Interactive, because in in-chat editing the diff IS the approval: there is no
447
+ * other moment at which the user gets to see what is about to happen. Hunks are
448
+ * accepted individually rather than all-or-nothing — partial acceptance is what
449
+ * makes the exchange read as collaboration instead of take-it-or-leave-it, and
450
+ * an edit is already the smallest independently applicable unit because it
451
+ * carries its own anchor.
267
452
  */
268
- declare function checkQuoteDrift(quotes: readonly DocumentQuoteRef[], documents: Pick<DocumentStore, "get">): Promise<DocumentQuoteRef[]>;
269
- /** Key under `Message.metadata` where quotes are stored for re-rendering. */
270
- declare const QUOTES_METADATA_KEY = "documentQuotes";
453
+ type EditReviewCard = {
454
+ kind: "editreview";
455
+ docId: string;
456
+ title: string;
457
+ /** Revision the edits were computed against; a stale one is refused. */
458
+ revision: number;
459
+ /** One line on why, in the model's words. */
460
+ summary?: string;
461
+ hunks: {
462
+ index: number;
463
+ block: number;
464
+ removed: string[];
465
+ added: string[];
466
+ }[];
467
+ };
271
468
  /**
272
- * Render quotes as the prefix of the user's message.
469
+ * A drafted email, before it is anyone's outbox.
273
470
  *
274
- * Fenced rather than indented, and labelled with the document and block range,
275
- * so the model can tell quoted material from the user's own words — and can
276
- * name what it is about to change when the edit tools arrive. A stamped drift
277
- * becomes a note between the label and the text.
471
+ * Always a draft the user completes — which is exactly the `draft` preset tier
472
+ * ("produces something the USER must approve/sign. No side effects"). The
473
+ * framework never holds a mail credential, for the same reason a Transport
474
+ * never holds an API key.
475
+ *
476
+ * Editable but not interactive: nothing waits on it. The run does not suspend,
477
+ * because the model asked no question — it produced a thing.
278
478
  */
279
- declare function formatQuotes(quotes: readonly DocumentQuoteRef[]): string;
280
- /** Prefix `text` with the quotes, keeping a blank line between them. */
281
- declare function withQuotes(text: string, quotes: readonly DocumentQuoteRef[]): string;
282
- /** Read quotes back off a message, for re-rendering the chips in history. */
283
- declare function quotesOf(metadata: Record<string, unknown> | undefined): DocumentQuoteRef[];
479
+ type EmailCard = {
480
+ kind: "email";
481
+ to: string[];
482
+ cc?: string[];
483
+ bcc?: string[];
484
+ subject: string;
485
+ /** Plain text. Markdown here would be a lie: mailto cannot carry it. */
486
+ body: string;
487
+ };
488
+ /** A host-registered card is any `{kind}` object; built-ins are the typed subset. */
489
+ type CardSpec = BuiltinCard | ({
490
+ kind: string;
491
+ } & Record<string, unknown>);
492
+ /** Envelope attached to a tool result, or returned by `visualize`. */
493
+ type Card = {
494
+ id: string;
495
+ spec: CardSpec;
496
+ /** Set when the payload was dropped from persisted history. */
497
+ expired?: boolean;
498
+ /** Tool call this card belongs to, for correlating an action back. */
499
+ callId?: string;
500
+ /**
501
+ * What the user answered, once they have.
502
+ *
503
+ * Lives on the card rather than in the renderer's local state because the card
504
+ * is re-mounted from history when the turn commits — state does not survive
505
+ * that, and a renderer left guessing shows the wrong answer.
506
+ */
507
+ action?: CardAction;
508
+ };
509
+ /** What the user did with an interactive card. Becomes the tool result. */
510
+ type CardAction = {
511
+ cardId: string;
512
+ callId?: string;
513
+ kind: string;
514
+ type: "submit" | "select" | "confirm" | "cancel" | "dismiss";
515
+ /** Selected option ids, form values, or nothing for confirm/cancel. */
516
+ value?: unknown;
517
+ at: number;
518
+ };
519
+ /** Marker key used to recognise a card inside an arbitrary tool output. */
520
+ declare const CARD_KEY: "$card";
521
+ type CardCarrier = {
522
+ [CARD_KEY]: Card;
523
+ } & Record<string, unknown>;
524
+ declare function isCardCarrier(value: unknown): value is CardCarrier;
525
+ /** Attach a card to a tool result without disturbing the data the model reads. */
526
+ declare function withCard<T extends Record<string, unknown>>(data: T, spec: CardSpec, id?: string): T & CardCarrier;
527
+ /**
528
+ * Remove a card payload from a tool output, leaving a note in its place.
529
+ *
530
+ * The card is for the user's eyes; the model gets the surrounding data. Sending
531
+ * both is double billing — and a chart spec with 2,000 points is the single
532
+ * largest thing a tool result can carry. Applied in two places, which must stay
533
+ * consistent: within a running turn (before each provider call) and when a
534
+ * persisted thread is rebuilt into context.
535
+ */
536
+ declare function stripCardPayload(output: unknown): unknown;
284
537
 
285
- type AgentErrorKind = "auth" | "rate-limit" | "overloaded" | "timeout" | "network" | "invalid-request" | "content-filter" | "context-length" | "not-supported" | "cancelled" | "tool-error" | "unknown";
286
- declare class AgentError extends Error {
287
- readonly kind: AgentErrorKind;
288
- readonly status?: number;
289
- readonly provider?: string;
290
- /** Seconds to wait before retrying, from a Retry-After header when present. */
291
- readonly retryAfter?: number;
292
- readonly cause?: unknown;
293
- readonly detail?: unknown;
294
- constructor(kind: AgentErrorKind, message: string, opts?: {
295
- status?: number;
296
- provider?: string;
297
- retryAfter?: number;
298
- cause?: unknown;
299
- detail?: unknown;
300
- });
301
- get retryable(): boolean;
302
- /** Compact shape for logs and for handing an error back to the model as data. */
303
- toJSON(): {
304
- kind: AgentErrorKind;
305
- message: string;
306
- status: number | undefined;
307
- provider: string | undefined;
308
- };
538
+ type TurnSegment = {
539
+ type: "text";
540
+ key: string;
541
+ text: string;
309
542
  }
310
- declare function isAgentError(e: unknown): e is AgentError;
543
+ /** The output slot of one tool call. Stable from first preview to final card. */
544
+ | {
545
+ type: "output";
546
+ key: string;
547
+ callId: string;
548
+ cards: Card[];
549
+ }
550
+ /** A card no call in this turn accounts for. */
551
+ | {
552
+ type: "card";
553
+ key: string;
554
+ card: Card;
555
+ };
556
+ type TurnLayoutOptions = {
557
+ /** Keep a slot for a call with no card yet. A live turn needs it for previews and skeletons. */
558
+ keepEmptyOutputs?: boolean;
559
+ };
311
560
  /**
312
- * Classify anything thrown. Used for errors that never went through an adapter
313
- * (a DNS failure, an aborted signal) and as the fallback in adapter mapping.
561
+ * True when a stored turn recorded where its cards belong. Turns saved before this
562
+ * existed carry no `callId` on their artifacts and keep the layout they had.
314
563
  */
315
- declare function toAgentError(e: unknown, provider?: string): AgentError;
316
- /** HTTP status → kind. Shared by every adapter so classification can't drift. */
317
- declare function kindFromStatus(status: number): AgentErrorKind;
318
-
319
- declare function bytesToBase64(bytes: Uint8Array): string;
320
- declare function base64ToBytes(s: string): Uint8Array;
564
+ declare function hasTurnOrder(parts: readonly ContentPart[]): boolean;
565
+ declare function layoutTurn(parts: readonly ContentPart[], cards: readonly Card[], options?: TurnLayoutOptions): TurnSegment[];
321
566
 
322
- type DirectTransportConfig = {
323
- /** Provider API root, no trailing slash. e.g. "https://api.openai.com/v1". */
324
- baseUrl: string;
325
- /** Static key, or a getter for keys that rotate / come from a keychain. */
326
- apiKey: string | (() => string | Promise<string>);
567
+ type DocumentSnapshot = {
568
+ id: string;
569
+ title: string;
570
+ markdown: string;
327
571
  /**
328
- * How the key rides on the wire. "bearer" (default) sends
329
- * `Authorization: Bearer <key>`; "x-api-key" sends the `x-api-key` header —
330
- * what Anthropic's Messages API expects.
572
+ * Optimistic-concurrency token, bumped on every accepted write.
573
+ *
574
+ * The user can change a document between the model reading it and proposing
575
+ * an edit — in another tab, or by accepting a different edit first. Without
576
+ * this the second edit would apply its find/replace to text that has moved.
577
+ * It is cheap now and impossible to retrofit, so it is required from the
578
+ * first version rather than added when someone hits the bug.
331
579
  */
332
- authStyle?: "bearer" | "x-api-key";
333
- /** Sent on every request; merged under per-request headers. */
334
- headers?: Record<string, string>;
580
+ revision: number;
335
581
  /**
336
- * Required to use this transport in a browser. Naming it forces the caller to
337
- * state the risk out loud instead of discovering it in production.
582
+ * Set when this revision is an undo: the revision whose body it checked out,
583
+ * resolved to the original rather than to another undo.
584
+ *
585
+ * Undo mints a new revision instead of rolling the number back, so without
586
+ * this the store cannot tell "v4, which is v2 restored" from "v4, a fresh
587
+ * edit" — and the next undo would step back one from v4, i.e. to v3, which is
588
+ * the body the user just undid. Walking back from here instead is what makes
589
+ * the second undo an undo rather than a redo.
338
590
  */
339
- dangerouslyAllowBrowser?: boolean;
340
- fetchImpl?: typeof fetch;
341
- };
342
- declare function buildUrl(baseUrl: string, path: string, query?: TransportRequest["query"]): string;
343
- declare function createDirectTransport(config: DirectTransportConfig): Transport;
344
-
345
- type ProxyTransportConfig = {
346
- /** Base path of your proxy route, e.g. "/api/agent". */
347
- url: string;
348
- /** Extra headers (session cookie is automatic; use this for CSRF tokens). */
349
- headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
350
- credentials?: RequestCredentials;
351
- fetchImpl?: typeof fetch;
591
+ restoredFrom?: number;
592
+ createdAt: number;
593
+ updatedAt: number;
352
594
  };
353
- /** The envelope a ProxyTransport POSTs to the BFF. Exported so the server half can type it. */
354
- type ProxyEnvelope = {
355
- provider: string;
356
- path: string;
357
- method: "GET" | "POST" | "DELETE";
358
- body?: unknown;
359
- query?: Record<string, string | number | boolean | undefined>;
360
- stream?: boolean;
595
+ /**
596
+ * Host-owned persistence. Mirrors ThreadStore/FileStore deliberately: same
597
+ * shape, same defensiveness, so a host that has implemented one has implemented
598
+ * this.
599
+ */
600
+ type DocumentStore = {
601
+ list(): Promise<DocumentSnapshot[]>;
602
+ get(id: string): Promise<DocumentSnapshot | undefined>;
603
+ create(input: {
604
+ title: string;
605
+ markdown: string;
606
+ id?: string;
607
+ }): Promise<DocumentSnapshot>;
361
608
  /**
362
- * Per-request headers for the UPSTREAM call (org ids, beta flags, an MCP
363
- * session id). The server half forwards them after stripping credential
364
- * headers and then applies its own key on top — a client can request
365
- * headers, never substitute the credential.
609
+ * Write a new body. Rejects when `expectedRevision` is not the current one —
610
+ * the store is where the check belongs, because it is the only place that
611
+ * sees concurrent writers.
612
+ *
613
+ * `restoredFrom` marks the write as an undo and must be persisted on the new
614
+ * snapshot (and cleared by any write without it). A store that drops it
615
+ * still undoes once; the second undo then walks forward instead of back.
366
616
  */
367
- headers?: Record<string, string>;
617
+ update(id: string, markdown: string, expectedRevision: number, opts?: {
618
+ restoredFrom?: number;
619
+ }): Promise<DocumentSnapshot>;
620
+ remove(id: string): Promise<void>;
621
+ /** Prior revisions, newest first. Undo is a checkout, never an inverse edit. */
622
+ history(id: string): Promise<DocumentSnapshot[]>;
368
623
  };
369
- /**
370
- * A `MultipartBody` as it travels inside the JSON envelope: bytes become
371
- * base64 strings so the client→BFF wire stays one method, one body shape.
372
- * Base64 costs +33%, so treat ~20 MB per upload as the practical ceiling —
373
- * beyond that, use a direct transport or your own upload route.
374
- */
375
- type SerializedMultipartBody = {
376
- kind: "multipart";
377
- fields: Record<string, string>;
378
- files: {
379
- field: string;
380
- filename: string;
381
- mediaType?: string;
382
- data: string;
383
- }[];
624
+ /** One navigable entry in a document's outline. */
625
+ type DocumentOutlineEntry = {
626
+ block: number;
627
+ kind: MarkdownBlockKind;
628
+ /** 1–6 for a heading block; absent otherwise. */
629
+ level?: number;
630
+ /** First line, trimmed — enough to steer by without paying for the body. */
631
+ preview: string;
632
+ chars: number;
384
633
  };
385
- declare function createProxyTransport(config: ProxyTransportConfig): Transport;
386
-
387
- /** Full-jitter exponential backoff. Full jitter (not equal) because synchronized
388
- * clients retrying a rate limit in lockstep is how a 429 becomes a 429 storm. */
389
- declare function backoffDelay(attempt: number, policy: RetryPolicy, retryAfterSec?: number): number;
390
- declare function parseRetryAfter(headers: Headers): number | undefined;
391
634
  /**
392
- * Retry `run` while it fails transiently. Non-retryable failures (auth, bad
393
- * request, content filter) throw on the first attempt — retrying them just
394
- * burns quota and delays the real error reaching the user.
395
- */
396
- declare function withRetry<T>(run: (attempt: number) => Promise<T>, opts?: {
397
- policy?: RetryPolicy;
398
- signal?: AbortSignal;
399
- provider?: string;
400
- onRetry?: (attempt: number, err: AgentError, delayMs: number) => void;
401
- }): Promise<T>;
402
- /**
403
- * Turn a non-OK `Response` into a typed `AgentError`, pulling the provider's own
404
- * message out of the body so the user sees "model X does not exist" rather than
405
- * "HTTP 404".
635
+ * One proposed change: find this exact text, put that in its place.
636
+ *
637
+ * Not a line range, which the previous edit in the same batch would invalidate,
638
+ * and not a whole-document rewrite, which costs tokens proportional to size ×
639
+ * edits, silently revises paragraphs nobody asked about, and — worst — leaves
640
+ * nothing meaningful to approve, because everything appears changed.
641
+ *
642
+ * `block` narrows the search to one block. Optional, but the model should send
643
+ * it whenever it read the text through an outline or a quote, because a short
644
+ * `find` that is unique within a block is often ambiguous across a document.
406
645
  */
407
- declare function errorFromResponse(res: Response, provider: string): Promise<AgentError>;
408
-
409
- type SSEMessage = {
410
- event: string;
411
- data: string;
412
- id?: string;
413
- retry?: number;
414
- };
415
- /**
416
- * Incremental line-oriented decoder. State is per-instance, not module-level —
417
- * a background job poll and a foreground stream can run concurrently, and
418
- * shared accumulator state would interleave their events into garbage.
419
- */
420
- declare class SSEDecoder {
421
- private event;
422
- private data;
423
- private id;
424
- private retry;
425
- /** Feed one line (terminator already removed). Returns an event when dispatched. */
426
- push(line: string): SSEMessage | null;
427
- /** Dispatch whatever has accumulated. Called on a blank line and at stream end. */
428
- flush(): SSEMessage | null;
429
- }
430
- /**
431
- * Decode a byte stream into SSE messages. `TextDecoder({stream:true})` is what
432
- * makes multi-byte characters split across chunks safe — decoding each chunk
433
- * independently corrupts any emoji or CJK text that straddles a boundary.
434
- */
435
- declare function parseSSE(stream: ReadableStream<Uint8Array>): AsyncGenerator<SSEMessage>;
436
- /**
437
- * SSE messages whose `data` is JSON, skipping the `[DONE]` sentinel that
438
- * OpenAI's Chat Completions stream terminates with.
439
- */
440
- declare function parseSSEJson<T = unknown>(stream: ReadableStream<Uint8Array>): AsyncGenerator<{
441
- event: string;
442
- data: T;
443
- }>;
444
-
445
- type ProviderProtocol = "openai-responses" | "openai-chat" | "anthropic-messages";
446
- type ProviderProfile = {
447
- /** Stable routing id. It must match the proxy provider key in proxy mode. */
448
- id: string;
449
- label: string;
450
- protocol: ProviderProtocol;
451
- /** Provider API root including its version prefix, without a trailing slash. */
452
- baseUrl: string;
453
- models?: ModelInfo[];
454
- capabilities?: Partial<ProviderCapabilities>;
455
- };
456
- declare const OPENAI_OFFICIAL_PROFILE: ProviderProfile;
457
- declare const ANTHROPIC_OFFICIAL_PROFILE: ProviderProfile;
458
- declare function createOpenAICompatibleProfile(profile: Omit<ProviderProfile, "protocol"> & {
459
- protocol?: "openai-chat";
460
- }): ProviderProfile;
461
- /** Normalize user-authored profile fields and reject unsafe/ambiguous roots. */
462
- declare function normalizeProviderProfile(profile: ProviderProfile): ProviderProfile;
463
- /** Build the wire adapter for a profile. Credentials remain in the transport. */
464
- declare function createProviderFromProfile(profileInput: ProviderProfile, transport: Transport): Provider;
465
- type ProfileDirectTransportConfig = Omit<DirectTransportConfig, "baseUrl" | "authStyle">;
466
- /** Build a BYOK/server-direct transport with the profile's URL and auth style. */
467
- declare function createDirectTransportForProfile(profileInput: ProviderProfile, config: ProfileDirectTransportConfig): Transport;
468
-
469
- type GeneratedMediaKind = "image" | "audio" | "video";
470
- type GeneratedMedia = {
471
- id: string;
472
- kind: GeneratedMediaKind;
473
- source: MediaSource;
474
- mediaType: string;
475
- provider: string;
476
- model?: string;
477
- revisedPrompt?: string;
478
- width?: number;
479
- height?: number;
480
- durationMs?: number;
481
- createdAt: number;
482
- };
483
- type MediaProviderCapabilities = {
484
- imageGeneration: boolean;
485
- speechGeneration: boolean;
486
- transcription: boolean;
487
- videoGeneration: boolean;
488
- asyncJobs: boolean;
489
- };
490
- type ImageGenerationRequest = {
491
- prompt: string;
492
- model?: string;
493
- n?: number;
494
- size?: string;
495
- quality?: string;
496
- style?: string;
497
- /** OpenAI-compatible response representation. Defaults to provider behavior. */
498
- responseFormat?: "url" | "b64_json";
499
- /** Escape hatch for endpoint-specific fields; normalized fields above win. */
500
- providerOptions?: Record<string, unknown>;
501
- };
502
- type SpeechGenerationRequest = {
503
- input: string;
504
- model?: string;
505
- voice?: string;
506
- format?: string;
507
- providerOptions?: Record<string, unknown>;
508
- };
509
- type TranscriptionRequest = {
510
- data: Blob | ArrayBuffer | Uint8Array;
511
- filename: string;
512
- mediaType?: string;
513
- model?: string;
514
- providerOptions?: Record<string, unknown>;
515
- };
516
- type Transcript = {
517
- text: string;
518
- language?: string;
519
- durationMs?: number;
520
- raw?: unknown;
521
- };
522
- type VideoGenerationRequest = {
523
- prompt: string;
524
- model?: string;
525
- image?: MediaSource;
526
- durationSeconds?: number;
527
- providerOptions?: Record<string, unknown>;
528
- };
529
- type MediaJobHandle = {
530
- provider: string;
531
- id: string;
532
- kind: GeneratedMediaKind;
533
- createdAt: number;
534
- };
535
- type MediaJobSnapshot = {
536
- handle: MediaJobHandle;
537
- status: "queued" | "running" | "completed" | "failed" | "cancelled";
538
- result?: GeneratedMedia[];
539
- error?: {
540
- message: string;
541
- code?: string;
542
- };
646
+ type DocumentEdit = {
647
+ block?: number;
648
+ find: string;
649
+ replace: string;
543
650
  };
544
- type MediaProvider = {
545
- readonly id: string;
546
- readonly label: string;
547
- readonly capabilities: MediaProviderCapabilities;
548
- generateImage?(req: ImageGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia[]>;
549
- generateSpeech?(req: SpeechGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia>;
550
- transcribe?(req: TranscriptionRequest, opts?: CallOptions): Promise<Transcript>;
551
- startVideoJob?(req: VideoGenerationRequest, opts?: CallOptions): Promise<MediaJobHandle>;
552
- pollMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;
553
- cancelMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;
651
+ /** Why a proposed edit could not be applied. Each maps to a different retry. */
652
+ type EditRejection =
653
+ /** No occurrence — the model is quoting text that is not there. Re-read. */
654
+ "not-found"
655
+ /** Several occurrences — the anchor is too short. Widen it or name a block. */
656
+ | "ambiguous"
657
+ /** The document moved underneath. Re-read and re-propose. */
658
+ | "stale-revision"
659
+ /** The named block does not exist. */
660
+ | "no-such-block";
661
+ type EditResult = {
662
+ ok: true;
663
+ markdown: string;
664
+ applied: AppliedEdit[];
665
+ } | {
666
+ ok: false;
667
+ reason: EditRejection;
668
+ message: string;
669
+ edit?: DocumentEdit;
554
670
  };
555
- /** Resolve an asset for HTML renderers without losing its MIME type. */
556
- declare function generatedMediaUrl(asset: GeneratedMedia): string | null;
557
-
558
- type OpenAIImageProviderConfig = {
559
- transport: Transport;
560
- /** Must match the provider key registered by createProxyHandler. */
561
- id?: string;
562
- label?: string;
563
- defaultModel?: string;
671
+ /** An edit resolved against the source — enough to render and to reverse. */
672
+ type AppliedEdit = {
673
+ edit: DocumentEdit;
674
+ /** Where the match landed in the ORIGINAL source. */
675
+ start: number;
676
+ end: number;
677
+ block: number;
564
678
  };
565
- declare function createOpenAIImageProvider(config: OpenAIImageProviderConfig): MediaProvider;
566
679
 
567
- type CardTone = "neutral" | "positive" | "negative" | "warning" | "info";
568
- type CardValueFormat = "text" | "number" | "currency" | "percent" | "bytes" | "duration" | "datetime" | "code";
569
- type TableColumn = {
570
- key: string;
571
- label: string;
572
- format?: CardValueFormat;
573
- align?: "left" | "right" | "center";
574
- /** Render this column's cell as an emphasis/status pill. */
575
- pill?: boolean;
576
- };
577
- type TableCard = {
578
- kind: "table";
579
- title?: string;
580
- caption?: string;
581
- columns: TableColumn[];
582
- rows: Record<string, unknown>[];
583
- /** Column key to sort by on first render. */
584
- sortBy?: string;
585
- sortDir?: "asc" | "desc";
586
- };
587
- type StatItem = {
588
- label: string;
589
- value: string | number;
590
- format?: CardValueFormat;
591
- /** Signed change vs a prior period; drives colour and arrow. */
592
- delta?: number;
593
- deltaFormat?: CardValueFormat;
594
- hint?: string;
595
- tone?: CardTone;
596
- };
597
- type StatsCard = {
598
- kind: "stats";
599
- title?: string;
600
- items: StatItem[];
601
- };
602
- type ChartSeries = {
603
- name: string;
604
- /** `[x, y]` pairs; x is a number, a timestamp, or a category label. */
605
- points: [string | number, number][];
606
- type?: "line" | "area" | "bar" | "scatter";
607
- color?: string;
608
- /** Plot against a secondary axis — volume under price, for instance. */
609
- axis?: "left" | "right";
610
- };
611
- type ChartAnnotation = {
612
- type: "hline" | "vline" | "band" | "marker";
613
- value: string | number;
614
- /** Second bound, for `band`. */
615
- to?: string | number;
616
- label?: string;
617
- tone?: CardTone;
618
- };
619
- type ChartCard = {
620
- kind: "chart";
621
- title?: string;
622
- /** OHLC candles are their own shape; series charts use `series`. */
623
- variant?: "series" | "candlestick";
624
- xLabel?: string;
625
- yLabel?: string;
626
- xType?: "time" | "number" | "category";
627
- series?: ChartSeries[];
628
- candles?: {
629
- t: string | number;
630
- o: number;
631
- h: number;
632
- l: number;
633
- c: number;
634
- v?: number;
635
- }[];
636
- annotations?: ChartAnnotation[];
637
- stacked?: boolean;
638
- };
639
- type TimelineCard = {
640
- kind: "timeline";
641
- title?: string;
642
- events: {
643
- at: string | number;
644
- label: string;
645
- detail?: string;
646
- tone?: CardTone;
647
- }[];
648
- };
649
- type KeyValueCard = {
650
- kind: "keyvalue";
651
- title?: string;
652
- items: {
653
- label: string;
654
- value: string | number;
655
- format?: CardValueFormat;
656
- tone?: CardTone;
657
- mono?: boolean;
658
- }[];
659
- };
660
- type ProgressStep = {
661
- label: string;
662
- status: "pending" | "active" | "done" | "failed" | "skipped";
663
- detail?: string;
664
- };
665
- type ProgressCard = {
666
- kind: "progress";
667
- title?: string;
668
- steps: ProgressStep[];
669
- /** 0–1. Omit for indeterminate. */
670
- fraction?: number;
671
- };
672
- type MediaCard = {
673
- kind: "media";
674
- title?: string;
675
- items: {
676
- url: string;
677
- alt?: string;
678
- caption?: string;
679
- mediaType?: string;
680
- /** Known intrinsic geometry keeps generated media from shifting on decode. */
681
- width?: number;
682
- height?: number;
683
- durationMs?: number;
684
- }[];
685
- layout?: "grid" | "single";
686
- };
687
- type MarkdownCard = {
688
- kind: "markdown";
689
- title?: string;
690
- body: string;
680
+ /** A span of a document artifact, resolved to source offsets. */
681
+ type DocumentQuoteRef = {
682
+ docId: string;
683
+ title: string;
684
+ /** Revision the span was taken from — compared at send time; see `drift`. */
685
+ revision: number;
686
+ /** Inclusive block index range. */
687
+ blocks: [number, number];
688
+ start: number;
689
+ end: number;
690
+ /** SOURCE markdown, not rendered text. */
691
+ text: string;
692
+ /**
693
+ * How the document had moved past `revision` when the message was sent.
694
+ * Absent when it had not, or when nothing checked — see `checkQuoteDrift`.
695
+ */
696
+ drift?: QuoteDrift;
691
697
  };
692
698
  /**
693
- * A document artifact — long-form Markdown the agent authored and the user
694
- * reads in a previewer rather than inline in the transcript.
695
- *
696
- * `docId` is the stable handle every later turn addresses: the body here is for
697
- * display only, and stripCardPayload removes it from what the model sees after
698
- * the turn that produced it. A model that wants to re-read the document calls
699
- * the read tool with this id — which is the point, because a document large
700
- * enough to deserve a previewer is too large to re-send every turn.
699
+ * What a quote's document did between the quoted revision and the send.
701
700
  *
702
- * `revision` is the optimistic-concurrency token. An edit carrying a stale one
703
- * is refused rather than applied to text that has since moved.
701
+ * The quoted revision can be old the moment it is taken — a document card
702
+ * further up the thread still shows the body it was created with — and the
703
+ * model cannot tell from the text alone. Told, it re-reads; not told, it
704
+ * proposes an edit against text that may no longer be there, or answers about
705
+ * a paragraph the user has since rewritten.
704
706
  */
705
- type DocumentCard = {
706
- kind: "document";
707
- docId: string;
708
- title: string;
709
- markdown: string;
707
+ type QuoteDrift =
708
+ /** Past the quoted revision. `intact`: the quoted text still appears verbatim. */
709
+ {
710
+ status: "moved";
710
711
  revision: number;
712
+ intact: boolean;
713
+ }
714
+ /** The document no longer exists. */
715
+ | {
716
+ status: "removed";
711
717
  };
712
718
  /**
713
- * A matrix of options against criteria.
719
+ * Compare a quote against the document as it is now. `undefined` when the
720
+ * quote is current.
714
721
  *
715
- * The most domain-portable card there is: legal clause-vs-clause, vendor
716
- * selection, pricing tiers, candidate evaluation, feature comparison. Boolean
717
- * values render as ✓/✗, so "does it have X" tables need no encoding by the model.
722
+ * Any revision other than the quoted one counts — a lower one means the id now
723
+ * names a different document, which is drift too.
718
724
  */
719
- type ComparisonCard = {
720
- kind: "comparison";
721
- title?: string;
722
- /** The things being compared — these become columns. */
723
- options: {
724
- id: string;
725
- label: string;
726
- note?: string;
727
- highlight?: boolean;
728
- }[];
729
- /** The dimensions they are compared on — these become rows. */
730
- criteria: {
731
- label: string;
732
- /** Keyed by option id. `true`/`false` render as ✓/✗; `null` renders as “—”. */
733
- values: Record<string, string | number | boolean | null>;
734
- detail?: string;
735
- weight?: "low" | "normal" | "high";
736
- }[];
725
+ declare function quoteDrift(quote: DocumentQuoteRef, current: Pick<DocumentSnapshot, "revision" | "markdown"> | undefined): QuoteDrift | undefined;
726
+ /**
727
+ * Stamp each quote with its drift against the store, ready to send.
728
+ *
729
+ * A lookup that throws leaves that quote unstamped rather than failing the
730
+ * send: the user's message matters more than the annotation, the quote still
731
+ * names its revision, and an edit made from it is still checked against the
732
+ * current one.
733
+ */
734
+ declare function checkQuoteDrift(quotes: readonly DocumentQuoteRef[], documents: Pick<DocumentStore, "get">): Promise<DocumentQuoteRef[]>;
735
+ /** Key under `Message.metadata` where quotes are stored for re-rendering. */
736
+ declare const QUOTES_METADATA_KEY = "documentQuotes";
737
+ /**
738
+ * Render quotes as the prefix of the user's message.
739
+ *
740
+ * Fenced rather than indented, and labelled with the document and block range,
741
+ * so the model can tell quoted material from the user's own words — and can
742
+ * name what it is about to change when the edit tools arrive. A stamped drift
743
+ * becomes a note between the label and the text.
744
+ */
745
+ declare function formatQuotes(quotes: readonly DocumentQuoteRef[]): string;
746
+ /** Prefix `text` with the quotes, keeping a blank line between them. */
747
+ declare function withQuotes(text: string, quotes: readonly DocumentQuoteRef[]): string;
748
+ /** Read quotes back off a message, for re-rendering the chips in history. */
749
+ declare function quotesOf(metadata: Record<string, unknown> | undefined): DocumentQuoteRef[];
750
+
751
+ type AgentErrorKind = "auth" | "rate-limit" | "overloaded" | "timeout" | "network" | "invalid-request" | "content-filter" | "context-length" | "not-supported" | "cancelled" | "tool-error" | "unknown";
752
+ declare class AgentError extends Error {
753
+ readonly kind: AgentErrorKind;
754
+ readonly status?: number;
755
+ readonly provider?: string;
756
+ /** Seconds to wait before retrying, from a Retry-After header when present. */
757
+ readonly retryAfter?: number;
758
+ readonly cause?: unknown;
759
+ readonly detail?: unknown;
760
+ constructor(kind: AgentErrorKind, message: string, opts?: {
761
+ status?: number;
762
+ provider?: string;
763
+ retryAfter?: number;
764
+ cause?: unknown;
765
+ detail?: unknown;
766
+ });
767
+ get retryable(): boolean;
768
+ /** Compact shape for logs and for handing an error back to the model as data. */
769
+ toJSON(): {
770
+ kind: AgentErrorKind;
771
+ message: string;
772
+ status: number | undefined;
773
+ provider: string | undefined;
774
+ };
775
+ }
776
+ declare function isAgentError(e: unknown): e is AgentError;
777
+ /**
778
+ * Classify anything thrown. Used for errors that never went through an adapter
779
+ * (a DNS failure, an aborted signal) and as the fallback in adapter mapping.
780
+ */
781
+ declare function toAgentError(e: unknown, provider?: string): AgentError;
782
+ /** HTTP status → kind. Shared by every adapter so classification can't drift. */
783
+ declare function kindFromStatus(status: number): AgentErrorKind;
784
+
785
+ declare function bytesToBase64(bytes: Uint8Array): string;
786
+ declare function base64ToBytes(s: string): Uint8Array;
787
+
788
+ type DirectTransportConfig = {
789
+ /** Provider API root, no trailing slash. e.g. "https://api.openai.com/v1". */
790
+ baseUrl: string;
791
+ /** Static key, or a getter for keys that rotate / come from a keychain. */
792
+ apiKey: string | (() => string | Promise<string>);
793
+ /**
794
+ * How the key rides on the wire. "bearer" (default) sends
795
+ * `Authorization: Bearer <key>`; "x-api-key" sends the `x-api-key` header —
796
+ * what Anthropic's Messages API expects.
797
+ */
798
+ authStyle?: "bearer" | "x-api-key";
799
+ /** Sent on every request; merged under per-request headers. */
800
+ headers?: Record<string, string>;
801
+ /**
802
+ * Required to use this transport in a browser. Naming it forces the caller to
803
+ * state the risk out loud instead of discovering it in production.
804
+ */
805
+ dangerouslyAllowBrowser?: boolean;
806
+ fetchImpl?: typeof fetch;
737
807
  };
738
- /** Items with a state. Compliance reviews, launch readiness, QA passes, audits. */
739
- type ChecklistCard = {
740
- kind: "checklist";
741
- title?: string;
742
- items: {
743
- label: string;
744
- status: "done" | "todo" | "blocked" | "na";
745
- detail?: string;
746
- /** Optional heading to group consecutive items under. */
747
- group?: string;
808
+ declare function buildUrl(baseUrl: string, path: string, query?: TransportRequest["query"]): string;
809
+ declare function createDirectTransport(config: DirectTransportConfig): Transport;
810
+
811
+ type ProxyTransportConfig = {
812
+ /** Base path of your proxy route, e.g. "/api/agent". */
813
+ url: string;
814
+ /** Extra headers (session cookie is automatic; use this for CSRF tokens). */
815
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
816
+ credentials?: RequestCredentials;
817
+ fetchImpl?: typeof fetch;
818
+ };
819
+ /** The envelope a ProxyTransport POSTs to the BFF. Exported so the server half can type it. */
820
+ type ProxyEnvelope = {
821
+ provider: string;
822
+ path: string;
823
+ method: "GET" | "POST" | "DELETE";
824
+ body?: unknown;
825
+ query?: Record<string, string | number | boolean | undefined>;
826
+ stream?: boolean;
827
+ /**
828
+ * Per-request headers for the UPSTREAM call (org ids, beta flags, an MCP
829
+ * session id). The server half forwards them after stripping credential
830
+ * headers and then applies its own key on top — a client can request
831
+ * headers, never substitute the credential.
832
+ */
833
+ headers?: Record<string, string>;
834
+ };
835
+ /**
836
+ * A `MultipartBody` as it travels inside the JSON envelope: bytes become
837
+ * base64 strings so the client→BFF wire stays one method, one body shape.
838
+ * Base64 costs +33%, so treat ~20 MB per upload as the practical ceiling —
839
+ * beyond that, use a direct transport or your own upload route.
840
+ */
841
+ type SerializedMultipartBody = {
842
+ kind: "multipart";
843
+ fields: Record<string, string>;
844
+ files: {
845
+ field: string;
846
+ filename: string;
847
+ mediaType?: string;
848
+ data: string;
748
849
  }[];
749
850
  };
750
- /** A single highlighted note. Disclaimers, caveats, prerequisites, warnings. */
751
- type CalloutCard = {
752
- kind: "callout";
753
- tone: "info" | "warning" | "danger" | "success" | "note";
754
- title?: string;
755
- body: string;
851
+ declare function createProxyTransport(config: ProxyTransportConfig): Transport;
852
+
853
+ /** Full-jitter exponential backoff. Full jitter (not equal) because synchronized
854
+ * clients retrying a rate limit in lockstep is how a 429 becomes a 429 storm. */
855
+ declare function backoffDelay(attempt: number, policy: RetryPolicy, retryAfterSec?: number): number;
856
+ declare function parseRetryAfter(headers: Headers): number | undefined;
857
+ /**
858
+ * Retry `run` while it fails transiently. Non-retryable failures (auth, bad
859
+ * request, content filter) throw on the first attempt — retrying them just
860
+ * burns quota and delays the real error reaching the user.
861
+ */
862
+ declare function withRetry<T>(run: (attempt: number) => Promise<T>, opts?: {
863
+ policy?: RetryPolicy;
864
+ signal?: AbortSignal;
865
+ provider?: string;
866
+ onRetry?: (attempt: number, err: AgentError, delayMs: number) => void;
867
+ }): Promise<T>;
868
+ /**
869
+ * Turn a non-OK `Response` into a typed `AgentError`, pulling the provider's own
870
+ * message out of the body so the user sees "model X does not exist" rather than
871
+ * "HTTP 404".
872
+ */
873
+ declare function errorFromResponse(res: Response, provider: string): Promise<AgentError>;
874
+
875
+ type SSEMessage = {
876
+ event: string;
877
+ data: string;
878
+ id?: string;
879
+ retry?: number;
756
880
  };
757
881
  /**
758
- * Sources behind a claim.
759
- *
760
- * Domain-agnostic and unusually important for agents specifically: it is the
761
- * card that lets a reader check the work rather than trust the summary.
882
+ * Incremental line-oriented decoder. State is per-instance, not module-level —
883
+ * a background job poll and a foreground stream can run concurrently, and
884
+ * shared accumulator state would interleave their events into garbage.
885
+ */
886
+ declare class SSEDecoder {
887
+ private event;
888
+ private data;
889
+ private id;
890
+ private retry;
891
+ /** Feed one line (terminator already removed). Returns an event when dispatched. */
892
+ push(line: string): SSEMessage | null;
893
+ /** Dispatch whatever has accumulated. Called on a blank line and at stream end. */
894
+ flush(): SSEMessage | null;
895
+ }
896
+ /**
897
+ * Decode a byte stream into SSE messages. `TextDecoder({stream:true})` is what
898
+ * makes multi-byte characters split across chunks safe — decoding each chunk
899
+ * independently corrupts any emoji or CJK text that straddles a boundary.
900
+ */
901
+ declare function parseSSE(stream: ReadableStream<Uint8Array>): AsyncGenerator<SSEMessage>;
902
+ /**
903
+ * SSE messages whose `data` is JSON, skipping the `[DONE]` sentinel that
904
+ * OpenAI's Chat Completions stream terminates with.
762
905
  */
763
- type CitationsCard = {
764
- kind: "citations";
765
- title?: string;
766
- items: {
767
- title: string;
768
- /** Publication, court, statute, dataset, site — whatever the source is. */
769
- source?: string;
770
- url?: string;
771
- date?: string | number;
772
- /** The specific passage relied on. */
773
- snippet?: string;
774
- locator?: string;
775
- relevance?: "high" | "medium" | "low";
776
- }[];
906
+ declare function parseSSEJson<T = unknown>(stream: ReadableStream<Uint8Array>): AsyncGenerator<{
907
+ event: string;
908
+ data: T;
909
+ }>;
910
+
911
+ type ProviderProtocol = "openai-responses" | "openai-chat" | "anthropic-messages";
912
+ type ProviderProfile = {
913
+ /** Stable routing id. It must match the proxy provider key in proxy mode. */
914
+ id: string;
915
+ label: string;
916
+ protocol: ProviderProtocol;
917
+ /** Provider API root including its version prefix, without a trailing slash. */
918
+ baseUrl: string;
919
+ models?: ModelInfo[];
920
+ capabilities?: Partial<ProviderCapabilities>;
777
921
  };
778
- /** Staged drop-off. Conversion funnels, hiring pipelines, case attrition, intake flows. */
779
- type FunnelCard = {
780
- kind: "funnel";
781
- title?: string;
782
- stages: {
783
- label: string;
784
- value: number;
785
- note?: string;
786
- }[];
787
- format?: CardValueFormat;
922
+ declare const OPENAI_OFFICIAL_PROFILE: ProviderProfile;
923
+ declare const ANTHROPIC_OFFICIAL_PROFILE: ProviderProfile;
924
+ declare function createOpenAICompatibleProfile(profile: Omit<ProviderProfile, "protocol"> & {
925
+ protocol?: "openai-chat";
926
+ }): ProviderProfile;
927
+ /** Normalize user-authored profile fields and reject unsafe/ambiguous roots. */
928
+ declare function normalizeProviderProfile(profile: ProviderProfile): ProviderProfile;
929
+ /** Build the wire adapter for a profile. Credentials remain in the transport. */
930
+ declare function createProviderFromProfile(profileInput: ProviderProfile, transport: Transport): Provider;
931
+ type ProfileDirectTransportConfig = Omit<DirectTransportConfig, "baseUrl" | "authStyle">;
932
+ /** Build a BYOK/server-direct transport with the profile's URL and auth style. */
933
+ declare function createDirectTransportForProfile(profileInput: ProviderProfile, config: ProfileDirectTransportConfig): Transport;
934
+
935
+ type GeneratedMediaKind = "image" | "audio" | "video";
936
+ type GeneratedMedia = {
937
+ id: string;
938
+ kind: GeneratedMediaKind;
939
+ source: MediaSource;
940
+ mediaType: string;
941
+ provider: string;
942
+ model?: string;
943
+ revisedPrompt?: string;
944
+ width?: number;
945
+ height?: number;
946
+ durationMs?: number;
947
+ createdAt: number;
788
948
  };
789
- /** One value against a scale, with optional named bands. Scores, risk levels, sentiment. */
790
- type GaugeCard = {
791
- kind: "gauge";
792
- title?: string;
793
- value: number;
794
- min?: number;
795
- max?: number;
796
- label?: string;
797
- bands?: {
798
- from: number;
799
- to: number;
800
- label: string;
801
- tone?: CardTone;
802
- }[];
803
- format?: CardValueFormat;
949
+ type MediaProviderCapabilities = {
950
+ imageGeneration: boolean;
951
+ speechGeneration: boolean;
952
+ transcription: boolean;
953
+ videoGeneration: boolean;
954
+ asyncJobs: boolean;
804
955
  };
805
- type TreeNode = {
806
- label: string;
807
- detail?: string;
808
- tone?: CardTone;
809
- children?: TreeNode[];
956
+ type ImageGenerationRequest = {
957
+ prompt: string;
958
+ model?: string;
959
+ n?: number;
960
+ size?: string;
961
+ quality?: string;
962
+ style?: string;
963
+ /** OpenAI-compatible response representation. Defaults to provider behavior. */
964
+ responseFormat?: "url" | "b64_json";
965
+ /** Escape hatch for endpoint-specific fields; normalized fields above win. */
966
+ providerOptions?: Record<string, unknown>;
810
967
  };
811
- /** Nested structure. Document outlines, org charts, taxonomies, decision trees. */
812
- type TreeCard = {
813
- kind: "tree";
814
- title?: string;
815
- nodes: TreeNode[];
968
+ type SpeechGenerationRequest = {
969
+ input: string;
970
+ model?: string;
971
+ voice?: string;
972
+ format?: string;
973
+ providerOptions?: Record<string, unknown>;
816
974
  };
817
- type CodeCard = {
818
- kind: "code";
819
- title?: string;
820
- language?: string;
821
- code: string;
822
- filename?: string;
975
+ type TranscriptionRequest = {
976
+ data: Blob | ArrayBuffer | Uint8Array;
977
+ filename: string;
978
+ mediaType?: string;
979
+ model?: string;
980
+ providerOptions?: Record<string, unknown>;
823
981
  };
824
- type DiffCard = {
825
- kind: "diff";
826
- title?: string;
827
- before: string;
828
- after: string;
982
+ type Transcript = {
983
+ text: string;
829
984
  language?: string;
985
+ durationMs?: number;
986
+ raw?: unknown;
830
987
  };
831
- type ChoiceCard = {
832
- kind: "choice";
833
- title?: string;
834
- prompt?: string;
835
- multiple?: boolean;
836
- options: {
837
- id: string;
838
- label: string;
839
- description?: string;
840
- /** Small facts shown on the option row: APR, TVL, price. */
841
- meta?: {
842
- label: string;
843
- value: string | number;
844
- format?: CardValueFormat;
845
- }[];
846
- imageUrl?: string;
847
- disabled?: boolean;
848
- disabledReason?: string;
849
- }[];
988
+ type VideoGenerationRequest = {
989
+ prompt: string;
990
+ model?: string;
991
+ image?: MediaSource;
992
+ durationSeconds?: number;
993
+ providerOptions?: Record<string, unknown>;
850
994
  };
851
- type FormField = {
852
- name: string;
853
- label: string;
854
- type: "text" | "textarea";
855
- placeholder?: string;
856
- required?: boolean;
857
- value?: string;
858
- } | {
859
- name: string;
860
- label: string;
861
- type: "number";
862
- min?: number;
863
- max?: number;
864
- step?: number;
865
- required?: boolean;
866
- value?: number;
867
- suffix?: string;
868
- } | {
869
- name: string;
870
- label: string;
871
- type: "select";
872
- options: {
873
- value: string;
874
- label: string;
875
- }[];
876
- required?: boolean;
877
- value?: string;
878
- } | {
879
- name: string;
880
- label: string;
881
- type: "boolean";
882
- value?: boolean;
995
+ type MediaJobHandle = {
996
+ provider: string;
997
+ id: string;
998
+ kind: GeneratedMediaKind;
999
+ createdAt: number;
883
1000
  };
884
- type FormCard = {
885
- kind: "form";
886
- title?: string;
887
- description?: string;
888
- fields: FormField[];
889
- submitLabel?: string;
1001
+ type MediaJobSnapshot = {
1002
+ handle: MediaJobHandle;
1003
+ status: "queued" | "running" | "completed" | "failed" | "cancelled";
1004
+ result?: GeneratedMedia[];
1005
+ error?: {
1006
+ message: string;
1007
+ code?: string;
1008
+ };
890
1009
  };
891
- type ConfirmCard = {
892
- kind: "confirm";
893
- title: string;
894
- /** The consequential summary — what will actually happen. */
895
- summary: {
896
- label: string;
897
- value: string | number;
898
- tone?: CardTone;
899
- mono?: boolean;
900
- }[];
901
- description?: string;
902
- confirmLabel?: string;
903
- cancelLabel?: string;
904
- /** Renders the confirm control as destructive. */
905
- danger?: boolean;
1010
+ type MediaProvider = {
1011
+ readonly id: string;
1012
+ readonly label: string;
1013
+ readonly capabilities: MediaProviderCapabilities;
1014
+ generateImage?(req: ImageGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia[]>;
1015
+ generateSpeech?(req: SpeechGenerationRequest, opts?: CallOptions): Promise<GeneratedMedia>;
1016
+ transcribe?(req: TranscriptionRequest, opts?: CallOptions): Promise<Transcript>;
1017
+ startVideoJob?(req: VideoGenerationRequest, opts?: CallOptions): Promise<MediaJobHandle>;
1018
+ pollMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;
1019
+ cancelMediaJob?(handle: MediaJobHandle, opts?: CallOptions): Promise<MediaJobSnapshot>;
1020
+ };
1021
+ /** Resolve an asset for HTML renderers without losing its MIME type. */
1022
+ declare function generatedMediaUrl(asset: GeneratedMedia): string | null;
1023
+
1024
+ type OpenAIImageProviderConfig = {
1025
+ transport: Transport;
1026
+ /** Must match the provider key registered by createProxyHandler. */
1027
+ id?: string;
1028
+ label?: string;
1029
+ defaultModel?: string;
1030
+ };
1031
+ declare function createOpenAIImageProvider(config: OpenAIImageProviderConfig): MediaProvider;
1032
+
1033
+ declare const SURFACE_CARD_KIND: "surface";
1034
+ declare const SURFACE_FORMAT_VERSION: 1;
1035
+ /** Hard ceilings. A model that exceeds one receives a correction, never a frozen tab. */
1036
+ declare const SURFACE_LIMITS: {
1037
+ readonly components: 200;
1038
+ readonly depth: 16;
1039
+ readonly dataChars: 64000;
1040
+ readonly specChars: 200000;
1041
+ readonly surfaces: 24;
1042
+ readonly listItems: 200;
1043
+ readonly queryRows: 2000;
1044
+ readonly actionUpdates: 8;
1045
+ readonly tabs: 12;
1046
+ };
1047
+ /** Read a value from the data model by JSON Pointer: `{ "$path": "/filters/region" }`. */
1048
+ type SurfacePathBinding = {
1049
+ $path: string;
1050
+ };
1051
+ /** Inside a `List` template, read a field of the current row. `""` is the row itself. */
1052
+ type SurfaceItemBinding = {
1053
+ $item: string;
1054
+ };
1055
+ /** Interpolate values into a string: `{ "$template": "Spend in {/region}" }`, `{.name}` for a row field. */
1056
+ type SurfaceTemplateBinding = {
1057
+ $template: string;
1058
+ };
1059
+ /** Filter, group and aggregate an array in the data model. */
1060
+ type SurfaceQueryBinding = {
1061
+ $query: SurfaceQuery;
1062
+ };
1063
+ type SurfaceBinding = SurfacePathBinding | SurfaceItemBinding | SurfaceTemplateBinding | SurfaceQueryBinding;
1064
+ type SurfaceWhereOp = "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "contains";
1065
+ type SurfaceWhere = {
1066
+ field: string;
1067
+ op?: SurfaceWhereOp;
1068
+ value: unknown;
1069
+ /** Skip this clause when the value equals this, so an "All" option needs no special case. */
1070
+ ignore?: string | number | boolean;
1071
+ };
1072
+ type SurfaceAggregateOp = "count" | "sum" | "avg" | "min" | "max";
1073
+ type SurfaceQuery = {
1074
+ /** JSON Pointer to an array of rows. */
1075
+ from: string;
1076
+ where?: SurfaceWhere[];
1077
+ groupBy?: string;
1078
+ aggregate?: {
1079
+ op: SurfaceAggregateOp;
1080
+ field?: string;
1081
+ };
1082
+ /** A row field; after `groupBy`, `key` or `value`. */
1083
+ sortBy?: string;
1084
+ sortDir?: "asc" | "desc";
1085
+ limit?: number;
1086
+ /** Return one field of each row instead of the row. */
1087
+ select?: string;
1088
+ /** Grouped results: `[key, value]` pairs (default, chart-ready) or `{ key, value }` rows. */
1089
+ shape?: "points" | "rows";
1090
+ };
1091
+ type SurfaceConditionOp = "truthy" | "falsy" | "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in";
1092
+ /** A declarative test over the data model, for `visibleWhen` and `disabledWhen`. */
1093
+ type SurfaceCondition = {
1094
+ path: string;
1095
+ op?: SurfaceConditionOp;
1096
+ value?: unknown;
906
1097
  };
907
- type BuiltinCard = TableCard | StatsCard | ChartCard | TimelineCard | KeyValueCard | ProgressCard | MediaCard | MarkdownCard | DocumentCard | EditReviewCard | EmailCard | CodeCard | DiffCard | ComparisonCard | ChecklistCard | CalloutCard | CitationsCard | FunnelCard | GaugeCard | TreeCard | ChoiceCard | FormCard | ConfirmCard;
908
- type BuiltinCardKind = BuiltinCard["kind"];
909
- /**
910
- * The approval surface for a proposed document edit.
911
- *
912
- * Interactive, because in in-chat editing the diff IS the approval: there is no
913
- * other moment at which the user gets to see what is about to happen. Hunks are
914
- * accepted individually rather than all-or-nothing — partial acceptance is what
915
- * makes the exchange read as collaboration instead of take-it-or-leave-it, and
916
- * an edit is already the smallest independently applicable unit because it
917
- * carries its own anchor.
918
- */
919
- type EditReviewCard = {
920
- kind: "editreview";
921
- docId: string;
922
- title: string;
923
- /** Revision the edits were computed against; a stale one is refused. */
924
- revision: number;
925
- /** One line on why, in the model's words. */
926
- summary?: string;
927
- hunks: {
928
- index: number;
929
- block: number;
930
- removed: string[];
931
- added: string[];
1098
+ /** The whole action vocabulary. Adding a member here is a security decision. */
1099
+ type SurfaceAction = {
1100
+ type: "set";
1101
+ updates: {
1102
+ path: string;
1103
+ value: unknown;
932
1104
  }[];
1105
+ } | {
1106
+ type: "tool";
1107
+ tool: string;
1108
+ args?: Record<string, unknown>;
1109
+ resultPath?: string;
1110
+ } | {
1111
+ type: "event";
1112
+ name: string;
1113
+ context?: Record<string, unknown>;
1114
+ };
1115
+ type SurfaceComponent = {
1116
+ id: string;
1117
+ component: string;
1118
+ visibleWhen?: SurfaceCondition;
1119
+ [prop: string]: unknown;
1120
+ };
1121
+ type SurfaceIssueCode = "invalid-shape" | "duplicate-id" | "unknown-component" | "invalid-prop" | "invalid-binding" | "invalid-action" | "tool-not-allowed" | "unsafe-content" | "invalid-card" | "invalid-data" | "missing-root" | "missing-child" | "cycle" | "too-deep" | "limit-exceeded" | "not-found" | "expired" | "stale-revision";
1122
+ /** One thing wrong, written for the model that has to fix it. */
1123
+ type SurfaceIssue = {
1124
+ code: SurfaceIssueCode;
1125
+ message: string;
1126
+ /** What to send instead. */
1127
+ fix: string;
1128
+ componentId?: string;
1129
+ path?: string;
933
1130
  };
934
1131
  /**
935
- * A drafted email, before it is anyone's outbox.
936
- *
937
- * Always a draft the user completes — which is exactly the `draft` preset tier
938
- * ("produces something the USER must approve/sign. No side effects"). The
939
- * framework never holds a mail credential, for the same reason a Transport
940
- * never holds an API key.
941
- *
942
- * Editable but not interactive: nothing waits on it. The run does not suspend,
943
- * because the model asked no question — it produced a thing.
1132
+ * The current state of a surface. Travels as a card spec, which is how it uses
1133
+ * the thread, history-shedding and renderer seams cards already have.
944
1134
  */
945
- type EmailCard = {
946
- kind: "email";
947
- to: string[];
948
- cc?: string[];
949
- bcc?: string[];
950
- subject: string;
951
- /** Plain text. Markdown here would be a lie: mailto cannot carry it. */
952
- body: string;
953
- };
954
- /** A host-registered card is any `{kind}` object; built-ins are the typed subset. */
955
- type CardSpec = BuiltinCard | ({
956
- kind: string;
957
- } & Record<string, unknown>);
958
- /** Envelope attached to a tool result, or returned by `visualize`. */
959
- type Card = {
960
- id: string;
961
- spec: CardSpec;
962
- /** Set when the payload was dropped from persisted history. */
1135
+ type SurfaceSpec = {
1136
+ kind: typeof SURFACE_CARD_KIND;
1137
+ version: typeof SURFACE_FORMAT_VERSION;
1138
+ surfaceId: string;
1139
+ title?: string;
1140
+ root: string;
1141
+ components: SurfaceComponent[];
1142
+ data: Record<string, unknown>;
1143
+ /** Bumped by every agent update and every local edit. */
1144
+ revision: number;
1145
+ /** The call that created it: where it lives in the transcript. */
1146
+ originCallId?: string;
1147
+ /** Parts that could not be accepted. The person sees a fallback in their place. */
1148
+ issues?: SurfaceIssue[];
1149
+ /** Removed by the agent. */
1150
+ deleted?: boolean;
1151
+ /** The payload was shed from saved history. */
963
1152
  expired?: boolean;
964
- /** Tool call this card belongs to, for correlating an action back. */
965
- callId?: string;
966
- /**
967
- * What the user answered, once they have.
968
- *
969
- * Lives on the card rather than in the renderer's local state because the card
970
- * is re-mounted from history when the turn commits — state does not survive
971
- * that, and a renderer left guessing shows the wrong answer.
972
- */
973
- action?: CardAction;
974
1153
  };
975
- /** What the user did with an interactive card. Becomes the tool result. */
976
- type CardAction = {
977
- cardId: string;
978
- callId?: string;
979
- kind: string;
980
- type: "submit" | "select" | "confirm" | "cancel" | "dismiss";
981
- /** Selected option ids, form values, or nothing for confirm/cancel. */
982
- value?: unknown;
1154
+ /** Patches for an existing surface, applied in order and validated before rendering. */
1155
+ type SurfaceOperation = {
1156
+ op: "upsertComponents";
1157
+ components: unknown[];
1158
+ } | {
1159
+ op: "removeComponents";
1160
+ ids: string[];
1161
+ } | {
1162
+ op: "setRoot";
1163
+ root: string;
1164
+ } | {
1165
+ op: "setTitle";
1166
+ title: string;
1167
+ } | {
1168
+ op: "setData";
1169
+ path: string;
1170
+ value: unknown;
1171
+ } | {
1172
+ op: "removeData";
1173
+ path: string;
1174
+ };
1175
+ type SurfaceActivityState = "queued" | "running" | "done" | "failed" | "refused" | "cancelled";
1176
+ /** What became of the last thing the person pressed. A press with no visible result reads as broken. */
1177
+ type SurfaceActivity = {
1178
+ componentId: string;
1179
+ state: SurfaceActivityState;
1180
+ message?: string;
983
1181
  at: number;
984
1182
  };
985
- /** Marker key used to recognise a card inside an arbitrary tool output. */
986
- declare const CARD_KEY: "$card";
987
- type CardCarrier = {
988
- [CARD_KEY]: Card;
989
- } & Record<string, unknown>;
990
- declare function isCardCarrier(value: unknown): value is CardCarrier;
991
- /** Attach a card to a tool result without disturbing the data the model reads. */
992
- declare function withCard<T extends Record<string, unknown>>(data: T, spec: CardSpec, id?: string): T & CardCarrier;
993
- /**
994
- * Remove a card payload from a tool output, leaving a note in its place.
995
- *
996
- * The card is for the user's eyes; the model gets the surrounding data. Sending
997
- * both is double billing — and a chart spec with 2,000 points is the single
998
- * largest thing a tool result can carry. Applied in two places, which must stay
999
- * consistent: within a running turn (before each provider call) and when a
1000
- * persisted thread is rebuilt into context.
1001
- */
1002
- declare function stripCardPayload(output: unknown): unknown;
1183
+ /** Recorded on the user message an action produces, so the transcript can show it as an action. */
1184
+ type SurfaceEventRecord = {
1185
+ surfaceId: string;
1186
+ componentId: string;
1187
+ title?: string;
1188
+ label?: string;
1189
+ type: "event" | "tool";
1190
+ name: string;
1191
+ context?: Record<string, unknown>;
1192
+ };
1193
+ declare const SURFACE_EVENT_METADATA_KEY: "surfaceEvent";
1194
+ /** How an interactive card answered inside a surface. Stored at the card's `bind` path. */
1195
+ type SurfaceCardAnswer = Pick<CardAction, "type" | "value" | "at">;
1196
+
1197
+ declare const SURFACE_ARTIFACT_KIND: string;
1198
+ /** One card id per surface, so a later snapshot replaces the earlier one in a run. */
1199
+ declare const surfaceCardId: (surfaceId: string) => string;
1200
+ declare function isSurfaceSpec(value: unknown): value is SurfaceSpec;
1201
+ /** The current state of every surface on a message path. Later snapshots win. */
1202
+ declare function foldSurfaces(messages: readonly Message[]): Record<string, SurfaceSpec>;
1203
+ /** The working copy a run reads and writes, so two calls in one step see each other. */
1204
+ declare class SurfaceLedger {
1205
+ private readonly surfaces;
1206
+ constructor(initial?: Record<string, SurfaceSpec>);
1207
+ get(surfaceId: string): SurfaceSpec | undefined;
1208
+ put(spec: SurfaceSpec): void;
1209
+ list(): SurfaceSpec[];
1210
+ /** Surfaces still on screen. */
1211
+ live(): SurfaceSpec[];
1212
+ }
1003
1213
 
1004
1214
  type ToolSide = "read" | "write" | "confirm";
1005
1215
  /**
@@ -1025,8 +1235,12 @@ type ToolExecutionContext = {
1025
1235
  callId: string;
1026
1236
  /** Emit a card mid-execution (progress updates on a long tool). */
1027
1237
  emitCard?: (spec: CardSpec) => void;
1028
- /** Ask the user something and await the answer. Powers `side: "confirm"`. */
1238
+ /** Ask the user something and await the answer. Absent when this host cannot ask. */
1029
1239
  requestCard?: (spec: CardSpec) => Promise<unknown>;
1240
+ /** The surfaces on this conversation's active path, as this run sees them. */
1241
+ surfaces?: SurfaceLedger;
1242
+ /** Tools a surface button may call in this run. */
1243
+ surfaceActionTools?: readonly string[];
1030
1244
  };
1031
1245
  type ToolResultExtras = {
1032
1246
  /**
@@ -1061,8 +1275,18 @@ type ToolDefinition = {
1061
1275
  /**
1062
1276
  * `confirm` suspends the run and shows an approval card before executing.
1063
1277
  * The distinction from `write` is intent: `write` acts, `confirm` asks first.
1278
+ * The runtime enforces this: with no approval, and no way to get one, the tool
1279
+ * does not run.
1064
1280
  */
1065
1281
  side?: ToolSide;
1282
+ /**
1283
+ * Who asks, for a `side: "confirm"` tool. `"runtime"` (the default) shows a
1284
+ * generic approval card before the tool starts. `"tool"` is for a tool whose
1285
+ * approval needs something only it can compute, such as a diff: it must call
1286
+ * `ctx.requestCard` itself before acting. A tool that asks for itself without
1287
+ * saying so is asked about twice, which is the safe way for that to go wrong.
1288
+ */
1289
+ confirmation?: "runtime" | "tool";
1066
1290
  /** Ask the provider to enforce the schema (OpenAI strict mode). */
1067
1291
  strict?: boolean;
1068
1292
  /** Default card renderer key when the result carries no explicit card. */
@@ -1600,176 +1824,197 @@ declare const editReviewCard: CardKindDefinition;
1600
1824
  declare const emailCard: CardKindDefinition;
1601
1825
  declare const codeCard: CardKindDefinition;
1602
1826
  declare const diffCard: CardKindDefinition;
1603
- declare const comparisonCard: CardKindDefinition;
1604
- declare const checklistCard: CardKindDefinition;
1605
- declare const calloutCard: CardKindDefinition;
1606
- declare const citationsCard: CardKindDefinition;
1607
- declare const funnelCard: CardKindDefinition;
1608
- declare const gaugeCard: CardKindDefinition;
1609
- declare const treeCard: CardKindDefinition;
1610
- declare const choiceCard: CardKindDefinition;
1611
- declare const formCard: CardKindDefinition;
1612
- declare const confirmCard: CardKindDefinition;
1613
- declare const BUILTIN_CARDS: CardKindDefinition[];
1614
-
1615
- /**
1616
- * The tool registry. Holds definitions, maps preset → allowlist, and renders the
1617
- * provider-facing `ToolSpec[]`.
1618
- *
1619
- * `resolve()` is the only way to get a tool set, and it always applies deny
1620
- * last — so a host-level kill switch cannot be re-granted by a preset or by a
1621
- * skill unlocking a tool.
1622
- */
1623
- declare class ToolRegistry {
1624
- private tools;
1625
- private presets;
1626
- private listeners;
1627
- private version;
1628
- private reversePresetIndex;
1629
- constructor(tools?: readonly ToolDefinition[]);
1630
- register(tool: ToolDefinition, presets?: readonly PresetName[]): this;
1631
- /** Register several tools into the same preset — the common bulk case. */
1632
- registerAll(tools: readonly ToolDefinition[], presets?: readonly PresetName[]): this;
1633
- addToPreset(preset: PresetName, ...names: string[]): this;
1634
- /**
1635
- * Change notification, so a UI (or an inspector hook) re-reads after a LATE
1636
- * registration — tools imported from an MCP server arrive long after mount,
1637
- * and a registry nobody can observe leaves them invisible until reload.
1638
- */
1639
- subscribe(listener: () => void): () => void;
1640
- /** Monotonic change counter — a stable snapshot value for useSyncExternalStore. */
1641
- getVersion(): number;
1642
- private touch;
1643
- get(name: string): ToolDefinition | undefined;
1644
- has(name: string): boolean;
1645
- list(): ToolDefinition[];
1646
- presetNames(): PresetName[];
1647
- /** Tool names in a preset that are actually registered. */
1648
- namesInPreset(preset: PresetName): string[];
1649
- /** Which presets grant `name`. Used by the UI to explain why a tool is available. */
1650
- presetsFor(name: string): PresetName[];
1651
- /** Tool name → presets that grant it, rebuilt on demand after the last mutation. */
1652
- private reverseIndex;
1653
- /**
1654
- * Resolve the tool set for a run.
1655
- *
1656
- * Two distinct grants, and keeping them separate is a security property:
1657
- *
1658
- * PRESETS grant AUTHORITY. Whether the caller may act at all.
1659
- * `allow` grants RELEVANCE. Usually a matched skill saying "these are the
1660
- * tools my instructions describe".
1661
- *
1662
- * A skill must therefore never be able to escalate past the capability tier.
1663
- * So `allow` can surface a tool that belongs to NO preset (private by
1664
- * default, unlocked by the skill that documents it), but a tool that IS in a
1665
- * preset still requires that preset to be enabled. Otherwise any skill could
1666
- * hand out the executor tier just by naming a tool.
1667
- *
1668
- * A name listed in a preset but never registered is skipped rather than
1669
- * throwing — presets are configuration and often outlive the tools they name.
1670
- */
1671
- resolve(resolution: ToolResolution): ToolDefinition[];
1672
- /** Provider-facing specs. The adapter turns these into its own wire shape. */
1673
- toSpecs(tools: readonly ToolDefinition[]): ToolSpec[];
1674
- /** Tools whose execution happens on the host, not here. */
1675
- hostExecuted(tools: readonly ToolDefinition[]): string[];
1676
- }
1677
-
1678
- type RepairResult = {
1679
- value: unknown;
1680
- repaired: boolean;
1681
- error?: string;
1682
- };
1683
- /**
1684
- * Normalize a tool name. Some OpenAI-compatible routers namespace tool names on
1685
- * the way out but not on the way in, so the model calls `functions.getPrice`
1686
- * for a tool we registered as `getPrice`.
1687
- */
1688
- declare function normalizeToolName(name: string): string;
1689
- /**
1690
- * Parse tool arguments, repairing what can be repaired losslessly.
1691
- * Returns `{}` rather than throwing when nothing is salvageable — an empty
1692
- * argument object lets the tool's own validation produce a message the model can
1693
- * act on, which beats a parse error the model never sees.
1694
- */
1695
- declare function repairToolArguments(raw: unknown): RepairResult;
1696
-
1697
- declare class PartialJsonParser {
1698
- private stack;
1699
- private token;
1700
- private root;
1701
- private started;
1702
- private done;
1703
- private broken;
1704
- private changes;
1705
- private cache;
1706
- /** True once the top-level value has closed. Input after it is ignored. */
1707
- get complete(): boolean;
1708
- /** True once the input stopped being JSON. The parser keeps its last good snapshot. */
1709
- get failed(): boolean;
1710
- /**
1711
- * Bumped whenever the snapshot would differ. Compare against the value you
1712
- * last rendered to skip deltas that changed nothing visible — whitespace, a
1713
- * key's characters, the digits of an unfinished number.
1714
- */
1715
- get version(): number;
1716
- push(chunk: string): void;
1717
- /**
1718
- * The value as far as it has arrived, or `undefined` before the top-level
1719
- * container opens. Stable by reference until `version` changes.
1720
- */
1721
- snapshot(): unknown;
1722
- private structural;
1723
- private startValue;
1724
- private open;
1725
- private close;
1726
- /** A value finished: hand it to the container it belongs to, or finish the root. */
1727
- private assign;
1728
- /** Consume string characters from `i`; returns where reading stopped. */
1729
- private readString;
1730
- }
1731
- /** One-shot form: the best value `text` supports so far, and whether it is whole. */
1732
- declare function parsePartialJson(text: string): {
1733
- value: unknown;
1734
- complete: boolean;
1827
+ declare const comparisonCard: CardKindDefinition;
1828
+ declare const checklistCard: CardKindDefinition;
1829
+ declare const calloutCard: CardKindDefinition;
1830
+ declare const citationsCard: CardKindDefinition;
1831
+ declare const funnelCard: CardKindDefinition;
1832
+ declare const gaugeCard: CardKindDefinition;
1833
+ declare const treeCard: CardKindDefinition;
1834
+ declare const choiceCard: CardKindDefinition;
1835
+ declare const formCard: CardKindDefinition;
1836
+ declare const confirmCard: CardKindDefinition;
1837
+ declare const BUILTIN_CARDS: CardKindDefinition[];
1838
+
1839
+ /** Segments of a pointer, or `undefined` when it is malformed or unsafe. `""` and `"/"` are the root. */
1840
+ declare function parsePointer(pointer: unknown): string[] | undefined;
1841
+ declare function getAt(data: unknown, pointer: string): unknown;
1842
+ /** A new data model with `value` at `pointer`, or `undefined` when the pointer cannot be written. */
1843
+ declare function setAt(data: Record<string, unknown>, pointer: string, value: unknown): Record<string, unknown> | undefined;
1844
+ /** A new data model without the value at `pointer`. Removing what is not there changes nothing. */
1845
+ declare function removeAt(data: Record<string, unknown>, pointer: string): Record<string, unknown> | undefined;
1846
+
1847
+ declare const isScriptUrl: (s: string) => boolean;
1848
+ type UnsafeFinding = {
1849
+ path: string;
1850
+ reason: string;
1851
+ };
1852
+ /**
1853
+ * First unsafe thing in `value`. `markup` also refuses HTML in strings: right for
1854
+ * a primitive's props, wrong for a code card, whose whole job is to show source.
1855
+ */
1856
+ declare function findUnsafe(value: unknown, opts?: {
1857
+ markup?: boolean;
1858
+ path?: string;
1859
+ }): UnsafeFinding | undefined;
1860
+ /** A URL a surface may load or link to: http(s), plus inline raster images for `image`. */
1861
+ declare function safeSurfaceUrl(url: unknown, use: "link" | "image"): string | undefined;
1862
+
1863
+ type SchemaProblem = {
1864
+ path: string;
1865
+ message: string;
1866
+ expected?: string;
1867
+ };
1868
+ type SchemaCheckOptions = {
1869
+ /** A value this returns true for is checked elsewhere, unless its schema is `x-static`. */
1870
+ isDynamic?: (value: unknown) => boolean;
1871
+ maxProblems?: number;
1735
1872
  };
1873
+ declare function checkSchema(schema: JSONSchema, value: unknown, path?: string, opts?: SchemaCheckOptions): SchemaProblem[];
1736
1874
 
1737
- type VisualizeToolOptions = {
1738
- cards: CardRegistry;
1739
- /** Restrict which kinds the agent may emit (a read-only chat may want no `confirm`). */
1740
- kinds?: string[];
1875
+ type BindingScope = {
1876
+ data: unknown;
1877
+ /** The current row, inside a `List` template. */
1878
+ item?: unknown;
1879
+ index?: number;
1880
+ };
1881
+ declare const BINDING_KEYS: readonly ["$path", "$item", "$template", "$query"];
1882
+ /** Exactly one `$` key and nothing else: anything looser would swallow ordinary objects. */
1883
+ declare function isSurfaceBinding(value: unknown): value is SurfaceBinding;
1884
+ /** True when any binding of the given form appears anywhere inside `value`. */
1885
+ declare function usesBinding(value: unknown, key: (typeof BINDING_KEYS)[number]): boolean;
1886
+ declare function formatTemplate(template: string, scope: BindingScope): string;
1887
+ /** Run a declarative query. Bad input yields an empty result, never a throw in a render. */
1888
+ declare function runSurfaceQuery(query: SurfaceQuery, scope: BindingScope): unknown;
1889
+ /** Replace every binding inside a spec value with what it currently reads. */
1890
+ declare function resolveSurfaceValue(value: unknown, scope: BindingScope, depth?: number): unknown;
1891
+ declare function evaluateSurfaceCondition(condition: SurfaceCondition | undefined, scope: BindingScope): boolean;
1892
+ /** An action with its bindings read at the moment the person pressed. */
1893
+ declare function resolveSurfaceAction(action: SurfaceAction, scope: BindingScope): SurfaceAction;
1894
+ /** Problems with one binding, as sentences. Empty means it is usable. */
1895
+ declare function bindingProblems(binding: SurfaceBinding): string[];
1896
+
1897
+ type SurfaceComponentCategory = "layout" | "display" | "input" | "action" | "card" | "custom";
1898
+ type SurfaceComponentDefinition = {
1899
+ name: string;
1900
+ category: SurfaceComponentCategory;
1901
+ /** One line for the index. Keep domain nouns out of it: this steers the model. */
1902
+ summary: string;
1903
+ /** Schema for the component's props, excluding `id`, `component` and `visibleWhen`. */
1904
+ props: JSONSchema;
1905
+ /** Ids of the components this one renders. */
1906
+ slots?: (props: Record<string, unknown>) => string[];
1907
+ /** The subset of `slots` rendered once per row, where `$item` is in scope. */
1908
+ templateSlots?: (props: Record<string, unknown>) => string[];
1909
+ };
1910
+ /** The prefix that addresses one card kind in the index, as in `Card:chart`. */
1911
+ declare const CARD_ENTRY_PREFIX = "Card:";
1912
+ declare const CARD_COMPONENT: SurfaceComponentDefinition;
1913
+ type SurfaceCatalogueOptions = {
1914
+ cards?: CardRegistry;
1915
+ /** Host components. Each needs a renderer under the same name in the UI layer. */
1916
+ components?: readonly SurfaceComponentDefinition[];
1917
+ };
1918
+ declare class SurfaceCatalogue {
1919
+ readonly cards: CardRegistry | undefined;
1920
+ private readonly definitions;
1921
+ constructor(options?: SurfaceCatalogueOptions);
1922
+ /** Add a host component. A built-in name cannot be replaced: its meaning is part of the format. */
1923
+ register(def: SurfaceComponentDefinition): this;
1924
+ get(name: string): SurfaceComponentDefinition | undefined;
1925
+ has(name: string): boolean;
1926
+ /** Card kinds usable inside a surface. A surface cannot contain a surface. */
1927
+ cardKinds(): CardKindDefinition[];
1928
+ /** Every addressable entry: components by name, cards as `Card:<kind>`. */
1929
+ names(): string[];
1930
+ /** One line per entry. Cheap enough to hand over whenever the model asks what exists. */
1931
+ index(): string;
1932
+ /** The full schema of one entry, or `undefined` for a name that does not exist. */
1933
+ schemaOf(name: string): {
1934
+ name: string;
1935
+ summary: string;
1936
+ props: JSONSchema;
1937
+ interactive?: boolean;
1938
+ } | undefined;
1939
+ }
1940
+
1941
+ declare const SURFACE_PRIMITIVES: SurfaceComponentDefinition[];
1942
+
1943
+ type SurfaceValidationContext = {
1944
+ catalogue: SurfaceCatalogue;
1945
+ data: Record<string, unknown>;
1946
+ /** Tools an action may call. Omitted means "checked at dispatch only". */
1947
+ actionTools?: readonly string[];
1948
+ /** Leave cards whose spec has bindings to the render that resolves them. */
1949
+ deferBoundCards?: boolean;
1950
+ };
1951
+ declare const isSurfaceId: (value: unknown) => value is string;
1952
+ declare function validateSurfaceAction(action: unknown, componentId: string, ctx: SurfaceValidationContext): SurfaceIssue[];
1953
+ /** Everything wrong with one component, judged alone. */
1954
+ declare function validateSurfaceComponent(raw: unknown, ctx: SurfaceValidationContext): SurfaceIssue[];
1955
+ /** Split a component list into what may render and what must be corrected. */
1956
+ declare function validateSurfaceComponents(raw: readonly unknown[], ctx: SurfaceValidationContext): {
1957
+ components: SurfaceComponent[];
1958
+ issues: SurfaceIssue[];
1741
1959
  };
1742
1960
  /**
1743
- * The generic visualization tool.
1744
- *
1745
- * The description carries the whole catalogue because model card-choice quality
1746
- * tracks how well the options are described far more than it tracks schema
1747
- * strictness — and a `oneOf` union across 13 shapes both bloats the request and
1748
- * degrades tool-call accuracy on most models. We take a loose schema plus a
1749
- * precise description, then validate and hand back a correction the model can
1750
- * act on.
1961
+ * Whole-graph checks: a root that exists, children that exist, no cycles, bounded
1962
+ * depth, and `$item` only where a row is in scope.
1751
1963
  */
1752
- declare function createVisualizeTool(opts: VisualizeToolOptions): ToolDefinition;
1964
+ declare function validateSurfaceGraph(root: string, components: readonly SurfaceComponent[], catalogue: SurfaceCatalogue, rejected?: ReadonlySet<string>): SurfaceIssue[];
1965
+
1966
+ type SurfaceBuildContext = {
1967
+ catalogue: SurfaceCatalogue;
1968
+ actionTools?: readonly string[];
1969
+ };
1970
+ /** `spec` is absent when nothing could be rendered at all. `issues` is what the model must correct. */
1971
+ type SurfaceBuildResult = {
1972
+ spec?: SurfaceSpec;
1973
+ issues: SurfaceIssue[];
1974
+ };
1975
+ /** Validate a complete surface from `createSurface` arguments. */
1976
+ declare function buildSurface(input: unknown, ctx: SurfaceBuildContext, opts?: {
1977
+ revision?: number;
1978
+ originCallId?: string;
1979
+ }): SurfaceBuildResult;
1753
1980
  /**
1754
- * `loadSkill` — the pull half of progressive disclosure.
1981
+ * Apply patches to a surface.
1755
1982
  *
1756
- * Paired with `SkillRegistry.manualIndex()` in the system prompt: the model sees
1757
- * a one-line menu every turn and pays for a skill's body only when it decides it
1758
- * needs one.
1983
+ * Data operations land first, whatever order they were sent in: a component is
1984
+ * validated against the data it binds to, and a model naturally writes the new
1985
+ * chart before the rows it reads. A rejected upsert keeps the previous version
1986
+ * of that component on screen.
1759
1987
  */
1760
- declare function createLoadSkillTool(skills: SkillRegistry): ToolDefinition;
1988
+ declare function applySurfaceOperations(spec: SurfaceSpec, operations: unknown, ctx: SurfaceBuildContext): SurfaceBuildResult;
1761
1989
  /**
1762
- * `updateCard` — let the agent revise a card it already emitted.
1763
- *
1764
- * Without this, a long-running operation can only append new progress cards, and
1765
- * the thread fills with near-identical snapshots.
1990
+ * A surface from arguments still streaming in: every complete, valid component so
1991
+ * far. The last entry is usually half-written, so a failure here is not an error,
1992
+ * only something that has not arrived.
1766
1993
  */
1767
- declare function createUpdateCardTool(cards: CardRegistry): ToolDefinition;
1768
- /** The default built-in set, wired to the given registries. */
1769
- declare function createBuiltinTools(opts: {
1770
- cards: CardRegistry;
1771
- skills?: SkillRegistry;
1772
- }): ToolDefinition[];
1994
+ declare function previewSurface(partial: unknown, catalogue: SurfaceCatalogue): SurfaceSpec | undefined;
1995
+ /**
1996
+ * Re-validate a spec at the renderer. A thread can be edited in storage and a
1997
+ * catalogue can shrink between sessions, so what was valid when written is not
1998
+ * trusted when read. Whether a bound card is valid depends on the data of the
1999
+ * moment, so that one check is left to the render that resolves it.
2000
+ */
2001
+ declare function sanitizeSurfaceSpec(spec: SurfaceSpec, catalogue: SurfaceCatalogue): SurfaceSpec;
2002
+
2003
+ declare const SURFACE_TOOL_NAMES: readonly ["createSurface", "updateSurface", "deleteSurface", "readSurface", "describeSurfaceComponents"];
2004
+ declare const SURFACE_GUIDE: string;
2005
+ type SurfaceToolsOptions = {
2006
+ catalogue: SurfaceCatalogue;
2007
+ };
2008
+ declare function createSurfaceTools(options: SurfaceToolsOptions): ToolDefinition[];
2009
+
2010
+ declare const SURFACE_SKILL_ID = "surface-authoring";
2011
+ /** A `manual` skill: one line in the index until the model loads it. */
2012
+ declare function createSurfaceSkill(catalogue: SurfaceCatalogue): Skill;
2013
+ /**
2014
+ * One line per surface on the active path. Data stays out: the model asks for it
2015
+ * with `readSurface` when it needs it, so an idle dashboard costs a line a turn.
2016
+ */
2017
+ declare function createSurfaceContextSource(): ContextSource;
1773
2018
 
1774
2019
  /**
1775
2020
  * Where the numbers in a metering record came from.
@@ -2032,6 +2277,8 @@ type ExecuteToolOptions = {
2032
2277
  * standalone `executeToolCall` caller can leave it unset and pay the scan.
2033
2278
  */
2034
2279
  toolIndex?: ReadonlyMap<string, ToolDefinition>;
2280
+ surfaces?: SurfaceLedger;
2281
+ surfaceActionTools?: readonly string[];
2035
2282
  };
2036
2283
  declare function executeToolCall(call: ToolCallRequest, opts: ExecuteToolOptions): Promise<ToolCallOutcome>;
2037
2284
  /**
@@ -2046,6 +2293,229 @@ declare function executeToolCall(call: ToolCallRequest, opts: ExecuteToolOptions
2046
2293
  */
2047
2294
  declare function executeToolCalls(calls: readonly ToolCallRequest[], opts: ExecuteToolOptions): Promise<ToolCallOutcome[]>;
2048
2295
 
2296
+ /**
2297
+ * The tool registry. Holds definitions, maps preset → allowlist, and renders the
2298
+ * provider-facing `ToolSpec[]`.
2299
+ *
2300
+ * `resolve()` is the only way to get a tool set, and it always applies deny
2301
+ * last — so a host-level kill switch cannot be re-granted by a preset or by a
2302
+ * skill unlocking a tool.
2303
+ */
2304
+ declare class ToolRegistry {
2305
+ private tools;
2306
+ private presets;
2307
+ private listeners;
2308
+ private version;
2309
+ private reversePresetIndex;
2310
+ constructor(tools?: readonly ToolDefinition[]);
2311
+ register(tool: ToolDefinition, presets?: readonly PresetName[]): this;
2312
+ /** Register several tools into the same preset — the common bulk case. */
2313
+ registerAll(tools: readonly ToolDefinition[], presets?: readonly PresetName[]): this;
2314
+ addToPreset(preset: PresetName, ...names: string[]): this;
2315
+ /**
2316
+ * Change notification, so a UI (or an inspector hook) re-reads after a LATE
2317
+ * registration — tools imported from an MCP server arrive long after mount,
2318
+ * and a registry nobody can observe leaves them invisible until reload.
2319
+ */
2320
+ subscribe(listener: () => void): () => void;
2321
+ /** Monotonic change counter — a stable snapshot value for useSyncExternalStore. */
2322
+ getVersion(): number;
2323
+ private touch;
2324
+ get(name: string): ToolDefinition | undefined;
2325
+ has(name: string): boolean;
2326
+ list(): ToolDefinition[];
2327
+ presetNames(): PresetName[];
2328
+ /** Tool names in a preset that are actually registered. */
2329
+ namesInPreset(preset: PresetName): string[];
2330
+ /** Which presets grant `name`. Used by the UI to explain why a tool is available. */
2331
+ presetsFor(name: string): PresetName[];
2332
+ /** Tool name → presets that grant it, rebuilt on demand after the last mutation. */
2333
+ private reverseIndex;
2334
+ /**
2335
+ * Resolve the tool set for a run.
2336
+ *
2337
+ * Two distinct grants, and keeping them separate is a security property:
2338
+ *
2339
+ * PRESETS grant AUTHORITY. Whether the caller may act at all.
2340
+ * `allow` grants RELEVANCE. Usually a matched skill saying "these are the
2341
+ * tools my instructions describe".
2342
+ *
2343
+ * A skill must therefore never be able to escalate past the capability tier.
2344
+ * So `allow` can surface a tool that belongs to NO preset (private by
2345
+ * default, unlocked by the skill that documents it), but a tool that IS in a
2346
+ * preset still requires that preset to be enabled. Otherwise any skill could
2347
+ * hand out the executor tier just by naming a tool.
2348
+ *
2349
+ * A name listed in a preset but never registered is skipped rather than
2350
+ * throwing — presets are configuration and often outlive the tools they name.
2351
+ */
2352
+ resolve(resolution: ToolResolution): ToolDefinition[];
2353
+ /** Provider-facing specs. The adapter turns these into its own wire shape. */
2354
+ toSpecs(tools: readonly ToolDefinition[]): ToolSpec[];
2355
+ /** Tools whose execution happens on the host, not here. */
2356
+ hostExecuted(tools: readonly ToolDefinition[]): string[];
2357
+ }
2358
+
2359
+ /**
2360
+ * What a surface action may call right now: the presets' grant, with deny applied.
2361
+ * `allow` is left out on purpose. A skill grants relevance for a turn, not authority
2362
+ * that outlives it on a button.
2363
+ */
2364
+ declare function surfaceActionTools(tools: ToolRegistry, resolution: ToolResolution): ToolDefinition[];
2365
+ type SurfaceToolAuthorization = {
2366
+ ok: true;
2367
+ tool: ToolDefinition;
2368
+ } | {
2369
+ ok: false;
2370
+ reason: string;
2371
+ };
2372
+ /** Decided at the moment of the press. What was allowed when the surface was drawn may not be now. */
2373
+ declare function authorizeSurfaceTool(name: string, args: unknown, tools: ToolRegistry, resolution: ToolResolution): SurfaceToolAuthorization;
2374
+ type SurfaceToolRunConfig = {
2375
+ tool: ToolDefinition;
2376
+ args: Record<string, unknown>;
2377
+ surfaceId: string;
2378
+ componentId: string;
2379
+ provider: string;
2380
+ model: string;
2381
+ vars?: Record<string, unknown>;
2382
+ signal?: AbortSignal;
2383
+ toolTimeoutMs?: number;
2384
+ meter?: MeterSink;
2385
+ meteringMetadata?: Readonly<Record<string, string>>;
2386
+ onUserDecision?: (callId: string, card: Card) => Promise<CardAction>;
2387
+ onHostTool?: (call: ToolCallRequest) => Promise<unknown>;
2388
+ };
2389
+ declare function runSurfaceToolAction(config: SurfaceToolRunConfig): AsyncGenerator<RunEvent, void, unknown>;
2390
+
2391
+ declare const A2UI_VERSION: "v0.9.1";
2392
+ declare const SURFACE_A2UI_CATALOG_ID: "urn:supersolutions:super-chat:surface-catalog:v1";
2393
+ type A2uiMessage = {
2394
+ version: typeof A2UI_VERSION;
2395
+ createSurface: {
2396
+ surfaceId: string;
2397
+ catalogId: string;
2398
+ sendDataModel: boolean;
2399
+ };
2400
+ } | {
2401
+ version: typeof A2UI_VERSION;
2402
+ updateComponents: {
2403
+ surfaceId: string;
2404
+ components: Record<string, unknown>[];
2405
+ };
2406
+ } | {
2407
+ version: typeof A2UI_VERSION;
2408
+ updateDataModel: {
2409
+ surfaceId: string;
2410
+ path: string;
2411
+ value: unknown;
2412
+ };
2413
+ } | {
2414
+ version: typeof A2UI_VERSION;
2415
+ deleteSurface: {
2416
+ surfaceId: string;
2417
+ };
2418
+ };
2419
+ /** The messages that would recreate this surface in an A2UI client. */
2420
+ declare function toA2uiMessages(spec: SurfaceSpec): A2uiMessage[];
2421
+
2422
+ type RepairResult = {
2423
+ value: unknown;
2424
+ repaired: boolean;
2425
+ error?: string;
2426
+ };
2427
+ /**
2428
+ * Normalize a tool name. Some OpenAI-compatible routers namespace tool names on
2429
+ * the way out but not on the way in, so the model calls `functions.getPrice`
2430
+ * for a tool we registered as `getPrice`.
2431
+ */
2432
+ declare function normalizeToolName(name: string): string;
2433
+ /**
2434
+ * Parse tool arguments, repairing what can be repaired losslessly.
2435
+ * Returns `{}` rather than throwing when nothing is salvageable — an empty
2436
+ * argument object lets the tool's own validation produce a message the model can
2437
+ * act on, which beats a parse error the model never sees.
2438
+ */
2439
+ declare function repairToolArguments(raw: unknown): RepairResult;
2440
+
2441
+ declare class PartialJsonParser {
2442
+ private stack;
2443
+ private token;
2444
+ private root;
2445
+ private started;
2446
+ private done;
2447
+ private broken;
2448
+ private changes;
2449
+ private cache;
2450
+ /** True once the top-level value has closed. Input after it is ignored. */
2451
+ get complete(): boolean;
2452
+ /** True once the input stopped being JSON. The parser keeps its last good snapshot. */
2453
+ get failed(): boolean;
2454
+ /**
2455
+ * Bumped whenever the snapshot would differ. Compare against the value you
2456
+ * last rendered to skip deltas that changed nothing visible — whitespace, a
2457
+ * key's characters, the digits of an unfinished number.
2458
+ */
2459
+ get version(): number;
2460
+ push(chunk: string): void;
2461
+ /**
2462
+ * The value as far as it has arrived, or `undefined` before the top-level
2463
+ * container opens. Stable by reference until `version` changes.
2464
+ */
2465
+ snapshot(): unknown;
2466
+ private structural;
2467
+ private startValue;
2468
+ private open;
2469
+ private close;
2470
+ /** A value finished: hand it to the container it belongs to, or finish the root. */
2471
+ private assign;
2472
+ /** Consume string characters from `i`; returns where reading stopped. */
2473
+ private readString;
2474
+ }
2475
+ /** One-shot form: the best value `text` supports so far, and whether it is whole. */
2476
+ declare function parsePartialJson(text: string): {
2477
+ value: unknown;
2478
+ complete: boolean;
2479
+ };
2480
+
2481
+ type VisualizeToolOptions = {
2482
+ cards: CardRegistry;
2483
+ /** Restrict which kinds the agent may emit (a read-only chat may want no `confirm`). */
2484
+ kinds?: string[];
2485
+ };
2486
+ /**
2487
+ * The generic visualization tool.
2488
+ *
2489
+ * The description carries the whole catalogue because model card-choice quality
2490
+ * tracks how well the options are described far more than it tracks schema
2491
+ * strictness — and a `oneOf` union across 13 shapes both bloats the request and
2492
+ * degrades tool-call accuracy on most models. We take a loose schema plus a
2493
+ * precise description, then validate and hand back a correction the model can
2494
+ * act on.
2495
+ */
2496
+ declare function createVisualizeTool(opts: VisualizeToolOptions): ToolDefinition;
2497
+ /**
2498
+ * `loadSkill` — the pull half of progressive disclosure.
2499
+ *
2500
+ * Paired with `SkillRegistry.manualIndex()` in the system prompt: the model sees
2501
+ * a one-line menu every turn and pays for a skill's body only when it decides it
2502
+ * needs one.
2503
+ */
2504
+ declare function createLoadSkillTool(skills: SkillRegistry): ToolDefinition;
2505
+ /**
2506
+ * `updateCard` — let the agent revise a card it already emitted.
2507
+ *
2508
+ * Without this, a long-running operation can only append new progress cards, and
2509
+ * the thread fills with near-identical snapshots.
2510
+ */
2511
+ declare function createUpdateCardTool(cards: CardRegistry): ToolDefinition;
2512
+ /** The default built-in set, wired to the given registries. */
2513
+ declare function createBuiltinTools(opts: {
2514
+ cards: CardRegistry;
2515
+ skills?: SkillRegistry;
2516
+ surfaces?: SurfaceCatalogue;
2517
+ }): ToolDefinition[];
2518
+
2049
2519
  type StopContext = {
2050
2520
  step: number;
2051
2521
  finishReason: FinishReason;
@@ -2120,6 +2590,12 @@ type RunConfig = {
2120
2590
  * long tool loops.
2121
2591
  */
2122
2592
  useServerHistory?: boolean;
2593
+ /**
2594
+ * The working copy of this conversation's surfaces. A client passes one so
2595
+ * edits the person makes mid-run are visible to `readSurface`; without it the
2596
+ * run derives its own from `messages`.
2597
+ */
2598
+ surfaces?: SurfaceLedger;
2123
2599
  };
2124
2600
  declare function runAgent(messages: readonly Message[], config: RunConfig): AsyncGenerator<RunEvent, void, unknown>;
2125
2601
 
@@ -2526,4 +3002,4 @@ declare function createMcpSkill(serverName: string, defs: readonly ToolDefinitio
2526
3002
  */
2527
3003
  declare function elicitViaCard(requestCard: (spec: CardSpec) => Promise<unknown>): McpElicitHandler;
2528
3004
 
2529
- export { ANTHROPIC_OFFICIAL_PROFILE, AgentError, type AgentErrorKind, type AppAction, type AppStateBinding, type AppStateSourceOptions, type AppliedEdit, BUILTIN_CARDS, type BudgetShares, type BuiltContext, type BuiltinCard, type BuiltinCardKind, CARD_KEY, CallOptions, type CalloutCard, type Card, type CardAction, type CardCarrier, type CardKindDefinition, CardRegistry, type CardSpec, type CardTone, type CardValidation, type CardValueFormat, type ChartAnnotation, type ChartCard, type ChartSeries, type ChecklistCard, type ChoiceCard, type CitationsCard, type CodeCard, type CompactionResult, type ComparisonCard, type ConfirmCard, ContentPart, ContextBuilder, type ContextBuilderOptions, type ContextLayer, type ContextSource, type ContextSourceInput, type ContextSourceResult, type ContextTrace, DEFAULT_PRESETS, DEFAULT_STOP_CONDITIONS, type DiffCard, type DirectTransportConfig, type DocumentCard, type DocumentEdit, type DocumentOutlineEntry, type DocumentQuoteRef, type DocumentSnapshot, type DocumentStore, type DocumentToolsOptions, type EditHunk, type EditRejection, type EditResult, type EditReviewCard, type EmailCard, type ExecuteToolOptions, type FileStore, FinishReason, type FormCard, type FormField, type FunnelCard, type GaugeCard, type GenerateImageToolOptions, GenerateResult, type GeneratedMedia, type GeneratedMediaKind, type ImageGenerationRequest, JSONSchema, JobHandle, JobStatus, type KeyValueCard, type LayerId, MAILTO_SAFE_LENGTH, MESSAGE_OVERHEAD_TOKENS, type MailtoLink, type MarkdownBlock, type MarkdownBlockKind, type MarkdownCard, type McpCallResult, McpClient, type McpClientConfig, type McpContent, type McpElicitHandler, type McpElicitRequest, type McpElicitResult, type McpImportOptions, McpRpcError, type McpServerInfo, type McpTool, type MediaCard, type MediaJobHandle, type MediaJobSnapshot, type MediaProvider, type MediaProviderCapabilities, MediaSource, type MemoryEntry, type MemorySourceOptions, type MemoryStore, Message, MessageRole, type MeterSink, type MeteringError, type MeteringRecord, type MeteringSource, type MeteringStatus, ModelInfo, NormalizedRequest, OPENAI_OFFICIAL_PROFILE, type OpenAIImageProviderConfig, PartialJsonParser, type PartialToolCall, type PresetName, type ProfileDirectTransportConfig, type ProgressCard, type ProgressStep, Provider, ProviderCapabilities, ProviderFileRef, type ProviderProfile, type ProviderProtocol, type ProxyEnvelope, type ProxyTransportConfig, QUOTES_METADATA_KEY, type QuoteDrift, type RepairResult, type ResolvedSkill, type RestThreadStoreConfig, type RetrievalDoc, type RetrievalSourceOptions, type RetrievedChunk, type Retriever, RetryPolicy, type RunConfig, type RunEvent, type RunMeteringRecord, type RunMode, type RunState, SSEDecoder, type SSEMessage, type SerializedMultipartBody, type Skill, type SkillContext, type SkillMatch, type SkillMatcher, type SkillMode, SkillRegistry, type SkillRegistryOptions, type SkillSection, type SpeechGenerationRequest, type StatItem, type StatsCard, type StepMeteringRecord, type StopCondition, type StopContext, type StoredFile, type StoredThread, type Summarizer, THREAD_SCHEMA_VERSION, type TableCard, type TableColumn, type ThreadMeta, type ThreadStore, type TimelineCard, type TokenBudget, type TokenCounter, type ToolCallOutcome, type ToolCallRequest, ToolCallStatus, type ToolDefinition, type ToolExecutionContext, ToolFailureKind, type ToolLoading, type ToolLoadingHint, ToolRegistry, type ToolResolution, type ToolResult, type ToolResultExtras, type ToolSide, ToolSpec, type TraceEntry, type Transcript, type TranscriptionRequest, Transport, TransportRequest, type TreeCard, type TreeNode, Usage, type VideoGenerationRequest, afterTool, appendReasoning, appendText, applyEdits, assistantMessage, backoffDelay, base64ToBytes, buildEml, buildMailto, buildSummaryPrompt, buildUrl, bytesToBase64, calloutCard, chartCard, check, checkQuoteDrift, checklistCard, childrenOf, choiceCard, citationsCard, codeCard, combineMeteringSources, compactError, compactHistory, comparisonCard, confirmCard, consecutiveFailures, countMessageTokens, countMessagesTokens, createAppActionTools, createAppStateSource, createBudget, createBuiltinTools, createDirectTransport, createDirectTransportForProfile, createDocumentTools, createEmailDraftTool, createGenerateImageTool, createHttpTransport, createKeywordRetriever, createLoadSkillTool, createLocalDocumentStore, createLocalFileStore, createLocalMemoryStore, createLocalThreadStore, createMcpSkill, createMemoryDocumentStore, createMemoryFileStore, createMemoryMemoryStore, createMemorySource, createMemoryThreadStore, createOpenAICompatibleProfile, createOpenAIImageProvider, createProviderFromProfile, createProxyTransport, createRememberTool, createRestThreadStore, createRetrievalSource, createUpdateCardTool, createVisualizeTool, deliverMetering, diffCard, documentCard, editReviewCard, elicitViaCard, emailCard, emlFilename, errorFromResponse, estimateJsonTokens, estimateTokens, executeToolCall, executeToolCalls, file, formCard, formatQuotes, funnelCard, gaugeCard, generatedMediaUrl, hunksOf, image, importMcpTools, initialRunState, isAgentError, isCardCarrier, isTextPart, isToolCallPart, isToolResultPart, keyValueCard, kindFromStatus, lastUserText, latestLeaf, linkLinear, makeCard, mapMcpResult, markdownCard, matchSkills, mediaCard, message, messageText, nextId, noToolCalls, normalizeProviderProfile, normalizeToolName, outlineOf, packByPriority, parsePartialJson, parseRetryAfter, parseSSE, parseSSEJson, pathTo, progressCard, quoteDrift, quotesOf, reduceRunEvent, renderSkill, repairToolArguments, resolvePartialCard, resolveToolLoading, runAgent, safeCutIndex, scoreSkill, searchBlocks, shouldStop, siblingsOf, spanOf, splitBlocks, statsCard, stepCountIs, stripCardPayload, stripUiOnlyParts, tableCard, text, threadSnapshot, timelineCard, toAgentError, tokenBudgetExceeded, tokenize, toolCall, toolCallsIn, toolResult, totalAllocated, treeCard, trimHistory, usageSource, userDeclined, userMessage, withCard, withQuotes, withRetry };
3005
+ export { A2UI_VERSION, type A2uiMessage, ANTHROPIC_OFFICIAL_PROFILE, AgentError, type AgentErrorKind, type AppAction, type AppStateBinding, type AppStateSourceOptions, type AppliedEdit, BUILTIN_CARDS, type BindingScope, type BudgetShares, type BuiltContext, type BuiltinCard, type BuiltinCardKind, CARD_COMPONENT, CARD_ENTRY_PREFIX, CARD_KEY, CallOptions, type CalloutCard, type Card, type CardAction, type CardCarrier, type CardKindDefinition, CardRegistry, type CardSpec, type CardTone, type CardValidation, type CardValueFormat, type ChartAnnotation, type ChartCard, type ChartSeries, type ChecklistCard, type ChoiceCard, type CitationsCard, type CodeCard, type CompactionResult, type ComparisonCard, type ConfirmCard, ContentPart, ContextBuilder, type ContextBuilderOptions, type ContextLayer, type ContextSource, type ContextSourceInput, type ContextSourceResult, type ContextTrace, DEFAULT_PRESETS, DEFAULT_STOP_CONDITIONS, type DiffCard, type DirectTransportConfig, type DocumentCard, type DocumentEdit, type DocumentOutlineEntry, type DocumentQuoteRef, type DocumentSnapshot, type DocumentStore, type DocumentToolsOptions, type EditHunk, type EditRejection, type EditResult, type EditReviewCard, type EmailCard, type ExecuteToolOptions, type FileStore, FinishReason, type FormCard, type FormField, type FunnelCard, type GaugeCard, type GenerateImageToolOptions, GenerateResult, type GeneratedMedia, type GeneratedMediaKind, type ImageGenerationRequest, JSONSchema, JobHandle, JobStatus, type KeyValueCard, type LayerId, MAILTO_SAFE_LENGTH, MESSAGE_OVERHEAD_TOKENS, type MailtoLink, type MarkdownBlock, type MarkdownBlockKind, type MarkdownCard, type McpCallResult, McpClient, type McpClientConfig, type McpContent, type McpElicitHandler, type McpElicitRequest, type McpElicitResult, type McpImportOptions, McpRpcError, type McpServerInfo, type McpTool, type MediaCard, type MediaJobHandle, type MediaJobSnapshot, type MediaProvider, type MediaProviderCapabilities, MediaSource, type MemoryEntry, type MemorySourceOptions, type MemoryStore, Message, MessageRole, type MeterSink, type MeteringError, type MeteringRecord, type MeteringSource, type MeteringStatus, ModelInfo, NormalizedRequest, OPENAI_OFFICIAL_PROFILE, type OpenAIImageProviderConfig, PartialJsonParser, type PartialToolCall, type PresetName, type ProfileDirectTransportConfig, type ProgressCard, type ProgressStep, Provider, ProviderCapabilities, ProviderFileRef, type ProviderProfile, type ProviderProtocol, type ProxyEnvelope, type ProxyTransportConfig, QUOTES_METADATA_KEY, type QuoteDrift, type RepairResult, type ResolvedSkill, type RestThreadStoreConfig, type RetrievalDoc, type RetrievalSourceOptions, type RetrievedChunk, type Retriever, RetryPolicy, type RunConfig, type RunEvent, type RunMeteringRecord, type RunMode, type RunState, SSEDecoder, type SSEMessage, SURFACE_A2UI_CATALOG_ID, SURFACE_ARTIFACT_KIND, SURFACE_CARD_KIND, SURFACE_EVENT_METADATA_KEY, SURFACE_FORMAT_VERSION, SURFACE_GUIDE, SURFACE_LIMITS, SURFACE_PRIMITIVES, SURFACE_SKILL_ID, SURFACE_TOOL_NAMES, type SchemaCheckOptions, type SchemaProblem, type SerializedMultipartBody, type Skill, type SkillContext, type SkillMatch, type SkillMatcher, type SkillMode, SkillRegistry, type SkillRegistryOptions, type SkillSection, type SpeechGenerationRequest, type StatItem, type StatsCard, type StepMeteringRecord, type StopCondition, type StopContext, type StoredFile, type StoredThread, type Summarizer, type SurfaceAction, type SurfaceActivity, type SurfaceActivityState, type SurfaceAggregateOp, type SurfaceBinding, type SurfaceBuildContext, type SurfaceBuildResult, type SurfaceCardAnswer, SurfaceCatalogue, type SurfaceCatalogueOptions, type SurfaceComponent, type SurfaceComponentCategory, type SurfaceComponentDefinition, type SurfaceCondition, type SurfaceConditionOp, type SurfaceEventRecord, type SurfaceIssue, type SurfaceIssueCode, type SurfaceItemBinding, SurfaceLedger, type SurfaceOperation, type SurfacePathBinding, type SurfaceQuery, type SurfaceQueryBinding, type SurfaceSpec, type SurfaceTemplateBinding, type SurfaceToolAuthorization, type SurfaceToolRunConfig, type SurfaceToolsOptions, type SurfaceValidationContext, type SurfaceWhere, type SurfaceWhereOp, THREAD_SCHEMA_VERSION, type TableCard, type TableColumn, type ThreadMeta, type ThreadStore, type TimelineCard, type TokenBudget, type TokenCounter, type ToolCallOutcome, type ToolCallRequest, ToolCallStatus, type ToolDefinition, type ToolExecutionContext, ToolFailureKind, type ToolLoading, type ToolLoadingHint, ToolRegistry, type ToolResolution, type ToolResult, type ToolResultExtras, type ToolSide, ToolSpec, type TraceEntry, type Transcript, type TranscriptionRequest, Transport, TransportRequest, type TreeCard, type TreeNode, type TurnLayoutOptions, type TurnSegment, type UnsafeFinding, Usage, type VideoGenerationRequest, afterTool, appendReasoning, appendText, applyEdits, applySurfaceOperations, assistantMessage, authorizeSurfaceTool, backoffDelay, base64ToBytes, bindingProblems, buildEml, buildMailto, buildSummaryPrompt, buildSurface, buildUrl, bytesToBase64, calloutCard, chartCard, check, checkQuoteDrift, checkSchema, checklistCard, childrenOf, choiceCard, citationsCard, codeCard, combineMeteringSources, compactError, compactHistory, comparisonCard, confirmCard, consecutiveFailures, countMessageTokens, countMessagesTokens, createAppActionTools, createAppStateSource, createBudget, createBuiltinTools, createDirectTransport, createDirectTransportForProfile, createDocumentTools, createEmailDraftTool, createGenerateImageTool, createHttpTransport, createKeywordRetriever, createLoadSkillTool, createLocalDocumentStore, createLocalFileStore, createLocalMemoryStore, createLocalThreadStore, createMcpSkill, createMemoryDocumentStore, createMemoryFileStore, createMemoryMemoryStore, createMemorySource, createMemoryThreadStore, createOpenAICompatibleProfile, createOpenAIImageProvider, createProviderFromProfile, createProxyTransport, createRememberTool, createRestThreadStore, createRetrievalSource, createSurfaceContextSource, createSurfaceSkill, createSurfaceTools, createUpdateCardTool, createVisualizeTool, deliverMetering, diffCard, documentCard, editReviewCard, elicitViaCard, emailCard, emlFilename, errorFromResponse, estimateJsonTokens, estimateTokens, evaluateSurfaceCondition, executeToolCall, executeToolCalls, file, findUnsafe, foldSurfaces, formCard, formatQuotes, formatTemplate, funnelCard, gaugeCard, generatedMediaUrl, getAt, hasTurnOrder, hunksOf, image, importMcpTools, initialRunState, isAgentError, isCardCarrier, isScriptUrl, isSurfaceBinding, isSurfaceId, isSurfaceSpec, isTextPart, isToolCallPart, isToolResultPart, keyValueCard, kindFromStatus, lastUserText, latestLeaf, layoutTurn, linkLinear, makeCard, mapMcpResult, markdownCard, matchSkills, mediaCard, message, messageText, nextId, noToolCalls, normalizeProviderProfile, normalizeToolName, outlineOf, packByPriority, parsePartialJson, parsePointer, parseRetryAfter, parseSSE, parseSSEJson, pathTo, previewSurface, progressCard, quoteDrift, quotesOf, reduceRunEvent, removeAt, renderSkill, repairToolArguments, resolvePartialCard, resolveSurfaceAction, resolveSurfaceValue, resolveToolLoading, runAgent, runSurfaceQuery, runSurfaceToolAction, safeCutIndex, safeSurfaceUrl, sanitizeSurfaceSpec, scoreSkill, searchBlocks, setAt, shouldStop, siblingsOf, spanOf, splitBlocks, statsCard, stepCountIs, stripCardPayload, stripUiOnlyParts, surfaceActionTools, surfaceCardId, tableCard, text, threadSnapshot, timelineCard, toA2uiMessages, toAgentError, tokenBudgetExceeded, tokenize, toolCall, toolCallsIn, toolResult, totalAllocated, treeCard, trimHistory, usageSource, userDeclined, userMessage, usesBinding, validateSurfaceAction, validateSurfaceComponent, validateSurfaceComponents, validateSurfaceGraph, withCard, withQuotes, withRetry };