@copilotkit/core 1.84.2-canary.1793809041 → 1.85.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,974 @@
1
+ import { D as ɵGenerativeUIDebugSource, J as A2UIMarkdownOperation, T as ɵGenerativeUIDebugRun, o as CopilotKitCore, st as MarkdownSegment } from "../index-BC1dzn_F.mjs";
2
+ import "../index.mjs";
3
+ import { AbstractAgent, Message } from "@ag-ui/client";
4
+ import { A2UIActionMessage, A2UIFunctionPermissions, A2UIFunctionReturnType, A2UIOperation, CopilotKitUIEnvelope, GenerativeUIActionBinding, GenerativeUIFunctionManifest, GenerativeUIManifest, GenerativeUIRejectedOperation, GenerativeUISurfaceContent, GenerativeUISurfaceStatus, GenerativeUISurfaceSummary, GenerativeUITarget, GenerativeUIUserEvent, StandardSchemaV1, ValidateOperationOptions } from "@copilotkit/shared";
5
+ import { GenerativeUI, GenerativeUIError, GenerativeUIErrorInfo, GenerativeUIInvokeResult, GenerativeUISchema } from "@copilotkit/shared/generative-ui";
6
+ import { SurfaceModel } from "@a2ui/web_core/v0_9";
7
+
8
+ //#region src/generative-ui/dispatcher.d.ts
9
+ /**
10
+ * A function that generated UI may call, as declared in
11
+ * `createGenerativeUI({ functions })`. Zod schemas fit `parameters`, because
12
+ * they implement Standard Schema.
13
+ */
14
+ interface GenerativeUIDeclaredFunction extends A2UIFunctionPermissions {
15
+ description?: string;
16
+ parameters: StandardSchemaV1;
17
+ returnType?: A2UIFunctionReturnType;
18
+ }
19
+ /**
20
+ * Holds the latest handler of one mounted `useGenerativeUIFunction`. The hook
21
+ * updates `current` on each render, so it registers only once per mount.
22
+ */
23
+ interface GenerativeUIHandlerRef {
24
+ current: (args: any) => unknown;
25
+ }
26
+ /** The component of a surface that called a function. */
27
+ interface GenerativeUIInvocationOrigin {
28
+ surfaceId: string;
29
+ componentId: string;
30
+ }
31
+ /**
32
+ * What called a function: a component of a surface, or the agent with a
33
+ * `callRendererFunction` operation.
34
+ */
35
+ type GenerativeUICallOrigin = GenerativeUIInvocationOrigin | {
36
+ functionCallId: string;
37
+ };
38
+ interface GenerativeUIDispatcher {
39
+ /**
40
+ * Call a declared function with arguments from generated UI or from the
41
+ * agent. Never throws: every failure becomes `{ ok: false, error }`.
42
+ */
43
+ invoke(name: string, args: unknown, origin: GenerativeUICallOrigin): Promise<GenerativeUIInvokeResult>;
44
+ /** The declared functions that have exactly one mounted handler, as JSON Schema. */
45
+ listExposed(): Record<string, GenerativeUIFunctionManifest>;
46
+ /**
47
+ * Mount a handler for a declared function. Returns the function that
48
+ * unmounts it. Calling the returned function more than once is safe.
49
+ */
50
+ register(name: string, ref: GenerativeUIHandlerRef): () => void;
51
+ /** How many handlers are mounted for `name`, for the inspector. */
52
+ handlerCount(name: string): number;
53
+ }
54
+ interface GenerativeUIDispatcherOptions {
55
+ /** The functions declared in `createGenerativeUI({ functions })`, read at call time. */
56
+ getDeclared: () => ReadonlyMap<string, GenerativeUIDeclaredFunction>;
57
+ /** Called for each failed `invoke`. A throw from it is ignored. */
58
+ onError?: (info: {
59
+ name: string;
60
+ origin: GenerativeUICallOrigin;
61
+ error: GenerativeUIError;
62
+ }) => void;
63
+ }
64
+ declare function createGenerativeUIDispatcher(options: GenerativeUIDispatcherOptions): GenerativeUIDispatcher;
65
+ //#endregion
66
+ //#region src/generative-ui/surface-manager.d.ts
67
+ declare function surfaceKey(threadId: string, surfaceId: string): string;
68
+ interface ManagedSurface {
69
+ readonly key: string;
70
+ readonly threadId: string;
71
+ readonly surfaceId: string;
72
+ readonly agentId: string | undefined;
73
+ /** Replaced by an empty model when the surface closes, to free its data. */
74
+ model: SurfaceModel<any>;
75
+ readonly createdAt: number;
76
+ target: string;
77
+ status: GenerativeUISurfaceStatus;
78
+ deleted: boolean;
79
+ /** Its first createSurface was rejected, so it never existed. */
80
+ failed: boolean;
81
+ /** Rejections reported by the runtime. */
82
+ serverRejected: GenerativeUIRejectedOperation[];
83
+ /** Rejections detected while applying operations in the browser. */
84
+ clientRejected: GenerativeUIRejectedOperation[];
85
+ /** The committed operations of the latest content, for the inspector. */
86
+ operations: readonly A2UIOperation[];
87
+ }
88
+ interface GenerativeUISurfaceManagerOptions {
89
+ onOperationRejected?: (info: {
90
+ surfaceId: string;
91
+ index: number;
92
+ reason: string;
93
+ }) => void;
94
+ }
95
+ /** What one mount of a target tells the model. */
96
+ interface GenerativeUITargetOptions {
97
+ /** Where the target is on the page and what to show in it. */
98
+ description?: string;
99
+ /**
100
+ * The only components that the surfaces of the target can use. Left out,
101
+ * every component of the UI is allowed.
102
+ */
103
+ components?: readonly string[];
104
+ }
105
+ /** A mounted target, as the manifest lists it. */
106
+ interface GenerativeUIMountedTarget {
107
+ id: string;
108
+ description?: string;
109
+ components?: string[];
110
+ }
111
+ /**
112
+ * Framework-agnostic store of generated surfaces. One web_core SurfaceModel per
113
+ * (threadId, surfaceId), shared by every mount. Applies only newly committed
114
+ * operations, validates each before applying it, and owns app state and the
115
+ * data model paths that the user wrote, so agent updates cannot overwrite
116
+ * them. App state never goes into a surface's data model. Selectors read it
117
+ * with `getState()`.
118
+ */
119
+ declare class GenerativeUISurfaceManager {
120
+ private readonly ui;
121
+ private readonly options;
122
+ private readonly surfaces;
123
+ private readonly bookkeeping;
124
+ private readonly listeners;
125
+ /** Mounts of each target id, in mount order. */
126
+ private readonly targets;
127
+ private state;
128
+ /**
129
+ * User-owned data model values, by surface key, then by path. Kept when a
130
+ * surface is rebuilt. Cleared when the surface is deleted.
131
+ */
132
+ private readonly owned;
133
+ /**
134
+ * Keys of the surfaces that a `deleteSurface` removed. A surface id is
135
+ * unique for the life of the page, so a key stays here when its surface is
136
+ * built again.
137
+ */
138
+ private readonly deletedKeys;
139
+ /**
140
+ * Surfaces that share their data model, by surface key: the parts of a
141
+ * chat surface that the prose lift split. A user write to one part goes
142
+ * to every part, so an input in one part drives a binding in another.
143
+ */
144
+ private readonly linked;
145
+ private readonly webCoreCatalog;
146
+ private activeThreadId;
147
+ private version;
148
+ constructor(ui: GenerativeUI, options?: GenerativeUISurfaceManagerOptions);
149
+ subscribe: (listener: () => void) => (() => void);
150
+ getVersion: () => number;
151
+ private notify;
152
+ setActiveThread(threadId: string | undefined): void;
153
+ getActiveThread(): string | undefined;
154
+ ingest(threadId: string, agentId: string | undefined, content: GenerativeUISurfaceContent): void;
155
+ /** The surface of a `key` (see `surfaceKey`), unless it is deleted. */
156
+ getSurfaceByKey(key: string): ManagedSurface | undefined;
157
+ getSurface(threadId: string, surfaceId: string): ManagedSurface | undefined;
158
+ getSurfaceForTarget(target: string, threadId?: string | undefined): ManagedSurface | undefined;
159
+ /**
160
+ * A surface whose first createSurface was rejected, so the chat can show
161
+ * the error where the surface would be. `undefined` for any other surface.
162
+ */
163
+ getFailedSurface(threadId: string, surfaceId: string): ManagedSurface | undefined;
164
+ /**
165
+ * The surfaces of a thread, for the model. A surface with user-owned
166
+ * values lists them in `dataModel`, so the model can read what the user
167
+ * entered. A surface with dropped operations lists them in `rejected`, so
168
+ * the model can fix them on the next run. A deleted surface, or one that
169
+ * was never created, has a `status`, so the model knows that the id is
170
+ * not a live surface.
171
+ */
172
+ describeSurfaces(threadId: string): Record<string, GenerativeUISurfaceSummary>;
173
+ /** Every surface that is not deleted, oldest first, for the inspector. */
174
+ debugSurfaces(): {
175
+ surfaceId: string;
176
+ threadId: string;
177
+ agentId: string | undefined;
178
+ target: string;
179
+ status: GenerativeUISurfaceStatus;
180
+ operations: readonly A2UIOperation[];
181
+ dataModel: any;
182
+ userValues: {
183
+ [k: string]: unknown;
184
+ };
185
+ rejected: ({
186
+ source: "runtime";
187
+ index: number;
188
+ reason: string;
189
+ } | {
190
+ source: "browser";
191
+ index: number;
192
+ reason: string;
193
+ })[];
194
+ }[];
195
+ /**
196
+ * Marks a target as mounted. Returns the function that unmounts it. Calling
197
+ * that function more than once has no effect.
198
+ *
199
+ * @param id - The target id.
200
+ * @param options - The description and the allowed components of this mount.
201
+ */
202
+ registerTarget(id: string, options?: GenerativeUITargetOptions): () => void;
203
+ /**
204
+ * The mounted targets. Each has the description and the component list of
205
+ * its earliest mount that has one.
206
+ */
207
+ getMountedTargets(): GenerativeUIMountedTarget[];
208
+ /**
209
+ * The component list of the earliest mount of `id` that has one.
210
+ * `undefined` when no mount of `id` limits its components.
211
+ */
212
+ private targetComponents;
213
+ /** The components that `validateOperation` allows on a surface. */
214
+ private allowedComponentsFor;
215
+ /**
216
+ * The app state object. It is the same object until a key changes, so it
217
+ * can be a `useSyncExternalStore` snapshot.
218
+ */
219
+ getState: () => Readonly<Record<string, unknown>>;
220
+ /** Sets one state key. Notifies only when the value changed. */
221
+ setState(key: string, value: unknown): void;
222
+ /** Removes one state key. Notifies only when the key was set. */
223
+ removeState(key: string): void;
224
+ /**
225
+ * Makes the surfaces of `surfaceIds` share their data model: a user write
226
+ * to one of them goes to all of them (see `setOwnedValue`). The markdown
227
+ * transport links the parts of a chat surface that the prose lift split.
228
+ * A later call for one of the surfaces replaces its group.
229
+ *
230
+ * @param threadId - The thread of the surfaces.
231
+ * @param surfaceIds - The surface ids of the group. One id clears a link.
232
+ */
233
+ linkSurfaces(threadId: string, surfaceIds: readonly string[]): void;
234
+ /**
235
+ * Writes a user value into the data model of a surface, and marks `path`
236
+ * as user-owned. Then agent writes to that path, or below it, are ignored.
237
+ * An agent write above it keeps the user value. Ownership ends when the
238
+ * surface is deleted. Does nothing for an unknown or deleted surface. The
239
+ * surfaces linked to it (see `linkSurfaces`) get the same write.
240
+ *
241
+ * @param key - The `key` of the surface.
242
+ * @param path - An absolute JSON pointer, for example "/form/email".
243
+ * @param value - The new value. It is copied.
244
+ * @throws Error when a path segment is "__proto__", "constructor" or
245
+ * "prototype", or when the path does not fit the data (for example, a
246
+ * segment above it holds a string).
247
+ */
248
+ setOwnedValue(key: string, path: string, value: unknown): void;
249
+ private writeOwnedValue;
250
+ /**
251
+ * Writes the user-owned values into the new, empty data model of a rebuilt
252
+ * surface. The agent operations are applied after it.
253
+ */
254
+ private restoreOwnedValues;
255
+ /**
256
+ * The value that an agent write puts at `path`, with the user-owned values
257
+ * below `path` written back into it. `undefined` when `path` is user-owned
258
+ * or below a user-owned path, so the agent cannot write it. Throws when a
259
+ * user value does not fit the new value.
260
+ */
261
+ private mergeOwnedValues;
262
+ private extendsApplied;
263
+ private createSurface;
264
+ private disposeSurface;
265
+ /**
266
+ * Marks a surface deleted and frees its components and data. The record
267
+ * stays, so the model is still told about the id and the bookkeeping does
268
+ * not rebuild the surface for content that was already applied.
269
+ */
270
+ private closeSurface;
271
+ /** The surfaces of a thread that a part of `surfaceId` reads, for tests. */
272
+ getLinkedSurfaceIds(threadId: string, surfaceId: string): string[];
273
+ /**
274
+ * Drops the node keys that the app sets: bound props and matched events.
275
+ * The model does not see them, so a model value for one is ignored, not
276
+ * rejected. This runs before validation, because validation rejects keys
277
+ * that are not in the manifest. It never changes the given operation.
278
+ */
279
+ private dropAppSetKeys;
280
+ private dropAppSetNodeKeys;
281
+ /**
282
+ * The surfaces that `validateOperation` gets for one operation of the
283
+ * content of `surface`.
284
+ *
285
+ * - `knownSurfaces`: the surface, when it exists before the operation. It
286
+ * does not exist before its first createSurface, or after a delete.
287
+ * - `createdSurfaces`: the surface, when a createSurface at this position
288
+ * uses its id again. That is the case after the first operation, and for
289
+ * a surface that was deleted before, unless the content replays that
290
+ * delete.
291
+ */
292
+ private surfacesFor;
293
+ private applyOperation;
294
+ /** The first node with props of the wrong type, as a reason. */
295
+ private nodesProblem;
296
+ /**
297
+ * Writes an agent value at `path` and keeps the user-owned values. A write
298
+ * to a user-owned path is ignored, not rejected. Gives the reason when the
299
+ * value does not fit the data, else `undefined`.
300
+ */
301
+ private writeAgentData;
302
+ private checkNodeProps;
303
+ private upsertNode;
304
+ }
305
+ //#endregion
306
+ //#region src/generative-ui/runtime.d.ts
307
+ /**
308
+ * What the engine needs from the runtime of a framework: the surfaces, the
309
+ * function dispatcher, and how user events and errors leave the UI. A
310
+ * framework's runtime object satisfies it structurally and adds its own
311
+ * config and theme on top.
312
+ */
313
+ interface GenerativeUIEngine {
314
+ manager: GenerativeUISurfaceManager;
315
+ dispatcher: GenerativeUIDispatcher;
316
+ /** The generative UI given to the provider. */
317
+ ui: GenerativeUI;
318
+ forwardEvent: (event: GenerativeUIUserEvent, agentId: string | undefined) => Promise<GenerativeUIInvokeResult>;
319
+ reportError: (info: GenerativeUIErrorInfo) => void;
320
+ }
321
+ /**
322
+ * Reports an error without ever throwing: `reportError` reaches host code
323
+ * (`onError`), and a throwing host callback must not break rendering or an
324
+ * event handler.
325
+ */
326
+ declare function reportErrorSafely(engine: Pick<GenerativeUIEngine, "reportError">, info: GenerativeUIErrorInfo): void;
327
+ //#endregion
328
+ //#region src/generative-ui/functions.d.ts
329
+ /**
330
+ * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
331
+ * resolved args (no bindings left in them) and gives a plain value. They
332
+ * run synchronously, so a prop bound to one updates in the same render as
333
+ * the data it reads. The signatures the model sees are in
334
+ * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
335
+ */
336
+ /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
337
+ declare class ExpressionError extends Error {
338
+ constructor(message: string);
339
+ }
340
+ type BasicFunction = (args: Record<string, unknown>) => unknown;
341
+ /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
342
+ declare function truthOf(value: unknown): boolean;
343
+ /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
344
+ declare function openUrlSafely(url: unknown): void;
345
+ /**
346
+ * The basic functions, except `formatString`, which needs the resolver.
347
+ * `calc` and `series` are added by `resolve.ts`, which imports both.
348
+ */
349
+ declare const BASIC_FUNCTIONS: Record<string, BasicFunction>;
350
+ /** True when the basic function `name` must run from a user gesture. */
351
+ declare function requiresUserActivation(name: string): boolean;
352
+ /** True when a basic function gives a ValidationResult. */
353
+ declare function givesValidationResult(name: string): boolean;
354
+ //#endregion
355
+ //#region src/generative-ui/markdown-source.d.ts
356
+ /** What renders in place of one ```a2ui fence, in order. */
357
+ type MarkdownFenceBlock = {
358
+ kind: "markdown";
359
+ markdown: string;
360
+ } | {
361
+ kind: "surface";
362
+ surfaceId: string;
363
+ };
364
+ /** The part of a generative UI that the markdown source reads. */
365
+ type MarkdownSourceUI = Pick<GenerativeUI, "id" | "manifestComponents">;
366
+ interface BuildMarkdownSurfacesOptions {
367
+ ui: MarkdownSourceUI;
368
+ /** The declared functions. A `functionCall` must name one of them. */
369
+ functions: Record<string, GenerativeUIFunctionManifest>;
370
+ /**
371
+ * The last message can still grow. Then an open fence in it is still
372
+ * streaming: its last, unfinished operation is left out, and the surface
373
+ * it creates has the status "streaming". Else an open fence is final.
374
+ */
375
+ running: boolean;
376
+ /**
377
+ * The results of the earlier builds of the same thread. A build then
378
+ * parses only the fences that changed, and builds only the surfaces whose
379
+ * operations changed. Left out, everything is built again.
380
+ */
381
+ cache?: MarkdownBuildCache;
382
+ }
383
+ /**
384
+ * Values by key, from the latest build. A value that a build does not use
385
+ * is dropped at the end of that build, so the cache does not grow.
386
+ */
387
+ declare class BuildMemo<V> {
388
+ private previous;
389
+ private current;
390
+ /**
391
+ * The value of `key`. It is computed when no earlier value is there, or
392
+ * when `isFresh` says that the earlier value is out of date.
393
+ */
394
+ get(key: string, compute: () => V, isFresh?: (value: V) => boolean): V;
395
+ endBuild(): void;
396
+ }
397
+ /** The surfaces that one draft gives, and the operations it was built from. */
398
+ interface BuiltDraft {
399
+ operations: A2UIMarkdownOperation[];
400
+ target: string;
401
+ streaming: boolean;
402
+ parts: SurfacePart[];
403
+ contents: GenerativeUISurfaceContent[];
404
+ }
405
+ /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
406
+ declare class MarkdownBuildCache {
407
+ readonly segments: BuildMemo<MarkdownSegment[]>;
408
+ readonly fences: BuildMemo<{
409
+ operations: A2UIMarkdownOperation[];
410
+ functionCalls: A2UIMarkdownOperation[];
411
+ }>;
412
+ readonly drafts: BuildMemo<BuiltDraft>;
413
+ /** The copies of an operation for other surface ids, by operation. */
414
+ readonly readdressed: WeakMap<object, Map<string, A2UIMarkdownOperation>>;
415
+ endBuild(): void;
416
+ }
417
+ /** The surface content, or one surface of it after the prose lift. */
418
+ type SurfacePart = {
419
+ kind: "markdown";
420
+ markdown: string;
421
+ } | {
422
+ kind: "surface";
423
+ surfaceId: string;
424
+ operations: A2UIMarkdownOperation[];
425
+ };
426
+ /** The key of one fence of one message. */
427
+ declare function fenceKey(messageId: string, fenceIndex: number): string;
428
+ /** One `callRendererFunction` line of a fence, in the order of the fences. */
429
+ interface MarkdownFunctionCall {
430
+ messageId: string;
431
+ fenceIndex: number;
432
+ /** The operation as the model wrote it. It is not validated yet. */
433
+ operation: A2UIMarkdownOperation;
434
+ }
435
+ /**
436
+ * Builds the surfaces of a thread from the ```a2ui fences of its assistant
437
+ * messages, in message order.
438
+ *
439
+ * - Operations are grouped by surfaceId across all messages. An operation
440
+ * with no surfaceId goes to the first surface of its fence, else to
441
+ * `<messageId>-<fenceIndex>`.
442
+ * - The fence that first writes a surface creates it. The `target=<id>` of
443
+ * that fence sets the target. With no target, the surface goes to the
444
+ * chat.
445
+ * - A later fence of the same reply for the same surfaceId updates it. A
446
+ * later reply that reuses the id of a chat surface gets a surface of its
447
+ * own, `<id>@<messageId>`. A page target is updated from any reply.
448
+ * - The status is "streaming" while the creating fence streams, else
449
+ * "ready".
450
+ * - Each operation is validated with `validateOperation`. Rejected ones are
451
+ * left out and listed in `rejected`.
452
+ * - Chat surfaces get the prose lift: informational cards lose their box,
453
+ * and prose becomes markdown that renders between sub-surfaces
454
+ * (`<surfaceId>#<n>`). An inline createSurface is split into its
455
+ * createSurface, updateDataModel and updateComponents first.
456
+ * - A `callRendererFunction` line is not part of a surface. It goes to
457
+ * `functionCalls`. A streaming line gives nothing, so a function never
458
+ * runs with a part of its args.
459
+ *
460
+ * The function is pure. Call it again on each stream update. The manager
461
+ * applies only the new operations, so unchanged surfaces do not render
462
+ * again.
463
+ *
464
+ * @param messages - The messages of one thread.
465
+ * @param options - The generative UI, its declared functions, and whether
466
+ * the last message can still grow.
467
+ * @returns `surfaces`, one content for each surface and sub-surface;
468
+ * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
469
+ * that is not in `fences` renders nothing); `functionCalls`, the function
470
+ * calls of the fences in order; and `parts`, the surface ids of the parts
471
+ * of each surface, by surface id.
472
+ *
473
+ * @example
474
+ * ```ts
475
+ * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
476
+ * ui,
477
+ * functions: {},
478
+ * running: agent.isRunning,
479
+ * });
480
+ * for (const content of surfaces) manager.ingest(threadId, agentId, content);
481
+ * ```
482
+ */
483
+ declare function buildMarkdownSurfaces(messages: readonly Message[], options: BuildMarkdownSurfacesOptions): {
484
+ surfaces: GenerativeUISurfaceContent[];
485
+ fences: Map<string, MarkdownFenceBlock[]>;
486
+ functionCalls: MarkdownFunctionCall[];
487
+ parts: Map<string, string[]>;
488
+ };
489
+ /**
490
+ * The markdown transport source of one surface manager. It turns the
491
+ * messages of a thread into surfaces in the manager, and keeps the blocks
492
+ * that each fence renders.
493
+ */
494
+ declare class MarkdownSurfaceSource {
495
+ private readonly manager;
496
+ private readonly ui;
497
+ private readonly functions;
498
+ /** By thread: the blocks of each fence, from the latest sync. */
499
+ private readonly fences;
500
+ /** By thread, then surface: the operations last ingested, as JSON. */
501
+ private readonly ingested;
502
+ /** By thread, then surface: the content last ingested. */
503
+ private readonly contents;
504
+ /** By thread: the results of the earlier builds. */
505
+ private readonly caches;
506
+ constructor(manager: GenerativeUISurfaceManager, ui: GenerativeUI);
507
+ /**
508
+ * Builds the surfaces of `threadId` from `messages` and gives them to the
509
+ * manager. A surface that an earlier sync of the thread made, and that the
510
+ * messages no longer write, is deleted. Other threads do not change.
511
+ *
512
+ * @param threadId - The thread of the messages.
513
+ * @param agentId - The agent that owns the thread.
514
+ * @param messages - All messages of the thread.
515
+ * @param options - `running`: the last message can still grow.
516
+ * @returns The function calls of the fences, in order. The source does
517
+ * not run them.
518
+ */
519
+ sync(threadId: string, agentId: string | undefined, messages: readonly Message[], options: {
520
+ running: boolean;
521
+ }): MarkdownFunctionCall[];
522
+ /**
523
+ * The blocks that a fence renders in the chat, from the latest sync of the
524
+ * thread. `undefined` when the fence renders nothing: it updates a surface
525
+ * of an earlier fence, its surface is for a named target, or it has no
526
+ * complete operation yet.
527
+ */
528
+ getFenceBlocks(threadId: string, messageId: string, fenceIndex: number): MarkdownFenceBlock[] | undefined;
529
+ }
530
+ /**
531
+ * The markdown source of a generative UI runtime. There is one source for
532
+ * each surface manager. The root syncs it, and the chat messages read the
533
+ * fence blocks from it.
534
+ */
535
+ declare function getMarkdownSurfaceSource(runtime: {
536
+ manager: GenerativeUISurfaceManager;
537
+ ui: GenerativeUI;
538
+ }): MarkdownSurfaceSource;
539
+ //#endregion
540
+ //#region src/generative-ui/function-calls.d.ts
541
+ type ReadonlyMessages = ReadonlyArray<Readonly<Message>>;
542
+ /** One agent-called function, as the model sent it. */
543
+ interface FunctionCallRequest {
544
+ functionCallId: string;
545
+ /** A `callRendererFunction` operation. It is not validated yet. */
546
+ operation: unknown;
547
+ }
548
+ /** The function calls of the tool transport: its function-call activities. */
549
+ declare function activityFunctionCalls(messages: ReadonlyMessages): FunctionCallRequest[];
550
+ /** The function calls of the markdown transport: its fence lines. */
551
+ declare function markdownFunctionCalls(calls: MarkdownFunctionCall[]): FunctionCallRequest[];
552
+ interface FunctionCallRunnerOptions {
553
+ /** Starts the follow-up runs. A framework's core subclass fits. */
554
+ core: Pick<CopilotKitCore, "runAgent">;
555
+ dispatcher: GenerativeUIDispatcher;
556
+ manifest: ValidateOperationOptions["manifest"];
557
+ /**
558
+ * Lets the app apply the state that the handlers set before the follow-up
559
+ * run reads it: React commits its pending updates, Angular runs a change
560
+ * detection tick.
561
+ */
562
+ settle: () => Promise<void>;
563
+ /** Gets a failed follow-up run. Development only. */
564
+ warn: (message: string, error: unknown) => void;
565
+ }
566
+ interface FunctionCallRunner {
567
+ /**
568
+ * Runs the calls of the thread of `agent` that did not run yet. When no
569
+ * run goes on, it also sends the pending answers.
570
+ *
571
+ * @param agent - The agent of the thread.
572
+ * @param requests - The function calls in the messages, in order.
573
+ * @param messages - All messages of the thread.
574
+ * @param running - A run goes on or starts now. The answers wait.
575
+ */
576
+ run(agent: AbstractAgent, requests: FunctionCallRequest[], messages: ReadonlyMessages, running: boolean): void;
577
+ }
578
+ /**
579
+ * Runs the functions that the agent calls with `callRendererFunction`, for
580
+ * both transports, and answers each call.
581
+ *
582
+ * - Each `functionCallId` runs once for each thread. A replay, a sync of
583
+ * the same messages again, or a call that already has an answer message
584
+ * does not run it again.
585
+ * - The answer is a hidden developer message with a `rendererFunctionResponse`.
586
+ * The answers go to the agent only when it is not running. Then one
587
+ * follow-up run starts for all of them.
588
+ * - A user turn has at most {@link MAX_FUNCTION_FOLLOW_UPS} follow-up runs.
589
+ * A call after that does not run. It gets a `follow_up_limit` error and
590
+ * starts no follow-up run.
591
+ */
592
+ declare function createFunctionCallRunner(options: FunctionCallRunnerOptions): FunctionCallRunner;
593
+ //#endregion
594
+ //#region src/generative-ui/calc.d.ts
595
+ /**
596
+ * The two CopilotKit value functions that A2UI 1.0 lacks: `calc`, an
597
+ * arithmetic expression over named args, and `series`, a computed list.
598
+ * Both are catalog functions in the sense of the spec: a catalog may
599
+ * declare functions beyond the basic ones, and the model learns them from
600
+ * the schema. The expression language is small and closed: numbers,
601
+ * strings, booleans, the args by name, `+ - * / %`, `^` (power),
602
+ * comparisons, `&& || !`, `cond ? a : b`, parentheses, min, max, round,
603
+ * floor, ceil, abs, pow, sqrt, exp, ln (also log), log10, and the
604
+ * constants pi and e. No property access, no assignment, no code.
605
+ */
606
+ type Value = number | string | boolean | null;
607
+ type CalcScope = Readonly<Record<string, unknown>>;
608
+ /**
609
+ * Evaluates `expression` with the names in `scope`. Gives a number, a
610
+ * string, a boolean or null. Throws an {@link ExpressionError} for a bad
611
+ * expression or a missing name.
612
+ */
613
+ declare function evaluateCalc(expression: unknown, scope: CalcScope): Value;
614
+ /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
615
+ declare function calc(args: Record<string, unknown>): Value;
616
+ /**
617
+ * The `series` function: `count` copies of `item`, with the loop variable
618
+ * (`variable`, default "i") counting from `start` (default 1) and the other
619
+ * args in scope of the `${...}` expressions of the item.
620
+ */
621
+ declare function series(args: Record<string, unknown>): unknown[];
622
+ //#endregion
623
+ //#region src/generative-ui/resolve.d.ts
624
+ /**
625
+ * Resolves the dynamic values of A2UI 1.0 in a prop, an event context, or
626
+ * a function argument: `{"@path"}` bindings read the data model,
627
+ * `{"@call"}` values run a basic function, and `formatString` interpolates
628
+ * `${...}` expressions. Objects and arrays are walked, so a binding can sit
629
+ * at any depth. A value with nothing dynamic in it keeps its identity.
630
+ */
631
+ /** Reads the data model. The surface data model of web_core fits. */
632
+ interface DataReader {
633
+ get(path: string): unknown;
634
+ }
635
+ interface ResolveContext {
636
+ data: DataReader;
637
+ /**
638
+ * The data model path of the template item this value belongs to, or
639
+ * `undefined` outside of a template. Relative paths resolve against it.
640
+ */
641
+ basePath: string | undefined;
642
+ }
643
+ interface Resolved<T = unknown> {
644
+ value: T;
645
+ /** The absolute data model paths that the value read. */
646
+ paths: Set<string>;
647
+ }
648
+ /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
649
+ declare function joinPath(base: string, segment: string): string;
650
+ /**
651
+ * The absolute data model path of a binding. A path without a leading "/"
652
+ * is relative to the current template item, or to the root outside of one.
653
+ */
654
+ declare function resolvePath(path: string, basePath: string | undefined): string;
655
+ /**
656
+ * The index of the template item at `basePath`: its last segment.
657
+ * `undefined` outside of a template.
658
+ */
659
+ declare function templateIndex(basePath: string | undefined): number | undefined;
660
+ /**
661
+ * Resolves one dynamic value: the value with every binding and function
662
+ * call replaced, plus the data model paths it read. Throws an
663
+ * {@link ExpressionError} for a bad function call.
664
+ */
665
+ /** The options of a resolution. */
666
+ interface ResolveOptions {
667
+ /** Keep every validator result as an object. */
668
+ keepValidation?: boolean;
669
+ /**
670
+ * True when `value` is the `checks` prop of a component: the condition
671
+ * of each check then keeps its validator result as an object.
672
+ */
673
+ isChecks?: boolean;
674
+ }
675
+ declare function resolveDynamicValue<T = unknown>(value: unknown, context: ResolveContext, options?: ResolveOptions): Resolved<T>;
676
+ type ResolveAttempt<T = unknown> = ({
677
+ ok: true;
678
+ } & Resolved<T>) | {
679
+ ok: false;
680
+ error: Error; /** The paths read before the failure. A change there may fix it. */
681
+ paths: Set<string>;
682
+ };
683
+ /**
684
+ * Like {@link resolveDynamicValue}, but a failure comes back as a result
685
+ * with the paths read so far, so the caller can keep watching them: a
686
+ * function that fails on an empty field works once the user fills it.
687
+ */
688
+ declare function tryResolveDynamicValue<T = unknown>(value: unknown, context: ResolveContext, options?: ResolveOptions): ResolveAttempt<T>;
689
+ /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
690
+ declare function containsDynamicValue(value: unknown): boolean;
691
+ //#endregion
692
+ //#region src/generative-ui/events.d.ts
693
+ /** One call of an event prop by a component. */
694
+ interface EventCall {
695
+ runtime: GenerativeUIEngine;
696
+ surface: ManagedSurface;
697
+ componentId: string;
698
+ /** The event prop name, for error messages. */
699
+ name: string;
700
+ /**
701
+ * The event `parameters`. When absent, the args go on unchecked. That is
702
+ * the case for a matched event without `parameters`: the function schema
703
+ * checks them.
704
+ */
705
+ parameters?: GenerativeUISchema;
706
+ args: unknown;
707
+ }
708
+ /**
709
+ * Runs one call of an event that the model bound: validates the component's
710
+ * args, merges them with the args from the binding (binding literals win),
711
+ * then calls a declared function or forwards an agent event. Never throws.
712
+ */
713
+ declare function invokeBoundEvent(params: EventCall & {
714
+ binding: GenerativeUIActionBinding; /** The template item path of the component, for relative paths. */
715
+ basePath: string | undefined;
716
+ }): Promise<GenerativeUIInvokeResult>;
717
+ /**
718
+ * Runs one call of an event that matches a declared function: validates the
719
+ * component's args with the event `parameters` (if any), then calls the
720
+ * function, which validates them with its own schema. Never throws.
721
+ */
722
+ declare function invokeMatchedEvent(params: EventCall & {
723
+ functionName: string;
724
+ }): Promise<GenerativeUIInvokeResult>;
725
+ //#endregion
726
+ //#region src/generative-ui/manifest.d.ts
727
+ /**
728
+ * The built-in functions (the A2UI basic catalog plus calc and series) as
729
+ * manifest entries. Their args are described by the short signature, not
730
+ * by a full JSON Schema: the renderer checks them when they run. An app
731
+ * function of the same name replaces the entry.
732
+ */
733
+ declare function builtInFunctionManifests(): Record<string, GenerativeUIFunctionManifest>;
734
+ /** What `buildCatalogManifest` adds to the catalog. */
735
+ interface CatalogManifestOptions {
736
+ /** The app functions with a mounted handler. A built-in of the same name is left out. */
737
+ functions?: Record<string, GenerativeUIFunctionManifest>;
738
+ /** The inline targets, after the chat target. */
739
+ targets?: GenerativeUITarget[];
740
+ /** The surfaces of the thread. */
741
+ surfaces?: Record<string, GenerativeUISurfaceSummary>;
742
+ }
743
+ /**
744
+ * The manifest of a catalog, with no React runtime: the components of `ui`,
745
+ * the built-in functions (minus the names the app declares) and
746
+ * `options.functions`, the chat target and `options.targets`, and
747
+ * `options.surfaces`. `buildGenerativeUIManifest` builds the per-run
748
+ * manifest with it; tools that run outside React use it directly.
749
+ *
750
+ * @example
751
+ * ```ts
752
+ * const manifest = buildCatalogManifest(standardUI);
753
+ * manifest.targets; // [{ id: "chat", kind: "chat" }]
754
+ * ```
755
+ */
756
+ declare function buildCatalogManifest(ui: Pick<GenerativeUI, "id" | "manifestComponents" | "functions">, options?: CatalogManifestOptions): GenerativeUIManifest;
757
+ /**
758
+ * Builds the per-run manifest. Never contains handlers or renderers.
759
+ *
760
+ * - `functions`: the built-in functions, then the declared functions with
761
+ * exactly one mounted handler.
762
+ * - `targets`: the chat first, then each mounted `<GenerativeUISurface>`,
763
+ * with its `description` and its `components` when it has them.
764
+ */
765
+ declare function buildGenerativeUIManifest(runtime: Pick<GenerativeUIEngine, "ui" | "manager" | "dispatcher">, threadId: string | undefined): GenerativeUIManifest;
766
+ /** How to build the envelope of one run. */
767
+ interface GenerativeUIEnvelopeOptions {
768
+ transport: CopilotKitUIEnvelope["metadata"]["extensions"]["copilotkit_transport"];
769
+ /**
770
+ * Send the component schemas. The tool transport always sends them,
771
+ * because the runtime validates operations with them.
772
+ */
773
+ includeCatalog: boolean;
774
+ /** True when the client also sends the guide as context entries. */
775
+ contextSent: boolean;
776
+ /**
777
+ * The markdown guideline. Left out, the markdown transport builds it from
778
+ * the manifest, with only the rule groups that the manifest uses. The
779
+ * tool transport sends none.
780
+ */
781
+ instructions?: string;
782
+ /** The user action that starts this run, when one does. */
783
+ action?: A2UIActionMessage;
784
+ }
785
+ /** The transport options of a framework's generative UI config. */
786
+ interface GenerativeUITransportConfig {
787
+ transport?: "tool" | "markdown";
788
+ /** Markdown only. Default `true`. */
789
+ sendContext?: boolean;
790
+ /** Markdown only. Default `true`. */
791
+ includeCatalog?: boolean;
792
+ }
793
+ /** What the envelope of a run says, from the provider config. */
794
+ declare function envelopeOptionsFor(config: GenerativeUITransportConfig): GenerativeUIEnvelopeOptions;
795
+ /**
796
+ * Builds the envelope that a run sends as `forwardedProps.copilotkit.ui`,
797
+ * from the per-run manifest. It has the A2UI v1.0 renderer capabilities
798
+ * shape: one inline catalog with the id of the UI, and the CopilotKit data
799
+ * in `metadata.extensions`.
800
+ *
801
+ * The inline catalog has no `components` only for the markdown transport
802
+ * with `includeCatalog: false`. It has `instructions` for the markdown
803
+ * transport, or when given.
804
+ *
805
+ * @param runtime - The generative UI runtime of the provider.
806
+ * @param threadId - The thread of the run. Its surfaces go in `copilotkit_surfaces`.
807
+ * @param options - The transport and what to send.
808
+ *
809
+ * @example
810
+ * ```ts
811
+ * const envelope = buildGenerativeUIEnvelope(runtime, agent.threadId, {
812
+ * transport: "tool",
813
+ * includeCatalog: true,
814
+ * contextSent: false,
815
+ * });
816
+ * envelope["1.0"].supportedCatalogIds; // [runtime.ui.id]
817
+ * ```
818
+ */
819
+ declare function buildGenerativeUIEnvelope(runtime: Pick<GenerativeUIEngine, "ui" | "manager" | "dispatcher">, threadId: string | undefined, options: GenerativeUIEnvelopeOptions): CopilotKitUIEnvelope;
820
+ //#endregion
821
+ //#region src/generative-ui/action-message.d.ts
822
+ /**
823
+ * Turns a user event that no function handles into the text of a visible
824
+ * user message.
825
+ *
826
+ * The first line is, in order: `userMessage`, `context.message`,
827
+ * `context.label`, the label of the source component (from `resolveLabel`),
828
+ * or the event name made readable (`choose_plan` becomes "Choose plan").
829
+ * Each other context field follows as one `key: value` line. Objects are
830
+ * written as JSON. `null` and `undefined` fields are skipped.
831
+ *
832
+ * @param event - The user event, as sent by a surface.
833
+ * @param resolveLabel - Finds the visible label of a component by id. Build
834
+ * one with {@link createComponentLabelResolver}.
835
+ *
836
+ * @example
837
+ * ```ts
838
+ * buildActionMessageText({
839
+ * name: "choose_plan",
840
+ * surfaceId: "plans",
841
+ * componentId: "team-button",
842
+ * userMessage: "I pick the Team plan",
843
+ * context: { seats: 12 },
844
+ * });
845
+ * // "I pick the Team plan\n\nseats: 12"
846
+ * ```
847
+ */
848
+ declare function buildActionMessageText(event: GenerativeUIUserEvent, resolveLabel?: (componentId: string) => string | undefined): string;
849
+ /**
850
+ * Builds a function that finds the visible label of a component on a surface.
851
+ *
852
+ * The label is the component's own string `label`, else its string `text`,
853
+ * else the first `child` or `children` component that has a string `label`
854
+ * or `text`. When a component id is defined more than once, the last
855
+ * definition wins, as in the renderer.
856
+ *
857
+ * @param operations - The committed operations of the surface.
858
+ *
859
+ * @example
860
+ * ```ts
861
+ * const resolveLabel = createComponentLabelResolver(surface.operations);
862
+ * buildActionMessageText(event, resolveLabel);
863
+ * ```
864
+ */
865
+ declare function createComponentLabelResolver(operations: readonly A2UIOperation[]): (componentId: string) => string | undefined;
866
+ /**
867
+ * The label resolver of a rendered surface: the components the surface has
868
+ * now, as one `updateComponents` operation, so that the label of the
869
+ * component that sent an event can be found.
870
+ */
871
+ declare function surfaceLabelResolver(surface: ManagedSurface): (componentId: string) => string | undefined;
872
+ //#endregion
873
+ //#region src/generative-ui/debug-source.d.ts
874
+ type RuntimeParts = Pick<GenerativeUIEngine, "ui" | "manager" | "dispatcher">;
875
+ /**
876
+ * What a run of `threadId` sends: its envelope, and the text that goes into
877
+ * the prompt of the model because of it.
878
+ *
879
+ * - Tool transport: the runtime adds the `render_ui` guide. It builds it
880
+ * from the envelope with `buildGenerativeUIPrompt`, as done here.
881
+ * - Markdown transport: the provider sends the guideline and the compact
882
+ * schema as context entries. With `sendContext: false`, the backend builds
883
+ * its own prompt, usually from the `instructions` of the envelope.
884
+ */
885
+ declare function describeGenerativeUIRun(runtime: RuntimeParts, threadId: string | undefined, options: GenerativeUIEnvelopeOptions): Pick<ɵGenerativeUIDebugRun, "envelope" | "prompt">;
886
+ /**
887
+ * The debug source that the provider gives core for the inspector. It builds
888
+ * a snapshot only when the inspector reads one.
889
+ *
890
+ * @param runtime - The generative UI parts of the provider.
891
+ * @param getOptions - The envelope options and agent ids of the current config.
892
+ * @returns The source, and `recordRun` for each run start.
893
+ */
894
+ declare function createGenerativeUIDebugSource(runtime: RuntimeParts, getOptions: () => {
895
+ options: GenerativeUIEnvelopeOptions;
896
+ agentIds: string[] | undefined;
897
+ }): {
898
+ source: ɵGenerativeUIDebugSource; /** Keeps what a run sent, so the inspector can show it. */
899
+ recordRun(run: ɵGenerativeUIDebugRun): void;
900
+ };
901
+ //#endregion
902
+ //#region src/generative-ui/accessibility.d.ts
903
+ /**
904
+ * The `accessibility` of the A2UI 1.0 component envelope, with its dynamic
905
+ * values resolved. Every component may carry it next to `id` and
906
+ * `component`; it is not a prop of the component.
907
+ */
908
+ interface GenerativeUIAccessibility {
909
+ /** A short name for assistive technologies, 1 to 3 words. */
910
+ label?: string;
911
+ /** Instructions, format requirements, or what an action does. */
912
+ description?: string;
913
+ /** How screen readers announce changes (WAI-ARIA `aria-live`). */
914
+ live?: "off" | "polite" | "assertive";
915
+ /** True hides the component and its children from assistive technologies. */
916
+ hidden?: boolean;
917
+ }
918
+ /** The ARIA attributes of a resolved `accessibility`, ready to spread. */
919
+ interface GenerativeUIAriaAttributes {
920
+ "aria-label"?: string;
921
+ "aria-description"?: string;
922
+ "aria-live"?: "off" | "polite" | "assertive";
923
+ "aria-hidden"?: true;
924
+ }
925
+ /**
926
+ * The accessibility of a component from its resolved `accessibility`
927
+ * value. Fields of the wrong type are left out: a label that is still a
928
+ * binding, or a list, names nothing.
929
+ */
930
+ declare function readAccessibility(value: unknown): GenerativeUIAccessibility | undefined;
931
+ /**
932
+ * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
933
+ * a region inherits the live setting of its ancestors, and a `status` role
934
+ * is live on its own, so only the explicit value silences it.
935
+ *
936
+ * @example
937
+ * ```ts
938
+ * accessibilityAttributes({ label: "Totals", live: "polite" });
939
+ * // { "aria-label": "Totals", "aria-live": "polite" }
940
+ * ```
941
+ */
942
+ declare function accessibilityAttributes(accessibility: GenerativeUIAccessibility | undefined): GenerativeUIAriaAttributes;
943
+ /**
944
+ * The role of a container that the envelope names. A generic element
945
+ * cannot carry a name, so a label or a description makes it a `group`,
946
+ * unless the component has a role of its own.
947
+ */
948
+ declare function namedRole(aria: GenerativeUIAriaAttributes, explicit: string | undefined): string | undefined;
949
+ /**
950
+ * The part of the attributes for the focusable control of a labelled pair:
951
+ * its name and its description. ARIA names are not inherited, so the
952
+ * wrapper of a control cannot name it.
953
+ */
954
+ declare function controlAria(aria: GenerativeUIAriaAttributes): Pick<GenerativeUIAriaAttributes, "aria-label" | "aria-description">;
955
+ /**
956
+ * The part of the attributes for the wrapper around a control: hidden and
957
+ * live cover the label and the control together.
958
+ */
959
+ declare function wrapperAria(aria: GenerativeUIAriaAttributes): Pick<GenerativeUIAriaAttributes, "aria-hidden" | "aria-live">;
960
+ //#endregion
961
+ //#region src/generative-ui/targets.d.ts
962
+ /** Scrolls `element` into view, unless it is already fully on screen. */
963
+ declare function scrollToSurface(element: HTMLElement): void;
964
+ /**
965
+ * The names of `requested` that `ui` has, without repeats, at most the
966
+ * number that the envelope takes. `warning` tells what was dropped.
967
+ */
968
+ declare function allowedComponents(requested: readonly string[], ui: GenerativeUI): {
969
+ names: string[];
970
+ warning: string;
971
+ };
972
+ //#endregion
973
+ export { BASIC_FUNCTIONS, BasicFunction, BuildMarkdownSurfacesOptions, CalcScope, CatalogManifestOptions, DataReader, ExpressionError, FunctionCallRequest, FunctionCallRunner, FunctionCallRunnerOptions, GenerativeUIAccessibility, GenerativeUIAriaAttributes, GenerativeUICallOrigin, GenerativeUIDeclaredFunction, GenerativeUIDispatcher, GenerativeUIDispatcherOptions, GenerativeUIEngine, GenerativeUIEnvelopeOptions, GenerativeUIHandlerRef, GenerativeUIInvocationOrigin, GenerativeUIMountedTarget, GenerativeUISurfaceManager, GenerativeUISurfaceManagerOptions, GenerativeUITargetOptions, GenerativeUITransportConfig, ManagedSurface, MarkdownBuildCache, MarkdownFenceBlock, MarkdownFunctionCall, MarkdownSurfaceSource, ReadonlyMessages, ResolveAttempt, ResolveContext, ResolveOptions, Resolved, accessibilityAttributes, activityFunctionCalls, allowedComponents, buildActionMessageText, buildCatalogManifest, buildGenerativeUIEnvelope, buildGenerativeUIManifest, buildMarkdownSurfaces, builtInFunctionManifests, calc, containsDynamicValue, controlAria, createComponentLabelResolver, createFunctionCallRunner, createGenerativeUIDebugSource, createGenerativeUIDispatcher, describeGenerativeUIRun, envelopeOptionsFor, evaluateCalc, fenceKey, getMarkdownSurfaceSource, givesValidationResult, invokeBoundEvent, invokeMatchedEvent, joinPath, markdownFunctionCalls, namedRole, openUrlSafely, readAccessibility, reportErrorSafely, requiresUserActivation, resolveDynamicValue, resolvePath, scrollToSurface, series, surfaceKey, surfaceLabelResolver, templateIndex, truthOf, tryResolveDynamicValue, wrapperAria };
974
+ //# sourceMappingURL=index.d.mts.map