@supersolutions/super-chat-core 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2529 @@
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';
5
+
6
+ /**
7
+ * Monotonic id. Deliberately not `crypto.randomUUID()` — ids show up in test
8
+ * snapshots and in `previous_response_id` correlation logs, and a stable,
9
+ * readable prefix is worth more here than global uniqueness. Callers that need
10
+ * cross-device uniqueness pass their own id.
11
+ */
12
+ declare function nextId(prefix?: string): string;
13
+ declare const text: (value: string) => ContentPart;
14
+ declare const image: (source: MediaSource, opts?: {
15
+ mediaType?: string;
16
+ detail?: "auto" | "low" | "high";
17
+ }) => ContentPart;
18
+ declare const file: (source: MediaSource, mediaType: string, filename?: string) => ContentPart;
19
+ declare const toolCall: (callId: string, name: string, input: unknown, opts?: {
20
+ status?: ToolCallStatus;
21
+ repaired?: boolean;
22
+ }) => ContentPart;
23
+ declare const toolResult: (callId: string, name: string, output: unknown, opts?: {
24
+ failure?: ToolFailureKind;
25
+ render?: string;
26
+ }) => ContentPart;
27
+ declare function message(role: MessageRole, parts: ContentPart[] | string, id?: string): Message;
28
+ declare const userMessage: (parts: ContentPart[] | string, id?: string) => Message;
29
+ declare const assistantMessage: (parts: ContentPart[] | string, id?: string) => Message;
30
+ declare const isTextPart: (p: ContentPart) => p is Extract<ContentPart, {
31
+ type: "text";
32
+ }>;
33
+ declare const isToolCallPart: (p: ContentPart) => p is Extract<ContentPart, {
34
+ type: "tool-call";
35
+ }>;
36
+ declare const isToolResultPart: (p: ContentPart) => p is Extract<ContentPart, {
37
+ type: "tool-result";
38
+ }>;
39
+ /** Concatenated text of a message — the "what did it actually say" reader. */
40
+ declare function messageText(m: Message): string;
41
+ /** Last user-authored text in a thread. Drives skill matching and intent checks. */
42
+ declare function lastUserText(messages: readonly Message[]): string;
43
+ declare function toolCallsIn(messages: readonly Message[]): Extract<ContentPart, {
44
+ type: "tool-call";
45
+ }>[];
46
+ /**
47
+ * Merge streamed text deltas into the trailing text part instead of appending a
48
+ * new part per token — otherwise a 2k-token reply becomes 2k parts and every
49
+ * React render walks all of them.
50
+ */
51
+ declare function appendText(parts: ContentPart[], delta: string): ContentPart[];
52
+ /** Same merge, for reasoning streams (which arrive interleaved with text). */
53
+ declare function appendReasoning(parts: ContentPart[], delta: string, signature?: string): ContentPart[];
54
+ /**
55
+ * Strip parts that exist only for the UI. Artifacts are host-rendered and have
56
+ * no provider representation; sending them would either 400 or waste tokens on
57
+ * a JSON blob the model can't act on.
58
+ */
59
+ declare function stripUiOnlyParts(m: Message): Message;
60
+
61
+ /** Root-first path from the root to `headId`. Unknown/missing head → []. */
62
+ declare function pathTo(tree: readonly Message[], headId: string | null | undefined): Message[];
63
+ /** Direct children of `parentId` (null = roots), in tree insertion order. */
64
+ declare function childrenOf(tree: readonly Message[], parentId: string | null): Message[];
65
+ /** The message plus its siblings (shared parent), in insertion order. */
66
+ declare function siblingsOf(tree: readonly Message[], id: string): Message[];
67
+ /**
68
+ * Deepest descendant of `fromId`, following the LATEST child at each level —
69
+ * switching to a branch resumes at where that branch last left off.
70
+ */
71
+ declare function latestLeaf(tree: readonly Message[], fromId: string): string;
72
+ /**
73
+ * Give a linear (pre-branching) message list its parent pointers. Used to
74
+ * migrate v1 stored threads and to accept plain arrays as `initialMessages`.
75
+ * Messages that already carry a parentId are left untouched.
76
+ */
77
+ declare function linkLinear(messages: readonly Message[]): Message[];
78
+
79
+ type MarkdownBlockKind =
80
+ /** A fenced code block, ``` or ~~~. Verbatim: no inline transforms. */
81
+ "fence"
82
+ /** An indented (four-space or tab) code block. Also verbatim. */
83
+ | "code"
84
+ /** Everything else: a paragraph, heading, list, quote or table. */
85
+ | "text";
86
+ /** A top-level block, addressed by its half-open span in the SOURCE string. */
87
+ type MarkdownBlock = {
88
+ start: number;
89
+ end: number;
90
+ kind: MarkdownBlockKind;
91
+ };
92
+ /**
93
+ * Top-level blocks in source order, with their spans.
94
+ *
95
+ * Blank lines that separate blocks belong to none of them, so a span always
96
+ * slices back to exactly the block's own text. Blank lines *inside* a block —
97
+ * within a fence, between the items of a loose list — are part of it.
98
+ */
99
+ declare function splitBlocks(src: string): MarkdownBlock[];
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;
128
+ };
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[]>;
157
+ };
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;
167
+ };
168
+ /**
169
+ * One proposed change: find this exact text, put that in its place.
170
+ *
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.
175
+ *
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.
179
+ */
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 = {
216
+ docId: string;
217
+ title: string;
218
+ /** Revision the span was taken from — compared at send time; see `drift`. */
219
+ 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
+ };
232
+ /**
233
+ * What a quote's document did between the quoted revision and the send.
234
+ *
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.
240
+ */
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";
251
+ };
252
+ /**
253
+ * Compare a quote against the document as it is now. `undefined` when the
254
+ * quote is current.
255
+ *
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.
258
+ */
259
+ declare function quoteDrift(quote: DocumentQuoteRef, current: Pick<DocumentSnapshot, "revision" | "markdown"> | undefined): QuoteDrift | undefined;
260
+ /**
261
+ * Stamp each quote with its drift against the store, ready to send.
262
+ *
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.
267
+ */
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";
271
+ /**
272
+ * Render quotes as the prefix of the user's message.
273
+ *
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.
278
+ */
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[];
284
+
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
+ };
309
+ }
310
+ declare function isAgentError(e: unknown): e is AgentError;
311
+ /**
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.
314
+ */
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;
321
+
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>);
327
+ /**
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.
331
+ */
332
+ authStyle?: "bearer" | "x-api-key";
333
+ /** Sent on every request; merged under per-request headers. */
334
+ headers?: Record<string, string>;
335
+ /**
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.
338
+ */
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;
352
+ };
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;
361
+ /**
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.
366
+ */
367
+ headers?: Record<string, string>;
368
+ };
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
+ }[];
384
+ };
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
+ /**
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".
406
+ */
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
+ };
543
+ };
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>;
554
+ };
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;
564
+ };
565
+ declare function createOpenAIImageProvider(config: OpenAIImageProviderConfig): MediaProvider;
566
+
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;
691
+ };
692
+ /**
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.
701
+ *
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.
704
+ */
705
+ type DocumentCard = {
706
+ kind: "document";
707
+ docId: string;
708
+ title: string;
709
+ markdown: string;
710
+ revision: number;
711
+ };
712
+ /**
713
+ * A matrix of options against criteria.
714
+ *
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.
718
+ */
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
+ }[];
737
+ };
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;
748
+ }[];
749
+ };
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;
756
+ };
757
+ /**
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.
762
+ */
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
+ }[];
777
+ };
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;
788
+ };
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;
804
+ };
805
+ type TreeNode = {
806
+ label: string;
807
+ detail?: string;
808
+ tone?: CardTone;
809
+ children?: TreeNode[];
810
+ };
811
+ /** Nested structure. Document outlines, org charts, taxonomies, decision trees. */
812
+ type TreeCard = {
813
+ kind: "tree";
814
+ title?: string;
815
+ nodes: TreeNode[];
816
+ };
817
+ type CodeCard = {
818
+ kind: "code";
819
+ title?: string;
820
+ language?: string;
821
+ code: string;
822
+ filename?: string;
823
+ };
824
+ type DiffCard = {
825
+ kind: "diff";
826
+ title?: string;
827
+ before: string;
828
+ after: string;
829
+ language?: string;
830
+ };
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
+ }[];
850
+ };
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;
883
+ };
884
+ type FormCard = {
885
+ kind: "form";
886
+ title?: string;
887
+ description?: string;
888
+ fields: FormField[];
889
+ submitLabel?: string;
890
+ };
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;
906
+ };
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[];
932
+ }[];
933
+ };
934
+ /**
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.
944
+ */
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. */
963
+ 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
+ };
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;
983
+ at: number;
984
+ };
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;
1003
+
1004
+ type ToolSide = "read" | "write" | "confirm";
1005
+ /**
1006
+ * A truthful preview of the output geometry while a tool is still running.
1007
+ *
1008
+ * This is host-only metadata: providers never see it. A function is useful for
1009
+ * tools such as image generation where count and aspect ratio come from the
1010
+ * call input rather than from the tool definition alone.
1011
+ */
1012
+ type ToolLoadingHint = {
1013
+ kind: "media" | "chart" | "table" | "document" | "generic";
1014
+ label: string;
1015
+ count?: number;
1016
+ /** CSS-compatible ratio, for example `1024 / 1536`. */
1017
+ aspectRatio?: string;
1018
+ };
1019
+ type ToolLoading = ToolLoadingHint | ((input: unknown) => ToolLoadingHint | undefined);
1020
+ type ToolExecutionContext = {
1021
+ /** Host-supplied per-run values: user id, session, network, locale. */
1022
+ vars: Record<string, unknown>;
1023
+ signal?: AbortSignal;
1024
+ /** The tool call's id, for correlating a card back to it. */
1025
+ callId: string;
1026
+ /** Emit a card mid-execution (progress updates on a long tool). */
1027
+ emitCard?: (spec: CardSpec) => void;
1028
+ /** Ask the user something and await the answer. Powers `side: "confirm"`. */
1029
+ requestCard?: (spec: CardSpec) => Promise<unknown>;
1030
+ };
1031
+ type ToolResultExtras = {
1032
+ /**
1033
+ * Update an EXISTING card instead of minting a new one: the runtime reuses
1034
+ * this id, and the reducer's upsert replaces the old card in place.
1035
+ */
1036
+ cardId?: string;
1037
+ /**
1038
+ * Tool names this result unlocks for the REST of the run (`loadSkill`'s pull
1039
+ * half). The runtime re-resolves the active set and re-declares specs to the
1040
+ * provider from the next step on.
1041
+ */
1042
+ unlockTools?: string[];
1043
+ };
1044
+ type ToolResult = ToolResultExtras & {
1045
+ /** What the model sees. Keep it small — this is re-sent every subsequent step. */
1046
+ output: unknown;
1047
+ /** What the user sees. Not sent to the model. */
1048
+ card?: CardSpec;
1049
+ failure?: "execution-error" | "denied" | "invalid-input" | "timeout" | "not-found";
1050
+ };
1051
+ type ToolDefinition = {
1052
+ name: string;
1053
+ description: string;
1054
+ inputSchema: JSONSchema;
1055
+ /**
1056
+ * Absent `execute` means the HOST runs this tool (browser-side: read the DOM,
1057
+ * open a wallet, use a local file). The runtime emits a `tool-call` event and
1058
+ * suspends until the host supplies a result.
1059
+ */
1060
+ execute?: (input: unknown, ctx: ToolExecutionContext) => Promise<ToolResult | unknown> | ToolResult | unknown;
1061
+ /**
1062
+ * `confirm` suspends the run and shows an approval card before executing.
1063
+ * The distinction from `write` is intent: `write` acts, `confirm` asks first.
1064
+ */
1065
+ side?: ToolSide;
1066
+ /** Ask the provider to enforce the schema (OpenAI strict mode). */
1067
+ strict?: boolean;
1068
+ /** Default card renderer key when the result carries no explicit card. */
1069
+ render?: string;
1070
+ /** Rough token cost of a typical result, for budgeting. */
1071
+ costHint?: number;
1072
+ /** Live-only output placeholder. Omit when the result's shape is unknown. */
1073
+ loading?: ToolLoading;
1074
+ /**
1075
+ * For a tool whose ARGUMENTS are a card (`visualize` is the built-in one):
1076
+ * a preview of that card from arguments that are still streaming. Called
1077
+ * with each tolerant parse of the partial JSON; return `undefined` until
1078
+ * there is something worth drawing. Route it through
1079
+ * `CardRegistry.partial` so interactive kinds and specs that fail
1080
+ * validation never preview. Live-only — the validated card from `execute`
1081
+ * replaces it, and it is never written to history.
1082
+ *
1083
+ * A tool whose card is computed BY `execute` has nothing to preview here:
1084
+ * the arguments are a query, not the answer.
1085
+ */
1086
+ partialCard?: (partialInput: unknown) => CardSpec | undefined;
1087
+ };
1088
+ /** Resolve a tool's streaming card preview; a throwing hook means "no preview", never a failed call. */
1089
+ declare function resolvePartialCard(tool: ToolDefinition | undefined, partialInput: unknown): CardSpec | undefined;
1090
+ /** Resolve a static or input-derived loading hint without leaking a function into run events. */
1091
+ declare function resolveToolLoading(loading: ToolLoading | undefined, input: unknown): ToolLoadingHint | undefined;
1092
+ type PresetName = string;
1093
+ type ToolResolution = {
1094
+ /** Preset names enabled for this run. */
1095
+ presets: readonly PresetName[];
1096
+ /** Extra tools unlocked beyond the presets (skills unlock their own tools). */
1097
+ allow?: readonly string[];
1098
+ /** Removed even if a preset grants them. Applied last. */
1099
+ deny?: readonly string[];
1100
+ };
1101
+ declare const DEFAULT_PRESETS: readonly ["observer", "draft", "executor"];
1102
+
1103
+ type GenerateImageToolOptions = {
1104
+ name?: string;
1105
+ /** Used when the model does not explicitly select one. */
1106
+ defaultModel?: string;
1107
+ };
1108
+ /**
1109
+ * Expose a MediaProvider to an agent without teaching the chat Provider any
1110
+ * image-generation wire format. The compact output goes back to the model;
1111
+ * the binary/URL payload stays in a media card for the user.
1112
+ */
1113
+ declare function createGenerateImageTool(provider: MediaProvider, options?: GenerateImageToolOptions): ToolDefinition;
1114
+
1115
+ type TokenCounter = (text: string) => number;
1116
+ /**
1117
+ * Estimate tokens for a string. Splits CJK from Latin because a single ratio is
1118
+ * wrong by 3x on Chinese/Japanese text — which matters here, since this
1119
+ * framework is being built by someone who writes prompts in both.
1120
+ */
1121
+ declare function estimateTokens(text: string): number;
1122
+ /** JSON payloads (tool args/results) tokenize worse than prose — count the serialized form. */
1123
+ declare function estimateJsonTokens(value: unknown): number;
1124
+ /** Fixed per-message overhead the provider adds for role markers and separators. */
1125
+ declare const MESSAGE_OVERHEAD_TOKENS = 4;
1126
+
1127
+ type BudgetShares = {
1128
+ /** Reserved for the model's reply. Never lent out. */
1129
+ output: number;
1130
+ system: number;
1131
+ skills: number;
1132
+ memory: number;
1133
+ history: number;
1134
+ tools: number;
1135
+ };
1136
+ type TokenBudget = {
1137
+ contextWindow: number;
1138
+ shares: BudgetShares;
1139
+ /** Safety margin, since estimation is approximate. */
1140
+ reservePct: number;
1141
+ };
1142
+ declare function createBudget(contextWindow: number, opts?: Partial<BudgetShares> & {
1143
+ reservePct?: number;
1144
+ maxOutputTokens?: number;
1145
+ }): TokenBudget;
1146
+ declare const totalAllocated: (b: TokenBudget) => number;
1147
+ /**
1148
+ * Fill a budget with prioritized items, greedily, highest first.
1149
+ *
1150
+ * Greedy rather than optimal (knapsack) because the ordering is meaningful:
1151
+ * skill priority encodes the author's intent about what must survive, and an
1152
+ * optimal packer would happily drop a critical high-priority skill to fit two
1153
+ * cheap ones.
1154
+ */
1155
+ declare function packByPriority<T>(items: readonly T[], limit: number, sizeOf: (item: T) => number): {
1156
+ included: T[];
1157
+ dropped: {
1158
+ item: T;
1159
+ size: number;
1160
+ }[];
1161
+ used: number;
1162
+ };
1163
+ declare function countMessageTokens(m: Message, counter?: TokenCounter): number;
1164
+ declare const countMessagesTokens: (messages: readonly Message[], counter?: TokenCounter) => number;
1165
+
1166
+ type SkillMode = "always" | "matched" | "manual";
1167
+ /** A sub-topic within a skill, matched and loaded independently. */
1168
+ type SkillSection = {
1169
+ id: string;
1170
+ name: string;
1171
+ aliases?: string[];
1172
+ body: string;
1173
+ };
1174
+ type SkillContext = {
1175
+ /** The text being matched against — usually the latest user message. */
1176
+ query: string;
1177
+ /** Host-supplied values (user id, network, locale) for dynamic bodies. */
1178
+ vars?: Record<string, unknown>;
1179
+ };
1180
+ type Skill = {
1181
+ id: string;
1182
+ name: string;
1183
+ /** One line. This is what the model sees in the skill index for manual skills. */
1184
+ description: string;
1185
+ mode: SkillMode;
1186
+ /** Trigger words. Matched case-insensitively against the query, both directions. */
1187
+ aliases?: string[];
1188
+ tags?: string[];
1189
+ /** Higher wins when the token budget forces a choice. Default 0. */
1190
+ priority?: number;
1191
+ /** Body, or a function for context-dependent bodies (e.g. injecting the user's balances). */
1192
+ body: string | ((ctx: SkillContext) => string | Promise<string>);
1193
+ sections?: SkillSection[];
1194
+ /** Tool names this skill unlocks when loaded. */
1195
+ tools?: string[];
1196
+ /** Pointers the model can be told about without paying for their content. */
1197
+ resources?: {
1198
+ name: string;
1199
+ description?: string;
1200
+ uri: string;
1201
+ }[];
1202
+ };
1203
+ type SkillMatch = {
1204
+ skill: Skill;
1205
+ score: number;
1206
+ /** Which sections matched, when the query was section-specific. */
1207
+ sections: SkillSection[];
1208
+ reason: string;
1209
+ };
1210
+ /** A skill rendered to text, ready to be placed in a context layer. */
1211
+ type ResolvedSkill = {
1212
+ id: string;
1213
+ name: string;
1214
+ text: string;
1215
+ tokens: number;
1216
+ score: number;
1217
+ mode: SkillMode;
1218
+ tools: string[];
1219
+ };
1220
+
1221
+ type SkillMatcher = (skills: readonly Skill[], query: string) => SkillMatch[];
1222
+ type SkillRegistryOptions = {
1223
+ /** Swap in embeddings/BM25 without touching the rest of the pipeline. */
1224
+ matcher?: SkillMatcher;
1225
+ /** Max `matched`-mode skills injected per turn. Guards against a query that hits everything. */
1226
+ maxMatched?: number;
1227
+ threshold?: number;
1228
+ };
1229
+ /** Render a skill (or just its matched sections) to the text that goes in context. */
1230
+ declare function renderSkill(skill: Skill, ctx: SkillContext, sections?: SkillSection[]): Promise<string>;
1231
+ declare class SkillRegistry {
1232
+ private skills;
1233
+ private readonly matcher;
1234
+ private readonly maxMatched;
1235
+ private readonly threshold;
1236
+ /** Cached `manualIndex()` render; invalidated by `register`/`unregister`. */
1237
+ private manualIndexCache;
1238
+ constructor(skills?: readonly Skill[], options?: SkillRegistryOptions);
1239
+ register(skill: Skill): this;
1240
+ unregister(id: string): this;
1241
+ get(id: string): Skill | undefined;
1242
+ list(): Skill[];
1243
+ match(query: string): SkillMatch[];
1244
+ /**
1245
+ * The skills that should be *pushed* into this turn's context: every `always`
1246
+ * skill, plus the top-scoring `matched` ones.
1247
+ *
1248
+ * `manual` skills are excluded by design — they are pulled by the model via
1249
+ * `loadSkill`, and pushing them would defeat the point of having the mode.
1250
+ */
1251
+ resolveForTurn(ctx: SkillContext, opts?: {
1252
+ forceIds?: string[];
1253
+ }): Promise<ResolvedSkill[]>;
1254
+ /**
1255
+ * One-line index of the skills the model may load on demand. Cheap enough to
1256
+ * include every turn — this is the "menu" half of progressive disclosure.
1257
+ */
1258
+ manualIndex(): string;
1259
+ /** Everything a `loadSkill` call should return for `id`. */
1260
+ load(id: string, ctx: SkillContext): Promise<{
1261
+ found: boolean;
1262
+ text: string;
1263
+ tools: string[];
1264
+ }>;
1265
+ }
1266
+
1267
+ declare function tokenize(input: string): string[];
1268
+ declare function scoreSkill(skill: Skill, query: string): {
1269
+ score: number;
1270
+ reason: string;
1271
+ sections: SkillSection[];
1272
+ };
1273
+ /** Rank skills by relevance. `threshold` filters noise; sorting is stable by id for determinism. */
1274
+ declare function matchSkills(skills: readonly Skill[], query: string, threshold?: number): SkillMatch[];
1275
+
1276
+ /** Named context layers, in the order they are assembled into the system block. */
1277
+ type LayerId = "identity" | "skills" | "skill-index" | "memory" | "environment" | "custom";
1278
+ type ContextLayer = {
1279
+ id: string;
1280
+ kind: LayerId;
1281
+ text: string;
1282
+ tokens: number;
1283
+ /** Survives budget pressure. Identity and safety rules should be pinned. */
1284
+ pinned?: boolean;
1285
+ priority: number;
1286
+ };
1287
+ type ContextSourceResult = {
1288
+ layers?: ContextLayer[];
1289
+ /** Extra tool names this source unlocks (a matched skill enabling its tools). */
1290
+ tools?: string[];
1291
+ };
1292
+ type ContextSourceInput = {
1293
+ messages: readonly Message[];
1294
+ /** Latest user text — what skills and memory retrieval match against. */
1295
+ query: string;
1296
+ vars: Record<string, unknown>;
1297
+ signal?: AbortSignal;
1298
+ };
1299
+ /**
1300
+ * A named contributor to the context. Sources run in parallel, so one slow
1301
+ * retrieval does not serialize behind another.
1302
+ */
1303
+ type ContextSource = {
1304
+ id: string;
1305
+ run(input: ContextSourceInput): Promise<ContextSourceResult> | ContextSourceResult;
1306
+ };
1307
+ type TraceEntry = {
1308
+ id: string;
1309
+ kind: LayerId | "history" | "source";
1310
+ status: "included" | "truncated" | "dropped" | "compacted" | "failed";
1311
+ tokens: number;
1312
+ /** Tokens before truncation/compaction, when those happened. */
1313
+ originalTokens?: number;
1314
+ detail?: string;
1315
+ ms?: number;
1316
+ };
1317
+ type ContextTrace = {
1318
+ entries: TraceEntry[];
1319
+ budget: TokenBudget;
1320
+ totals: {
1321
+ system: number;
1322
+ history: number;
1323
+ tools: number;
1324
+ total: number;
1325
+ };
1326
+ /** Estimated headroom left for the reply. Negative means we over-packed. */
1327
+ headroom: number;
1328
+ warnings: string[];
1329
+ };
1330
+ type BuiltContext = {
1331
+ system: string;
1332
+ messages: Message[];
1333
+ /** Tool names allowed this turn, after skill unlocks. */
1334
+ toolNames: string[];
1335
+ trace: ContextTrace;
1336
+ skills: ResolvedSkill[];
1337
+ };
1338
+
1339
+ type CompactionResult = {
1340
+ messages: Message[];
1341
+ strategy: "none" | "trim" | "summarize";
1342
+ droppedCount: number;
1343
+ tokensBefore: number;
1344
+ tokensAfter: number;
1345
+ summary?: string;
1346
+ };
1347
+ /**
1348
+ * Move a cut point later until it lands on a message that can legally start a
1349
+ * history: a user or assistant turn that is not a dangling tool reply, and not
1350
+ * an assistant turn whose tool calls were left behind.
1351
+ */
1352
+ declare function safeCutIndex(messages: readonly Message[], desired: number): number;
1353
+ declare function trimHistory(messages: readonly Message[], limitTokens: number, counter?: TokenCounter,
1354
+ /** Pass this when the caller already scanned `messages` (e.g. `compactHistory`'s `tokensBefore`) to skip a second full-history scan. */
1355
+ knownTokensBefore?: number): CompactionResult;
1356
+ type Summarizer = (messages: readonly Message[], signal?: AbortSignal) => Promise<string>;
1357
+ type CompactOptions = {
1358
+ limitTokens: number;
1359
+ /** Turns always kept verbatim at the tail. */
1360
+ keepRecent?: number;
1361
+ summarizer?: Summarizer;
1362
+ counter?: TokenCounter;
1363
+ signal?: AbortSignal;
1364
+ };
1365
+ /**
1366
+ * Compact history to fit `limitTokens`.
1367
+ *
1368
+ * Falls back to `trim` whenever summarization is unavailable or fails —
1369
+ * a summarizer that errors must never take the user's turn down with it.
1370
+ */
1371
+ declare function compactHistory(messages: readonly Message[], opts: CompactOptions): Promise<CompactionResult>;
1372
+ /**
1373
+ * Default summarization prompt builder. Exposed so a host can reuse the exact
1374
+ * framing with its own model call.
1375
+ */
1376
+ declare function buildSummaryPrompt(messages: readonly Message[]): string;
1377
+
1378
+ type ContextBuilderOptions = {
1379
+ /** Base instructions. Always pinned — identity is not negotiable under pressure. */
1380
+ identity?: string;
1381
+ skills?: SkillRegistry;
1382
+ sources?: ContextSource[];
1383
+ budget?: TokenBudget;
1384
+ contextWindow?: number;
1385
+ maxOutputTokens?: number;
1386
+ counter?: TokenCounter;
1387
+ summarizer?: Summarizer;
1388
+ /** Verbatim turns kept at the tail when summarizing. */
1389
+ keepRecent?: number;
1390
+ /**
1391
+ * Appended to instructions when any card-capable tool is present. Tells the
1392
+ * model where cards appear so its prose reads correctly around them — without
1393
+ * this, models narrate "as you can see in the table below" above a card that
1394
+ * renders above the text.
1395
+ */
1396
+ cardPlacementNote?: string;
1397
+ };
1398
+ declare class ContextBuilder {
1399
+ private readonly opts;
1400
+ constructor(opts?: ContextBuilderOptions);
1401
+ /** The skill registry this builder draws from, for UI that lists or pins skills. */
1402
+ get skillRegistry(): SkillRegistry | undefined;
1403
+ /** The identity block, for a settings pane that lets the user read or edit it. */
1404
+ get identity(): string | undefined;
1405
+ build(input: {
1406
+ messages: readonly Message[];
1407
+ vars?: Record<string, unknown>;
1408
+ /** Skills to force in regardless of matching (a user pinning one in the UI). */
1409
+ forceSkillIds?: string[];
1410
+ /** Tool names available before skill unlocks. */
1411
+ baseTools?: string[];
1412
+ signal?: AbortSignal;
1413
+ }): Promise<BuiltContext>;
1414
+ }
1415
+
1416
+ /**
1417
+ * A map of the document, cheap enough to send every turn.
1418
+ *
1419
+ * Editing is a directed activity — "the third section", "the bit about
1420
+ * renewal" — not a similarity search, so the model needs to navigate rather
1421
+ * than retrieve. An outline costs a line per block and lets it ask for exactly
1422
+ * the span it wants; without one it either guesses or is handed the whole
1423
+ * document, and the whole document is what this design exists to avoid.
1424
+ */
1425
+ declare function outlineOf(markdown: string): DocumentOutlineEntry[];
1426
+ /** Source text of a block range, inclusive. Out-of-range yields "". */
1427
+ declare function spanOf(markdown: string, from: number, to?: number): string;
1428
+ /** Blocks whose text contains `query`, case-insensitively. */
1429
+ declare function searchBlocks(markdown: string, query: string): DocumentOutlineEntry[];
1430
+ /**
1431
+ * Apply edits to a document, or refuse.
1432
+ *
1433
+ * Refusing is half the job and the more important half. A find that matches
1434
+ * nothing means the model is quoting text that is not there; a find that
1435
+ * matches twice means it has not said which one. Guessing either — taking the
1436
+ * first match, say — produces a change in the wrong place that the diff will
1437
+ * present as if it were intended, and the user approves it. So both are
1438
+ * rejections with a reason the model can act on, exactly as tools/repair.ts
1439
+ * treats malformed arguments: an invalid input to retry, not a result.
1440
+ *
1441
+ * Edits are resolved against the ORIGINAL text and spliced into it in one pass,
1442
+ * so earlier edits cannot shift the offsets of later ones. Two edits that
1443
+ * overlap are a contradiction rather than a merge, and are refused.
1444
+ */
1445
+ declare function applyEdits(markdown: string, edits: readonly DocumentEdit[]): EditResult;
1446
+ /** Line-level view of one edit, for the approval card. */
1447
+ type EditHunk = {
1448
+ index: number;
1449
+ block: number;
1450
+ removed: string[];
1451
+ added: string[];
1452
+ };
1453
+ /**
1454
+ * One hunk per edit, rather than a computed diff.
1455
+ *
1456
+ * The point of hunks here is that the user can accept some and reject others,
1457
+ * and an edit is already the smallest independently-applicable unit — it
1458
+ * carries its own anchor. Deriving hunks from a text diff instead would produce
1459
+ * regions that are not separately applicable, which is the wrong shape for the
1460
+ * question being asked.
1461
+ */
1462
+ declare function hunksOf(applied: readonly AppliedEdit[]): EditHunk[];
1463
+
1464
+ declare function createMemoryDocumentStore(): DocumentStore;
1465
+ declare function createLocalDocumentStore(key?: string): DocumentStore;
1466
+
1467
+ type DocumentToolsOptions = {
1468
+ store: DocumentStore;
1469
+ /** Cap on what a single read returns, so one call cannot flood context. */
1470
+ maxSpanChars?: number;
1471
+ /**
1472
+ * Cap on how many documents `listDocuments` names at once.
1473
+ *
1474
+ * The list is the cheapest thing here per entry and the easiest to let grow
1475
+ * without noticing: a host that has accumulated four hundred documents would
1476
+ * otherwise spend a page of context on the index before the model has read a
1477
+ * word of any of them.
1478
+ */
1479
+ maxListed?: number;
1480
+ };
1481
+ /**
1482
+ * Build the document tools against a host store.
1483
+ *
1484
+ * `editDocument` is `side: "confirm"` and does its own asking: it computes the
1485
+ * change, shows it as an edit review, and writes only what came back accepted.
1486
+ * There is no path that writes without that answer.
1487
+ *
1488
+ * `listDocuments` is what makes the rest of them reachable. A docId arrives in
1489
+ * a tool result and then lives only in the transcript — which compaction trims,
1490
+ * and which a new thread never had. Without an index, "a document outlives its
1491
+ * thread" is true of the store and false of the agent: the document survives
1492
+ * and nothing can name it. It returns titles and sizes, never bodies, so
1493
+ * carrying it costs a line per document.
1494
+ */
1495
+ declare function createDocumentTools(opts: DocumentToolsOptions): ToolDefinition[];
1496
+ /**
1497
+ * Draft an email for the user to send.
1498
+ *
1499
+ * `draft` tier, and the tier is the whole point: this produces something the
1500
+ * user approves and sends themselves. There is no send path and no credential,
1501
+ * which is what makes it safe to hand out.
1502
+ */
1503
+ declare function createEmailDraftTool(): ToolDefinition;
1504
+
1505
+ /** Roughly where mail clients start truncating a mailto: URL. */
1506
+ declare const MAILTO_SAFE_LENGTH = 2000;
1507
+ type MailtoLink = {
1508
+ href: string;
1509
+ /** True when the href is long enough that a client may cut it short. */
1510
+ mayTruncate: boolean;
1511
+ length: number;
1512
+ };
1513
+ declare function buildMailto(email: EmailCard): MailtoLink;
1514
+ /**
1515
+ * An RFC 5322 message.
1516
+ *
1517
+ * Deliberately without a Date or Message-ID: this is a DRAFT, and stamping it
1518
+ * with a send time it did not have would be a small lie that some clients then
1519
+ * display as fact. The user's own client fills both in when they send.
1520
+ */
1521
+ declare function buildEml(email: EmailCard): string;
1522
+ /** A filename that will not upset a filesystem. */
1523
+ declare function emlFilename(email: EmailCard): string;
1524
+
1525
+ type CardValidation = {
1526
+ ok: true;
1527
+ } | {
1528
+ ok: false;
1529
+ error: string;
1530
+ expected?: string;
1531
+ };
1532
+ type CardKindDefinition = {
1533
+ kind: string;
1534
+ /** One line for the `visualize` tool description — this is what steers model choice. */
1535
+ summary: string;
1536
+ schema: JSONSchema;
1537
+ validate: (spec: unknown) => CardValidation;
1538
+ /** Interactive cards must render at top level and never collapse. */
1539
+ interactive?: boolean;
1540
+ /** Approximate token cost of the spec, for context budgeting of replayed cards. */
1541
+ estimateTokens?: (spec: CardSpec) => number;
1542
+ /**
1543
+ * Derive a renderable spec from one that is still streaming in — keep what
1544
+ * has fully arrived, drop the entry still being written when the renderer
1545
+ * cannot show it yet. Return `undefined` until there is something worth
1546
+ * drawing. The result must pass `validate`: `CardRegistry.partial` checks
1547
+ * it, so a preview is a VALID card that is merely incomplete, never a
1548
+ * malformed one.
1549
+ *
1550
+ * Omit for kinds that should keep a skeleton until they are whole. Ignored
1551
+ * on interactive kinds: a control the user can act on must never be shown
1552
+ * before the spec behind it is complete and validated.
1553
+ */
1554
+ partial?: (spec: Record<string, unknown>) => CardSpec | undefined;
1555
+ };
1556
+ /** Small validator helpers — enough to give the model an actionable correction. */
1557
+ declare const check: {
1558
+ object(spec: unknown, kind: string): CardValidation | Record<string, unknown>;
1559
+ arrayField(spec: Record<string, unknown>, field: string, kind: string, minLength?: number): CardValidation | unknown[];
1560
+ };
1561
+ declare class CardRegistry {
1562
+ private kinds;
1563
+ constructor(definitions?: readonly CardKindDefinition[]);
1564
+ register(def: CardKindDefinition): this;
1565
+ has(kind: string): boolean;
1566
+ get(kind: string): CardKindDefinition | undefined;
1567
+ list(): CardKindDefinition[];
1568
+ isInteractive(kind: string): boolean;
1569
+ /**
1570
+ * Validate a spec. An unknown kind is a hard failure with the list of valid
1571
+ * kinds attached — a model that receives "unknown kind: barchart, valid kinds
1572
+ * are: chart, table, …" fixes itself on the next step, whereas one that
1573
+ * receives a silently-dropped card repeats the mistake forever.
1574
+ */
1575
+ validate(spec: unknown): CardValidation;
1576
+ /**
1577
+ * A preview of a spec that is still streaming, or `undefined` when there
1578
+ * should not be one: an unknown kind, an interactive kind, a kind with no
1579
+ * `partial`, or a derived spec its own validator rejects. The one place that
1580
+ * decides whether a partial spec may reach a renderer.
1581
+ */
1582
+ partial(spec: unknown): CardSpec | undefined;
1583
+ /** The catalogue text embedded in the `visualize` tool description. */
1584
+ describe(): string;
1585
+ /** Per-kind schemas, for hosts that prefer one tool per card kind. */
1586
+ schemas(): Record<string, JSONSchema>;
1587
+ }
1588
+ declare function makeCard(spec: CardSpec, callId?: string, id?: string): Card;
1589
+
1590
+ declare const tableCard: CardKindDefinition;
1591
+ declare const statsCard: CardKindDefinition;
1592
+ declare const chartCard: CardKindDefinition;
1593
+ declare const timelineCard: CardKindDefinition;
1594
+ declare const keyValueCard: CardKindDefinition;
1595
+ declare const progressCard: CardKindDefinition;
1596
+ declare const mediaCard: CardKindDefinition;
1597
+ declare const markdownCard: CardKindDefinition;
1598
+ declare const documentCard: CardKindDefinition;
1599
+ declare const editReviewCard: CardKindDefinition;
1600
+ declare const emailCard: CardKindDefinition;
1601
+ declare const codeCard: CardKindDefinition;
1602
+ 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;
1735
+ };
1736
+
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[];
1741
+ };
1742
+ /**
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.
1751
+ */
1752
+ declare function createVisualizeTool(opts: VisualizeToolOptions): ToolDefinition;
1753
+ /**
1754
+ * `loadSkill` — the pull half of progressive disclosure.
1755
+ *
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.
1759
+ */
1760
+ declare function createLoadSkillTool(skills: SkillRegistry): ToolDefinition;
1761
+ /**
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.
1766
+ */
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[];
1773
+
1774
+ /**
1775
+ * Where the numbers in a metering record came from.
1776
+ *
1777
+ * Core currently only emits `provider` or `unavailable`. `estimated` and
1778
+ * `mixed` are reserved so hosts can enrich records without replacing this
1779
+ * contract when a provider omits usage.
1780
+ */
1781
+ type MeteringSource = "provider" | "estimated" | "mixed" | "unavailable";
1782
+ /** Terminal outcome of a provider step or the containing run. */
1783
+ type MeteringStatus = "completed" | "failed" | "cancelled";
1784
+ type MeteringError = {
1785
+ kind: AgentErrorKind;
1786
+ message: string;
1787
+ };
1788
+ type MeteringBase = {
1789
+ /** Stable within a run; suitable as an idempotency key in a host ledger. */
1790
+ id: string;
1791
+ runId: string;
1792
+ provider: string;
1793
+ requestedModel: string;
1794
+ mode: RunMode;
1795
+ status: MeteringStatus;
1796
+ usage: Usage;
1797
+ source: MeteringSource;
1798
+ startedAt: number;
1799
+ finishedAt: number;
1800
+ durationMs: number;
1801
+ /** Host-owned dimensions. Core never interprets or sends these upstream. */
1802
+ metadata?: Readonly<Record<string, string>>;
1803
+ error?: MeteringError;
1804
+ };
1805
+ /** Exactly one terminal record is emitted for every attempted provider call. */
1806
+ type StepMeteringRecord = MeteringBase & {
1807
+ scope: "step";
1808
+ step: number;
1809
+ /** The provider's actual model, when it reports one. */
1810
+ reportedModel?: string;
1811
+ responseId?: string;
1812
+ finishReason?: FinishReason;
1813
+ };
1814
+ /** Exactly one summary record is emitted when a run terminates. */
1815
+ type RunMeteringRecord = MeteringBase & {
1816
+ scope: "run";
1817
+ steps: number;
1818
+ finishReason: FinishReason;
1819
+ /** Unique actual model ids observed across completed steps. */
1820
+ reportedModels?: string[];
1821
+ };
1822
+ type MeteringRecord = StepMeteringRecord | RunMeteringRecord;
1823
+ /**
1824
+ * Optional delivery target in addition to the public `metering` RunEvent.
1825
+ *
1826
+ * Delivery is awaited to preserve ordering. A sink failure is fail-open: it
1827
+ * is reported to `onError`, when supplied, but never changes the agent run.
1828
+ * Durable storage, retries and pricing remain host responsibilities.
1829
+ */
1830
+ type MeterSink = {
1831
+ record(record: MeteringRecord): void | Promise<void>;
1832
+ onError?(error: unknown, record: MeteringRecord): void | Promise<void>;
1833
+ };
1834
+ declare function usageSource(usage: Usage): MeteringSource;
1835
+ declare function combineMeteringSources(sources: readonly MeteringSource[]): MeteringSource;
1836
+ declare function deliverMetering(sink: MeterSink | undefined, record: MeteringRecord): Promise<void>;
1837
+
1838
+ type RunEvent = {
1839
+ type: "run-start";
1840
+ runId: string;
1841
+ mode: RunMode;
1842
+ }
1843
+ /** Emitted before the first provider call — the whole "why did it send that" answer. */
1844
+ | {
1845
+ type: "context-built";
1846
+ trace: ContextTrace;
1847
+ system: string;
1848
+ toolNames: string[];
1849
+ } | {
1850
+ type: "step-start";
1851
+ step: number;
1852
+ } | {
1853
+ type: "text-delta";
1854
+ delta: string;
1855
+ } | {
1856
+ type: "reasoning-delta";
1857
+ delta: string;
1858
+ }
1859
+ /**
1860
+ * Live-only: a tool call's arguments as far as they have streamed. Stream
1861
+ * mode only; never sent for a kind that is interactive. `partialCard` is a
1862
+ * VALID but incomplete card, present only when the tool previews one.
1863
+ */
1864
+ | {
1865
+ type: "tool-call-input-delta";
1866
+ callId: string;
1867
+ name: string;
1868
+ partialInput: unknown;
1869
+ partialCard?: CardSpec;
1870
+ loading?: ToolLoadingHint;
1871
+ } | {
1872
+ type: "tool-call";
1873
+ callId: string;
1874
+ name: string;
1875
+ input: unknown;
1876
+ repaired?: boolean;
1877
+ loading?: ToolLoadingHint;
1878
+ }
1879
+ /** A `confirm`-side tool, or an interactive card, is waiting on the user. */
1880
+ | {
1881
+ type: "awaiting-user";
1882
+ callId: string;
1883
+ card: Card;
1884
+ } | {
1885
+ type: "user-responded";
1886
+ callId: string;
1887
+ action: CardAction;
1888
+ } | {
1889
+ type: "tool-result";
1890
+ callId: string;
1891
+ name: string;
1892
+ output: unknown;
1893
+ failure?: string;
1894
+ ms: number;
1895
+ }
1896
+ /** A card was produced — by a tool result, or mid-execution by a long tool. */
1897
+ | {
1898
+ type: "card";
1899
+ card: Card;
1900
+ } | {
1901
+ type: "card-updated";
1902
+ cardId: string;
1903
+ spec: CardSpec;
1904
+ } | {
1905
+ type: "step-finish";
1906
+ step: number;
1907
+ finishReason: FinishReason;
1908
+ usage?: Usage;
1909
+ }
1910
+ /** Background mode: the provider accepted the job and we are now polling. */
1911
+ | {
1912
+ type: "job-started";
1913
+ handle: JobHandle;
1914
+ } | {
1915
+ type: "job-status";
1916
+ handle: JobHandle;
1917
+ status: JobStatus;
1918
+ } | {
1919
+ type: "message";
1920
+ parts: ContentPart[];
1921
+ }
1922
+ /** Canonical, idempotent per-step and per-run usage observation. */
1923
+ | {
1924
+ type: "metering";
1925
+ record: MeteringRecord;
1926
+ } | {
1927
+ type: "usage";
1928
+ usage: Usage;
1929
+ } | {
1930
+ type: "run-finish";
1931
+ runId: string;
1932
+ finishReason: FinishReason;
1933
+ usage: Usage;
1934
+ steps: number;
1935
+ } | {
1936
+ type: "error";
1937
+ error: unknown;
1938
+ recoverable: boolean;
1939
+ };
1940
+ type RunMode = "stream" | "sync" | "background";
1941
+ /** Accumulated state a host can rebuild from the event stream. */
1942
+ type RunState = {
1943
+ runId: string;
1944
+ mode: RunMode;
1945
+ status: "idle" | "running" | "awaiting-user" | "done" | "error";
1946
+ parts: ContentPart[];
1947
+ cards: Card[];
1948
+ usage: Usage;
1949
+ steps: number;
1950
+ /** Live tool output slots, removed as their correlated result arrives. */
1951
+ pendingTools: Record<string, {
1952
+ callId: string;
1953
+ name: string;
1954
+ loading?: ToolLoadingHint;
1955
+ }>;
1956
+ /**
1957
+ * Calls whose arguments are streaming or have streamed, keyed by callId:
1958
+ * the latest `tool-call-input-delta` for each. Kept past `tool-call` so a
1959
+ * card preview holds its place until the validated card replaces it, and
1960
+ * removed with the call's `tool-result`. Live-only — never committed.
1961
+ */
1962
+ partialTools?: Record<string, PartialToolCall>;
1963
+ trace?: ContextTrace;
1964
+ /**
1965
+ * Tool names actually exposed to the model this run — the base presets PLUS
1966
+ * anything a matched skill unlocked. Distinct from what the registry would
1967
+ * return for the presets alone, which is why it is recorded rather than
1968
+ * recomputed by the UI.
1969
+ */
1970
+ toolNames?: string[];
1971
+ job?: {
1972
+ handle: JobHandle;
1973
+ status: JobStatus;
1974
+ };
1975
+ pendingCard?: Card;
1976
+ error?: unknown;
1977
+ finishReason?: FinishReason;
1978
+ };
1979
+ type PartialToolCall = {
1980
+ callId: string;
1981
+ name: string;
1982
+ partialInput: unknown;
1983
+ partialCard?: CardSpec;
1984
+ loading?: ToolLoadingHint;
1985
+ };
1986
+ declare function initialRunState(runId: string, mode: RunMode): RunState;
1987
+ /**
1988
+ * The canonical reducer. React, a CLI renderer and a server-side recorder all
1989
+ * use this one function, so they can never disagree about what a run looked like.
1990
+ */
1991
+ declare function reduceRunEvent(state: RunState, event: RunEvent): RunState;
1992
+
1993
+ type ToolCallRequest = {
1994
+ callId: string;
1995
+ name: string;
1996
+ input: unknown;
1997
+ };
1998
+ type ToolCallOutcome = {
1999
+ callId: string;
2000
+ name: string;
2001
+ output: unknown;
2002
+ card?: Card;
2003
+ failure?: string;
2004
+ /** Tool names this outcome unlocked for the rest of the run (loadSkill). */
2005
+ unlockTools?: string[];
2006
+ ms: number;
2007
+ };
2008
+ /** Shrink an error to something worth carrying in history. */
2009
+ declare function compactError(e: unknown): {
2010
+ error: string;
2011
+ kind?: string;
2012
+ };
2013
+ type ExecuteToolOptions = {
2014
+ tools: readonly ToolDefinition[];
2015
+ vars: Record<string, unknown>;
2016
+ signal?: AbortSignal;
2017
+ timeoutMs?: number;
2018
+ onCard?: (card: Card) => void;
2019
+ /** Suspend and ask the user. Supplied by the runtime; resolves on a CardAction. */
2020
+ requestCard?: (callId: string, spec: CardSpec) => Promise<unknown>;
2021
+ /** Host-executed tools (no `execute`) are delegated here. */
2022
+ onHostTool?: (call: ToolCallRequest) => Promise<unknown>;
2023
+ /**
2024
+ * `executeToolCalls` only: fires as each call settles, in COMPLETION order,
2025
+ * exactly once per call — failures and timeouts included. This is how a
2026
+ * fast result reaches the UI without waiting on the slowest call in the step.
2027
+ */
2028
+ onOutcome?: (outcome: ToolCallOutcome) => void;
2029
+ /**
2030
+ * Precomputed name→tool index. `executeToolCalls` builds this once per
2031
+ * batch and reuses it here instead of a linear `tools.find` per call; a
2032
+ * standalone `executeToolCall` caller can leave it unset and pay the scan.
2033
+ */
2034
+ toolIndex?: ReadonlyMap<string, ToolDefinition>;
2035
+ };
2036
+ declare function executeToolCall(call: ToolCallRequest, opts: ExecuteToolOptions): Promise<ToolCallOutcome>;
2037
+ /**
2038
+ * Execute a step's calls concurrently.
2039
+ *
2040
+ * Parallel because models emit independent calls in one step and running them
2041
+ * serially triples the latency of a three-lookup turn. Two orders, on purpose:
2042
+ * `onOutcome` reports each call as it FINISHES, so a 50ms lookup is not held
2043
+ * hostage by a 900ms one; the returned array is in CALL order, since that is
2044
+ * what gets written back to history and humans read the transcript top to
2045
+ * bottom.
2046
+ */
2047
+ declare function executeToolCalls(calls: readonly ToolCallRequest[], opts: ExecuteToolOptions): Promise<ToolCallOutcome[]>;
2048
+
2049
+ type StopContext = {
2050
+ step: number;
2051
+ finishReason: FinishReason;
2052
+ outcomes: readonly ToolCallOutcome[];
2053
+ usage: Usage;
2054
+ };
2055
+ type StopCondition = (ctx: StopContext) => boolean;
2056
+ declare const stepCountIs: (n: number) => StopCondition;
2057
+ /** Stop as soon as a specific tool has run — the "one action then report" shape. */
2058
+ declare const afterTool: (...names: string[]) => StopCondition;
2059
+ /** Stop when the model produced prose with no tool calls. The natural end. */
2060
+ declare const noToolCalls: StopCondition;
2061
+ declare const tokenBudgetExceeded: (maxTotal: number) => StopCondition;
2062
+ /**
2063
+ * Stop after `n` consecutive failing steps.
2064
+ *
2065
+ * The failure mode this catches: a tool that errors identically every time
2066
+ * (bad credential, missing config). The model will happily retry it until the
2067
+ * step cap, producing nothing but latency and spend.
2068
+ */
2069
+ declare const consecutiveFailures: (n: number) => StopCondition;
2070
+ /** Stop when the user declined an interactive card — proceeding would ignore them. */
2071
+ declare const userDeclined: StopCondition;
2072
+ declare function shouldStop(conditions: readonly StopCondition[] | undefined, ctx: StopContext): boolean;
2073
+ /** A sane default set for an interactive chat agent. */
2074
+ declare const DEFAULT_STOP_CONDITIONS: StopCondition[];
2075
+
2076
+ type RunConfig = {
2077
+ provider: Provider;
2078
+ model: string;
2079
+ contextBuilder: ContextBuilder;
2080
+ tools: ToolRegistry;
2081
+ toolResolution: ToolResolution;
2082
+ mode?: RunMode;
2083
+ maxSteps?: number;
2084
+ stopWhen?: StopCondition[];
2085
+ vars?: Record<string, unknown>;
2086
+ temperature?: number;
2087
+ maxOutputTokens?: number;
2088
+ reasoning?: NormalizedRequest["reasoning"];
2089
+ toolChoice?: NormalizedRequest["toolChoice"];
2090
+ /** Provider-hosted tools (web search, code interpreter), keyed by provider id. */
2091
+ providerTools?: NormalizedRequest["providerTools"];
2092
+ responseFormat?: NormalizedRequest["responseFormat"];
2093
+ topP?: number;
2094
+ stopSequences?: string[];
2095
+ /** Provider-side conversation storage opt-out (OpenAI `store`). */
2096
+ store?: boolean;
2097
+ metadata?: Record<string, string>;
2098
+ /** Usage delivery target. Pricing and persistence belong to the host. */
2099
+ meter?: MeterSink;
2100
+ /** Host-only dimensions copied onto metering records, never sent upstream. */
2101
+ meteringMetadata?: Readonly<Record<string, string>>;
2102
+ /** The per-provider escape hatch, keyed by provider id. */
2103
+ providerOptions?: NormalizedRequest["providerOptions"];
2104
+ toolTimeoutMs?: number;
2105
+ signal?: AbortSignal;
2106
+ /**
2107
+ * Resolve an interactive card. The host shows it and returns the user's
2108
+ * answer. Absent means interactive cards auto-decline rather than hang.
2109
+ */
2110
+ onUserDecision?: (callId: string, card: Card) => Promise<CardAction>;
2111
+ /** Execute a tool that has no `execute` (browser-side capabilities). */
2112
+ onHostTool?: (call: ToolCallRequest) => Promise<unknown>;
2113
+ /** Persist a background job handle so a reload can resume it. */
2114
+ onJobHandle?: (handle: NonNullable<GenerateResult["responseId"]> extends string ? unknown : never) => void;
2115
+ /** Skills the user pinned in the UI. */
2116
+ forceSkillIds?: string[];
2117
+ /**
2118
+ * Chain via the provider's stored response instead of resending history.
2119
+ * Only used when the provider supports it; cuts input tokens dramatically on
2120
+ * long tool loops.
2121
+ */
2122
+ useServerHistory?: boolean;
2123
+ };
2124
+ declare function runAgent(messages: readonly Message[], config: RunConfig): AsyncGenerator<RunEvent, void, unknown>;
2125
+
2126
+ type StoredFile = {
2127
+ ref: ProviderFileRef;
2128
+ filename: string;
2129
+ mediaType?: string;
2130
+ sizeBytes?: number;
2131
+ /** Thread the file was first attached in, if any. */
2132
+ threadId?: string;
2133
+ createdAt: number;
2134
+ };
2135
+ type FileStore = {
2136
+ list(): Promise<StoredFile[]>;
2137
+ /** Keyed by `ref.id`. */
2138
+ get(id: string): Promise<StoredFile | undefined>;
2139
+ put(file: StoredFile): Promise<void>;
2140
+ remove(id: string): Promise<void>;
2141
+ };
2142
+ declare function createMemoryFileStore(): FileStore;
2143
+ /** localStorage-backed store. Every read is defensive — see JobStore. */
2144
+ declare function createLocalFileStore(key?: string): FileStore;
2145
+
2146
+ type ThreadMeta = {
2147
+ id: string;
2148
+ /** Derived at save time from the first user message; never model-generated. */
2149
+ title?: string;
2150
+ createdAt: number;
2151
+ updatedAt: number;
2152
+ messageCount: number;
2153
+ };
2154
+ declare const THREAD_SCHEMA_VERSION: 2;
2155
+ type StoredThread = {
2156
+ version: typeof THREAD_SCHEMA_VERSION;
2157
+ meta: ThreadMeta;
2158
+ /** The full message TREE (flat, parentId pointers) — abandoned branches included. */
2159
+ messages: Message[];
2160
+ /** Leaf of the active branch. Absent → the last message (v1-era linearity). */
2161
+ headId?: string | null;
2162
+ };
2163
+ type ThreadStore = {
2164
+ /** Metadata only — a thread picker must not load every message ever sent. */
2165
+ list(): Promise<ThreadMeta[]>;
2166
+ load(id: string): Promise<StoredThread | undefined>;
2167
+ save(thread: StoredThread): Promise<void>;
2168
+ remove(id: string): Promise<void>;
2169
+ };
2170
+ /** Build a JSON-safe snapshot: safe-clone, derive title, stamp meta. */
2171
+ declare function threadSnapshot(id: string, messages: readonly Message[], prior?: ThreadMeta, headId?: string | null): StoredThread;
2172
+ declare function createMemoryThreadStore(): ThreadStore;
2173
+ /**
2174
+ * localStorage-backed store, key per thread: `{prefix}:index` holds the meta
2175
+ * list, `{prefix}:{id}` holds one thread. One growing thread must not rewrite
2176
+ * every other thread on each save (the job store's single-blob layout is fine
2177
+ * for handles; it is wrong for conversations).
2178
+ *
2179
+ * Every read is defensive — a corrupted entry reads as absent, never a throw.
2180
+ * A version other than the current one also reads as absent: v2 migrates
2181
+ * deliberately, it does not crash v1 readers.
2182
+ */
2183
+ declare function createLocalThreadStore(prefix?: string): ThreadStore;
2184
+ type RestThreadStoreConfig = {
2185
+ /** Base path of your thread API, e.g. "/api/threads". */
2186
+ url: string;
2187
+ /** Extra headers (auth, CSRF). A function is called per request. */
2188
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
2189
+ credentials?: RequestCredentials;
2190
+ fetchImpl?: typeof fetch;
2191
+ /**
2192
+ * Called when a request fails. Default: swallow. Persistence is
2193
+ * fire-and-forget at the call site, so a thrown error would surface as an
2194
+ * unhandled rejection rather than anything a user can act on — but a host
2195
+ * that wants telemetry needs the hook.
2196
+ */
2197
+ onError?: (error: unknown, op: "list" | "load" | "save" | "remove") => void;
2198
+ };
2199
+ /**
2200
+ * REST-backed store — the "bring your own backend" implementation.
2201
+ *
2202
+ * The wire contract, four calls:
2203
+ * GET {url} → ThreadMeta[]
2204
+ * GET {url}/{id} → StoredThread (404 = absent, not an error)
2205
+ * PUT {url}/{id} ← StoredThread
2206
+ * DELETE {url}/{id}
2207
+ *
2208
+ * Reads stay defensive in the same way the localStorage store is: a failed or
2209
+ * malformed response degrades to "not found" / "empty list" rather than
2210
+ * throwing into a render or a run. Records still go through `migrate`, so a
2211
+ * server that stored v1 payloads keeps working.
2212
+ */
2213
+ declare function createRestThreadStore(config: RestThreadStoreConfig): ThreadStore;
2214
+
2215
+ type MemoryEntry = {
2216
+ /** Stable slug ("preferred-language"), so a fact updates instead of duplicating. */
2217
+ key: string;
2218
+ value: string;
2219
+ updatedAt: number;
2220
+ };
2221
+ type MemoryStore = {
2222
+ /** `vars` carries host scoping (user id, workspace) — the store decides what it means. */
2223
+ list(vars?: Record<string, unknown>): Promise<MemoryEntry[]>;
2224
+ set(key: string, value: string, vars?: Record<string, unknown>): Promise<void>;
2225
+ remove(key: string, vars?: Record<string, unknown>): Promise<void>;
2226
+ };
2227
+ declare function createMemoryMemoryStore(opts?: {
2228
+ maxEntries?: number;
2229
+ }): MemoryStore;
2230
+ /** localStorage-backed store — same defensiveness as the job/file stores. */
2231
+ declare function createLocalMemoryStore(storageKey?: string, opts?: {
2232
+ maxEntries?: number;
2233
+ }): MemoryStore;
2234
+ type MemorySourceOptions = {
2235
+ id?: string;
2236
+ /** Budget-pressure priority; identity is 1000, skills ~800. */
2237
+ priority?: number;
2238
+ /** Cap on injected entries — memory must not crowd out the conversation. */
2239
+ maxEntries?: number;
2240
+ };
2241
+ /** The read half: remembered facts as a context layer, every turn. */
2242
+ declare function createMemorySource(store: MemoryStore, opts?: MemorySourceOptions): ContextSource;
2243
+ /** The write half: the model saves/updates/forgets a fact, visibly. */
2244
+ declare function createRememberTool(store: MemoryStore): ToolDefinition;
2245
+
2246
+ type RetrievedChunk = {
2247
+ id: string;
2248
+ text: string;
2249
+ /** Where this came from — shown to the user in citations. */
2250
+ source?: string;
2251
+ title?: string;
2252
+ uri?: string;
2253
+ /** Higher is better; used only for ordering, scale is the retriever's. */
2254
+ score?: number;
2255
+ };
2256
+ type Retriever = {
2257
+ retrieve(query: string, opts?: {
2258
+ limit?: number;
2259
+ signal?: AbortSignal;
2260
+ vars?: Record<string, unknown>;
2261
+ }): Promise<RetrievedChunk[]>;
2262
+ };
2263
+ type RetrievalSourceOptions = {
2264
+ id?: string;
2265
+ /** Max chunks injected per turn. */
2266
+ limit?: number;
2267
+ /** Budget-pressure priority; memory is 500. */
2268
+ priority?: number;
2269
+ /** Skip retrieval entirely for queries shorter than this (greetings). */
2270
+ minQueryLength?: number;
2271
+ };
2272
+ /** Plug a retriever into context assembly as a cited-evidence layer. */
2273
+ declare function createRetrievalSource(retriever: Retriever, opts?: RetrievalSourceOptions): ContextSource;
2274
+ type RetrievalDoc = {
2275
+ id: string;
2276
+ text: string;
2277
+ title?: string;
2278
+ source?: string;
2279
+ uri?: string;
2280
+ };
2281
+ /**
2282
+ * Zero-dependency lexical retriever: paragraphs scored by token overlap with
2283
+ * the query (CJK-safe via the skills tokenizer). The reference implementation
2284
+ * a host swaps for a real index — and enough for a playground to demonstrate
2285
+ * the whole retrieve → inject → cite loop honestly.
2286
+ */
2287
+ declare function createKeywordRetriever(docs: readonly RetrievalDoc[]): Retriever;
2288
+
2289
+ type AppStateBinding<T = unknown> = {
2290
+ /** Stable id — also the context layer id and the trace entry name. */
2291
+ id: string;
2292
+ /**
2293
+ * What this state IS, in the model's vocabulary. This is the description the
2294
+ * model reasons about, so write it for the model: "the checkout form the
2295
+ * user is filling in", not "checkoutFormState".
2296
+ */
2297
+ description: string;
2298
+ /** Read the CURRENT value. Called fresh every turn — never cached. */
2299
+ read(): T | Promise<T>;
2300
+ /**
2301
+ * Serialize for the prompt. Default is pretty JSON; override to summarize a
2302
+ * large store down to what the model actually needs.
2303
+ */
2304
+ serialize?(value: T): string;
2305
+ /** Skip injection entirely (a closed dialog's state is noise). */
2306
+ when?(value: T): boolean;
2307
+ };
2308
+ type AppAction<I = Record<string, unknown>> = {
2309
+ /** Tool name the model calls — verb-shaped: `applyFilter`, `openDocument`. */
2310
+ name: string;
2311
+ description: string;
2312
+ inputSchema: JSONSchema;
2313
+ /**
2314
+ * Perform it against the host app. The return value is what the model reads
2315
+ * back, so return the RESULT ("filter applied, 12 rows match"), not `void` —
2316
+ * an action whose outcome the model can't observe is an action it will
2317
+ * repeat.
2318
+ */
2319
+ run(input: I): unknown | Promise<unknown>;
2320
+ /**
2321
+ * `confirm` suspends the run behind an interactive card before executing —
2322
+ * the right default for anything the user would want to see first.
2323
+ */
2324
+ side?: ToolSide;
2325
+ };
2326
+ type AppStateSourceOptions = {
2327
+ id?: string;
2328
+ /** Budget-pressure priority. Memory is 500, retrieval 400. */
2329
+ priority?: number;
2330
+ };
2331
+ /**
2332
+ * The read half: host application state as a context layer, refreshed every
2333
+ * turn. Bindings that throw are skipped rather than failing the turn — a
2334
+ * component unmounting mid-run must cost context, not the conversation.
2335
+ */
2336
+ declare function createAppStateSource(bindings: readonly AppStateBinding<any>[], opts?: AppStateSourceOptions): ContextSource;
2337
+ /**
2338
+ * The write half: host actions as ordinary tools.
2339
+ *
2340
+ * Returned, not registered — the host calls `registry.registerAll(...)` with
2341
+ * the preset it decides these deserve. That is the same rule MCP imports
2342
+ * follow, and for the same reason: a tool that can mutate the user's document
2343
+ * must get its authority explicitly, never by virtue of being wired up.
2344
+ */
2345
+ declare function createAppActionTools(actions: readonly AppAction<any>[]): ToolDefinition[];
2346
+
2347
+ type McpServerInfo = {
2348
+ name: string;
2349
+ version?: string;
2350
+ };
2351
+ type McpTool = {
2352
+ name: string;
2353
+ description?: string;
2354
+ inputSchema: JSONSchema;
2355
+ };
2356
+ type McpContent = {
2357
+ type: "text";
2358
+ text: string;
2359
+ } | {
2360
+ type: "image";
2361
+ data: string;
2362
+ mimeType: string;
2363
+ } | {
2364
+ type: "resource";
2365
+ resource: {
2366
+ uri: string;
2367
+ text?: string;
2368
+ mimeType?: string;
2369
+ };
2370
+ };
2371
+ type McpCallResult = {
2372
+ content: McpContent[];
2373
+ /** Structured output, when the tool declares an output schema. */
2374
+ structuredContent?: unknown;
2375
+ /** Tool-level failure — the tool ran and reports an error the MODEL should see. */
2376
+ isError?: boolean;
2377
+ };
2378
+ /** `elicitation/create` — the server asks the USER for structured input mid-call. */
2379
+ type McpElicitRequest = {
2380
+ message: string;
2381
+ requestedSchema?: {
2382
+ type?: "object";
2383
+ properties?: Record<string, {
2384
+ type?: string;
2385
+ title?: string;
2386
+ description?: string;
2387
+ enum?: unknown[];
2388
+ default?: unknown;
2389
+ }>;
2390
+ required?: string[];
2391
+ };
2392
+ };
2393
+ type McpElicitResult = {
2394
+ action: "accept";
2395
+ content: Record<string, unknown>;
2396
+ } | {
2397
+ action: "decline";
2398
+ } | {
2399
+ action: "cancel";
2400
+ };
2401
+ type McpElicitHandler = (params: McpElicitRequest) => Promise<McpElicitResult>;
2402
+
2403
+ type McpClientConfig = {
2404
+ transport: Transport;
2405
+ /** Routing id in the proxy's provider map. Default "mcp". */
2406
+ provider?: string;
2407
+ /** Server-relative path of the MCP endpoint. Default "/". */
2408
+ path?: string;
2409
+ protocolVersion?: string;
2410
+ clientInfo?: {
2411
+ name: string;
2412
+ version: string;
2413
+ };
2414
+ /**
2415
+ * Answer `elicitation/create` — the server asking the USER for structured
2416
+ * input mid-call. Without a handler, elicitations are declined (never hung).
2417
+ * `importMcpTools` bridges this onto the interactive-card suspension, so an
2418
+ * eliciting server gets the same form-card UX as a local `confirm` tool.
2419
+ */
2420
+ onElicit?: McpElicitHandler;
2421
+ };
2422
+ /** Thrown for protocol-level JSON-RPC errors (unknown method, bad params). */
2423
+ declare class McpRpcError extends Error {
2424
+ readonly code: number;
2425
+ readonly data?: unknown;
2426
+ constructor(code: number, message: string, data?: unknown);
2427
+ }
2428
+ declare class McpClient {
2429
+ private readonly transport;
2430
+ private readonly provider;
2431
+ private readonly path;
2432
+ private readonly protocolVersion;
2433
+ private readonly clientInfo;
2434
+ private readonly onElicit;
2435
+ private rpcId;
2436
+ private sessionId;
2437
+ private handshake;
2438
+ /** The in-flight `connect()` call, if any — concurrent callers await this instead of starting their own `initialize` round trip. */
2439
+ private connecting;
2440
+ constructor(config: McpClientConfig);
2441
+ /**
2442
+ * Idempotent: a second call returns the cached handshake. Concurrent calls
2443
+ * while the first is still in flight share that same call rather than each
2444
+ * firing their own `initialize` round trip.
2445
+ */
2446
+ connect(): Promise<{
2447
+ serverInfo: McpServerInfo;
2448
+ protocolVersion: string;
2449
+ }>;
2450
+ private doConnect;
2451
+ /** All tools, following `nextCursor` pagination to exhaustion. */
2452
+ listTools(opts?: {
2453
+ signal?: AbortSignal;
2454
+ }): Promise<McpTool[]>;
2455
+ /**
2456
+ * Call a tool. A JSON-RPC error comes back as a failed `McpCallResult`
2457
+ * rather than a throw — tool errors are for the model to read, and an
2458
+ * exception here would abort the whole agent turn instead of one step.
2459
+ */
2460
+ callTool(name: string, args: unknown, opts?: {
2461
+ signal?: AbortSignal;
2462
+ onElicit?: McpElicitHandler;
2463
+ }): Promise<McpCallResult>;
2464
+ /** Best-effort session teardown; servers may not support DELETE. */
2465
+ close(): Promise<void>;
2466
+ private ensureConnected;
2467
+ private request;
2468
+ private post;
2469
+ private rpc;
2470
+ /** Answer a server-initiated request (elicitation); unknown methods get a JSON-RPC error. */
2471
+ private answerServerRequest;
2472
+ private settle;
2473
+ }
2474
+ /**
2475
+ * Credential-free direct HTTP transport for MCP servers that need no key (a
2476
+ * local dev server, the playground's mock route). Anything with a token that
2477
+ * must stay secret belongs behind `createProxyHandler` instead.
2478
+ */
2479
+ declare function createHttpTransport(opts: {
2480
+ baseUrl: string;
2481
+ headers?: Record<string, string>;
2482
+ fetchImpl?: typeof fetch;
2483
+ }): Transport;
2484
+
2485
+ type McpImportOptions = {
2486
+ /**
2487
+ * Prefix for imported tool names ("namespace_toolName"), so two servers with
2488
+ * a `search` tool can coexist. Defaults to the server's sanitized name.
2489
+ */
2490
+ namespace?: string;
2491
+ /** Defaults to "read": a remote server's tools are reads until the host says otherwise. */
2492
+ side?: ToolSide;
2493
+ costHint?: number;
2494
+ /** Override the result mapping per server. */
2495
+ mapResult?: (result: McpCallResult) => ToolResult;
2496
+ };
2497
+ /**
2498
+ * Fetch the server's tool list and wrap each tool in a `ToolDefinition` whose
2499
+ * executor calls back through the client. Throws when two tools collide after
2500
+ * namespacing — a silent overwrite would drop a tool with no trace.
2501
+ */
2502
+ declare function importMcpTools(client: McpClient, opts?: McpImportOptions): Promise<ToolDefinition[]>;
2503
+ /**
2504
+ * Default MCP result → ToolResult mapping.
2505
+ *
2506
+ * The model reads `output`; a UI-worthy image rides as a card. Kept small on
2507
+ * purpose — the output is billed on every later turn of the thread.
2508
+ */
2509
+ declare function mapMcpResult(result: McpCallResult): ToolResult;
2510
+ /**
2511
+ * The relevance half of the composition: a `matched` skill that names the
2512
+ * imported tools, so they surface when the conversation is about them —
2513
+ * exactly how a locally defined domain tool becomes visible. Registering the
2514
+ * tools makes them EXIST; registering this skill makes them REACHABLE. The
2515
+ * authority tier still comes from presets, which this never touches.
2516
+ */
2517
+ declare function createMcpSkill(serverName: string, defs: readonly ToolDefinition[], opts?: {
2518
+ id?: string;
2519
+ priority?: number;
2520
+ }): Skill;
2521
+ /**
2522
+ * MCP elicitation → interactive form card. The server's `requestedSchema`
2523
+ * becomes form fields; the user's submission becomes the `accept` content, a
2524
+ * dismissal becomes `decline`. This is the bridge that makes an eliciting MCP
2525
+ * server feel like a first-class interactive tool instead of a hang.
2526
+ */
2527
+ declare function elicitViaCard(requestCard: (spec: CardSpec) => Promise<unknown>): McpElicitHandler;
2528
+
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 };