@copilotkit/core 1.84.2-canary.1793809041 → 1.84.2-canary.openbot-intel-fixes

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,3902 +1,2 @@
1
- import * as _ag_ui_client0 from "@ag-ui/client";
2
- import { AbstractAgent, AgentCapabilities, AgentSubscriber, BaseEvent, Context, HttpAgent, HttpAgentConfig, Interrupt, Message, ResumeEntry, RunAgentInput, RunAgentParameters, RunAgentResult, State, Tool, ToolCall } from "@ag-ui/client";
3
- import { A2UIOperation, CopilotKitUIEnvelope, DebugConfig, GenerativeUIComponentManifest, GenerativeUIJSONSchema, GenerativeUIRejectedOperation, GenerativeUISurfaceStatus, GenerativeUITarget, InspectorMetadataV1, InspectorMetadataV1 as InspectorMetadataV1$1, IntelligenceRuntimeInfo, IntelligenceRuntimeInfo as IntelligenceRuntimeInfo$1, ResolvedDebugConfig, RuntimeEntitlementResponse, RuntimeInfo, RuntimeLicenseStatus, RuntimeLicenseStatus as RuntimeLicenseStatus$1, RuntimeMode, RuntimeMode as RuntimeMode$1, StandardSchemaV1, ThreadEndpointRuntimeInfo, ThreadEndpointRuntimeInfo as ThreadEndpointRuntimeInfo$1 } from "@copilotkit/shared";
4
- import { Observable, OperatorFunction, Subscription } from "rxjs";
5
- import { CaptureOptions, CollectorOptions, JsonValue, JsonValue as JsonValue$1, StartResult, StartResult as StartResult$1, TrajectoryCaptureOptions } from "@copilotkit/learning";
6
-
7
- //#region src/core/learning-bridge.d.ts
8
- /** Interaction capture settings for {@link CopilotKitCore}. See `@copilotkit/learning`. */
9
- interface LegacyLearningConfig extends Omit<CollectorOptions, "enrich" | "capture"> {
10
- /** Capture modules, plus `agentText: false` to omit message text (included in full by default). */
11
- capture?: CaptureOptions & {
12
- agentText?: boolean;
13
- };
14
- }
15
- type LearningConfig = LegacyLearningConfig | (TrajectoryCaptureOptions & {
16
- sink?: undefined;
17
- });
18
- type TrajectoryStartOptions = {
19
- trajectoryId?: string;
20
- /**
21
- * Used only by explicit custom sinks. Authenticated capture warns and ignores
22
- * this option; assign Learning Spaces on the server with
23
- * `getTrajectoryLearningContainerIds` on `CopilotKitIntelligence`.
24
- */
25
- learningContainerIds?: string[];
26
- };
27
- /** Returned by {@link CopilotKitCore.registerOpenThread}. */
28
- interface OpenThreadRegistration {
29
- /** The view now shows another Thread. */
30
- update(threadId: string): void;
31
- /** The view that showed this Thread is gone. */
32
- unregister(): void;
33
- }
34
- //#endregion
35
- //#region src/types.d.ts
36
- /**
37
- * Status of a tool call execution
38
- */
39
- declare enum ToolCallStatus {
40
- InProgress = "inProgress",
41
- Executing = "executing",
42
- Complete = "complete"
43
- }
44
- type CopilotRuntimeTransport = "rest" | "single" | "auto";
45
- /**
46
- * Context passed to a frontend tool handler
47
- */
48
- type FrontendToolHandlerContext = {
49
- toolCall: ToolCall;
50
- /**
51
- * The agent that invoked the tool. Absent when the tool is invoked through
52
- * the WebMCP browser API (`document.modelContext`), which has no agent.
53
- */
54
- agent?: AbstractAgent;
55
- /** Aborted when `stopAgent()` is called. Handlers can check `signal.aborted`
56
- * or pass the signal to fetch/setTimeout to cooperatively cancel. */
57
- signal?: AbortSignal;
58
- /**
59
- * True when CopilotKit runs this call while restoring a thread's history on
60
- * connect, for a call that a previous page or client left without a result.
61
- * Absent for a call made by a live run. See `reconnectBehavior`.
62
- */
63
- isReplay?: boolean;
64
- };
65
- /**
66
- * What a frontend tool does with its own calls that are still unanswered when
67
- * a thread's history is restored (a reload, a remount, or a thread switch).
68
- * Only calls after the latest user message are eligible; older unanswered
69
- * calls remain historical and never resume work on reconnect.
70
- *
71
- * - `"passive"` (default) — show the call, but do not run the handler. Nothing
72
- * the handler did runs twice.
73
- * - `"resume-pending"` — run the handler for each call that has no result,
74
- * with `isReplay: true` in its context, then continue the run as usual
75
- * (follow-up included, unless `followUp` is false).
76
- *
77
- * Use `"resume-pending"` only for a handler that is safe to run more than
78
- * once. A call does not start twice at the same time in one CopilotKit
79
- * instance, but it can run again after a stop or a thread switch if its result
80
- * never reached the agent, and two tabs or devices that restore the same
81
- * thread can each run it.
82
- *
83
- * If one assistant message also calls a tool that stays passive, the follow-up
84
- * run sends that call without a result, which some model providers reject.
85
- * Opt in every tool the agent calls together, or set `followUp: false`.
86
- */
87
- type FrontendToolReconnectBehavior = "passive" | "resume-pending";
88
- /**
89
- * Annotations for a WebMCP tool, passed through to
90
- * `document.modelContext.registerTool`. Mirrors the WebMCP spec's tool
91
- * annotations. These are hints for browser agents only — they do not enforce
92
- * any policy on their own.
93
- */
94
- type WebMCPToolAnnotations = {
95
- /**
96
- * Hint that the tool does not modify state. Defaults to false.
97
- * Set it for read-only tools (search, status lookup, ...).
98
- */
99
- readOnlyHint?: boolean;
100
- /**
101
- * Hint that the tool's output may contain untrusted content
102
- * (e.g. user-generated or external content). Defaults to false.
103
- */
104
- untrustedContentHint?: boolean;
105
- };
106
- /**
107
- * WebMCP registration options for a frontend tool.
108
- */
109
- type WebMCPToolConfig = {
110
- /** Hints that tell browser agents how the tool behaves. */annotations?: WebMCPToolAnnotations;
111
- };
112
- type FrontendTool<T extends Record<string, unknown> = Record<string, unknown>> = {
113
- /**
114
- * @internal Classifies local execution. Omitted means an ordinary frontend
115
- * tool. Pending calls in the latest user turn are eligible for restoration.
116
- * Human-in-the-loop handlers are restored from history replay;
117
- * other handlers only with `reconnectBehavior: "resume-pending"`. Tools
118
- * without a handler restore missing empty completion results automatically.
119
- * This field is not sent to the agent as part of the tool schema.
120
- */
121
- type?: "frontend" | "human-in-the-loop";
122
- name: string;
123
- description?: string;
124
- parameters?: StandardSchemaV1<any, T>;
125
- handler?: (args: T, context: FrontendToolHandlerContext) => Promise<unknown>;
126
- followUp?: boolean;
127
- /**
128
- * Whether to run the handler again for a call that is still unanswered when
129
- * the thread's history is restored. Defaults to `"passive"`. See
130
- * {@link FrontendToolReconnectBehavior}.
131
- */
132
- reconnectBehavior?: FrontendToolReconnectBehavior;
133
- /**
134
- * Optional agent ID to constrain this tool to a specific agent.
135
- * If specified, this tool will only be available to the specified agent.
136
- */
137
- agentId?: string;
138
- /**
139
- * Whether this tool is available to the agent.
140
- * Set to false to hide the tool from the agent without unregistering it.
141
- * Defaults to true when not specified.
142
- */
143
- available?: boolean;
144
- /**
145
- * Also expose this tool to browser agents through the WebMCP API
146
- * (`document.modelContext`) while keeping the normal agent registration.
147
- *
148
- * - `true` — register with default annotations.
149
- * - `{ annotations }` — register with the given WebMCP annotations.
150
- * - `false` / `undefined` — do not register.
151
- *
152
- * The tool's `handler` runs when a browser agent calls the tool; the handler
153
- * context then has no `agent`. No-op in environments without WebMCP support
154
- * (e.g. React Native, or browsers without the API enabled).
155
- */
156
- webmcp?: boolean | WebMCPToolConfig;
157
- };
158
- type Suggestion = {
159
- title: string;
160
- message: string; /** Indicates whether this suggestion is still being generated. */
161
- isLoading: boolean; /** Optional CSS class name applied to the suggestion pill. */
162
- className?: string;
163
- };
164
- type SuggestionAvailability = "before-first-message" | "after-first-message" | "always" | "disabled";
165
- type DynamicSuggestionsConfig = {
166
- /**
167
- * A prompt or instructions for the GPT to generate suggestions.
168
- */
169
- instructions: string;
170
- /**
171
- * The minimum number of suggestions to generate. Defaults to `1`.
172
- * @default 1
173
- */
174
- minSuggestions?: number;
175
- /**
176
- * The maximum number of suggestions to generate. Defaults to `3`.
177
- * @default 1
178
- */
179
- maxSuggestions?: number;
180
- /**
181
- * When the suggestions are available. Defaults to "after-first-message".
182
- */
183
- available?: SuggestionAvailability;
184
- /**
185
- * The agent ID of the provider of the suggestions. Defaults to `"default"`.
186
- */
187
- providerAgentId?: string;
188
- /**
189
- * The agent ID of the consumer of the suggestions. Defaults to `"*"` (all agents).
190
- */
191
- consumerAgentId?: string;
192
- };
193
- type StaticSuggestionsConfig = {
194
- /**
195
- * The suggestions to display.
196
- */
197
- suggestions: Omit<Suggestion, "isLoading">[];
198
- /**
199
- * When the suggestions are available. Defaults to "before-first-message".
200
- */
201
- available?: SuggestionAvailability;
202
- /**
203
- * The agent ID of the consumer of the suggestions. Defaults to `"*"` (all agents).
204
- */
205
- consumerAgentId?: string;
206
- };
207
- type SuggestionsConfig = DynamicSuggestionsConfig | StaticSuggestionsConfig;
208
- //#endregion
209
- //#region src/utils/connect-replay.d.ts
210
- /** Internal connection callbacks; HTTP connections keep their EOF behavior. */
211
- interface ConnectionReplayLifecycle {
212
- onReplayStarted?: () => void;
213
- onReplayFinished?: () => void;
214
- }
215
- /**
216
- * Whether a RUN_ERROR received while connecting is stored history (`replay`)
217
- * or a failure of a run that is happening now (`live`). `unknown` when the
218
- * transport reports no replay boundaries, as with HTTP `/connect`.
219
- */
220
- type RunErrorPhase = "replay" | "live" | "unknown";
221
- //#endregion
222
- //#region src/core/message-filter.d.ts
223
- /**
224
- * Rewrites the message list a runtime agent sends on each run.
225
- *
226
- * CopilotKit sends the whole thread on every request. When the backend already
227
- * stores the conversation (a LangGraph checkpointer, a Mastra memory store, a
228
- * Strands `SessionManager`, an Agent Framework chat history provider), that
229
- * history is dead weight: the payload grows without bound, and an agent that
230
- * merges the inbound list with its own store can show the model every turn
231
- * twice. See https://github.com/CopilotKit/CopilotKit/issues/1482.
232
- *
233
- * The filter runs on the outbound payload only. It never touches the messages
234
- * the UI renders, so trimming here does not shorten the visible transcript.
235
- *
236
- * Return the messages to send. Returning an empty array is valid and means
237
- * "send nothing but the run metadata".
238
- *
239
- * @param messages - The thread as the client holds it, in order, with
240
- * `activity`-role messages already removed.
241
- * @param context - Which agent is about to run.
242
- */
243
- type CopilotKitMessageFilter = (messages: Message[], context: {
244
- agentId: string;
245
- }) => Message[];
246
- //#endregion
247
- //#region src/agent.d.ts
248
- type ResolvedRuntimeMode = RuntimeMode$1 | "pending";
249
- interface ProxiedCopilotRuntimeAgentConfig extends Omit<HttpAgentConfig, "url"> {
250
- runtimeUrl?: string;
251
- transport?: CopilotRuntimeTransport;
252
- credentials?: RequestCredentials;
253
- runtimeMode?: ResolvedRuntimeMode;
254
- intelligence?: IntelligenceRuntimeInfo$1;
255
- capabilities?: AgentCapabilities;
256
- debug?: ResolvedDebugConfig;
257
- /**
258
- * When set, runtime requests (HTTP path, single-route envelope, intelligence
259
- * delegate) are routed to this agent on the runtime instead of `agentId`.
260
- * The local `agentId` remains the registry key used for subscriber
261
- * bookkeeping; only outbound routing is overridden.
262
- */
263
- runtimeAgentId?: string;
264
- /**
265
- * Rewrites the outbound message list on every run. See
266
- * {@link CopilotKitMessageFilter}. Not applied in Intelligence mode.
267
- */
268
- messageFilter?: CopilotKitMessageFilter;
269
- }
270
- declare class ProxiedCopilotRuntimeAgent extends HttpAgent {
271
- #private;
272
- runtimeUrl?: string;
273
- credentials?: RequestCredentials;
274
- readonly runtimeAgentId?: string;
275
- private transport;
276
- /**
277
- * The runtime URL exactly as the caller supplied it. `runtimeUrl` is the
278
- * slash-stripped form used for path joins; the single-route endpoint (run,
279
- * connect, stop, info envelopes) is this verbatim value, because a trailing
280
- * slash can select a different proxy location.
281
- */
282
- private readonly runtimeEndpointUrl?;
283
- private singleEndpointUrl?;
284
- private runtimeMode;
285
- private intelligence?;
286
- private _capabilities?;
287
- private delegate?;
288
- private runtimeInfoPromise?;
289
- private connectionAttempt?;
290
- private _messageFilter?;
291
- /**
292
- * The HTTP `run` this agent started and has not yet seen finish, as the
293
- * exact `{ threadId, runId }` it POSTed. `abortRun` narrows `/stop` to this
294
- * run only while `threadId` still matches: `threadId` is a public field the
295
- * host may reassign under a live run, and a runId from another thread must
296
- * not be sent as if it were this thread's. Released when the run stream
297
- * finalizes, cleared on `connect` (a reconnected thread may run under a
298
- * runId this client never saw) and never copied by `clone`. Without a
299
- * provable active run the stop stays thread-wide.
300
- */
301
- private activeRun?;
302
- constructor(config: ProxiedCopilotRuntimeAgentConfig);
303
- /**
304
- * Adopt the runtime mode a fresh `/info` just reported.
305
- *
306
- * A live proxy outlives the runtime configuration that minted it: a
307
- * redeploy, an env-var change or a rollback can flip `intelligence` → `sse`
308
- * under a page that is already open. The registry preserves the proxy across
309
- * that re-sync on purpose — it is backing an open conversation — so the new
310
- * mode is pushed onto the instance here instead of replacing it.
311
- *
312
- * Without this the mode was decided once, at construction, and `run()` kept
313
- * taking the delegate path against a runtime serving plain SSE, where
314
- * `response.json()` on a `text/event-stream` body throws for the rest of the
315
- * page's life. See #7130.
316
- *
317
- * A delegate built for the old mode is torn down: it speaks a protocol the
318
- * runtime no longer serves, and it may be holding a websocket open. The
319
- * memoized `/info` promise goes with it — it answered for the old
320
- * configuration, so a later `ensureRuntimeConfiguration()` must re-ask
321
- * rather than treat that answer as current.
322
- *
323
- * Only `wsUrl` is compared on the Intelligence metadata, because that is the
324
- * one field the delegate bakes in at construction.
325
- */
326
- adoptRuntimeMode(runtimeMode: ResolvedRuntimeMode, intelligence: IntelligenceRuntimeInfo$1 | undefined): void;
327
- /**
328
- * The agent id used for outbound runtime requests — `runtimeAgentId` when
329
- * set (manually-registered proxy), otherwise `agentId` (registry id
330
- * matches runtime id). Subscriber bookkeeping keeps using `agentId`
331
- * directly.
332
- *
333
- * Throws when both are unset: a proxy reaching an HTTP path with no
334
- * routable id is a bug, and a missing id would otherwise produce a
335
- * malformed `/agent//run` or `/agent/undefined/connect` URL silently.
336
- */
337
- private routedAgentId;
338
- get capabilities(): AgentCapabilities | undefined;
339
- /**
340
- * The filter applied to the outbound message list on every run.
341
- *
342
- * Registry-owned. `AgentRegistry` writes it whenever the core-level filter
343
- * changes, so an agent discovered before the app configured one still picks
344
- * it up — and so a value written here by hand is replaced on the registry's
345
- * next sweep. Configure it through `CopilotKitCore` instead.
346
- */
347
- get messageFilter(): CopilotKitMessageFilter | undefined;
348
- set messageFilter(filter: CopilotKitMessageFilter | undefined);
349
- requestInit(input: RunAgentInput): RequestInit;
350
- getCapabilities(): Promise<AgentCapabilities>;
351
- detachActiveRun(): Promise<void>;
352
- abortRun(): void;
353
- connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
354
- connect(input: RunAgentInput, lifecycle?: ConnectionReplayLifecycle): Observable<BaseEvent>;
355
- run(input: RunAgentInput): Observable<BaseEvent>;
356
- clone(): ProxiedCopilotRuntimeAgent;
357
- /** Run presentation-only MCP reads on a separate client agent so their
358
- * lifecycle cannot replace an in-flight approval's detach/completion state. */
359
- ɵrunMcpResourceRead(parameters: RunAgentParameters): Promise<RunAgentResult>;
360
- /**
361
- * Drop the delegate's cached `lastSeenEventId` for this thread so
362
- * the next connect requests a full historical replay from the
363
- * gateway. Used by `RunHandler.connectAgent` on a detected thread
364
- * switch (the chat moved between threads, so its local
365
- * messages/state are about to be cleared and need rebuilding from
366
- * the gateway). Skipped on same-thread churn re-connects so the
367
- * gateway can resume from the cursor instead.
368
- *
369
- * No-op for non-Intelligence runtime modes — the HTTP transport
370
- * doesn't replay.
371
- */
372
- clearReplayCursor(threadId: string): void;
373
- private resolveDelegate;
374
- /** Resolve transport and runtime mode before the first outbound request. */
375
- private ensureRuntimeConfiguration;
376
- private fetchRuntimeInfo;
377
- private fetchRuntimeInfoAutoDetect;
378
- private createSingleRouteRequestInit;
379
- private createIntelligenceDelegate;
380
- private syncDelegate;
381
- }
382
- //#endregion
383
- //#region src/core/agent-registry.d.ts
384
- declare const ɵRUNTIME_PROBE_TIMEOUT_MS = 5000;
385
- interface CopilotKitCoreAddAgentParams {
386
- id: string;
387
- agent: AbstractAgent;
388
- }
389
- /**
390
- * Parameters for registering a proxied agent against an existing runtime agent.
391
- */
392
- interface CopilotKitCoreRegisterProxiedAgentParams {
393
- /**
394
- * The local registry id under which the proxy is registered. Used by
395
- * `useAgent`, state-manager subscriptions, and all subscriber bookkeeping.
396
- * Must not collide with any existing local or runtime-discovered agent id.
397
- */
398
- agentId: string;
399
- /**
400
- * The id of the runtime agent that this proxy routes outbound HTTP requests
401
- * to. Invisible to subscribers — only affects URL paths and single-route
402
- * envelopes.
403
- */
404
- runtimeAgentId: string;
405
- }
406
- interface CopilotKitCoreRegisterProxiedAgentResult {
407
- agent: ProxiedCopilotRuntimeAgent;
408
- unregister: () => void;
409
- }
410
- /**
411
- * Manages agent registration, lifecycle, and runtime connectivity for CopilotKitCore.
412
- * Handles both local development agents and remote runtime agents.
413
- */
414
- declare class AgentRegistry {
415
- private core;
416
- private _agents;
417
- private localAgents;
418
- private remoteAgents;
419
- private readonly mintedThreadIds;
420
- private _runtimeUrl?;
421
- /** The runtime URL as the caller supplied it; the single-route endpoint uses it verbatim. */
422
- private _runtimeEndpointUrl?;
423
- private _connectionInFlight?;
424
- private _runtimeConnectionGeneration;
425
- private _activeRuntimeConnectionAttempt?;
426
- private _runtimeEntitlementRetryTimer?;
427
- private _runtimeEntitlementRetryAttemptedKey?;
428
- private _runtimeEntitlementRetryPendingKey?;
429
- private _runtimeVersion?;
430
- private _runtimeConnectionStatus;
431
- private _runtimeTransport;
432
- private _requestedTransport;
433
- private _audioFileTranscriptionEnabled;
434
- private _runtimeMode;
435
- private _intelligence?;
436
- private _threadEndpoints?;
437
- private _singleRouteResourceOperations;
438
- private _suggestions?;
439
- private _inspectorLearning;
440
- private _inspectorMetadata?;
441
- private _inspectorMetadataSupported;
442
- private inspectorMetadataRefreshReady;
443
- private inspectorMetadataConnectionGeneration;
444
- private inspectorMetadataGeneration;
445
- private inspectorMetadataHeadersGeneration;
446
- private inspectorMetadataCredentialsGeneration;
447
- private inspectorMetadataAbortController?;
448
- private inspectorMetadataNotificationQueue;
449
- private _a2uiEnabled;
450
- private _a2uiAgents?;
451
- private _openGenerativeUIEnabled;
452
- private _licenseStatus?;
453
- private _runtimeEntitlements?;
454
- private _telemetryDisabled;
455
- private remoteAgentConnections;
456
- private runtimeFetch?;
457
- private runtimeProbeInFlight;
458
- private runtimeProbeToken;
459
- private runtimeProbeAbortController?;
460
- private runtimeRecoveryRunning;
461
- private runtimeRecoveryPending;
462
- private runtimeHealthGeneration;
463
- /**
464
- * The headers each HttpAgent was constructed with, captured on the first
465
- * `applyHeadersToAgent` call for that agent (which, for agents the registry
466
- * owns, happens at registration before any core headers are applied). Core
467
- * headers are merged ON TOP of this baseline so that headers configured
468
- * directly on an agent (e.g. an `Authorization` for a self-hosted backend)
469
- * survive registration instead of being silently replaced. The baseline is
470
- * captured once and never re-captured, so a later direct mutation of
471
- * `agent.headers` is not folded into it. See #5635.
472
- */
473
- private agentOwnHeaders;
474
- constructor(core: CopilotKitCore);
475
- /**
476
- * Get all agents as a readonly record
477
- */
478
- get agents(): Readonly<Record<string, AbstractAgent>>;
479
- get runtimeUrl(): string | undefined;
480
- get runtimeVersion(): string | undefined;
481
- get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus;
482
- get runtimeTransport(): CopilotRuntimeTransport;
483
- get audioFileTranscriptionEnabled(): boolean;
484
- get runtimeMode(): RuntimeMode$1;
485
- get intelligence(): IntelligenceRuntimeInfo$1 | undefined;
486
- get threadEndpoints(): ThreadEndpointRuntimeInfo$1 | undefined;
487
- get suggestions(): boolean | undefined;
488
- get inspectorLearning(): boolean;
489
- get inspectorMetadata(): InspectorMetadataV1$1 | undefined;
490
- get a2uiEnabled(): boolean;
491
- /**
492
- * Agent ids the runtime applies A2UI to (#5369). `undefined` means A2UI
493
- * applies to every agent — or is disabled entirely; check `a2uiEnabled`.
494
- */
495
- get a2uiAgents(): string[] | undefined;
496
- get openGenerativeUIEnabled(): boolean;
497
- get licenseStatus(): RuntimeLicenseStatus$1 | undefined;
498
- /** Structured Runtime entitlement authority advertised by `/info`. */
499
- get runtimeEntitlements(): RuntimeEntitlementResponse | undefined;
500
- get runtimeEntitlementRetryPending(): boolean;
501
- get telemetryDisabled(): boolean;
502
- /**
503
- * Initialize agents from configuration
504
- */
505
- initialize(agents: Record<string, AbstractAgent>): void;
506
- /**
507
- * Set the runtime URL and update connection
508
- */
509
- setRuntimeUrl(runtimeUrl: string | undefined, options?: {
510
- deferConnection?: boolean;
511
- }): void;
512
- /**
513
- * Start the initial runtime connection if it has not been started yet.
514
- *
515
- * Backs {@link CopilotKitCore.connect}. Idempotent: it only kicks off a fetch
516
- * when a `runtimeUrl` is set and the connection is still `Disconnected` (its
517
- * state before any connect attempt). `updateRuntimeConnection` flips the
518
- * status to `Connecting` synchronously, so a second call — e.g. React
519
- * StrictMode double-invoking the mount effect — bails here. A genuine config
520
- * change still reconnects through `setRuntimeUrl`/`setRuntimeTransport`. See
521
- * #5801.
522
- */
523
- connectRuntime(): void;
524
- setRuntimeTransport(runtimeTransport: CopilotRuntimeTransport): void;
525
- private hasLiveRuntimeKnowledgeToProtect;
526
- private reconcileRecoveredAgents;
527
- private carriesConversationState;
528
- private abandonRuntimeHealthProbe;
529
- /**
530
- * Set all agents at once (for development use)
531
- */
532
- setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void;
533
- /**
534
- * Add a single agent (for development use)
535
- */
536
- addAgent__unsafe_dev_only({
537
- id,
538
- agent
539
- }: CopilotKitCoreAddAgentParams): void;
540
- /**
541
- * Remove an agent by ID (for development use)
542
- */
543
- removeAgent__unsafe_dev_only(id: string): void;
544
- /**
545
- * Register a proxied agent that routes outbound runtime requests to an
546
- * existing runtime agent (`runtimeAgentId`) while exposing a distinct local
547
- * registry id (`agentId`). Throws if `agentId` is already taken by either a
548
- * local or runtime-discovered agent.
549
- *
550
- * Use this to mount multiple frontend agents against a single runtime
551
- * agent (e.g. a chat-1 / chat-2 pair both proxying to "default") without
552
- * implicit per-thread cloning. The returned `unregister` removes the proxy
553
- * from the registry and emits `onAgentsChanged`.
554
- */
555
- registerProxiedAgent({
556
- agentId,
557
- runtimeAgentId
558
- }: CopilotKitCoreRegisterProxiedAgentParams): CopilotKitCoreRegisterProxiedAgentResult;
559
- /**
560
- * Get an agent by ID
561
- */
562
- getAgent(id: string): AbstractAgent | undefined;
563
- /**
564
- * Shared core-and-own-header merge for a single agent. Captures the
565
- * agent's construction-time headers once (the per-agent baseline in
566
- * `agentOwnHeaders`), then either keeps only that baseline — a
567
- * `ProxiedCopilotRuntimeAgent`, whose core headers are added by
568
- * `ɵruntimeFetch` when each request is actually sent instead, so a key the
569
- * builder stops returning can never ride along from a stale copy baked
570
- * onto the agent (see #1937) — or merges `coreHeaders` on top of it (any
571
- * other `HttpAgent`; core wins on a key conflict, see #5635).
572
- */
573
- private applyHeaderRecordToAgent;
574
- /**
575
- * Apply the last resolved header snapshot to an agent, merged ON TOP of
576
- * the agent's own construction-time headers. Non-`HttpAgent` agents are
577
- * left untouched because only `HttpAgent` carries a `headers` field. See
578
- * #5635.
579
- *
580
- * Never invokes the headers builder — safe to call from anywhere (dev-only
581
- * registration helpers, a React effect that re-runs on every render)
582
- * without risking a synchronous throw or an unhandled async rejection from
583
- * a user-supplied builder. Use `prepareAgentHeadersForRun` (friends-only)
584
- * on the run/connect path, where a builder failure can be awaited and
585
- * reported once.
586
- */
587
- applyHeadersToAgent(agent: AbstractAgent): void;
588
- /**
589
- * Apply the last resolved header snapshot to every agent, without
590
- * triggering a builder call per agent. Used by `initialize` and
591
- * `setHeaders`; a run re-applies with fresh headers anyway (see
592
- * `prepareAgentHeadersForRun`).
593
- */
594
- applyHeadersToAgents(agents: Record<string, AbstractAgent>): void;
595
- /**
596
- * Resolve headers fresh and apply them to `agent` right before a run or
597
- * connect actually sends (#1937) — the resolving counterpart to
598
- * `applyHeadersToAgent`. Friends-only: only the run handler should call
599
- * this, since resolving can invoke a user-supplied builder that throws
600
- * synchronously or returns a rejecting promise. Resolution is synchronous
601
- * for a record or a sync builder; this returns a promise only when an
602
- * async builder must be awaited first, and callers that need the write to
603
- * have landed before continuing must await a returned promise.
604
- *
605
- * A `ProxiedCopilotRuntimeAgent` never invokes the builder here: its core
606
- * headers are added by `ɵruntimeFetch` at send time instead, so only its
607
- * own headers are (re)applied.
608
- */
609
- prepareAgentHeadersForRun(agent: AbstractAgent): void | Promise<void>;
610
- /**
611
- * Apply current credentials to an agent
612
- */
613
- applyCredentialsToAgent(agent: AbstractAgent): void;
614
- /**
615
- * Apply current credentials to all agents
616
- */
617
- applyCredentialsToAgents(agents: Record<string, AbstractAgent>): void;
618
- /**
619
- * Carry the mode a fresh `/info` reported onto a proxy this re-sync kept.
620
- *
621
- * `canReuseRuntimeAgent` deliberately ignores the mode: a preserved proxy is
622
- * backing an open conversation, and replacing the instance to change one
623
- * field would drop it. The mode is therefore pushed onto the survivor here,
624
- * the same way headers and credentials are. Without it the mode was fixed at
625
- * construction, so a runtime that flipped `intelligence` → `sse` under an
626
- * open page left every later run on the delegate path. See #7130.
627
- */
628
- applyRuntimeModeToAgent(agent: AbstractAgent, runtimeInfo: RuntimeInfo): void;
629
- /**
630
- * Apply the core's message filter to an agent.
631
- *
632
- * The test is the class, not which bucket the agent is registered in: every
633
- * `ProxiedCopilotRuntimeAgent` gets the core filter, whether it came from
634
- * `/info` or from `registerProxiedAgent` (which files its proxy under
635
- * `localAgents`). Agents of any other class are left untouched — an
636
- * `AbstractAgent` the app built has no such hook, and its owner already has
637
- * the AG-UI middleware seam.
638
- *
639
- * This is the sole writer of `agent.messageFilter` in normal operation. The
640
- * public setter exists for the registry and for tests; a value written
641
- * directly onto an agent is replaced the next time the registry sweeps, the
642
- * same way per-agent credentials are.
643
- */
644
- applyMessageFilterToAgent(agent: AbstractAgent): void;
645
- /**
646
- * Apply the core's message filter to all agents
647
- */
648
- applyMessageFilterToAgents(agents: Record<string, AbstractAgent>): void;
649
- /** Preserve the exact configured URL when posting to a single endpoint. */
650
- get runtimeEndpointUrl(): string | undefined;
651
- createRuntimeFetch(): typeof fetch;
652
- private armRuntimeRequestWatchdog;
653
- applyRuntimeFetchToAgent(agent: AbstractAgent): void;
654
- applyRuntimeFetchToAgents(agents: Record<string, AbstractAgent>): void;
655
- /** Refresh metadata after the Core header snapshot changes. */
656
- handleHeadersChanged(): void;
657
- /** Refresh metadata after the Core credentials mode changes. */
658
- handleCredentialsChanged(): void;
659
- /**
660
- * Fetch trusted inspector metadata independently from runtime discovery.
661
- * Optional-route failures degrade to absent metadata and never affect the
662
- * runtime connection state.
663
- */
664
- refreshInspectorMetadata(): Promise<void>;
665
- private fetchInspectorMetadataRest;
666
- private fetchInspectorMetadataSingle;
667
- private isInspectorMetadataRequestCurrent;
668
- private invalidateInspectorMetadataConnection;
669
- /**
670
- * Publish one state transition without making refreshes wait on subscribers.
671
- * Each queued callback closes over its readonly snapshot so reentrant changes
672
- * cannot replace the value that an older publication is still delivering.
673
- */
674
- private setInspectorMetadata;
675
- private setRuntimeConnectionStatus;
676
- private handleRuntimeRequestOutcome;
677
- private fetchRuntimeInfoWithTimeout;
678
- private probeRuntimeReachability;
679
- private markRuntimeUnreachable;
680
- private recoverRuntimeConnection;
681
- /**
682
- * Update runtime connection and fetch remote agents
683
- */
684
- private updateRuntimeConnection;
685
- /** Return the stable key that scopes connection and entitlement retries. */
686
- private runtimeConnectionKey;
687
- /** Return whether a proxy still targets this Runtime connection. */
688
- private canReuseRuntimeAgent;
689
- /** Return whether an async attempt still owns the active Runtime state. */
690
- private isCurrentRuntimeConnection;
691
- /** Cancel a pending entitlement retry and allow a new target to retry. */
692
- private resetRuntimeEntitlementRetry;
693
- /** Schedule one retry after Runtime's short failed-entitlement cache. */
694
- private updateRuntimeEntitlementRetry;
695
- /** Start the bounded retry after the original connection has settled. */
696
- private executeRuntimeEntitlementRetry;
697
- private performRuntimeConnection;
698
- private fetchRuntimeInfo;
699
- /**
700
- * The URL a single-route request targets: the runtime URL as the caller
701
- * supplied it. `runtimeUrl` is the slash-stripped form used for path joins;
702
- * a trailing slash can select a different proxy location, so the endpoint
703
- * itself keeps it.
704
- */
705
- private singleEndpointUrlFor;
706
- private fetchRuntimeInfoSingle;
707
- /**
708
- * Auto-detect transport by trying REST first, then falling back to single-endpoint.
709
- * The caller commits the detected transport only after confirming this
710
- * connection attempt is still current.
711
- */
712
- private fetchRuntimeInfoAutoDetect;
713
- /**
714
- * Assign agent IDs to a record of agents
715
- */
716
- private assignAgentIds;
717
- /**
718
- * Validate and assign an agent ID
719
- */
720
- private validateAndAssignAgentId;
721
- /**
722
- * Notify subscribers of runtime status changes
723
- */
724
- private notifyRuntimeStatusChanged;
725
- /**
726
- * Notify subscribers of agent changes
727
- */
728
- private notifyAgentsChanged;
729
- private notifyInspectorMetadataChanged;
730
- }
731
- //#endregion
732
- //#region src/core/context-store.d.ts
733
- /**
734
- * A context entry with optional per-agent scoping.
735
- * When `agentIds` is set, the entry is forwarded only to runs of those agents;
736
- * when omitted, the entry is forwarded to every agent run.
737
- */
738
- interface ScopedContext extends Context {
739
- agentIds?: string[];
740
- }
741
- /**
742
- * Manages context storage and lifecycle for CopilotKitCore.
743
- * Context represents additional information available to agents during execution.
744
- */
745
- declare class ContextStore {
746
- private core;
747
- private _context;
748
- constructor(core: CopilotKitCore);
749
- /**
750
- * Get all context entries as a readonly record
751
- */
752
- get context(): Readonly<Record<string, ScopedContext>>;
753
- /**
754
- * Add a new context entry. Pass `agentIds` to restrict the entry to runs of
755
- * specific agents (#5369); omit it for context every agent should receive.
756
- * @returns The ID of the created context entry
757
- */
758
- addContext({
759
- description,
760
- value,
761
- agentIds
762
- }: ScopedContext): string;
763
- /**
764
- * Build the context array for a run of the given agent: entries scoped to
765
- * other agents are dropped, and the scoping metadata is stripped so only
766
- * protocol-shaped `{ description, value }` entries go over the wire.
767
- */
768
- getContextForAgent(agentId?: string): Context[];
769
- /**
770
- * Remove a context entry by ID
771
- */
772
- removeContext(id: string): void;
773
- /**
774
- * Notify all subscribers of context changes
775
- */
776
- private notifySubscribers;
777
- }
778
- //#endregion
779
- //#region src/core/state-manager.d.ts
780
- interface CopilotKitCoreContinuationHandoff {
781
- cancel(): void;
782
- bind(input: object): void;
783
- }
784
- /**
785
- * Manages state and message tracking by run for CopilotKitCore.
786
- * Tracks agent state snapshots and message-to-run associations.
787
- */
788
- declare class StateManager {
789
- private core;
790
- private stateByRun;
791
- private messageToRun;
792
- private rawEventByMessage;
793
- private activeRun;
794
- private agentSubscriptions;
795
- private pendingContinuations;
796
- private interruptedRuns;
797
- /** Find the interrupted logical run without consuming its pending answers. */
798
- getContinuationRunId(agent: AbstractAgent, input: Pick<RunAgentInput, "threadId" | "resume" | "forwardedProps">): string | undefined;
799
- constructor(core: CopilotKitCore);
800
- /**
801
- * Initialize state tracking for an agent
802
- */
803
- initialize(): void;
804
- markNextRunAsContinuation(agent: AbstractAgent, expectedRunId?: string): CopilotKitCoreContinuationHandoff;
805
- /**
806
- * Subscribe to an agent's events to track state and messages.
807
- */
808
- subscribeToAgent(agent: AbstractAgent): void;
809
- /**
810
- * Unsubscribe an agent's subscription.
811
- */
812
- unsubscribeFromAgent(agentId: string): void;
813
- /**
814
- * Get state for a specific run
815
- * Returns a deep copy to prevent external mutations
816
- */
817
- getStateByRun(agentId: string, threadId: string, runId: string): State | undefined;
818
- /**
819
- * Get runId associated with a message
820
- */
821
- getRunIdForMessage(agentId: string, threadId: string, messageId: string): string | undefined;
822
- /**
823
- * Get direct text-start metadata associated with a message.
824
- */
825
- getRawEventForMessage(agentId: string, threadId: string, messageId: string): unknown;
826
- /**
827
- * Get all states for an agent's thread
828
- */
829
- getStatesForThread(agentId: string, threadId: string): Map<string, State>;
830
- /**
831
- * Get all run IDs for an agent's thread
832
- */
833
- getRunIdsForThread(agentId: string, threadId: string): string[];
834
- /**
835
- * Handle run started event
836
- */
837
- private handleRunStarted;
838
- /**
839
- * Handle run finished event
840
- */
841
- private handleRunFinished;
842
- /**
843
- * Handle state snapshot event
844
- */
845
- private handleStateSnapshot;
846
- /**
847
- * Handle state delta event
848
- */
849
- private handleStateDelta;
850
- /**
851
- * Capture only defined metadata from a normalized direct text-start event.
852
- */
853
- private handleTextMessageStart;
854
- /**
855
- * Handle messages snapshot event
856
- */
857
- private handleMessagesSnapshot;
858
- /**
859
- * Handle new message event
860
- */
861
- private handleNewMessage;
862
- /**
863
- * Save state for a specific run
864
- */
865
- private saveState;
866
- /**
867
- * Associate a message with a run
868
- */
869
- private associateMessageWithRun;
870
- private pruneRawEvents;
871
- /**
872
- * Clear all state for an agent
873
- */
874
- clearAgentState(agentId: string): void;
875
- /**
876
- * Clear all state for a thread
877
- */
878
- clearThreadState(agentId: string, threadId: string): void;
879
- }
880
- //#endregion
881
- //#region src/core/run-handler.d.ts
882
- interface CopilotKitCoreRunAgentParams {
883
- agent: AbstractAgent;
884
- forwardedProps?: Record<string, unknown>;
885
- /**
886
- * Optional caller-supplied run identifier forwarded to the underlying AG-UI
887
- * agent. When omitted, the agent creates one.
888
- */
889
- runId?: string;
890
- /**
891
- * Per-interrupt responses addressing every open AG-UI interrupt from the
892
- * previous run. Forwarded to the agent as the standard `resume` array.
893
- */
894
- resume?: ResumeEntry[];
895
- }
896
- interface CopilotKitCoreConnectAgentParams {
897
- agent: AbstractAgent;
898
- }
899
- interface CopilotKitCoreGetToolParams {
900
- toolName: string;
901
- agentId?: string;
902
- }
903
- /**
904
- * Parameters for programmatic tool execution via `copilotkit.runTool()`.
905
- */
906
- interface CopilotKitCoreRunToolParams {
907
- /** Name of the registered frontend tool to execute. */
908
- name: string;
909
- /** Optional agent ID. If omitted, uses the default agent lookup. */
910
- agentId?: string;
911
- /** Parameters to pass to the tool handler. */
912
- parameters?: Record<string, unknown>;
913
- /**
914
- * Whether to trigger an LLM follow-up after tool execution.
915
- * - `false` (default): execute tool, add messages to history, done.
916
- * - `"generate"`: after execution, trigger another agent run so the LLM responds to the tool result.
917
- * - Any other string: add a user message with this text, then trigger another agent run.
918
- */
919
- followUp?: string | false;
920
- }
921
- /**
922
- * Result of programmatic tool execution via `copilotkit.runTool()`.
923
- */
924
- interface CopilotKitCoreRunToolResult {
925
- /** The unique ID of the tool call. */
926
- toolCallId: string;
927
- /** The stringified result from the tool handler. */
928
- result: string;
929
- /** Error message if the handler failed. */
930
- error?: string;
931
- }
932
- /**
933
- * A registered A2UI catalog component, as exposed to the inspector via
934
- * `CopilotKitCore.catalogComponents`. `schema` is an opaque JSON-schema-ish
935
- * value (the built catalog's Zod schema or a serialized form); the inspector
936
- * treats it as unknown. `description` is optional because the built
937
- * `ComponentApi` does not carry descriptions.
938
- */
939
- interface CopilotKitCoreCatalogComponent {
940
- name: string;
941
- description?: string;
942
- schema: unknown;
943
- }
944
- /**
945
- * Handles agent execution, tool calling, and agent connectivity for CopilotKitCore.
946
- * Manages the complete lifecycle of agent runs including tool execution and follow-ups.
947
- */
948
- declare class RunHandler {
949
- private core;
950
- /**
951
- * Tools owned by the framework provider, replaced wholesale by
952
- * {@link initialize} and {@link setTools} whenever the provider re-syncs its
953
- * props or runtime feature flags.
954
- */
955
- private _propTools;
956
- /**
957
- * Tools registered imperatively via {@link addTool} — `useFrontendTool`,
958
- * `useHumanInTheLoop`, and direct `core.addTool()` callers. Held separately
959
- * from {@link _propTools} so a provider re-sync cannot wipe them: they shared
960
- * one array before, so the `/info` response flipping `openGenerativeUI` (or
961
- * any other provider-prop change) silently dropped every hook-registered
962
- * tool (#4952). Key = `capabilityKey(name, agentId)`.
963
- */
964
- private _hookTools;
965
- /**
966
- * Memoized merge of both buckets, invalidated on every registry write.
967
- *
968
- * This is about identity, not speed: `tools` is public and used to return the
969
- * same array instance until something mutated the registry, so consumers can
970
- * hold it or use it as an effect dependency. Rebuilding the merge on every
971
- * read would hand out a new array each time.
972
- */
973
- private _cachedMergedTools;
974
- /**
975
- * The full list of A2UI catalog components registered by the provider.
976
- * Order is preserved for display in the inspector.
977
- */
978
- private _catalogComponents;
979
- /**
980
- * Names of catalog components the caller has explicitly disabled. A name
981
- * absent from this set is enabled (default). Survives re-registration so a
982
- * catalog identity change does not silently re-enable a disabled component.
983
- */
984
- private _disabledCatalogComponents;
985
- /**
986
- * Keys of frontend tools explicitly disabled at runtime via the Inspector's
987
- * Capabilities tool (`setToolEnabled`). Kept independently of each tool's own
988
- * `available` flag so a hook re-registering the tool (which resets
989
- * `available`) does not clobber the override. Key = `capabilityKey(name, agentId)`.
990
- */
991
- private _disabledToolKeys;
992
- /**
993
- * Registry keys already reported by {@link warnOnMissingToolParameters}.
994
- * Development only, and per instance rather than per module so tests and
995
- * multiple cores stay independent. Deliberately NOT cleared by
996
- * {@link removeTool}: `useFrontendTool` tears down and re-registers on every
997
- * dependency change, so clearing it would turn one warning into one per
998
- * render. Key = `capabilityKey(name, agentId)`.
999
- */
1000
- private _warnedMissingToolParameters;
1001
- /**
1002
- * Abort controllers of each agent's in-flight run chains (a run plus its
1003
- * recursive follow-ups), recording whether a chain, including its tool
1004
- * execution, was aborted via `stopAgent()` or `agent.abortRun()`. Every run
1005
- * that is not a follow-up gets a fresh controller, so a run started after
1006
- * Stop is not born aborted while the stopped chain is still settling. Keyed
1007
- * by agent so that stopping one agent never cancels another agent's run on
1008
- * the same core.
1009
- */
1010
- private _runAbortControllers;
1011
- /**
1012
- * Per-agent `runAgent` depth (in-flight runs plus their recursive
1013
- * follow-ups), so that the `agent.abortRun()` intercept is installed while
1014
- * any of the agent's runs is in flight and removed once none is, and so
1015
- * that runaway follow-up chains trip `MAX_FOLLOW_UP_DEPTH`.
1016
- */
1017
- private _runDepths;
1018
- /**
1019
- * Each agent's own `abortRun`, saved while RunHandler's intercept is
1020
- * installed. Restored only once none of the agent's runs is in flight, so an
1021
- * overlapping run keeps the intercept after an earlier run finishes.
1022
- */
1023
- private _originalAbortRuns;
1024
- /**
1025
- * The request each agent's in-flight run belongs to. Its follow-up runs
1026
- * send the same ID, so Intelligence counts the chain as one request.
1027
- */
1028
- private _activeRequestIds;
1029
- /**
1030
- * Request IDs of recent logical runs, so an approval that resumes a paused
1031
- * run sends the ID of the request that paused. Oldest entries go first.
1032
- */
1033
- private _requestIdByRun;
1034
- /**
1035
- * Keeps tools that opt in via `webmcp` registered on the page's WebMCP model
1036
- * context (`document.modelContext`), in addition to the normal agent
1037
- * registration. Reconciled on every tool registry mutation.
1038
- */
1039
- private _webmcpRegistry;
1040
- /**
1041
- * Tracks the threadId of the most recent `connectAgent` call so we
1042
- * can distinguish a fresh thread restore (different threadId than
1043
- * last time — chat is rebuilding state from scratch, must clear
1044
- * messages/state and ask the gateway for a full replay) from a
1045
- * same-thread churn re-connect (effect-dep churn or transient
1046
- * disconnect — local messages/state are still meaningful, must
1047
- * preserve them and let the gateway resume from
1048
- * `lastSeenEventId`).
1049
- *
1050
- * Tyler's bug fired because every `connectAgent` was treated as a
1051
- * fresh restore, which forced the gateway to replay the full
1052
- * thread history on every churn re-connect and amplified the
1053
- * downstream churn into duplicate `cpki_event_id` rows in the
1054
- * inspector and intermittent "Message not found" toasts.
1055
- */
1056
- private _lastConnectedThreadIdsByAgent;
1057
- private _lastActiveThreadIdsByAgent;
1058
- private _anonymousAgentIds;
1059
- private _nextAnonymousAgentId;
1060
- /** Prevent reconnects from starting an interaction already executing locally. */
1061
- private _executingToolCalls;
1062
- private _connectionGenerations;
1063
- private _runGenerations;
1064
- private _interactionAbortControllers;
1065
- constructor(core: CopilotKitCore);
1066
- /**
1067
- * Abort the current run. Called by `CopilotKitCore.stopAgent()` to signal
1068
- * that in-flight tool handlers should stop and `processAgentResult` should
1069
- * not start a follow-up run.
1070
- */
1071
- abortCurrentRun(agent: AbstractAgent): void;
1072
- private abortAgentRuns;
1073
- /** Signal of the agent's most recently started in-flight run, if any. */
1074
- private latestRunSignal;
1075
- /**
1076
- * Typed access to CopilotKitCore's internal ("friend") methods.
1077
- * Centralises the single unavoidable cast so call-sites stay clean.
1078
- */
1079
- private get _internal();
1080
- /**
1081
- * Return a stable restore-tracking key for the logical agent being
1082
- * connected. Named agents share their last-thread marker across proxy
1083
- * instances; anonymous agents fall back to object identity.
1084
- */
1085
- private getConnectRestoreKey;
1086
- /**
1087
- * Get all tools as a readonly array: provider-owned tools in registration
1088
- * order, with imperatively-added tools appended and taking precedence over a
1089
- * provider tool of the same name + agentId.
1090
- */
1091
- get tools(): Readonly<FrontendTool<any>[]>;
1092
- /**
1093
- * Initialize with tools
1094
- */
1095
- initialize(tools: FrontendTool<any>[]): void;
1096
- /**
1097
- * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),
1098
- * and shadows a provider tool of the same name + agentId.
1099
- */
1100
- addTool<T extends Record<string, unknown> = Record<string, unknown>>(tool: FrontendTool<T>): void;
1101
- /**
1102
- * Report, once per tool and at development time only, a tool registered with
1103
- * no `parameters` schema.
1104
- *
1105
- * `createToolSchema` substitutes `{ type: "object", properties: {} }` for a
1106
- * missing `parameters` and returns silently, and `parameters` is optional on
1107
- * `FrontendTool`, so nothing — not the compiler, not the runtime — tells the
1108
- * developer that the model was handed a tool with nothing to fill in. It then
1109
- * calls the tool with no arguments. `useComponent`, `useFrontendTool` and
1110
- * `useHumanInTheLoop` all funnel into {@link addTool}; the provider's `tools`
1111
- * prop funnels into {@link initialize} and {@link setTools}.
1112
- *
1113
- * A parameterless tool is legitimate (a HITL confirm dialog, say), so this
1114
- * stays a warning rather than an error. An explicit empty schema
1115
- * (`parameters: z.object({})`) is the way to say "takes none on purpose": it
1116
- * satisfies the check below and `createToolSchema` reduces it to the same
1117
- * advertised `{ type: "object", properties: {} }` that omitting `parameters`
1118
- * produces, so silencing the warning costs nothing on the wire.
1119
- */
1120
- private warnOnMissingToolParameters;
1121
- /**
1122
- * Remove a tool by name and optionally by agentId
1123
- */
1124
- removeTool(id: string, agentId?: string): void;
1125
- /**
1126
- * Get a tool by name and optionally by agentId.
1127
- * If agentId is provided, it will first look for an agent-specific tool,
1128
- * then fall back to a global tool with the same name.
1129
- */
1130
- getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined;
1131
- /**
1132
- * Set all provider-owned tools at once. Replaces the previous provider set;
1133
- * tools registered via {@link addTool} are unaffected.
1134
- */
1135
- setTools(tools: FrontendTool<any>[]): void;
1136
- /**
1137
- * Return the registered A2UI catalog components (readonly).
1138
- */
1139
- get catalogComponents(): ReadonlyArray<CopilotKitCoreCatalogComponent>;
1140
- /**
1141
- * Replace the registered catalog component list. Preserves the disabled set
1142
- * (by name) so re-registration does not re-enable disabled components.
1143
- */
1144
- setCatalogComponents(components: CopilotKitCoreCatalogComponent[]): void;
1145
- /**
1146
- * Enable or disable a catalog component by name.
1147
- */
1148
- setCatalogComponentEnabled(name: string, enabled: boolean): void;
1149
- /**
1150
- * Whether a catalog component is enabled. Unknown names default to enabled.
1151
- */
1152
- isCatalogComponentEnabled(name: string): boolean;
1153
- /**
1154
- * Connect an agent (establish initial connection)
1155
- */
1156
- connectAgent({
1157
- agent
1158
- }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult>;
1159
- /**
1160
- * Run an agent
1161
- */
1162
- runAgent({
1163
- agent,
1164
- forwardedProps,
1165
- resume,
1166
- runId
1167
- }: CopilotKitCoreRunAgentParams, continuationHandoff?: CopilotKitCoreContinuationHandoff,
1168
- /**
1169
- * Set only by `processAgentResult` for a recursive follow-up: the
1170
- * controller of the run being followed up, which the follow-up shares.
1171
- */
1172
-
1173
- followUpOf?: AbortController): Promise<RunAgentResult>;
1174
- private rememberRequestId;
1175
- /**
1176
- * Process agent result and execute tools
1177
- */
1178
- private processAgentResult;
1179
- /** A later user message supersedes pending work from an older turn. */
1180
- private isInLatestUserTurn;
1181
- /** Locate a missing result before saved results for later calls in its batch. */
1182
- private toolResultInsertionIndex;
1183
- /** Identify transport placeholders that must not count as completed answers. */
1184
- private isFrontendPlaceholderResult;
1185
- /**
1186
- * Shared handler execution logic used by executeSpecificTool, executeWildcardTool, and runTool.
1187
- * Handles arg parsing, subscriber notifications, handler invocation, result stringification,
1188
- * and error handling.
1189
- */
1190
- private executeToolHandler;
1191
- /**
1192
- * Execute a specific tool
1193
- */
1194
- private executeSpecificTool;
1195
- /**
1196
- * Execute a wildcard tool.
1197
- * Wildcard tools receive args wrapped as `{toolName, args}`, which differs from
1198
- * specific tools, so this method keeps its own arg-wrapping logic rather than
1199
- * delegating to `executeToolHandler`.
1200
- */
1201
- private executeWildcardTool;
1202
- /**
1203
- * Programmatically execute a registered frontend tool without going through an LLM turn.
1204
- * The handler runs, render components show up in the UI, and both the tool call and
1205
- * result messages are added to `agent.messages`.
1206
- */
1207
- runTool(params: CopilotKitCoreRunToolParams): Promise<CopilotKitCoreRunToolResult>;
1208
- /** Stable identity for a tool override: agent-scope + name (NUL-separated). */
1209
- private capabilityKey;
1210
- /**
1211
- * Enable/disable a registered frontend tool at runtime without unregistering
1212
- * it. A disabled tool is omitted from {@link buildFrontendTools}, so the agent
1213
- * never receives it. Unlike the per-tool `available` flag, this override
1214
- * survives the tool being re-registered.
1215
- */
1216
- setToolEnabled(name: string, enabled: boolean, agentId?: string): void;
1217
- /** Whether a tool is currently enabled (not overridden off). Defaults true. */
1218
- isToolEnabled(name: string, agentId?: string): boolean;
1219
- /**
1220
- * Build frontend tools for an agent
1221
- */
1222
- buildFrontendTools(agentId?: string): Tool[];
1223
- /**
1224
- * Reconcile the WebMCP registrations with the current tool registry. Tools
1225
- * opt in via `webmcp: true` or `webmcp: { annotations }`; the same
1226
- * availability rules as `buildFrontendTools` apply. WebMCP tools are
1227
- * page-level, so unlike the agent tool list they are not filtered by
1228
- * agentId — a name collision across agentIds keeps the first registration.
1229
- */
1230
- private syncWebMCP;
1231
- /**
1232
- * Create an agent error subscriber
1233
- */
1234
- private createAgentErrorSubscriber;
1235
- }
1236
- /**
1237
- * Ensures parsed tool arguments are a plain object.
1238
- * Throws for non-object values so the caller's catch block can emit
1239
- * a structured TOOL_ARGUMENT_PARSE_FAILED error.
1240
- *
1241
- * @internal Exported for testing only.
1242
- */
1243
- declare function ensureObjectArgs(parsed: unknown, toolName: string): Record<string, unknown>;
1244
- /**
1245
- * Parses raw tool call arguments into a validated object.
1246
- *
1247
- * Some LLM providers (e.g. @ai-sdk/openai-compatible) may send empty string "",
1248
- * null, or undefined instead of "{}". This function normalises those cases to an
1249
- * empty object so callers don't crash on JSON.parse("").
1250
- *
1251
- * A debug-level warning is emitted when the fallback triggers so silent coercion
1252
- * is observable in logs.
1253
- *
1254
- * @internal Exported for testing only.
1255
- */
1256
- declare function parseToolArguments(rawArgs: unknown, toolName: string): Record<string, unknown>;
1257
- //#endregion
1258
- //#region src/utils/micro-redux.d.ts
1259
- /**
1260
- * The minimal action shape used by this micro-redux implementation.
1261
- */
1262
- interface AnyAction {
1263
- type: string;
1264
- }
1265
- /**
1266
- * A typed action creator function with a `type` literal and runtime matcher.
1267
- */
1268
- type ActionCreator<Type extends string, Args extends unknown[] = unknown[], Action extends AnyAction & {
1269
- type: Type;
1270
- } = {
1271
- type: Type;
1272
- }> = ((...args: Args) => Action) & {
1273
- type: Type;
1274
- match(action: AnyAction): action is Action;
1275
- };
1276
- /**
1277
- * Extracts the action type produced by an action creator.
1278
- */
1279
- type ActionFromCreator<T> = T extends ((...args: any[]) => infer A) ? A : never;
1280
- /**
1281
- * Extracts a union of actions produced by a tuple/array of action creators.
1282
- */
1283
- type ActionFromCreators<Creators extends readonly ActionCreator<string, any[], any>[]> = ActionFromCreator<Creators[number]>;
1284
- /**
1285
- * A reducer transforms state in response to actions.
1286
- */
1287
- type Reducer<State, Action extends AnyAction = AnyAction> = (state: State | undefined, action: Action) => State;
1288
- /**
1289
- * A selector derives a value from state.
1290
- */
1291
- type Selector<State, Result> = (state: State) => Result;
1292
- /**
1293
- * Marker config for action creators that accept no payload.
1294
- */
1295
- interface EmptyActionConfig {
1296
- readonly kind: "empty";
1297
- }
1298
- declare const PROPS_MARKER: unique symbol;
1299
- /**
1300
- * Marker config for action creators that require payload props.
1301
- */
1302
- interface PropsActionConfig<Props extends Record<string, unknown>> {
1303
- readonly kind: "props";
1304
- readonly [PROPS_MARKER]?: Props;
1305
- }
1306
- /**
1307
- * Supported action creator config node in an action group.
1308
- */
1309
- type ActionConfig = EmptyActionConfig | PropsActionConfig<Record<string, unknown>>;
1310
- /**
1311
- * Shape of an action group declaration object.
1312
- */
1313
- type ActionGroupConfig = Record<string, ActionConfig>;
1314
- /**
1315
- * Maps an action group declaration to a strongly typed action-creator object.
1316
- */
1317
- type ActionGroupResult<Source extends string, Config extends ActionGroupConfig> = { [K in keyof Config & string]: Config[K] extends PropsActionConfig<infer P> ? ActionCreator<`[${Source}] ${K}`, [P], {
1318
- type: `[${Source}] ${K}`;
1319
- } & P> : ActionCreator<`[${Source}] ${K}`, [], {
1320
- type: `[${Source}] ${K}`;
1321
- }> };
1322
- interface OnReducerEntry<State, Action extends AnyAction = AnyAction, Creators extends readonly ActionCreator<string, any[], any>[] = readonly ActionCreator<string, any[], any>[]> {
1323
- creators: Creators;
1324
- reducer: (state: State, action: Action) => State;
1325
- }
1326
- type ActionFromOnReducerEntry<TEntry> = TEntry extends OnReducerEntry<any, infer TAction, any> ? TAction : never;
1327
- /**
1328
- * Effect contract for streams that emit actions to dispatch.
1329
- */
1330
- interface DispatchingEffect<State, InputAction extends AnyAction = AnyAction, OutputAction extends AnyAction = AnyAction> {
1331
- run: (actions$: Observable<InputAction>, state$: Observable<State>) => Observable<OutputAction>;
1332
- dispatch: true;
1333
- }
1334
- /**
1335
- * Effect contract for side-effect-only streams whose emissions are ignored.
1336
- */
1337
- interface NonDispatchingEffect<State, InputAction extends AnyAction = AnyAction> {
1338
- run: (actions$: Observable<InputAction>, state$: Observable<State>) => Observable<unknown>;
1339
- dispatch: false;
1340
- }
1341
- /**
1342
- * Union of supported effect shapes.
1343
- */
1344
- type Effect<State, InputAction extends AnyAction = AnyAction, OutputAction extends AnyAction = AnyAction> = DispatchingEffect<State, InputAction, OutputAction> | NonDispatchingEffect<State, InputAction>;
1345
- /**
1346
- * Lifecycle actions dispatched by the store.
1347
- */
1348
- type StoreLifecycleAction = {
1349
- type: "@@micro-redux/init";
1350
- } | {
1351
- type: "@@micro-redux/stop";
1352
- };
1353
- /**
1354
- * Options for a dispatching effect.
1355
- */
1356
- interface DispatchingEffectOptions {
1357
- dispatch?: true;
1358
- }
1359
- /**
1360
- * Options for a non-dispatching effect.
1361
- */
1362
- interface NonDispatchingEffectOptions {
1363
- dispatch: false;
1364
- }
1365
- /**
1366
- * Declares a payload-based action config for `createActionGroup`.
1367
- *
1368
- * @example
1369
- * ```ts
1370
- * const actions = createActionGroup("User", {
1371
- * loaded: props<{ id: string }>(),
1372
- * });
1373
- * ```
1374
- */
1375
- declare function props<Props extends Record<string, unknown>>(): PropsActionConfig<Props>;
1376
- /**
1377
- * Declares a no-payload action config for `createActionGroup`.
1378
- *
1379
- * @example
1380
- * ```ts
1381
- * const actions = createActionGroup("User", {
1382
- * reset: empty(),
1383
- * });
1384
- * ```
1385
- */
1386
- declare function empty(): EmptyActionConfig;
1387
- /**
1388
- * Creates a namespaced group of typed action creators.
1389
- *
1390
- * Action types are formatted as: `[Source] actionName`.
1391
- */
1392
- declare function createActionGroup<const Source extends string, const Config extends ActionGroupConfig>(source: Source, config: Config): ActionGroupResult<Source, Config>;
1393
- /**
1394
- * Registers one reducer handler for one or more action creators.
1395
- *
1396
- * @throws Error when called without at least one action creator and reducer.
1397
- */
1398
- declare function on<State, const Creators extends readonly ActionCreator<string, any[], any>[], Action extends ActionFromCreators<Creators>>(...args: [...creators: Creators, reducer: (state: State, action: Action) => State]): OnReducerEntry<State, Action, Creators>;
1399
- /**
1400
- * Creates a reducer from an initial state and `on(...)` handler entries.
1401
- *
1402
- * Unknown action types return the current state unchanged.
1403
- */
1404
- declare function createReducer<State, const Entries extends readonly OnReducerEntry<any, any, any>[]>(initialState: State, ...entries: Entries): Reducer<State, ActionFromOnReducerEntry<Entries[number]>>;
1405
- /**
1406
- * Creates a memoized selector from a single projector.
1407
- */
1408
- declare function createSelector<State, Result>(projector: (state: State) => Result): Selector<State, Result>;
1409
- /**
1410
- * Creates a memoized selector from input selectors and a projector.
1411
- *
1412
- * Memoization uses one-entry caching over the latest input selector values.
1413
- */
1414
- declare function createSelector<State, const Selectors extends readonly Selector<State, unknown>[], Result>(...args: [...selectors: Selectors, projector: (...inputs: { [K in keyof Selectors]: ReturnType<Selectors[K]> }) => Result]): Selector<State, Result>;
1415
- /**
1416
- * RxJS operator that maps state emissions through a selector and suppresses
1417
- * unchanged projected values via reference equality.
1418
- */
1419
- declare function select<State, Result>(selector: Selector<State, Result>): OperatorFunction<State, Result>;
1420
- /**
1421
- * RxJS operator that filters an action stream by action creators and narrows
1422
- * the output action type to the matched creator union.
1423
- *
1424
- * @throws Error when called without at least one action creator.
1425
- */
1426
- declare function ofType<const Creators extends readonly ActionCreator<string, any[], AnyAction>[]>(...creators: Creators): OperatorFunction<AnyAction, ActionFromCreators<Creators>>;
1427
- /**
1428
- * Creates a dispatching effect. Emitted actions are automatically dispatched.
1429
- */
1430
- declare function createEffect<State, InputAction extends AnyAction, OutputAction extends AnyAction>(factory: (actions$: Observable<InputAction>, state$: Observable<State>) => Observable<OutputAction>, options?: DispatchingEffectOptions): DispatchingEffect<State, InputAction, OutputAction>;
1431
- /**
1432
- * Creates a non-dispatching effect. Emitted values are ignored.
1433
- */
1434
- declare function createEffect<State, InputAction extends AnyAction>(factory: (actions$: Observable<InputAction>, state$: Observable<State>) => Observable<unknown>, options: NonDispatchingEffectOptions): NonDispatchingEffect<State, InputAction>;
1435
- /**
1436
- * Store interface returned by `createStore`.
1437
- */
1438
- interface Store<State, Action extends AnyAction = AnyAction> {
1439
- dispatch(action: Action): void;
1440
- getState(): State;
1441
- readonly state$: Observable<State>;
1442
- readonly actions$: Observable<Action | StoreLifecycleAction>;
1443
- select<Result>(selector: Selector<State, Result>): Observable<Result>;
1444
- init(): void;
1445
- stop(): void;
1446
- }
1447
- /**
1448
- * Creates a small observable store with reducer + effects.
1449
- *
1450
- * Behavior:
1451
- * - `init()` starts effects and dispatches `@@micro-redux/init`.
1452
- * - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.
1453
- * - Effect action observation is scheduled on `asapScheduler` to avoid
1454
- * synchronous re-entrancy in the effect loop.
1455
- * - Any effect error triggers fail-fast teardown and errors both `actions$`
1456
- * and `state$`.
1457
- */
1458
- declare function createStore<State, Action extends AnyAction = AnyAction>(options: {
1459
- reducer: Reducer<State, Action | StoreLifecycleAction>;
1460
- effects?: Array<Effect<State, Action | StoreLifecycleAction, Action>>;
1461
- }): Store<State, Action>;
1462
- //#endregion
1463
- //#region src/threads.d.ts
1464
- interface ThreadRecord {
1465
- id: string;
1466
- organizationId: string;
1467
- agentId: string;
1468
- createdById: string;
1469
- name: string | null;
1470
- archived: boolean;
1471
- createdAt: string;
1472
- updatedAt: string;
1473
- lastRunAt?: string;
1474
- }
1475
- interface ThreadRuntimeContext {
1476
- runtimeUrl: string;
1477
- /**
1478
- * Optional: `environment.fetch` is expected to be `ɵruntimeFetch`, which
1479
- * already resolves and overlays the current core headers at send time
1480
- * (#1937). Set explicitly only when the store's `fetch` does NOT already
1481
- * carry headers.
1482
- */
1483
- headers?: Record<string, string>;
1484
- wsUrl?: string;
1485
- agentId: string;
1486
- includeArchived?: boolean;
1487
- limit?: number;
1488
- }
1489
- type ThreadMetadataEvent = {
1490
- operation: "created" | "renamed" | "archived" | "unarchived" | "updated";
1491
- threadId: string;
1492
- userId: string;
1493
- organizationId: string;
1494
- occurredAt: string;
1495
- thread: ThreadRecord;
1496
- } | {
1497
- operation: "deleted";
1498
- threadId: string;
1499
- userId: string;
1500
- organizationId: string;
1501
- occurredAt: string;
1502
- deleted: {
1503
- id: string;
1504
- };
1505
- };
1506
- /**
1507
- * Internal notification emitted when Intelligence observes new run activity
1508
- * for a thread without changing that thread's metadata row.
1509
- */
1510
- type ThreadRunActivityNotification = {
1511
- type: "thread_run_activity";
1512
- threadId: string;
1513
- agentId?: string;
1514
- runId?: string;
1515
- eventType: string;
1516
- latestEventId?: string;
1517
- };
1518
- interface ThreadEnvironment {
1519
- fetch: typeof fetch;
1520
- /**
1521
- * Optional callback invoked whenever a thread mutation (rename, archive,
1522
- * unarchive, delete) is rejected by the server. Lets framework wrappers
1523
- * surface a transient error toast without subscribing to the error
1524
- * selector. The error is also recorded in `state.error` regardless.
1525
- *
1526
- * Fired after any rollback (delete) has been applied to local state.
1527
- */
1528
- onError?: (error: Error) => void;
1529
- }
1530
- interface ThreadState {
1531
- threads: ThreadRecord[];
1532
- isLoading: boolean;
1533
- isFetchingNextPage: boolean;
1534
- error: Error | null;
1535
- /**
1536
- * Error from the most recent failed next-page (`fetchMore`) load, or `null`.
1537
- * Tracked SEPARATELY from `error` so a paginated-load failure surfaces an
1538
- * inline "couldn't load more" affordance without replacing the already-loaded
1539
- * list with a full-panel error. Cleared when a fetch-more is retried or when
1540
- * one succeeds; reset on context change / stop.
1541
- */
1542
- fetchMoreError: Error | null;
1543
- context: ThreadRuntimeContext | null;
1544
- sessionId: number;
1545
- metadataCredentialsRequested: boolean;
1546
- metadataJoinCode: string | null;
1547
- nextCursor: string | null;
1548
- /** Number of thread mutations currently awaiting a server response. */
1549
- inFlightMutationCount: number;
1550
- /**
1551
- * Rows optimistically removed by an in-flight `delete`, keyed by the
1552
- * originating request id. DELETE is the one mutation that rolls back on
1553
- * rejection, so the removed row is parked here and restored if the server
1554
- * rejects. Rename/archive/unarchive are optimistic no-rollback and do not
1555
- * populate this map.
1556
- */
1557
- pendingDeletes: Record<string, ThreadRecord>;
1558
- }
1559
- /**
1560
- * The set of memoized thread selectors bound to a single store instance.
1561
- *
1562
- * @see createThreadSelectors
1563
- */
1564
- interface ThreadSelectors {
1565
- threads: (state: ThreadState) => ThreadRecord[];
1566
- isLoading: (state: ThreadState) => boolean;
1567
- error: (state: ThreadState) => Error | null;
1568
- fetchMoreError: (state: ThreadState) => Error | null;
1569
- hasNextPage: (state: ThreadState) => boolean;
1570
- isFetchingNextPage: (state: ThreadState) => boolean;
1571
- isMutating: (state: ThreadState) => boolean;
1572
- }
1573
- /**
1574
- * Builds a fresh set of memoized thread selectors.
1575
- *
1576
- * Each `createSelector` closure owns a private one-entry cache. Sharing a
1577
- * single module-level selector instance across multiple concurrent stores
1578
- * (e.g. a `<CopilotThreadsDrawer>` plus an independent `useThreads`) makes every
1579
- * cross-store emission a cache miss, defeating memoization and risking
1580
- * emission instability for any future selector that allocates a new
1581
- * object/array. Creating a per-store instance keeps each store's cache
1582
- * isolated so concurrent stores never thrash one another.
1583
- */
1584
- declare function createThreadSelectors(): ThreadSelectors;
1585
- interface ThreadStore {
1586
- start(): void;
1587
- stop(): void;
1588
- setContext(context: ThreadRuntimeContext | null): void;
1589
- /** Re-fetches the thread list without resetting the current list to empty. */
1590
- refresh(): void;
1591
- /**
1592
- * Re-fetches the thread list without resetting the current list to empty.
1593
- *
1594
- * Public, design-named alias of {@link refresh} used by the drawer's
1595
- * error-state Retry affordance and the Active/All filter-change refetch.
1596
- */
1597
- refetchThreads(): void;
1598
- /**
1599
- * Resets to a fresh, client-side thread so the welcome screen can show.
1600
- *
1601
- * Lazy creation: no phantom row is added to the list — the new thread only
1602
- * materializes once its first run persists server-side. This is distinct
1603
- * from selecting an existing thread (which the wrapper marks *explicit*,
1604
- * suppressing the welcome screen): the thread produced here is NOT explicit.
1605
- */
1606
- startNewThread(): void;
1607
- fetchNextPage(): void;
1608
- renameThread(threadId: string, name: string): Promise<void>;
1609
- archiveThread(threadId: string): Promise<void>;
1610
- unarchiveThread(threadId: string): Promise<void>;
1611
- deleteThread(threadId: string): Promise<void>;
1612
- /**
1613
- * Subscribes to synthetic run-activity notifications without changing the
1614
- * thread metadata list.
1615
- */
1616
- subscribeToRunActivity?(callback: (notification: ThreadRunActivityNotification) => void): Subscription;
1617
- getState(): ThreadState;
1618
- /**
1619
- * Returns a stable initial snapshot for server-side rendering.
1620
- *
1621
- * `useSyncExternalStore` requires a `getServerSnapshot` during SSR/prerender
1622
- * (e.g. Next.js); without one React throws "Missing getServerSnapshot". The
1623
- * returned reference is stable across calls so React does not loop. There is
1624
- * no client-side thread data during prerender, so this is the empty initial
1625
- * state.
1626
- */
1627
- getServerState(): ThreadState;
1628
- select: Store<ThreadState>["select"];
1629
- /**
1630
- * Memoized selectors bound to THIS store instance.
1631
- *
1632
- * Subscriptions should pass these to {@link select} (e.g.
1633
- * `store.select(store.selectors.threads)`) so each store keeps its own
1634
- * one-entry memo cache. Sharing the module-level singletons across
1635
- * concurrent stores defeats memoization and risks emission instability.
1636
- */
1637
- selectors: ThreadSelectors;
1638
- }
1639
- declare function createThreadStore(environment: ThreadEnvironment): ThreadStore;
1640
- type ɵThread = ThreadRecord;
1641
- type ɵThreadRuntimeContext = ThreadRuntimeContext;
1642
- type ɵThreadMetadataEvent = ThreadMetadataEvent;
1643
- type ɵThreadEnvironment = ThreadEnvironment;
1644
- type ɵThreadStore = ThreadStore;
1645
- type ɵThreadSelectors = ThreadSelectors;
1646
- declare const ɵthreadAdapterEvents: ActionGroupResult<"Thread Adapter", {
1647
- readonly started: EmptyActionConfig;
1648
- readonly stopped: EmptyActionConfig;
1649
- readonly contextChanged: PropsActionConfig<{
1650
- context: ThreadRuntimeContext | null;
1651
- }>;
1652
- readonly fetchNextPageRequested: EmptyActionConfig;
1653
- readonly renameRequested: PropsActionConfig<{
1654
- requestId: string;
1655
- threadId: string;
1656
- name: string;
1657
- }>;
1658
- readonly archiveRequested: PropsActionConfig<{
1659
- requestId: string;
1660
- threadId: string;
1661
- }>;
1662
- readonly unarchiveRequested: PropsActionConfig<{
1663
- requestId: string;
1664
- threadId: string;
1665
- }>;
1666
- readonly deleteRequested: PropsActionConfig<{
1667
- requestId: string;
1668
- threadId: string;
1669
- }>;
1670
- readonly newThreadStarted: EmptyActionConfig;
1671
- }>;
1672
- declare const ɵcreateThreadSelectors: typeof createThreadSelectors;
1673
- declare const ɵselectThreads: (state: ThreadState) => ThreadRecord[];
1674
- declare const ɵselectThreadsIsLoading: (state: ThreadState) => boolean;
1675
- declare const ɵselectThreadsError: (state: ThreadState) => Error | null;
1676
- declare const ɵselectFetchMoreError: (state: ThreadState) => Error | null;
1677
- declare const ɵselectHasNextPage: (state: ThreadState) => boolean;
1678
- declare const ɵselectIsFetchingNextPage: (state: ThreadState) => boolean;
1679
- declare const ɵselectIsMutating: (state: ThreadState) => boolean;
1680
- /**
1681
- * Number of consecutive WebSocket connection failures after which the
1682
- * threads channel tears itself down rather than retrying indefinitely.
1683
- * Exposed for tests so they can assert teardown semantics without
1684
- * hardcoding the threshold separately from production.
1685
- */
1686
- declare const ɵMAX_SOCKET_RETRIES = 5;
1687
- /**
1688
- * How long a thread REST request is given before the store gives up on it.
1689
- * Exposed for tests for the same reason as {@link ɵMAX_SOCKET_RETRIES}: a
1690
- * separately hardcoded copy silently drifts away from this one.
1691
- */
1692
- declare const ɵTHREAD_REQUEST_TIMEOUT_MS = 15000;
1693
- //#endregion
1694
- //#region src/core/generative-ui-debug.d.ts
1695
- /** @internal One declared function of the generative UI, for the inspector. */
1696
- interface ɵGenerativeUIDebugFunction {
1697
- description?: string;
1698
- parameters: GenerativeUIJSONSchema;
1699
- /** How many `useGenerativeUIFunction` handlers are mounted. Only 1 is valid. */
1700
- handlers: number;
1701
- }
1702
- /** @internal One surface that the browser holds, for the inspector. */
1703
- interface ɵGenerativeUIDebugSurface {
1704
- surfaceId: string;
1705
- threadId: string;
1706
- agentId: string | undefined;
1707
- target: string;
1708
- status: GenerativeUISurfaceStatus;
1709
- /** The committed operations, in order. The browser can still reject some. */
1710
- operations: readonly A2UIOperation[];
1711
- /** The current data model. */
1712
- dataModel: unknown;
1713
- /** The values that the user wrote, by path. Agent writes to them are ignored. */
1714
- userValues: Record<string, unknown>;
1715
- rejected: Array<GenerativeUIRejectedOperation & {
1716
- source: "runtime" | "browser";
1717
- }>;
1718
- }
1719
- /** @internal One part of the text that a run adds to the prompt of the model. */
1720
- interface ɵGenerativeUIDebugPromptSection {
1721
- title: string;
1722
- /** Who adds the text to the prompt. */
1723
- source: "runtime" | "context" | "backend";
1724
- text: string;
1725
- }
1726
- /** @internal What one run sends, or what the next run will send. */
1727
- interface ɵGenerativeUIDebugRun {
1728
- agentId: string | undefined;
1729
- threadId: string | undefined;
1730
- /** When the run started. Left out for the next run. */
1731
- startedAt?: number;
1732
- /** `forwardedProps.copilotkit.ui` of the run. */
1733
- envelope: CopilotKitUIEnvelope;
1734
- prompt: ɵGenerativeUIDebugPromptSection[];
1735
- }
1736
- /** @internal The state of a generative UI, for the inspector. */
1737
- interface ɵGenerativeUIDebugSnapshot {
1738
- catalogId: string;
1739
- transport: "tool" | "markdown";
1740
- /** The agents that get the generative UI. Left out: every agent. */
1741
- agentIds?: string[];
1742
- components: Record<string, GenerativeUIComponentManifest>;
1743
- /** The id of the catalog that declared each component, by name. */
1744
- componentCatalogs: Record<string, string>;
1745
- functions: Record<string, ɵGenerativeUIDebugFunction>;
1746
- /** The app state that bound props read, by key. */
1747
- state: Record<string, unknown>;
1748
- /** The chat first, then each mounted `<GenerativeUISurface>`. */
1749
- targets: GenerativeUITarget[];
1750
- activeThreadId: string | undefined;
1751
- surfaces: ɵGenerativeUIDebugSurface[];
1752
- lastRun: ɵGenerativeUIDebugRun | undefined;
1753
- nextRun: ɵGenerativeUIDebugRun;
1754
- }
1755
- /**
1756
- * @internal What a framework package (react-core) gives core, so that the
1757
- * inspector can show its generative UI. `getSnapshot` builds the snapshot
1758
- * when it is called, so a source that nobody reads costs nothing.
1759
- */
1760
- interface ɵGenerativeUIDebugSource {
1761
- getSnapshot(): ɵGenerativeUIDebugSnapshot;
1762
- /** Calls `listener` when the snapshot changes. Returns the unsubscribe. */
1763
- subscribe(listener: () => void): () => void;
1764
- }
1765
- //#endregion
1766
- //#region src/memory-errors.d.ts
1767
- /**
1768
- * Memory error registry — stable codes for the errors the memory store throws.
1769
- *
1770
- * The memory store (`memory.ts`) used to throw bare `new Error("Failed to fetch
1771
- * memories: 500")` / `"Request timed out"` / `"Request failed: <status>"`. Those
1772
- * reach the `error` selector (and the consumer UI via `useMemories` /
1773
- * `injectMemories`) verbatim, with no machine-readable `code`/`category`/
1774
- * `retryable`, so they cannot be grouped in observability or branched on by
1775
- * consumers.
1776
- *
1777
- * Per the repo's error-handling architecture standard (AGENTS.md: "Each project
1778
- * must maintain an explicit error registry"), this file is the explicit registry
1779
- * for the memory feature. It is deliberately scoped to memory — not a repo-wide
1780
- * registry refactor — because `packages/core` has no pre-existing
1781
- * code/category/retryable registry convention to plug into (the runtime's
1782
- * `lib/error-messages.ts` is a message-templating table, not a typed
1783
- * code/category/retryable registry). It mirrors the existing
1784
- * `AgentThreadLockedError extends Error` precedent in
1785
- * `intelligence-agent.ts`: a real `Error` subclass so `instanceof Error` holds
1786
- * and the public `MemoryState.error: Error | null` contract is preserved.
1787
- *
1788
- * `docsPath` is recorded per entry per the standard; there is no
1789
- * `docs/errors/<project>.md` in this repo, so this docblock plus the registry
1790
- * are the source of truth.
1791
- *
1792
- * Each registry entry carries:
1793
- * - `code`: stable identifier (e.g. `MEMORY_LIST_FAILED`).
1794
- * - `category`: one of the standard categories
1795
- * (`validation`|`auth`|`permission`|`not_found`|`conflict`|`rate_limit`|`internal`|`dependency`).
1796
- * - `retryable`: whether a retry could plausibly succeed (timeouts + transient
1797
- * dependency failures are retryable; client-caused 4xx are not).
1798
- * - `message`: the default human-readable message (callers may override with a
1799
- * status-bearing string to preserve the prior wording).
1800
- * - `docsPath`: documentation pointer for the code.
1801
- */
1802
- /** Standard error categories from the repo error-handling architecture. */
1803
- type MemoryErrorCategory = "validation" | "auth" | "permission" | "not_found" | "conflict" | "rate_limit" | "internal" | "dependency";
1804
- /** Stable codes for the memory store's surfaced errors. */
1805
- type MemoryErrorCode = "MEMORY_LIST_FAILED" | "MEMORY_RECALL_FAILED" | "MEMORY_CREDENTIALS_FAILED" | "MEMORY_MUTATION_FAILED" | "MEMORY_REQUEST_TIMEOUT";
1806
- /** A single registry entry describing one memory error code. */
1807
- interface MemoryErrorRegistryEntry {
1808
- readonly code: MemoryErrorCode;
1809
- readonly category: MemoryErrorCategory;
1810
- readonly retryable: boolean;
1811
- readonly message: string;
1812
- readonly docsPath: string;
1813
- }
1814
- /**
1815
- * The memory error registry: the single source of truth for memory error
1816
- * metadata. Keyed by `code` so a code maps to exactly one category/retryable
1817
- * default.
1818
- *
1819
- * Categories/retryable rationale:
1820
- * - List/credentials/mutation failures are `dependency` (the runtime/platform
1821
- * the store calls failed). A 5xx is transient (`retryable: true`); a 4xx is
1822
- * caller-caused, so the helpers below downgrade those to non-retryable.
1823
- * - Timeouts are `dependency` and `retryable: true` (the request may simply be
1824
- * slow).
1825
- */
1826
- declare const MEMORY_ERROR_REGISTRY: Readonly<Record<MemoryErrorCode, MemoryErrorRegistryEntry>>;
1827
- /**
1828
- * An `Error` carrying a stable memory error `code`, `category`, and `retryable`
1829
- * flag so consumers and observability can branch on it without string-matching
1830
- * the message.
1831
- *
1832
- * It is a real `Error` subclass: `instanceof Error` is true, so the public
1833
- * `MemoryState.error: Error | null` contract (and the `error: Error | null`
1834
- * surfaced by `useMemories` / `injectMemories`) holds unchanged. Existing
1835
- * consumers that only read `.message` keep working; the richer fields are
1836
- * additive.
1837
- */
1838
- declare class MemoryError extends Error {
1839
- /** Stable, machine-readable error identifier. */
1840
- readonly code: MemoryErrorCode;
1841
- /** Coarse error category for grouping/observability. */
1842
- readonly category: MemoryErrorCategory;
1843
- /** Whether retrying the operation could plausibly succeed. */
1844
- readonly retryable: boolean;
1845
- /**
1846
- * @param code - Registry code identifying this error.
1847
- * @param options - Optional overrides:
1848
- * - `message`: human-readable message (defaults to the registry message;
1849
- * callers pass a status-bearing string to preserve prior wording).
1850
- * - `retryable`: overrides the registry default (e.g. a 4xx list failure is
1851
- * not retryable even though the code's default is).
1852
- * - `cause`: the underlying error, preserved for debugging.
1853
- */
1854
- constructor(code: MemoryErrorCode, options?: {
1855
- message?: string;
1856
- retryable?: boolean;
1857
- cause?: unknown;
1858
- });
1859
- }
1860
- /**
1861
- * Narrows an HTTP status to whether the failure is worth retrying: a 5xx (or a
1862
- * missing/0 status) is a transient dependency failure and retryable; a 4xx is
1863
- * caller-caused and not. Used so a `MEMORY_LIST_FAILED`/`MEMORY_MUTATION_FAILED`
1864
- * carries an accurate `retryable` flag derived from the response status.
1865
- */
1866
- declare function isRetryableStatus(status: number): boolean;
1867
- //#endregion
1868
- //#region src/memory.d.ts
1869
- /** Public, customer-facing memory kind vocabulary (single taxonomy, no mapping). */
1870
- type MemoryKind = "topical" | "episodic" | "operational";
1871
- /** Visibility scope of a memory. */
1872
- type MemoryScope = "user" | "project";
1873
- /**
1874
- * Health of the realtime (`user_meta:memories:<code>`) connection that streams
1875
- * live `memory_metadata` deltas. Distinct from `available`/`error`, which
1876
- * describe the REST list route: `realtimeStatus` reports ONLY whether the
1877
- * realtime socket/channel is live so the UI can stop showing a "live" indicator
1878
- * over a frozen snapshot once the socket permanently gives up.
1879
- *
1880
- * - `"connecting"` — fetching join credentials / opening the socket / joining
1881
- * the channel (the default, and the state every `contextChanged`/`stopped`
1882
- * resets to).
1883
- * - `"connected"` — the channel join succeeded; live deltas are flowing.
1884
- * - `"unavailable"` — the socket exhausted its retries or the join failed
1885
- * permanently; the snapshot is frozen and no deltas will arrive. This is a
1886
- * silent degrade for `available`/`error` (those stay untouched) — only this
1887
- * signal flips.
1888
- */
1889
- type MemoryRealtimeStatus = "connecting" | "connected" | "unavailable";
1890
- /**
1891
- * A memory as projected across the public REST/realtime boundary — the minimal
1892
- * shape the SDK surfaces. Mirrors the server's `PublicMemory` projection.
1893
- */
1894
- interface Memory {
1895
- id: string;
1896
- kind: MemoryKind;
1897
- scope: MemoryScope;
1898
- content: string;
1899
- sourceThreadIds: readonly string[];
1900
- invalidatedAt: string | null;
1901
- /** Relevance score from a `recall()` (hybrid RAG) query; `undefined` for list/realtime/mutation memories. */
1902
- score?: number;
1903
- }
1904
- /** Input for creating a memory; `scope` defaults to `"user"` (v1 is user-scoped). */
1905
- interface NewMemory {
1906
- content: string;
1907
- kind: MemoryKind;
1908
- scope?: MemoryScope;
1909
- sourceThreadIds?: readonly string[];
1910
- }
1911
- /**
1912
- * New values for superseding (updating) a memory — same shape as create.
1913
- *
1914
- * Supersede is a FULL replacement, not a partial patch: this is the complete
1915
- * definition of the new memory that replaces the old one. `content` and `kind`
1916
- * are required and must be re-supplied, and an omitted `sourceThreadIds` resets
1917
- * the new memory's source threads to `[]` — it does NOT preserve the prior
1918
- * memory's value.
1919
- */
1920
- type MemoryChanges = NewMemory;
1921
- /** Outcome of a mutation, tracked so the caller's promise resolves/rejects. */
1922
- type MemoryMutationOutcome = {
1923
- requestId: string;
1924
- sessionId: number;
1925
- ok: true;
1926
- memory: Memory | null;
1927
- } | {
1928
- requestId: string;
1929
- sessionId: number;
1930
- ok: false;
1931
- error: Error;
1932
- };
1933
- /**
1934
- * Runtime wiring for the memory store: where to reach the REST surface and the
1935
- * headers (auth + `X-Cpki-User-Id`) to send. Scoped to the current user; v1
1936
- * surfaces user-scoped memories only.
1937
- */
1938
- interface MemoryRuntimeContext {
1939
- runtimeUrl: string;
1940
- /** WebSocket URL for the realtime gateway (e.g. `wss://gw.example.com/client`). */
1941
- wsUrl: string;
1942
- /**
1943
- * Optional: `environment.fetch` is expected to be `ɵruntimeFetch`, which
1944
- * already resolves and overlays the current core headers at send time
1945
- * (#1937). Set explicitly only when the store's `fetch` does NOT already
1946
- * carry headers.
1947
- */
1948
- headers?: Record<string, string>;
1949
- includeInvalidated?: boolean;
1950
- }
1951
- /**
1952
- * In-memory state for the memory store. Session-guarded like the thread store:
1953
- * `sessionId` is bumped whenever the runtime context changes so that responses
1954
- * and realtime deltas from a previous context are ignored.
1955
- */
1956
- interface MemoryState {
1957
- memories: Memory[];
1958
- isLoading: boolean;
1959
- inFlightMutationCount: number;
1960
- error: Error | null;
1961
- context: MemoryRuntimeContext | null;
1962
- sessionId: number;
1963
- available: boolean;
1964
- realtimeStatus: MemoryRealtimeStatus;
1965
- }
1966
- declare const memoryDomainEvents: ActionGroupResult<"Memory Domain", {
1967
- readonly memoryUpserted: PropsActionConfig<{
1968
- sessionId: number;
1969
- memory: Memory;
1970
- }>;
1971
- readonly memoryInvalidated: PropsActionConfig<{
1972
- sessionId: number;
1973
- memoryId: string;
1974
- }>;
1975
- readonly realtimeConnecting: PropsActionConfig<{
1976
- sessionId: number;
1977
- }>;
1978
- readonly realtimeConnected: PropsActionConfig<{
1979
- sessionId: number;
1980
- }>;
1981
- readonly realtimeUnavailable: PropsActionConfig<{
1982
- sessionId: number;
1983
- }>;
1984
- }>;
1985
- /** Wire shape of a memory inside a `memory_metadata` payload (carries tenant ids). */
1986
- interface MemoryMetadataPayloadMemory extends Memory {
1987
- organizationId: string;
1988
- projectId: string;
1989
- }
1990
- /**
1991
- * The realtime `memory_metadata` event broadcast on a memory channel:
1992
- * `created`/`updated` carry the full memory, `invalidated` carries only its id.
1993
- * The same wire shape is delivered on both the user channel
1994
- * (`user_meta:memories:<code>`, current user's memories) and the optional
1995
- * project channel (`project_meta:memories:<code>`, memories shared across the
1996
- * project); the store reduces both into one id-keyed list.
1997
- */
1998
- type MemoryMetadataEvent = {
1999
- operation: "created" | "updated";
2000
- memoryId: string;
2001
- organizationId: string;
2002
- projectId: string;
2003
- occurredAt: string;
2004
- memory: MemoryMetadataPayloadMemory;
2005
- } | {
2006
- operation: "invalidated";
2007
- memoryId: string;
2008
- organizationId: string;
2009
- projectId: string;
2010
- occurredAt: string;
2011
- invalidated: {
2012
- id: string;
2013
- };
2014
- };
2015
- /**
2016
- * Maps a realtime `memory_metadata` event to the domain action that applies it:
2017
- * `created`/`updated` upsert the projected memory, `invalidated` removes it by
2018
- * id. Carries the current `sessionId` so the reducer's session guard can drop
2019
- * deltas left over from a previous context.
2020
- */
2021
- declare function mapMemoryMetadataEvent(event: MemoryMetadataEvent, sessionId: number): ReturnType<typeof memoryDomainEvents.memoryUpserted> | ReturnType<typeof memoryDomainEvents.memoryInvalidated>;
2022
- /**
2023
- * Dependencies injected into the memory store. The store opens its own
2024
- * `user_meta:memories:<joinCode>` socket/channel and does not share the
2025
- * thread store's socket, so only a `fetch` implementation is required.
2026
- */
2027
- interface MemoryEnvironment {
2028
- fetch: typeof fetch;
2029
- }
2030
- interface MemoryStore {
2031
- start(): void;
2032
- stop(): void;
2033
- setContext(context: MemoryRuntimeContext | null): void;
2034
- /**
2035
- * Re-fetches the REST snapshot without clearing the current list. Resolves
2036
- * once the re-pull settles (success or failure) for the current context, so
2037
- * callers (e.g. a `useMemories` `refresh()`) can await it. Resolves
2038
- * immediately when no context is set.
2039
- */
2040
- refresh(): Promise<void>;
2041
- /**
2042
- * Semantically recalls memories via `POST {runtimeUrl}/memories/recall`
2043
- * (hybrid RAG). Returns memories ordered by relevance, each carrying a
2044
- * `score`. Does NOT mutate the snapshot — a one-shot query. Rejects when no
2045
- * context is set or the request fails.
2046
- */
2047
- recall(query: string, opts?: {
2048
- limit?: number;
2049
- scope?: MemoryScope;
2050
- }): Promise<Memory[]>;
2051
- /** Creates a memory; resolves to the stored memory (server-authoritative). */
2052
- addMemory(input: NewMemory): Promise<Memory>;
2053
- /** Supersedes a memory; resolves to the new memory (its id changes). */
2054
- updateMemory(id: string, changes: MemoryChanges): Promise<Memory>;
2055
- /** Retires a memory (non-lossy delete). */
2056
- removeMemory(id: string): Promise<void>;
2057
- getState(): MemoryState;
2058
- /**
2059
- * Stable, render-safe state for SSR/prerender. React's
2060
- * `useSyncExternalStore` requires a `getServerSnapshot` during SSR/prerender
2061
- * (e.g. Next.js); without one React throws "Missing getServerSnapshot". The
2062
- * returned reference is stable across calls so React does not loop. There is
2063
- * no client-side memory data during prerender, so this is the empty initial
2064
- * state (no memories, not loading, no error).
2065
- */
2066
- getServerState(): MemoryState;
2067
- select: Store<MemoryState>["select"];
2068
- }
2069
- /**
2070
- * Creates the framework-agnostic memory store: a REST snapshot on `setContext`,
2071
- * server-authoritative add/update/remove mutations, and realtime
2072
- * `memory_metadata` deltas off the injected `user_meta` event source — all
2073
- * reduced into observable state.
2074
- */
2075
- declare function createMemoryStore(environment: MemoryEnvironment): MemoryStore;
2076
- type ɵMemoryState = MemoryState;
2077
- type ɵMemoryRuntimeContext = MemoryRuntimeContext;
2078
- type ɵMemoryMetadataEvent = MemoryMetadataEvent;
2079
- type ɵMemoryEnvironment = MemoryEnvironment;
2080
- type ɵMemoryStore = MemoryStore;
2081
- declare const ɵmemoryAdapterEvents: ActionGroupResult<"Memory Adapter", {
2082
- readonly started: EmptyActionConfig;
2083
- readonly stopped: EmptyActionConfig;
2084
- readonly contextChanged: PropsActionConfig<{
2085
- context: MemoryRuntimeContext | null;
2086
- }>;
2087
- readonly addRequested: PropsActionConfig<{
2088
- requestId: string;
2089
- input: NewMemory;
2090
- }>;
2091
- readonly updateRequested: PropsActionConfig<{
2092
- requestId: string;
2093
- id: string;
2094
- changes: MemoryChanges;
2095
- }>;
2096
- readonly removeRequested: PropsActionConfig<{
2097
- requestId: string;
2098
- id: string;
2099
- }>;
2100
- }>;
2101
- declare const ɵmemoryRestEvents: ActionGroupResult<"Memory REST", {
2102
- readonly listRequested: PropsActionConfig<{
2103
- sessionId: number;
2104
- }>;
2105
- readonly listSucceeded: PropsActionConfig<{
2106
- sessionId: number;
2107
- memories: Memory[];
2108
- }>;
2109
- readonly listFailed: PropsActionConfig<{
2110
- sessionId: number;
2111
- error: Error;
2112
- }>;
2113
- readonly listUnavailable: PropsActionConfig<{
2114
- sessionId: number;
2115
- }>;
2116
- readonly mutationFinished: PropsActionConfig<{
2117
- outcome: MemoryMutationOutcome;
2118
- }>;
2119
- readonly credentialsRequested: PropsActionConfig<{
2120
- sessionId: number;
2121
- }>;
2122
- readonly credentialsSucceeded: PropsActionConfig<{
2123
- sessionId: number;
2124
- joinToken?: string;
2125
- joinCode?: string;
2126
- projectJoinToken?: string;
2127
- projectJoinCode?: string;
2128
- }>;
2129
- readonly credentialsFailed: PropsActionConfig<{
2130
- sessionId: number;
2131
- error: Error;
2132
- }>;
2133
- readonly credentialsUnavailable: PropsActionConfig<{
2134
- sessionId: number;
2135
- }>;
2136
- }>;
2137
- declare const ɵmemoryDomainEvents: ActionGroupResult<"Memory Domain", {
2138
- readonly memoryUpserted: PropsActionConfig<{
2139
- sessionId: number;
2140
- memory: Memory;
2141
- }>;
2142
- readonly memoryInvalidated: PropsActionConfig<{
2143
- sessionId: number;
2144
- memoryId: string;
2145
- }>;
2146
- readonly realtimeConnecting: PropsActionConfig<{
2147
- sessionId: number;
2148
- }>;
2149
- readonly realtimeConnected: PropsActionConfig<{
2150
- sessionId: number;
2151
- }>;
2152
- readonly realtimeUnavailable: PropsActionConfig<{
2153
- sessionId: number;
2154
- }>;
2155
- }>;
2156
- declare const ɵmemoryReducer: Reducer<MemoryState>;
2157
- declare const ɵmapMemoryMetadataEvent: typeof mapMemoryMetadataEvent;
2158
- declare const ɵselectMemories: Selector<MemoryState, Memory[]>;
2159
- declare const ɵselectMemoriesIsLoading: Selector<MemoryState, boolean>;
2160
- declare const ɵselectMemoriesError: Selector<MemoryState, Error | null>;
2161
- declare const ɵselectMemoriesIsMutating: Selector<MemoryState, boolean>;
2162
- declare const ɵselectMemoriesAvailable: Selector<MemoryState, boolean>;
2163
- declare const ɵselectMemoriesRealtimeStatus: Selector<MemoryState, MemoryRealtimeStatus>;
2164
- //#endregion
2165
- //#region src/core/header-source.d.ts
2166
- type HeaderRecordInput = Record<string, string | null | undefined>;
2167
- /**
2168
- * What `headers` accepts: a record, a sync builder, or an async builder. A
2169
- * builder runs once per request, when the request is sent. See #1937.
2170
- */
2171
- type CopilotKitHeadersSource = HeaderRecordInput | (() => HeaderRecordInput) | (() => Promise<HeaderRecordInput>);
2172
- declare class CopilotKitHeaderResolutionError extends Error {
2173
- readonly name = "CopilotKitHeaderResolutionError";
2174
- constructor(cause: unknown);
2175
- }
2176
- /**
2177
- * Add default headers (e.g. the public API key) to a source, only where the
2178
- * source left the key unset or empty. The single shared replacement for the
2179
- * React, Vue and Angular providers' own merges.
2180
- */
2181
- declare function ɵwithHeaderDefaults(source: CopilotKitHeadersSource, defaults: Record<string, string>): CopilotKitHeadersSource;
2182
- //#endregion
2183
- //#region src/core/core.d.ts
2184
- /**
2185
- * Run properties that go only to the runs of some agents.
2186
- * See `CopilotKitCore.addScopedProperties`.
2187
- */
2188
- interface ScopedProperties {
2189
- /** The properties to merge on top of the base run properties. */
2190
- properties: Record<string, unknown>;
2191
- /** The agents that get these properties. When omitted, every agent gets them. */
2192
- agentIds?: string[];
2193
- }
2194
- /** Configuration options for `CopilotKitCore`. */
2195
- interface CopilotKitCoreConfig {
2196
- /** The endpoint of the CopilotRuntime. */
2197
- runtimeUrl?: string;
2198
- /** Transport style for CopilotRuntime endpoints. Defaults to REST. */
2199
- runtimeTransport?: CopilotRuntimeTransport;
2200
- /**
2201
- * When true, the constructor sets the runtime config but does NOT start the
2202
- * `/info` connection. Call {@link CopilotKitCore.connect} to start it —
2203
- * typically from a host's commit-phase effect. This prevents a burst of
2204
- * duplicate `/info` requests when a host constructs (and discards) the core
2205
- * during render, e.g. React concurrent rendering / Suspense / StrictMode.
2206
- * See https://github.com/CopilotKit/CopilotKit/issues/5801.
2207
- */
2208
- deferInitialConnection?: boolean;
2209
- /** Mapping from agent name to its `AbstractAgent` instance. For development only - production requires CopilotRuntime. */
2210
- agents__unsafe_dev_only?: Record<string, AbstractAgent>;
2211
- /**
2212
- * Headers sent with every runtime request: a record, or a sync or async
2213
- * builder that runs when each request is sent. Merged on top of each
2214
- * `HttpAgent`'s own headers (core wins on a key conflict). See `setHeaders`.
2215
- */
2216
- headers?: CopilotKitHeadersSource;
2217
- /** Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies). */
2218
- credentials?: RequestCredentials;
2219
- /**
2220
- * Rewrites the message list sent to runtime agents on every run. Use it when
2221
- * the backend already stores the conversation and re-sending it is waste or
2222
- * duplication. See `setMessageFilter` and {@link CopilotKitMessageFilter}.
2223
- */
2224
- messageFilter?: CopilotKitMessageFilter;
2225
- /** Properties sent as `forwardedProps` to the AG-UI agent. */
2226
- properties?: Record<string, unknown>;
2227
- /** Ordered collection of frontend tools available to the core. */
2228
- tools?: FrontendTool<any>[];
2229
- /** Suggestions config for the core. */
2230
- suggestionsConfig?: SuggestionsConfig[];
2231
- /** Enable debug logging for the client-side event pipeline. */
2232
- debug?: DebugConfig;
2233
- /**
2234
- * Turns on interaction capture (`@copilotkit/learning`). Capture starts only
2235
- * when {@link CopilotKitCore.startTrajectory} authenticates and joins the
2236
- * capture channel. The default path captures outside-chat activity. An explicit
2237
- * legacy sink also receives Thread, message, tool call, and run context.
2238
- * Update future captures with
2239
- * {@link CopilotKitCore.setLearningConfig}.
2240
- */
2241
- learning?: LearningConfig;
2242
- }
2243
- interface CopilotKitCoreStopAgentParams {
2244
- agent: AbstractAgent;
2245
- }
2246
- type CopilotKitCoreGetSuggestionsResult = {
2247
- suggestions: Suggestion[];
2248
- isLoading: boolean;
2249
- };
2250
- declare enum CopilotKitCoreErrorCode {
2251
- RUNTIME_INFO_FETCH_FAILED = "runtime_info_fetch_failed",
2252
- AGENT_CONNECT_FAILED = "agent_connect_failed",
2253
- AGENT_RUN_FAILED = "agent_run_failed",
2254
- AGENT_RUN_FAILED_EVENT = "agent_run_failed_event",
2255
- /**
2256
- * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is
2257
- * `"replay"` when the error belongs to stored thread history replayed on
2258
- * connect, `"live"` when the run is happening now, and `"unknown"` when the
2259
- * transport cannot tell. Show a live-failure notice only for `"live"`.
2260
- */
2261
- AGENT_RUN_ERROR_EVENT = "agent_run_error_event",
2262
- TOOL_ARGUMENT_PARSE_FAILED = "tool_argument_parse_failed",
2263
- TOOL_HANDLER_FAILED = "tool_handler_failed",
2264
- TOOL_NOT_FOUND = "tool_not_found",
2265
- AGENT_NOT_FOUND = "agent_not_found",
2266
- /**
2267
- * Emitted when an agent run fails because the thread is already locked
2268
- * by another active run.
2269
- *
2270
- * @example
2271
- * ```tsx
2272
- * <CopilotKitProvider
2273
- * onError={({ code, error, context }) => {
2274
- * if (code === "agent_thread_locked") {
2275
- * // Show "Agent is busy, retry?" UI
2276
- * }
2277
- * }}
2278
- * />
2279
- * ```
2280
- */
2281
- AGENT_THREAD_LOCKED = "agent_thread_locked",
2282
- TRANSCRIPTION_FAILED = "transcription_failed",
2283
- TRANSCRIPTION_SERVICE_NOT_CONFIGURED = "transcription_service_not_configured",
2284
- TRANSCRIPTION_INVALID_AUDIO = "transcription_invalid_audio",
2285
- TRANSCRIPTION_RATE_LIMITED = "transcription_rate_limited",
2286
- TRANSCRIPTION_AUTH_FAILED = "transcription_auth_failed",
2287
- TRANSCRIPTION_NETWORK_ERROR = "transcription_network_error",
2288
- SUBSCRIBER_CALLBACK_FAILED = "subscriber_callback_failed",
2289
- /**
2290
- * The `headers` builder threw, rejected, or returned something other than
2291
- * an object. The request was not sent. `error.cause` is the builder's error.
2292
- */
2293
- HEADER_RESOLUTION_FAILED = "header_resolution_failed"
2294
- }
2295
- interface CopilotKitCoreSubscriber {
2296
- onTrajectoryChanged?: (event: {
2297
- copilotkit: CopilotKitCore;
2298
- trajectoryId: string | null;
2299
- }) => void | Promise<void>;
2300
- onRuntimeConnectionStatusChanged?: (event: {
2301
- copilotkit: CopilotKitCore;
2302
- status: CopilotKitCoreRuntimeConnectionStatus;
2303
- }) => void | Promise<void>;
2304
- onToolExecutionStart?: (event: {
2305
- copilotkit: CopilotKitCore;
2306
- toolCallId: string;
2307
- agentId: string;
2308
- toolName: string;
2309
- args: unknown;
2310
- }) => void | Promise<void>;
2311
- onToolExecutionEnd?: (event: {
2312
- copilotkit: CopilotKitCore;
2313
- toolCallId: string;
2314
- agentId: string;
2315
- toolName: string;
2316
- result: string;
2317
- error?: string;
2318
- }) => void | Promise<void>;
2319
- onAgentsChanged?: (event: {
2320
- copilotkit: CopilotKitCore;
2321
- agents: Readonly<Record<string, AbstractAgent>>;
2322
- }) => void | Promise<void>;
2323
- /**
2324
- * Fired when an agent run or connect begins. The `agent` may be a per-thread
2325
- * clone that is not present in `core.agents`, so `onAgentsChanged` never fires
2326
- * for it. Subscribers (e.g. the inspector) can use this to subscribe to the
2327
- * running instance's AG-UI events.
2328
- */
2329
- onAgentRunStarted?: (event: {
2330
- copilotkit: CopilotKitCore;
2331
- agent: AbstractAgent;
2332
- }) => void | Promise<void>;
2333
- onContextChanged?: (event: {
2334
- copilotkit: CopilotKitCore;
2335
- context: Readonly<Record<string, Context>>;
2336
- }) => void | Promise<void>;
2337
- /**
2338
- * Fired when the A2UI catalog component list changes (registration) or when
2339
- * a component is enabled/disabled. Consumers (the provider, the inspector)
2340
- * re-derive the filtered catalog from this event.
2341
- */
2342
- onCatalogComponentsChanged?: (event: {
2343
- copilotkit: CopilotKitCore;
2344
- catalogComponents: ReadonlyArray<CopilotKitCoreCatalogComponent>;
2345
- }) => void | Promise<void>;
2346
- onSuggestionsConfigChanged?: (event: {
2347
- copilotkit: CopilotKitCore;
2348
- suggestionsConfig: Readonly<Record<string, SuggestionsConfig>>;
2349
- }) => void | Promise<void>;
2350
- onSuggestionsChanged?: (event: {
2351
- copilotkit: CopilotKitCore;
2352
- agentId: string;
2353
- suggestions: Suggestion[];
2354
- }) => void | Promise<void>;
2355
- onSuggestionsStartedLoading?: (event: {
2356
- copilotkit: CopilotKitCore;
2357
- agentId: string;
2358
- }) => void | Promise<void>;
2359
- onSuggestionsFinishedLoading?: (event: {
2360
- copilotkit: CopilotKitCore;
2361
- agentId: string;
2362
- }) => void | Promise<void>;
2363
- onPropertiesChanged?: (event: {
2364
- copilotkit: CopilotKitCore;
2365
- properties: Readonly<Record<string, unknown>>;
2366
- }) => void | Promise<void>;
2367
- onHeadersChanged?: (event: {
2368
- copilotkit: CopilotKitCore;
2369
- headers: Readonly<Record<string, string>>;
2370
- }) => void | Promise<void>;
2371
- onInspectorMetadataChanged?: (event: {
2372
- copilotkit: CopilotKitCore;
2373
- inspectorMetadata: InspectorMetadataV1 | undefined;
2374
- }) => void | Promise<void>;
2375
- onError?: (event: {
2376
- copilotkit: CopilotKitCore;
2377
- error: Error;
2378
- code: CopilotKitCoreErrorCode;
2379
- context: Record<string, any>;
2380
- }) => void | Promise<void>;
2381
- onThreadStoreRegistered?: (event: {
2382
- copilotkit: CopilotKitCore;
2383
- agentId: string;
2384
- store: ɵThreadStore;
2385
- }) => void | Promise<void>;
2386
- /**
2387
- * Fired when a thread store is removed from the registry, either by an
2388
- * explicit `unregister()` call or by a `register()` call that replaces an
2389
- * existing store for the same `agentId`.
2390
- *
2391
- * The previous store is delivered via `prevStore` so subscribers can tear
2392
- * down state that depends on the concrete instance (e.g. cancel an active
2393
- * subscription) without consulting the registry. By the time async
2394
- * subscribers resume after an `await`, a replacement `register()` may have
2395
- * already installed the new store under the same key, so calling
2396
- * `registry.get(agentId)` inside this callback is unsafe and may return
2397
- * the new store instead of the unregistered one.
2398
- */
2399
- onThreadStoreUnregistered?: (event: {
2400
- copilotkit: CopilotKitCore;
2401
- agentId: string;
2402
- prevStore: ɵThreadStore;
2403
- }) => void | Promise<void>;
2404
- }
2405
- interface CopilotKitCoreSubscription {
2406
- unsubscribe: () => void;
2407
- }
2408
- /**
2409
- * The callback keys accepted by {@link CopilotKitCore.subscribeToAgentWithOptions}.
2410
- * This tuple is the single source of truth — both the
2411
- * `SubscribeToAgentSubscriber` type and the runtime `ALLOWED_KEYS` set
2412
- * are derived from it, so they cannot desynchronise.
2413
- */
2414
- declare const SUBSCRIBE_TO_AGENT_KEYS: readonly ["onMessagesChanged", "onStateChanged", "onRunInitialized", "onRunStartedEvent", "onRunFinalized", "onRunFailed", "onRunErrorEvent"];
2415
- /**
2416
- * The subset of `AgentSubscriber` callbacks accepted by
2417
- * {@link CopilotKitCore.subscribeToAgentWithOptions}. Only the callbacks
2418
- * listed in {@link SUBSCRIBE_TO_AGENT_KEYS} are supported:
2419
- * `onMessagesChanged`, `onStateChanged`, and the run lifecycle
2420
- * callbacks (`onRunInitialized`, `onRunStartedEvent`, `onRunFinalized`, `onRunFailed`,
2421
- * `onRunErrorEvent`).
2422
- *
2423
- * Two categories of `AgentSubscriber` members are excluded:
2424
- *
2425
- * - **AG-UI event handlers** (`onEvent`, `onToolCallStartEvent`, etc.)
2426
- * return `AgentStateMutation` with `stopPropagation` — semantics that
2427
- * the throttle and error-protection wrappers cannot safely mediate.
2428
- *
2429
- * - **Per-item notification callbacks** (`onNewMessage`, `onNewToolCall`)
2430
- * return `void` and have no mutation concerns, but are excluded to keep
2431
- * the surface area minimal — `onMessagesChanged` already covers the
2432
- * same data at a coarser granularity, and throttling per-item callbacks
2433
- * would have different semantic expectations.
2434
- *
2435
- * `onRunErrorEvent` and `onRunStartedEvent` are AG-UI event handlers whose
2436
- * return types include `stopPropagation`. They are included so framework
2437
- * consumers can reflect running-state changes while a connection stays open:
2438
- * a live error clears busy and a successor run marks it busy again. Consumers
2439
- * use these callbacks for notification and return `void`.
2440
- *
2441
- * Note: the included lifecycle callbacks return
2442
- * `Omit<AgentStateMutation, "stopPropagation">` (or full
2443
- * `AgentStateMutation` for the included AG-UI event handlers). On the error
2444
- * path, `safeCall` discards those return values (see its inline
2445
- * documentation).
2446
- *
2447
- * Use `agent.subscribe()` directly when event mutation or per-item
2448
- * notification semantics are needed.
2449
- */
2450
- type SubscribeToAgentSubscriber = Pick<AgentSubscriber, (typeof SUBSCRIBE_TO_AGENT_KEYS)[number]>;
2451
- /** Options for {@link CopilotKitCore.subscribeToAgentWithOptions}. */
2452
- interface SubscribeToAgentOptions {
2453
- /**
2454
- * Throttle interval (ms) for `onMessagesChanged` / `onStateChanged`.
2455
- * Non-negative finite number; `0` explicitly disables throttling.
2456
- * Falls back to `defaultThrottleMs` when `undefined`.
2457
- */
2458
- throttleMs?: number;
2459
- }
2460
- declare enum CopilotKitCoreRuntimeConnectionStatus {
2461
- Disconnected = "disconnected",
2462
- Connected = "connected",
2463
- Connecting = "connecting",
2464
- Error = "error"
2465
- }
2466
- /**
2467
- * Internal interface for delegate classes to access CopilotKitCore methods.
2468
- * This provides type safety while allowing controlled access to private functionality.
2469
- */
2470
- interface CopilotKitCoreFriendsAccess {
2471
- notifySubscribers(handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>, errorMessage: string): Promise<void>;
2472
- emitError(params: {
2473
- error: Error;
2474
- code: CopilotKitCoreErrorCode;
2475
- context?: Record<string, any>;
2476
- }): Promise<void>;
2477
- readonly headers: Readonly<Record<string, string>>;
2478
- resolveHeaders(): Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>;
2479
- readonly credentials: RequestCredentials | undefined;
2480
- readonly messageFilter: CopilotKitMessageFilter | undefined;
2481
- readonly properties: Readonly<Record<string, unknown>>;
2482
- readonly context: Readonly<Record<string, Context>>;
2483
- readonly debug?: DebugConfig;
2484
- buildFrontendTools(agentId?: string): _ag_ui_client0.Tool[];
2485
- getContextForAgent(agentId?: string): Context[];
2486
- getPropertiesForAgent(agentId?: string): Record<string, unknown>;
2487
- getAgent(id: string): AbstractAgent | undefined;
2488
- /**
2489
- * Re-apply the last resolved header snapshot to a single agent, merged on
2490
- * top of the headers the agent was constructed with (see #5635). Never
2491
- * invokes the headers builder — safe to call from anywhere without risking
2492
- * a synchronous throw or an unhandled async rejection from a user-supplied
2493
- * builder.
2494
- */
2495
- applyHeadersToAgent(agent: AbstractAgent): void;
2496
- /**
2497
- * Resolve headers fresh (including invoking a sync/async builder) and
2498
- * apply them to `agent` right before a run or connect actually sends
2499
- * (#1937). Friends-only — only the run handler should call this, since
2500
- * unlike `applyHeadersToAgent` it can throw synchronously or return a
2501
- * rejecting promise. Returns a promise only when an async builder must be
2502
- * awaited first; callers that need the write to have landed before
2503
- * continuing must await a returned promise.
2504
- */
2505
- prepareAgentHeadersForRun(agent: AbstractAgent): void | Promise<void>;
2506
- readonly suggestionEngine: {
2507
- clearSuggestions(agentId: string): void;
2508
- reloadSuggestions(agentId: string): void;
2509
- };
2510
- /**
2511
- * Called before each follow-up agent run (after tool execution).
2512
- * See CopilotKitCore.waitForPendingFrameworkUpdates for details.
2513
- */
2514
- waitForPendingFrameworkUpdates(): Promise<void>;
2515
- readonly stateManager: {
2516
- getContinuationRunId(agent: AbstractAgent, input: Pick<RunAgentInput, "threadId" | "resume" | "forwardedProps">): string | undefined;
2517
- markNextRunAsContinuation(agent: AbstractAgent, expectedRunId?: string): CopilotKitCoreContinuationHandoff;
2518
- };
2519
- }
2520
- declare class CopilotKitCore {
2521
- private headerSource;
2522
- private _credentials?;
2523
- private _messageFilter?;
2524
- private _properties;
2525
- private _scopedProperties;
2526
- private _defaultThrottleMs?;
2527
- private _debug?;
2528
- private subscribers;
2529
- private agentRegistry;
2530
- private contextStore;
2531
- private suggestionEngine;
2532
- private runHandler;
2533
- private stateManager;
2534
- private threadStoreRegistry;
2535
- private learningBridge;
2536
- private notifiedTrajectoryId;
2537
- private readonly learningConfiguredListeners;
2538
- private _generativeUIDebugSource;
2539
- private readonly generativeUIDebugListeners;
2540
- /**
2541
- * The single core-owned memory store, created lazily on first
2542
- * `getMemoryStore()` and kept user-scoped for the lifetime of the core.
2543
- * Its runtime context is wired by the core itself (see `syncMemoryContext`),
2544
- * so callers never register or look it up by `agentId`.
2545
- */
2546
- private _memoryStore?;
2547
- /**
2548
- * Tracks the agent IDs from the most recent `onAgentsChanged` notification.
2549
- * Used to gate thread-store auto-unregister so the FIRST empty-agents
2550
- * notification (before published agents are merged in) does not rip out a
2551
- * store that was registered prior to that initial notification.
2552
- */
2553
- private previousAgentIds;
2554
- constructor({
2555
- runtimeUrl,
2556
- runtimeTransport,
2557
- deferInitialConnection,
2558
- headers,
2559
- credentials,
2560
- messageFilter,
2561
- properties,
2562
- agents__unsafe_dev_only,
2563
- tools,
2564
- suggestionsConfig,
2565
- debug,
2566
- learning
2567
- }: CopilotKitCoreConfig);
2568
- /**
2569
- * Internal method used by delegate classes and subclasses to notify subscribers
2570
- */
2571
- protected notifySubscribers(handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>, errorMessage: string): Promise<void>;
2572
- /**
2573
- * Internal method used by delegate classes to emit errors
2574
- */
2575
- private emitError;
2576
- /**
2577
- * Log a message to the console and emit an error to subscribers.
2578
- * Catches failures from `emitError` itself to prevent unhandled rejections.
2579
- */
2580
- private logAndEmitError;
2581
- /**
2582
- * Snapshot accessors
2583
- */
2584
- get context(): Readonly<Record<string, ScopedContext>>;
2585
- get agents(): Readonly<Record<string, AbstractAgent>>;
2586
- get tools(): Readonly<FrontendTool<any>[]>;
2587
- get catalogComponents(): ReadonlyArray<CopilotKitCoreCatalogComponent>;
2588
- get runtimeUrl(): string | undefined;
2589
- setRuntimeUrl(runtimeUrl: string | undefined): void;
2590
- /**
2591
- * Start the runtime `/info` connection if it has not been started yet.
2592
- *
2593
- * Intended to be driven from a host's commit-phase effect when the core was
2594
- * constructed with {@link CopilotKitCoreConfig.deferInitialConnection}. Safe
2595
- * to call repeatedly — it is a no-op once a connection is in progress or
2596
- * settled, so a double-invoked mount effect (React StrictMode) collapses to a
2597
- * single request. See #5801.
2598
- */
2599
- connect(): void;
2600
- get runtimeTransport(): CopilotRuntimeTransport;
2601
- setRuntimeTransport(runtimeTransport: CopilotRuntimeTransport): void;
2602
- get runtimeVersion(): string | undefined;
2603
- /**
2604
- * The last resolved headers. With a builder this is the value from the most
2605
- * recent request, not necessarily current; call `resolveHeaders()` for that.
2606
- */
2607
- get headers(): Readonly<Record<string, string>>;
2608
- /**
2609
- * Resolve the current headers. Synchronous for a record or a sync builder,
2610
- * a promise for an async builder. Concurrent calls share one builder call.
2611
- * The returned object is shared; copy it before modifying.
2612
- */
2613
- resolveHeaders(): Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>;
2614
- /** Changes only on `setHeaders` or a new source, never on a new token. */
2615
- get ɵheadersGeneration(): number;
2616
- get credentials(): RequestCredentials | undefined;
2617
- get messageFilter(): CopilotKitMessageFilter | undefined;
2618
- get properties(): Readonly<Record<string, unknown>>;
2619
- /**
2620
- * Default throttle interval (ms) used by `subscribeToAgentWithOptions()`
2621
- * when the caller does not specify an explicit `throttleMs`.
2622
- * `undefined` means no default is configured; `0` means no throttling.
2623
- */
2624
- get defaultThrottleMs(): number | undefined;
2625
- /**
2626
- * Set the default throttle interval (ms) for `subscribeToAgentWithOptions()`.
2627
- *
2628
- * Accepts a non-negative finite number or `undefined` (to clear the
2629
- * default). Invalid values (NaN, Infinity, negative) are logged as
2630
- * errors and ignored — the previous valid value is preserved.
2631
- */
2632
- setDefaultThrottleMs(value: number | undefined): void;
2633
- get debug(): DebugConfig | undefined;
2634
- setDebug(debug: DebugConfig | undefined): void;
2635
- get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus;
2636
- /** @internal The verbatim single-endpoint URL, including any trailing slash. */
2637
- get ɵruntimeEndpointUrl(): string | undefined;
2638
- get ɵruntimeFetch(): typeof fetch;
2639
- get audioFileTranscriptionEnabled(): boolean;
2640
- get runtimeMode(): RuntimeMode;
2641
- get intelligence(): IntelligenceRuntimeInfo | undefined;
2642
- get threadEndpoints(): ThreadEndpointRuntimeInfo | undefined;
2643
- get suggestions(): boolean | undefined;
2644
- /** Whether the connected Runtime exposes debug-authorized Learning data. */
2645
- get inspectorLearning(): boolean;
2646
- /** Trusted, optional metadata advertised by the connected runtime. */
2647
- get inspectorMetadata(): InspectorMetadataV1 | undefined;
2648
- /** Refresh trusted inspector metadata without reconnecting runtime agents. */
2649
- refreshInspectorMetadata(): Promise<void>;
2650
- get a2uiEnabled(): boolean;
2651
- /**
2652
- * Agent ids the runtime applies A2UI to. `undefined` means A2UI applies to
2653
- * every agent (or is disabled — check `a2uiEnabled`).
2654
- */
2655
- get a2uiAgents(): string[] | undefined;
2656
- get openGenerativeUIEnabled(): boolean;
2657
- get licenseStatus(): RuntimeLicenseStatus | undefined;
2658
- /** Structured Runtime entitlement authority advertised by `/info`. */
2659
- get runtimeEntitlements(): RuntimeEntitlementResponse | undefined;
2660
- /** Whether Core still has a bounded Runtime entitlement retry to settle. */
2661
- get runtimeEntitlementRetryPending(): boolean;
2662
- get telemetryDisabled(): boolean;
2663
- /**
2664
- * Configuration updates
2665
- */
2666
- /**
2667
- * Replace the headers sent with every runtime request.
2668
- *
2669
- * This is an overwrite, not a merge — the supplied object becomes the
2670
- * complete header set. Entries whose value is `null` or `undefined` are
2671
- * dropped, which is how you clear a header (e.g. removing `Authorization`
2672
- * on logout) without leaving an empty-string value behind:
2673
- *
2674
- * ```ts
2675
- * copilotkit.setHeaders({
2676
- * ...copilotkit.headers,
2677
- * Authorization: token ? `Bearer ${token}` : null,
2678
- * });
2679
- * ```
2680
- *
2681
- * The resulting header set is also re-applied to every agent in the registry
2682
- * and `onHeadersChanged` subscribers are notified. These headers are merged
2683
- * ON TOP of the headers each `HttpAgent` was constructed with, so per-agent
2684
- * headers (e.g. an `Authorization` for a self-hosted backend) are preserved;
2685
- * on a key conflict the core-level value wins.
2686
- *
2687
- * Because the agent's construction-time headers form the merge baseline, this
2688
- * method can override a per-agent header but cannot REMOVE one: clearing a
2689
- * core key here only drops the core-level override, after which the agent's
2690
- * own value (if any) re-surfaces. To change a header an agent was constructed
2691
- * with, set it at the provider/core level instead of on the agent, or update
2692
- * it on the agent directly. The clear-on-logout pattern above is for
2693
- * core-level headers.
2694
- *
2695
- * Pass a function to have headers evaluated when each request is sent
2696
- * (sync or async). Setting the same function again is a no-op. A new token
2697
- * from the builder doesn't notify `onHeadersChanged`. On a user switch,
2698
- * call `setHeaders` with a NEW function (or a record), or remount.
2699
- *
2700
- * Passing a record equal (by value) to the currently applied record is
2701
- * also a no-op — safe to call on every render with a fresh object literal.
2702
- */
2703
- setHeaders(headers: CopilotKitHeadersSource): void;
2704
- setCredentials(credentials: RequestCredentials | undefined): void;
2705
- /**
2706
- * Replace the message filter applied to every runtime agent.
2707
- *
2708
- * Applies to agents already discovered as well as ones discovered later, so
2709
- * a filter set before `/info` lands is not lost. Pass `undefined` to go back
2710
- * to sending the full thread.
2711
- */
2712
- setMessageFilter(messageFilter: CopilotKitMessageFilter | undefined): void;
2713
- /**
2714
- * Add run properties that go only to the runs of `agentIds`. When
2715
- * `agentIds` is omitted, every agent gets them. They merge on top of the
2716
- * base `properties`.
2717
- *
2718
- * When an entry value and the existing value under the same key are both
2719
- * plain objects, their keys merge one level deep. So several entries can
2720
- * add keys under one namespace (for example `copilotkit`).
2721
- *
2722
- * @param entry - The properties and the optional agent ids.
2723
- * @returns The id to pass to `removeScopedProperties`.
2724
- *
2725
- * @example
2726
- * const id = copilotkit.addScopedProperties({
2727
- * properties: { copilotkit: { theme: "dark" } },
2728
- * agentIds: ["research"],
2729
- * });
2730
- * copilotkit.removeScopedProperties(id);
2731
- */
2732
- addScopedProperties({
2733
- properties,
2734
- agentIds
2735
- }: ScopedProperties): string;
2736
- /** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */
2737
- removeScopedProperties(id: string): void;
2738
- /**
2739
- * Build the forwarded properties for a run of the given agent: the base
2740
- * properties plus every scoped entry that matches the agent. An entry with
2741
- * `agentIds` does not match when `agentId` is omitted.
2742
- */
2743
- getPropertiesForAgent(agentId?: string): Record<string, unknown>;
2744
- setProperties(properties: Record<string, unknown>): void;
2745
- /**
2746
- * Agent management (delegated to AgentRegistry)
2747
- */
2748
- setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void;
2749
- addAgent__unsafe_dev_only(params: CopilotKitCoreAddAgentParams): void;
2750
- removeAgent__unsafe_dev_only(id: string): void;
2751
- /**
2752
- * Register a proxied agent against an existing runtime agent. The proxy is
2753
- * exposed under `agentId` (local registry id) and routes outbound runtime
2754
- * requests to `runtimeAgentId`. Throws if `agentId` is already taken.
2755
- *
2756
- * Returns the minted proxy and an `unregister` handle for cleanup.
2757
- *
2758
- * Use this to mount multiple frontend agents against a single runtime
2759
- * agent (e.g. one per chat window) without implicit per-thread cloning.
2760
- *
2761
- * @example
2762
- * const { agent, unregister } = copilotkit.registerProxiedAgent({
2763
- * agentId: "chat-1",
2764
- * runtimeAgentId: "default",
2765
- * });
2766
- * // ... <CopilotChat agentId="chat-1" />
2767
- * // on cleanup:
2768
- * unregister();
2769
- */
2770
- registerProxiedAgent(params: CopilotKitCoreRegisterProxiedAgentParams): CopilotKitCoreRegisterProxiedAgentResult;
2771
- getAgent(id: string): AbstractAgent | undefined;
2772
- /** Updates settings for the next capture. Removing the config stops capture. */
2773
- setLearningConfig(config: LearningConfig | undefined): void;
2774
- /**
2775
- * @internal Whether a `learning` config is set. Unlike {@link trajectoryId},
2776
- * it does not change with capture start, connection failures or reconnects.
2777
- */
2778
- get ɵlearningConfigured(): boolean;
2779
- /**
2780
- * @internal Whether captured events may carry agent message text: false
2781
- * without a `learning` config, or when a custom sink sets
2782
- * `capture.agentText` to false. A running custom-sink capture keeps the
2783
- * choice it started with.
2784
- */
2785
- get ɵlearningCapturesAgentText(): boolean;
2786
- /** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */
2787
- ɵsubscribeToLearningConfigured(listener: () => void): () => void;
2788
- /**
2789
- * @internal The generative UI of the framework package, for the inspector.
2790
- * `undefined` when no provider has a `generativeUI` config.
2791
- */
2792
- get ɵgenerativeUIDebugSource(): ɵGenerativeUIDebugSource | undefined;
2793
- /** @internal Set by the framework package. `undefined` removes it. */
2794
- ɵsetGenerativeUIDebugSource(source: ɵGenerativeUIDebugSource | undefined): void;
2795
- /** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */
2796
- ɵsubscribeToGenerativeUIDebugSource(listener: () => void): () => void;
2797
- /** The active capture's Trajectory ID, or null while capture is stopped. */
2798
- get trajectoryId(): string | null;
2799
- private notifyTrajectoryChanged;
2800
- /**
2801
- * Starts one Trajectory after Runtime authorization and the Gateway join.
2802
- * Omit the ID to create one. Repeated starts await the active connection;
2803
- * a different ID stops the previous capture. Explicit sinks retain the
2804
- * prototype's synchronous capture and require a stop before changing IDs.
2805
- *
2806
- * @example copilotkit.startTrajectory({ trajectoryId: crypto.randomUUID() })
2807
- */
2808
- startTrajectory(options?: TrajectoryStartOptions): Promise<StartResult$1>;
2809
- /** Cancels pending work and stops capture, attempting one final batch without waiting for its ACK. */
2810
- stopTrajectory(): void;
2811
- /**
2812
- * Records an outcome that clicks cannot show, such as a saved report or an
2813
- * approved deal. The wire adds `value.seq`; arrays, primitives, and objects
2814
- * already containing `seq` are preserved under `value.data`. Explicit legacy
2815
- * sinks retain object-only events with open-Thread enrichment.
2816
- * No-op while no Trajectory runs. Events emitted during connection recovery
2817
- * count as dropped. Built-in names such as `click` are rejected.
2818
- *
2819
- * @example copilotkit.emitTrajectoryEvent("deal.approved", { dealId: "deal-1" })
2820
- */
2821
- emitTrajectoryEvent(name: string, value?: JsonValue$1): void;
2822
- /**
2823
- * Tells Core that a view shows this Thread, so captured interactions can link to it.
2824
- * Framework bindings call this; call it yourself only without a CopilotKit provider.
2825
- */
2826
- registerOpenThread(params: {
2827
- agentId: string;
2828
- threadId: string;
2829
- }): OpenThreadRegistration;
2830
- /**
2831
- * Re-apply the last resolved header snapshot to a single agent (delegated
2832
- * to AgentRegistry). Core headers are merged on top of the agent's own
2833
- * construction-time headers rather than replacing them, so headers
2834
- * configured directly on an `HttpAgent` (e.g. an `Authorization` for a
2835
- * self-hosted backend) survive header updates instead of being silently
2836
- * dropped (see #5635). On a key conflict the core-level value wins.
2837
- *
2838
- * The merge baseline is the agent's headers as captured the first time the
2839
- * agent is applied (at registration), so the way to change headers
2840
- * afterwards is `setHeaders` (which re-applies to every agent), not mutating
2841
- * `agent.headers` directly — a direct mutation is overwritten on the next
2842
- * re-apply.
2843
- *
2844
- * A `ProxiedCopilotRuntimeAgent` keeps only its own construction-time
2845
- * headers here — core headers are added by `ɵruntimeFetch` when each
2846
- * request is sent (see #1937), so `agent.headers` never carries a stale
2847
- * copy of a core header the builder has since stopped returning.
2848
- *
2849
- * Never invokes the headers builder (unlike the run/connect path's
2850
- * internal `prepareAgentHeadersForRun`): safe to call from a dev-only
2851
- * registration helper or a React effect that re-runs on every render
2852
- * without risking a synchronous throw or an unhandled async rejection from
2853
- * a user-supplied builder.
2854
- */
2855
- applyHeadersToAgent(agent: AbstractAgent): void;
2856
- /**
2857
- * Resolve headers fresh and apply them to `agent` right before a run or
2858
- * connect actually sends (#1937). Friends-only (delegated to
2859
- * AgentRegistry) — the run handler is the sole caller, since resolving can
2860
- * invoke a user-supplied builder that throws or rejects.
2861
- */
2862
- private prepareAgentHeadersForRun;
2863
- /**
2864
- * Context management (delegated to ContextStore).
2865
- * Pass `agentIds` to restrict the entry to runs of specific agents;
2866
- * omit it for context every agent should receive.
2867
- */
2868
- addContext(context: ScopedContext): string;
2869
- removeContext(id: string): void;
2870
- /**
2871
- * Build the context array for a run of the given agent, dropping entries
2872
- * scoped to other agents and stripping the scoping metadata.
2873
- */
2874
- getContextForAgent(agentId?: string): Context[];
2875
- /**
2876
- * Thread store registry (delegated to ThreadStoreRegistry)
2877
- */
2878
- registerThreadStore(agentId: string, store: ɵThreadStore): void;
2879
- unregisterThreadStore(agentId: string): void;
2880
- getThreadStore(agentId: string): ɵThreadStore | undefined;
2881
- getThreadStores(): Readonly<Record<string, ɵThreadStore>>;
2882
- /**
2883
- * Returns the single core-owned, user-scoped memory store, creating and
2884
- * starting it on first access. Unlike thread stores, memory is not scoped per
2885
- * agent: there is exactly one store whose runtime context the core wires
2886
- * itself (see `syncMemoryContext`), so consumers (e.g. a `useMemories`
2887
- * binding) just read this store rather than registering one.
2888
- */
2889
- getMemoryStore(): ɵMemoryStore;
2890
- /**
2891
- * Lazily creates, starts, and context-syncs the core-owned memory store on
2892
- * first access, then returns it. Subsequent calls return the existing store.
2893
- * The store uses the Core Runtime fetch so REST and single-route transports
2894
- * share the same resource behavior. Its Runtime context is synced at once.
2895
- */
2896
- private ensureMemoryStore;
2897
- /**
2898
- * Pushes the current runtime wiring into the memory store. When the runtime
2899
- * is connected and both the intelligence WebSocket URL and runtime URL are
2900
- * available, the store receives a context (runtime URL, WebSocket URL);
2901
- * otherwise its context is cleared. No-op when the store has not been
2902
- * created yet.
2903
- *
2904
- * Headers are deliberately NOT part of this context: the store's `fetch` is
2905
- * `ɵruntimeFetch` (see `ensureMemoryStore`), which already resolves and
2906
- * overlays the current core headers at send time (#1937) — a header
2907
- * snapshot copied here would go stale between context syncs.
2908
- */
2909
- private syncMemoryContext;
2910
- /**
2911
- * Suggestions management (delegated to SuggestionEngine)
2912
- */
2913
- addSuggestionsConfig(config: SuggestionsConfig): string;
2914
- removeSuggestionsConfig(id: string): void;
2915
- reloadSuggestions(agentId: string): void;
2916
- clearSuggestions(agentId: string): void;
2917
- getSuggestions(agentId: string): CopilotKitCoreGetSuggestionsResult;
2918
- /**
2919
- * Tool management (delegated to RunHandler)
2920
- */
2921
- addTool<T extends Record<string, unknown> = Record<string, unknown>>(tool: FrontendTool<T>): void;
2922
- removeTool(id: string, agentId?: string): void;
2923
- getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined;
2924
- setTools(tools: FrontendTool<any>[]): void;
2925
- /**
2926
- * Enable/disable a registered frontend tool at runtime without unregistering
2927
- * it (Inspector "Capabilities" tool). A disabled tool is omitted from the
2928
- * tool list sent to the agent on the next run. The override is keyed by name
2929
- * (+ optional agentId) and survives the tool being re-registered.
2930
- */
2931
- setToolEnabled(name: string, enabled: boolean, agentId?: string): void;
2932
- /** Whether a registered tool is currently enabled (defaults true). */
2933
- isToolEnabled(name: string, agentId?: string): boolean;
2934
- /**
2935
- * A2UI catalog component management (delegated to RunHandler).
2936
- * Registers the full component list and controls per-component enablement.
2937
- */
2938
- setCatalogComponents(components: CopilotKitCoreCatalogComponent[]): void;
2939
- setCatalogComponentEnabled(name: string, enabled: boolean): void;
2940
- isCatalogComponentEnabled(name: string): boolean;
2941
- /**
2942
- * Subscription lifecycle
2943
- */
2944
- subscribe(subscriber: CopilotKitCoreSubscriber): CopilotKitCoreSubscription;
2945
- /**
2946
- * Subscribe to an agent's notification and lifecycle events with
2947
- * optional configuration (e.g. throttling).
2948
- *
2949
- * Wraps every callback with error protection (`safeCall`) and applies
2950
- * the options before delegating to `agent.subscribe()`.
2951
- *
2952
- * See {@link SubscribeToAgentSubscriber} for the accepted callback subset
2953
- * and the rationale for excluding AG-UI event handlers.
2954
- */
2955
- subscribeToAgentWithOptions(agent: AbstractAgent, subscriber: SubscribeToAgentSubscriber, options?: SubscribeToAgentOptions): CopilotKitCoreSubscription;
2956
- /**
2957
- * Agent connectivity (delegated to RunHandler)
2958
- */
2959
- connectAgent(params: CopilotKitCoreConnectAgentParams): Promise<_ag_ui_client0.RunAgentResult>;
2960
- stopAgent(params: CopilotKitCoreStopAgentParams): void;
2961
- runAgent(params: CopilotKitCoreRunAgentParams): Promise<_ag_ui_client0.RunAgentResult>;
2962
- /**
2963
- * Programmatically execute a registered frontend tool without going through an LLM turn.
2964
- * The handler runs, render components show up in the UI, and both the tool call and
2965
- * result messages are added to `agent.messages`.
2966
- */
2967
- runTool(params: CopilotKitCoreRunToolParams): Promise<CopilotKitCoreRunToolResult>;
2968
- /**
2969
- * State management (delegated to StateManager)
2970
- */
2971
- getStateByRun(agentId: string, threadId: string, runId: string): State | undefined;
2972
- getRunIdForMessage(agentId: string, threadId: string, messageId: string): string | undefined;
2973
- getRawEventForMessage(agentId: string, threadId: string, messageId: string): unknown;
2974
- getRunIdsForThread(agentId: string, threadId: string): string[];
2975
- /**
2976
- * Internal method used by RunHandler to build frontend tools
2977
- */
2978
- private buildFrontendTools;
2979
- /**
2980
- * Called before each follow-up agent run (after tool execution).
2981
- *
2982
- * When a frontend tool handler calls framework state setters (e.g. React's
2983
- * setState), those updates are batched and deferred — they do not take effect
2984
- * until the framework's scheduler runs (React uses MessageChannel).
2985
- * useAgentContext registers context via useLayoutEffect, which runs
2986
- * synchronously after React commits that deferred batch.
2987
- *
2988
- * Without yielding here, the follow-up runAgent reads the context store
2989
- * synchronously while the deferred updates are still pending, producing stale
2990
- * context for the next agent turn.
2991
- *
2992
- * Override in framework-specific subclasses to yield to the framework
2993
- * scheduler before the follow-up run. The base implementation is a no-op
2994
- * because non-React environments have no deferred state to flush.
2995
- */
2996
- waitForPendingFrameworkUpdates(): Promise<void>;
2997
- }
2998
- //#endregion
2999
- //#region src/core/suggestion-engine.d.ts
3000
- /**
3001
- * Manages suggestion generation, streaming, and lifecycle for CopilotKitCore.
3002
- * Handles both dynamic (AI-generated) and static suggestions.
3003
- */
3004
- declare class SuggestionEngine {
3005
- private core;
3006
- private _suggestionsConfig;
3007
- private _suggestions;
3008
- private _runningSuggestions;
3009
- constructor(core: CopilotKitCore);
3010
- /**
3011
- * Initialize with suggestion configs
3012
- */
3013
- initialize(suggestionsConfig: SuggestionsConfig[]): void;
3014
- /**
3015
- * Add a suggestion configuration
3016
- * @returns The ID of the created config
3017
- */
3018
- addSuggestionsConfig(config: SuggestionsConfig): string;
3019
- /**
3020
- * Remove a suggestion configuration by ID
3021
- */
3022
- removeSuggestionsConfig(id: string): void;
3023
- /**
3024
- * Reload suggestions for a specific agent
3025
- * This triggers generation of new suggestions based on current configs
3026
- */
3027
- reloadSuggestions(agentId: string): void;
3028
- /**
3029
- * Clear all suggestions for a specific agent
3030
- */
3031
- clearSuggestions(agentId: string): void;
3032
- /**
3033
- * Get current suggestions for an agent
3034
- */
3035
- getSuggestions(agentId: string): CopilotKitCoreGetSuggestionsResult;
3036
- /**
3037
- * Generate suggestions by running a provider agent and extracting the
3038
- * `copilotkitSuggest` tool call from its streamed messages.
3039
- *
3040
- * Two transports, one set of mechanics: both seed an agent with the
3041
- * consumer's messages + state and the instruction, then `runAgent` with
3042
- * forced `copilotkitSuggest` tool choice, parsing suggestions as messages
3043
- * stream in via `onMessagesChanged`.
3044
- *
3045
- * - **Stateless** (runtime advertises `suggestions` and transport isn't
3046
- * `single`): a stock `HttpAgent` pointed at `/agent/:id/suggest`. That
3047
- * endpoint runs the provider directly and streams AG-UI SSE **without**
3048
- * persisting a thread, and a plain `HttpAgent` only ever speaks REST SSE —
3049
- * it never routes through the Intelligence websocket delegate (which would
3050
- * persist a thread). This is the path that removes the thread flood.
3051
- * - **Fallback** (capability absent → old runtime, or `single` transport):
3052
- * clone the provider agent and run it client-side, as before.
3053
- *
3054
- * Gated to non-`single` transports because this client only builds the
3055
- * multi-route `/agent/:id/suggest` URL; single-route deployments (not the
3056
- * persisting-thread/Intelligence case) fall through to the clone fallback.
3057
- */
3058
- private generateSuggestions;
3059
- /**
3060
- * Finalize suggestions by marking them as no longer loading
3061
- */
3062
- private finalizeSuggestions;
3063
- /**
3064
- * Extract suggestions from messages (called during streaming)
3065
- */
3066
- extractSuggestions(messages: readonly Message[], suggestionId: string, consumerAgentId: string, isRunning: boolean): void;
3067
- /**
3068
- * Notify subscribers of suggestions config changes
3069
- */
3070
- private notifySuggestionsConfigChanged;
3071
- /**
3072
- * Notify subscribers of suggestions changes
3073
- */
3074
- private notifySuggestionsChanged;
3075
- /**
3076
- * Notify subscribers that suggestions started loading
3077
- */
3078
- private notifySuggestionsStartedLoading;
3079
- /**
3080
- * Notify subscribers that suggestions finished loading
3081
- */
3082
- private notifySuggestionsFinishedLoading;
3083
- /**
3084
- * Check if suggestions should be shown based on availability and message count
3085
- */
3086
- private shouldShowSuggestions;
3087
- /**
3088
- * Add static suggestions directly without AI generation
3089
- */
3090
- private addStaticSuggestions;
3091
- }
3092
- /**
3093
- * Detects an `AbortController`-driven cancellation so the stateless path can
3094
- * treat it as an expected (non-error) outcome on clear/reload.
3095
- */
3096
- declare function isAbortError(error: unknown): boolean;
3097
- //#endregion
3098
- //#region src/core/webmcp.d.ts
3099
- /**
3100
- * The subset of the WebMCP `ModelContext` API
3101
- * (https://webmachinelearning.github.io/webmcp/) that the registry depends on.
3102
- * Kept structural so the code works against the real browser API and test
3103
- * doubles alike. Aborting the registration signal unregisters the tool.
3104
- */
3105
- interface WebMCPModelContext {
3106
- registerTool(tool: {
3107
- name: string;
3108
- description: string;
3109
- inputSchema: Record<string, unknown>;
3110
- execute: (args: Record<string, unknown>, options: {
3111
- signal?: AbortSignal;
3112
- }) => Promise<unknown>;
3113
- annotations?: WebMCPToolAnnotations;
3114
- }, options: {
3115
- signal: AbortSignal;
3116
- }): Promise<undefined>;
3117
- }
3118
- /**
3119
- * Return the page's `document.modelContext`, or null when WebMCP is not
3120
- * available (SSR, React Native, browsers without the API enabled).
3121
- */
3122
- declare function getWebMCPModelContext(): WebMCPModelContext | null;
3123
- /**
3124
- * Keeps a set of frontend tools registered on the page's WebMCP model context.
3125
- *
3126
- * `sync(desired)` reconciles the registrations with the desired set: tools that
3127
- * are gone (or were re-registered with a new tool object) are unregistered by
3128
- * aborting their registration signal, and new tools are registered with an
3129
- * `execute` that delegates to the frontend tool's own handler.
3130
- *
3131
- * All WebMCP-API constraints live here so callers only supply the desired set:
3132
- * a tool without a description is skipped with a warning (the spec rejects
3133
- * empty descriptions), and failures from `registerTool` (duplicate name,
3134
- * unsupported context, ...) are warned rather than thrown.
3135
- */
3136
- declare class WebMCPRegistry {
3137
- private entries;
3138
- private warnedNames;
3139
- /** Names currently kept registered on the model context. */
3140
- get registeredNames(): string[];
3141
- /** Reconcile the registered tools with the desired set. */
3142
- sync(desired: Map<string, FrontendTool<any>>): void;
3143
- /**
3144
- * Build the WebMCP model-context tool for a frontend tool. The `execute`
3145
- * callback delegates to the frontend tool's own handler, so a browser agent
3146
- * call runs the same application code as an agent call.
3147
- */
3148
- private buildModelContextTool;
3149
- /** Log `message` once per tool name. Repeated syncs must not spam the log. */
3150
- private warnOnce;
3151
- }
3152
- //#endregion
3153
- //#region src/utils/markdown.d.ts
3154
- declare function completePartialMarkdown(input: string): string;
3155
- //#endregion
3156
- //#region src/utils/http-agent.d.ts
3157
- /**
3158
- * Whether an agent is an `HttpAgent`, including one built from another copy of
3159
- * `@ag-ui/client` (an app that pins its own 0.x version next to CopilotKit's
3160
- * 1.0, for example). `instanceof` is false across package copies, which made
3161
- * CopilotKit silently skip headers and abort wiring for those agents. The
3162
- * fallback checks the public fields CopilotKit uses, which every published
3163
- * `HttpAgent` has.
3164
- */
3165
- declare function ɵisHttpAgent(agent: unknown): agent is HttpAgent;
3166
- //#endregion
3167
- //#region src/intelligence-agent.d.ts
3168
- interface IntelligenceAgentSharedState {
3169
- lastSeenEventIds: Map<string, string>;
3170
- }
3171
- declare class AgentThreadLockedError extends Error {
3172
- constructor(threadId?: string);
3173
- }
3174
- /**
3175
- * The gateway could not replay a live run's events, so the client cannot
3176
- * verify the run it is following. The run itself may still be going on the
3177
- * server; reconnecting to the thread shows its real state.
3178
- */
3179
- declare class IntelligenceReplayFailedError extends Error {
3180
- readonly threadId: string;
3181
- readonly runId: string | null;
3182
- readonly code = "INTELLIGENCE_REPLAY_FAILED";
3183
- constructor(threadId: string, runId: string | null);
3184
- }
3185
- /**
3186
- * Typed contract for agents that expose the completion promise of their
3187
- * currently in-flight run.
3188
- *
3189
- * `IntelligenceAgent` resolves this promise once a run's observable pipeline
3190
- * finalizes (see {@link IntelligenceAgent.connectAgent}). Consumers (e.g. the
3191
- * v2 `CopilotChat` send-serialization path) await it to let an in-flight run —
3192
- * notably an interrupt RESUME — finish before dispatching a new run, instead
3193
- * of pre-empting it.
3194
- *
3195
- * The base `AbstractAgent` from `@ag-ui/client` only declares this property
3196
- * privately, so it is reachable only through this contract plus the
3197
- * {@link isRunCompletionAware} type guard. This keeps callers off `as unknown`
3198
- * casts while still degrading safely for agents that don't implement it.
3199
- */
3200
- interface RunCompletionAware {
3201
- /**
3202
- * Resolves when the active run's pipeline finalizes (completes, errors, or is
3203
- * detached). `undefined` when no run is in flight.
3204
- */
3205
- readonly activeRunCompletionPromise?: Promise<void>;
3206
- }
3207
- /**
3208
- * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes
3209
- * an `activeRunCompletionPromise` property, so callers can await an in-flight
3210
- * run without an `as unknown as` cast. Returns false for agents that don't
3211
- * implement the contract, letting the caller skip the await and degrade safely.
3212
- */
3213
- declare function isRunCompletionAware(agent: unknown): agent is RunCompletionAware;
3214
- interface IntelligenceAgentConfig {
3215
- /** Phoenix websocket URL, e.g. "ws://localhost:4000/socket" */
3216
- url: string;
3217
- /** Runtime base URL, e.g. "http://localhost:4000" */
3218
- runtimeUrl: string;
3219
- /** HTTP transport for run/connect requests. Defaults to REST. */
3220
- transport?: "rest" | "single";
3221
- /** Agent identifier for REST endpoints */
3222
- agentId: string;
3223
- /** Optional params sent on socket connect (e.g. auth token) */
3224
- socketParams?: Record<string, string>;
3225
- /** Optional headers sent with REST requests */
3226
- headers?: Record<string, string>;
3227
- /** Optional credentials mode for fetch requests */
3228
- credentials?: RequestCredentials;
3229
- fetch?: typeof fetch;
3230
- }
3231
- declare class IntelligenceAgent extends AbstractAgent {
3232
- private config;
3233
- private socket;
3234
- private activeChannel;
3235
- private canonicalRunId;
3236
- private sharedState;
3237
- constructor(config: IntelligenceAgentConfig, sharedState?: IntelligenceAgentSharedState);
3238
- /**
3239
- * Headers sent with the REST join requests (`/connect`, `/run`).
3240
- *
3241
- * Deliberately a public accessor pair rather than a plain read of `config`.
3242
- * `ProxiedCopilotRuntimeAgent` builds its delegate once and caches it for the
3243
- * proxy's lifetime, so a header that changes later (a tenant switch, a
3244
- * rotated bearer) would otherwise never reach the gateway. The accessor is
3245
- * what closes that gap: `syncDelegate` refreshes the delegate before every
3246
- * join, and its `hasHeaders` probe is an `"headers" in agent` check — which a
3247
- * prototype accessor satisfies but a `private config` does not.
3248
- *
3249
- * The setter replaces the config object instead of mutating it because
3250
- * `clone()` hands the same config reference to the copy. An in-place write
3251
- * would therefore have a per-thread clone's headers land on the original's
3252
- * config too. The join path itself would survive that (`syncDelegate`
3253
- * rewrites the headers just before every join), but the re-acquisition inside
3254
- * an already-running pipeline does not go through `syncDelegate` — so a
3255
- * clone's tenant could ride out on the original's socket-error refresh. That
3256
- * is the same cross-tenant leak this accessor exists to prevent.
3257
- */
3258
- get headers(): Record<string, string> | undefined;
3259
- set headers(headers: Record<string, string> | undefined);
3260
- /** Credentials mode for the REST join requests. Live for the same reason as {@link headers}. */
3261
- get credentials(): RequestCredentials | undefined;
3262
- set credentials(credentials: RequestCredentials | undefined);
3263
- clone(): IntelligenceAgent;
3264
- /**
3265
- * Override of AbstractAgent.connectAgent that removes the `verifyEvents` step.
3266
- *
3267
- * IntelligenceAgent uses long-lived WebSocket connections rather than
3268
- * request-scoped SSE streams. When connecting to replay historical messages
3269
- * for an existing thread, the connection semantics don't map to a single
3270
- * agent run start/stop cycle: the replayed events may omit the
3271
- * RUN_STARTED/RUN_FINISHED bookends, or carry events from several past runs,
3272
- * either of which makes `verifyEvents` stall or error out.
3273
- *
3274
- * See {@link ɵconnectWithoutEventVerification} for the pipeline itself, which
3275
- * the self-hosted `/connect` path shares for the same reason.
3276
- */
3277
- connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
3278
- abortRun(): void;
3279
- /**
3280
- * Trigger the run via REST, then join the realtime thread channel and relay
3281
- * server-pushed AG-UI events to the Observable subscriber.
3282
- */
3283
- run(input: RunAgentInput): Observable<BaseEvent>;
3284
- /**
3285
- * Reconnect to an existing thread by fetching websocket credentials and
3286
- * joining the realtime thread channel.
3287
- */
3288
- /**
3289
- * Reconnect to an existing thread by fetching websocket credentials
3290
- * and joining the realtime thread channel.
3291
- *
3292
- * Note: this method does NOT clear the replay cursor. Whether to
3293
- * request a full historical replay vs. resume from
3294
- * `lastSeenEventId` is a decision the caller (typically
3295
- * `RunHandler.connectAgent`) makes by calling
3296
- * {@link clearReconnectCursor} ahead of time on a fresh thread
3297
- * restore. Same-thread churn re-connects preserve the cursor so the
3298
- * gateway only streams events past it instead of replaying the
3299
- * entire history every time the chat re-opens a socket.
3300
- */
3301
- protected connect(input: RunAgentInput, lifecycle?: ConnectionReplayLifecycle): Observable<BaseEvent>;
3302
- /**
3303
- * Tear down a specific channel + socket pair that belongs to one pipeline.
3304
- * Only nulls instance references when they still point to the owned resource,
3305
- * so a concurrent pipeline's resources are never clobbered.
3306
- */
3307
- private cleanupOwned;
3308
- private cleanup;
3309
- private requestJoinCredentials$;
3310
- private normalizeJoinCredentials;
3311
- private observeThread$;
3312
- private observeThreadSession$;
3313
- private joinThreadChannel$;
3314
- private observeSocketHealth$;
3315
- private observeThreadEvents$;
3316
- private observeControlEvent$;
3317
- private observeChannelEvent$;
3318
- private createThreadNotifications;
3319
- private buildRuntimeUrl;
3320
- private createThreadChannelParams;
3321
- private getLastSeenEventId;
3322
- private getReconnectCursor;
3323
- /**
3324
- * Drop the cached `lastSeenEventId` cursor for `threadId` so the
3325
- * next connect to that topic asks the gateway for a full historical
3326
- * replay (rather than resuming). Public because
3327
- * `RunHandler.connectAgent` calls it on a detected thread switch
3328
- * to rebuild local state from scratch, and skips it on same-thread
3329
- * churn so the gateway can resume.
3330
- */
3331
- clearReconnectCursor(threadId: string): void;
3332
- private updateLastSeenEventId;
3333
- private updateLastSeenEventIdFromControl;
3334
- private advanceLastSeenEventId;
3335
- private readEventId;
3336
- private readControlEventId;
3337
- private readDurableEventId;
3338
- private canFallbackCompleteConnect;
3339
- private applyCanonicalRunIdentity;
3340
- private isSocketReconnectExhaustedError;
3341
- }
3342
- //#endregion
3343
- //#region src/utils/phoenix-observable.d.ts
3344
- /**
3345
- * Minimal Phoenix push contract used by the observable adapters.
3346
- */
3347
- interface ɵPhoenixPushLike {
3348
- receive(status: string, callback: (payload?: unknown) => unknown): ɵPhoenixPushLike;
3349
- }
3350
- /**
3351
- * Minimal Phoenix channel contract used by the observable adapters.
3352
- */
3353
- interface ɵPhoenixChannelLike {
3354
- on(event: string, callback: (payload: unknown) => void): number;
3355
- off(event: string, ref?: number): void;
3356
- onError?(callback: (reason?: unknown) => void): unknown;
3357
- join(params?: Record<string, unknown>): ɵPhoenixPushLike;
3358
- push?(event: string, payload: unknown): ɵPhoenixPushLike;
3359
- leave(): void;
3360
- }
3361
- /**
3362
- * Minimal Phoenix socket contract used by the observable adapters.
3363
- */
3364
- interface ɵPhoenixSocketLike {
3365
- connect(): void;
3366
- disconnect(): void;
3367
- channel(topic: string, params?: Record<string, unknown>): ɵPhoenixChannelLike;
3368
- onError(callback: (error?: unknown) => void): unknown;
3369
- onOpen(callback: () => void): unknown;
3370
- }
3371
- /**
3372
- * Socket lifecycle notifications exposed by {@link ɵphoenixSocket$}.
3373
- */
3374
- type ɵPhoenixSocketSignal = {
3375
- type: "open";
3376
- } | {
3377
- type: "error";
3378
- error?: unknown;
3379
- };
3380
- /**
3381
- * Terminal outcomes of a Phoenix channel join attempt.
3382
- */
3383
- type ɵPhoenixJoinOutcome = {
3384
- type: "joined";
3385
- } | {
3386
- type: "error";
3387
- response?: unknown;
3388
- } | {
3389
- type: "timeout";
3390
- };
3391
- /**
3392
- * Active Phoenix socket session plus its derived lifecycle stream.
3393
- */
3394
- interface ɵPhoenixSocketSession {
3395
- socket: ɵPhoenixSocketLike;
3396
- signals$: Observable<ɵPhoenixSocketSignal>;
3397
- }
3398
- /**
3399
- * Active Phoenix channel session plus its derived join-outcome stream.
3400
- */
3401
- interface ɵPhoenixChannelSession {
3402
- channel: ɵPhoenixChannelLike;
3403
- joinOutcome$: Observable<ɵPhoenixJoinOutcome>;
3404
- }
3405
- /**
3406
- * Options for creating a cold Phoenix socket session stream.
3407
- */
3408
- interface ɵPhoenixSocketOptions {
3409
- url: string;
3410
- options?: Record<string, unknown>;
3411
- }
3412
- /**
3413
- * Options for creating a cold Phoenix channel session stream from a socket stream.
3414
- */
3415
- interface ɵPhoenixChannelOptions {
3416
- socket$: Observable<ɵPhoenixSocketSession>;
3417
- topic: string;
3418
- params?: Record<string, unknown>;
3419
- leaveOnUnsubscribe?: boolean;
3420
- }
3421
- /**
3422
- * Create a cold Phoenix socket session.
3423
- *
3424
- * The socket is constructed and connected on subscription, and disconnected on
3425
- * teardown. Each subscription creates an isolated socket instance.
3426
- *
3427
- * Heartbeats default to every 15s: Phoenix's own 30s default matches common
3428
- * reverse-proxy WebSocket idle timeouts (e.g. Azure Application Gateway), which
3429
- * would drop the socket during a quiet run. Callers may override it.
3430
- */
3431
- declare function ɵphoenixSocket$(options: ɵPhoenixSocketOptions): Observable<ɵPhoenixSocketSession>;
3432
- /**
3433
- * Create a cold Phoenix channel session from a socket session stream.
3434
- *
3435
- * A channel is created and joined for each active socket session. If the
3436
- * upstream socket session changes, the previous channel is left before the
3437
- * next one becomes active.
3438
- */
3439
- declare function ɵphoenixChannel$(options: ɵPhoenixChannelOptions): Observable<ɵPhoenixChannelSession>;
3440
- /**
3441
- * Observe a named Phoenix channel event as an observable payload stream.
3442
- */
3443
- declare function ɵobservePhoenixEvent$<T>(channel: ɵPhoenixChannelLike, eventName: string): Observable<T>;
3444
- /**
3445
- * Flatten channel sessions into their join-outcome stream.
3446
- */
3447
- declare function ɵobservePhoenixJoinOutcome$(channel$: Observable<ɵPhoenixChannelSession>): Observable<ɵPhoenixJoinOutcome>;
3448
- /**
3449
- * Complete when a channel joins successfully, or error if the join fails.
3450
- */
3451
- declare function ɵjoinPhoenixChannel$(channel$: Observable<ɵPhoenixChannelSession>): Observable<never>;
3452
- /**
3453
- * Flatten socket sessions into their lifecycle signal stream.
3454
- */
3455
- declare function ɵobservePhoenixSocketSignals$(socket$: Observable<ɵPhoenixSocketSession>): Observable<ɵPhoenixSocketSignal>;
3456
- /**
3457
- * Error after a socket emits the configured number of consecutive error
3458
- * signals, resetting the counter after each successful open signal.
3459
- */
3460
- declare function ɵobservePhoenixSocketHealth$(socketSignals$: Observable<ɵPhoenixSocketSignal>, maxConsecutiveErrors: number): Observable<never>;
3461
- //#endregion
3462
- //#region src/features.d.ts
3463
- /**
3464
- * Central registry of CopilotKit feature names.
3465
- *
3466
- * Feature names are the strings passed to a license context's `checkFeature`
3467
- * (see `@copilotkit/shared`'s `LicenseContextValue`). Historically the only
3468
- * features referenced by literal were the chat surfaces (`chat`, `sidebar`,
3469
- * `popup`); this module makes the set explicit and typed so new surfaces —
3470
- * such as the threads drawer — register a real, discoverable feature name
3471
- * rather than an ad-hoc string scattered across components.
3472
- *
3473
- * `checkFeature` itself still accepts any `string` for backward compatibility;
3474
- * this registry simply documents and types the names CopilotKit recognises.
3475
- */
3476
- /**
3477
- * The set of feature names CopilotKit recognises.
3478
- *
3479
- * Frozen so the array cannot be mutated at runtime. Add new surfaces here when
3480
- * they begin gating behaviour on `checkFeature`.
3481
- */
3482
- declare const ɵCOPILOTKIT_FEATURES: readonly ["chat", "sidebar", "popup", "threads"];
3483
- /**
3484
- * Union of recognised CopilotKit feature names.
3485
- */
3486
- type ɵCopilotKitFeature = (typeof ɵCOPILOTKIT_FEATURES)[number];
3487
- /**
3488
- * Type guard: returns `true` when `name` is a recognised CopilotKit feature.
3489
- *
3490
- * @param name - Candidate feature name.
3491
- * @returns Whether `name` is a registered feature.
3492
- *
3493
- * @example
3494
- * ```ts
3495
- * if (ɵisCopilotKitFeature("threads")) {
3496
- * // narrowed to ɵCopilotKitFeature
3497
- * }
3498
- * ```
3499
- */
3500
- declare function ɵisCopilotKitFeature(name: string): name is ɵCopilotKitFeature;
3501
- //#endregion
3502
- //#region src/interrupt-state.d.ts
3503
- /** @internal Application authors must not depend on this contract. */
3504
- interface ɵInterruptEvent<TValue = unknown> {
3505
- name: string;
3506
- value: TValue;
3507
- }
3508
- /** @internal Application authors must not depend on this contract. */
3509
- type ɵPendingInterrupt<TValue = unknown> = {
3510
- kind: "legacy";
3511
- event: ɵInterruptEvent<TValue>;
3512
- } | {
3513
- kind: "standard";
3514
- interrupts: readonly Interrupt[];
3515
- };
3516
- /** @internal Application authors must not depend on this contract. */
3517
- interface ɵInterruptToolResult {
3518
- toolCallId: string;
3519
- content: Extract<Message, {
3520
- role: "tool";
3521
- }>["content"];
3522
- }
3523
- /** @internal Application authors must not depend on this contract. */
3524
- type ɵInterruptDecision = {
3525
- kind: "ignored";
3526
- } | {
3527
- kind: "waiting";
3528
- } | {
3529
- kind: "dismiss";
3530
- } | {
3531
- kind: "expired";
3532
- interrupt: Interrupt;
3533
- } | {
3534
- kind: "legacy-resume";
3535
- payload: unknown;
3536
- interruptValue: unknown;
3537
- } | {
3538
- kind: "resume";
3539
- resume: ResumeEntry[];
3540
- toolResults: ɵInterruptToolResult[];
3541
- };
3542
- /**
3543
- * @internal Framework-neutral interrupt response state shared by framework
3544
- * adapters. Application authors must not depend on this API.
3545
- */
3546
- declare class ɵInterruptState<TValue = unknown> {
3547
- #private;
3548
- /** Return the active normalized interrupt without exposing mutable state. */
3549
- get pending(): ɵPendingInterrupt<TValue> | null;
3550
- /** Replace the current interrupt with a legacy custom-event interrupt. */
3551
- setLegacy(event: ɵInterruptEvent<TValue>): void;
3552
- /** Replace the current interrupt with an AG-UI standard interrupt set. */
3553
- setStandard(interrupts: readonly Interrupt[]): void;
3554
- /** Clear all pending interrupt data and accumulated responses. */
3555
- clear(): void;
3556
- /** Record a resolved response and return the next framework action. */
3557
- resolve(payload?: unknown, interruptId?: string, messages?: readonly Message[]): ɵInterruptDecision;
3558
- /** Record a cancelled response and return the next framework action. */
3559
- cancel(interruptId?: string, messages?: readonly Message[]): ɵInterruptDecision;
3560
- /** Reject ambiguous assistant definitions before executing or answering a call. */
3561
- validateToolCalls(messages: readonly Message[]): void;
3562
- /** Let UI adapters ignore answers for exactly one successful frontend result. */
3563
- isCompletedToolCall(interruptId: string | undefined, messages: readonly Message[]): boolean;
3564
- /** Resume only when saved frontend results answer every pending interrupt. */
3565
- resumeWithToolResults(messages: readonly Message[]): ɵInterruptDecision;
3566
- }
3567
- /** @internal Share decisions and the single resume claim for an agent's pending batch. */
3568
- declare function ɵgetAgentInterruptState(agent: AbstractAgent, interrupts?: readonly Interrupt[]): ɵInterruptState;
3569
- /** @internal A new run owns a new batch, even if the server reuses interrupt IDs. */
3570
- declare function ɵclearAgentInterruptState(agent: AbstractAgent): void;
3571
- //#endregion
3572
- //#region src/inspector-thread-bridge.d.ts
3573
- declare const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID: "cpk-inspector-thread";
3574
- type InspectorViewThreadPayload = {
3575
- requestId: string;
3576
- threadId: string;
3577
- agentId: string;
3578
- };
3579
- type InspectorStopViewingPayload = {
3580
- requestId: string;
3581
- agentId: string;
3582
- };
3583
- type InspectorActiveThreadPayload = {
3584
- requestId: string;
3585
- threadId: string;
3586
- agentId: string;
3587
- source: "app" | "override";
3588
- };
3589
- type InspectorViewThreadResultPayload = {
3590
- requestId: string;
3591
- threadId: string;
3592
- agentId: string;
3593
- ok: true;
3594
- } | {
3595
- requestId: string;
3596
- threadId: string;
3597
- agentId: string;
3598
- ok: false;
3599
- reason: "connect-failed";
3600
- };
3601
- /** The Inspector thread bridge is development-only. */
3602
- declare function isInspectorThreadBridgeEnabled(): boolean;
3603
- declare function createInspectorThreadRequestId(): string;
3604
- /**
3605
- * Ask the first mounted official chat for the matching agent to load a thread.
3606
- * Returns false when no chat claims the request synchronously.
3607
- */
3608
- declare function emitInspectorViewThread(payload: InspectorViewThreadPayload): boolean;
3609
- declare function emitInspectorStopViewing(payload: InspectorStopViewingPayload): void;
3610
- declare function emitInspectorActiveThread(payload: InspectorActiveThreadPayload): void;
3611
- declare function emitInspectorViewThreadResult(payload: InspectorViewThreadResultPayload): void;
3612
- declare function onInspectorViewThread(handler: (payload: InspectorViewThreadPayload) => boolean): () => void;
3613
- declare function onInspectorStopViewing(handler: (payload: InspectorStopViewingPayload) => void): () => void;
3614
- declare function onInspectorActiveThread(handler: (payload: InspectorActiveThreadPayload) => void): () => void;
3615
- declare function onInspectorViewThreadResult(handler: (payload: InspectorViewThreadResultPayload) => void): () => void;
3616
- //#endregion
3617
- //#region src/a2ui-markdown/fence-parser.d.ts
3618
- /** Language of a fenced code block that carries A2UI operations. */
3619
- declare const A2UI_FENCE_LANGUAGE = "a2ui";
3620
- /**
3621
- * One part of an assistant message, in source order: prose markdown, or the
3622
- * body of a top-level ```a2ui fence. `target` is the id from a
3623
- * `target=<id>` token in the fence info string. With no target, the surface
3624
- * goes to the chat.
3625
- */
3626
- type MarkdownSegment = {
3627
- type: "markdown";
3628
- text: string;
3629
- } | {
3630
- type: "a2ui";
3631
- index: number;
3632
- text: string;
3633
- closed: boolean;
3634
- target?: string;
3635
- };
3636
- /**
3637
- * Split a (possibly still streaming) markdown string into prose segments and
3638
- * top-level ```a2ui fences. Fences of other languages stay inside prose
3639
- * segments byte-for-byte, and a2ui markers inside them are ignored. Only
3640
- * column-0 fences are recognised, so a fence indented inside a list item is
3641
- * left to the markdown renderer.
3642
- *
3643
- * The first info-string token must be exactly `a2ui`. A later
3644
- * `target=<id>` token sets `target` on the segment (for example
3645
- * ```` ```a2ui target=recommendations ````). Other tokens are ignored.
3646
- *
3647
- * An a2ui segment's `text` is the fence body. For a closed fence it ends with
3648
- * "\n" when non-empty. For an open (still streaming or aborted) fence it is
3649
- * everything after the opener line, minus a half-streamed closing marker.
3650
- *
3651
- * @param markdown - The assistant message text, complete or still streaming.
3652
- * @returns The segments in source order.
3653
- *
3654
- * @example
3655
- * ```ts
3656
- * for (const segment of splitA2UIMarkdown(message.content)) {
3657
- * if (segment.type === "a2ui") renderSurface(segment.text, segment.target);
3658
- * else renderMarkdown(segment.text);
3659
- * }
3660
- * ```
3661
- */
3662
- declare function splitA2UIMarkdown(markdown: string): MarkdownSegment[];
3663
- //#endregion
3664
- //#region src/a2ui-markdown/operations.d.ts
3665
- /**
3666
- * An A2UI v1.0 message as the model wrote it in an a2ui fence: an object that
3667
- * carries one of createSurface, updateComponents, updateDataModel,
3668
- * deleteSurface or callRendererFunction. The shape is not checked yet.
3669
- * Validate it (for example with `validateOperation` from `@copilotkit/shared`)
3670
- * before it reaches a surface or runs a function.
3671
- *
3672
- * It is named `A2UIMarkdownOperation` because `@copilotkit/shared` already
3673
- * exports the strict `A2UIOperation` type.
3674
- */
3675
- type A2UIMarkdownOperation = Record<string, unknown>;
3676
- /**
3677
- * Read `"key":"value"` from partial JSON. The first match anywhere in the
3678
- * text wins, at any depth.
3679
- *
3680
- * @param partialJson - JSON text that can still be streaming.
3681
- * @param key - The field name.
3682
- * @returns The string value, or null until its closing quote has arrived.
3683
- *
3684
- * @example
3685
- * ```ts
3686
- * extractStringField('{"createSurface":{"surfaceId":"plan","cat', "surfaceId"); // "plan"
3687
- * ```
3688
- */
3689
- declare function extractStringField(partialJson: string, key: string): string | null;
3690
- /**
3691
- * Find `"key":[` in partial JSON and return every complete item of that array
3692
- * so far, plus whether the array has closed. Items of a `components` array get
3693
- * structural-key depth repair: a component that lost closing braces is fixed
3694
- * when its `id`, `component`, `child` or `children` key shows where it ends.
3695
- *
3696
- * @param partialJson - JSON text that can still be streaming.
3697
- * @param key - The name of the array field.
3698
- * @returns `{ items, closed }`, or null when the key (with an array value)
3699
- * has not appeared yet.
3700
- *
3701
- * @example
3702
- * ```ts
3703
- * const result = extractCompleteArrayItems(streamedText, "components");
3704
- * if (result) render(result.items);
3705
- * ```
3706
- */
3707
- declare function extractCompleteArrayItems(partialJson: string, key: string): {
3708
- items: unknown[];
3709
- closed: boolean;
3710
- } | null;
3711
- /**
3712
- * The surfaceId an operation targets: the one nested under its operation key,
3713
- * else a top-level `surfaceId`. A `callRendererFunction` operation targets no
3714
- * surface, so it gets undefined.
3715
- *
3716
- * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`
3717
- * already exports a strict `getOperationSurfaceId`. This one also reads a
3718
- * top-level `surfaceId`, which models sometimes write.
3719
- *
3720
- * @param op - An operation from an a2ui fence.
3721
- * @returns The surfaceId, or undefined when the operation names none or is a
3722
- * function call.
3723
- *
3724
- * @example
3725
- * ```ts
3726
- * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: "plan" } }); // "plan"
3727
- * ```
3728
- */
3729
- declare function getMarkdownOperationSurfaceId(op: A2UIMarkdownOperation): string | undefined;
3730
- /**
3731
- * Parse the body of an a2ui fence as a stream of top-level JSON values, so
3732
- * operations may be one per line (the documented format), several per line,
3733
- * pretty-printed over many lines, or wrapped in a top-level array (which is
3734
- * flattened). Whitespace and commas between objects are ignored.
3735
- *
3736
- * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),
3737
- * its raw text goes to `invalidLines` and whatever `partialOperation` can
3738
- * salvage (complete components, data-model entries, createSurface fields)
3739
- * is kept.
3740
- * - An unbalanced object followed by a line that opens a new operation is
3741
- * treated the same way.
3742
- * - The trailing unbalanced object (still streaming, or never closed) is
3743
- * `partialObject` and yields a partial operation when it has usable data.
3744
- * - Other text between objects is skipped and reported in `recovered` (and in
3745
- * `invalidLines`, which predates it).
3746
- *
3747
- * `partialLine` is a deprecated alias of `partialObject`.
3748
- *
3749
- * @param fenceText - The body of an a2ui fence (`text` of an a2ui
3750
- * `MarkdownSegment`), complete or still streaming.
3751
- * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.
3752
- *
3753
- * @example
3754
- * ```ts
3755
- * const { operations } = extractFenceOperations(segment.text);
3756
- * ```
3757
- */
3758
- declare function extractFenceOperations(fenceText: string): {
3759
- operations: A2UIMarkdownOperation[];
3760
- partialObject: string | null;
3761
- partialLine: string | null;
3762
- invalidLines: string[];
3763
- recovered: string[]; /** Complete lines that were off by one closing brace and were repaired. */
3764
- repairedLines: string[];
3765
- };
3766
- /**
3767
- * Normalise a fence's operations for the renderer: drop unknown messages, fill
3768
- * in `version` and missing `surfaceId`s, keep only the first `createSurface`,
3769
- * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize
3770
- * `createSurface` when the model omitted it, and report the
3771
- * surfaceId (the first one found, else `fallbackSurfaceId`).
3772
- *
3773
- * `callRendererFunction` operations target no surface. They get no surfaceId,
3774
- * do not cause a synthesized `createSurface`, and come back in
3775
- * `functionCalls` (in fence order), never in `operations`.
3776
- *
3777
- * @param input.operations - Operations from `extractFenceOperations`.
3778
- * @param input.fallbackSurfaceId - The surfaceId to use when no operation
3779
- * names one.
3780
- * @param input.catalogId - The client catalog. It replaces a catalogId of the
3781
- * model that `catalogIds` does not list.
3782
- * @param input.catalogIds - The catalogs that the model can name. Left out,
3783
- * only `catalogId`.
3784
- * @returns `{ surfaceId, operations, functionCalls }`.
3785
- *
3786
- * @example
3787
- * ```ts
3788
- * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({
3789
- * operations: extractFenceOperations(segment.text).operations,
3790
- * fallbackSurfaceId: `${messageId}-${segment.index}`,
3791
- * catalogId,
3792
- * });
3793
- * ```
3794
- */
3795
- declare function prepareSurfaceOperations(input: {
3796
- operations: A2UIMarkdownOperation[];
3797
- fallbackSurfaceId: string;
3798
- catalogId: string;
3799
- catalogIds?: readonly string[];
3800
- }): {
3801
- surfaceId: string;
3802
- operations: A2UIMarkdownOperation[];
3803
- functionCalls: A2UIMarkdownOperation[];
3804
- };
3805
- /**
3806
- * More ids a component renders, beyond `child`, `children` and the table
3807
- * cells: the typed child references of its catalog, which can sit at any
3808
- * depth of its props (the `child` of each entry of `tabs`). The catalog
3809
- * knows them; the operations alone do not.
3810
- */
3811
- type ChildIdsOf = (component: Record<string, unknown>) => string[] | "unknown";
3812
- /** The options of the walks that follow child ids. */
3813
- interface ChildWalkOptions {
3814
- childIds?: ChildIdsOf;
3815
- }
3816
- /**
3817
- * Ids of the `Card` components that are interactive panels: at least one
3818
- * descendant (via `child`, `children` or table component cells) is a control
3819
- * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,
3820
- * RadioGroup, Slider, SegmentedControl, DateTimeInput).
3821
- *
3822
- * @param components - The components of one surface.
3823
- * @returns The ids of the interactive cards.
3824
- *
3825
- * @example
3826
- * ```ts
3827
- * const interactive = classifySurfaceCards(components);
3828
- * const keepsBox = interactive.has("quote-form");
3829
- * ```
3830
- */
3831
- declare function classifySurfaceCards(components: Record<string, unknown>[], options?: ChildWalkOptions): Set<string>;
3832
- /**
3833
- * Markdown mode: only interactive panels keep a box. Every `Card` that is not
3834
- * an interactive panel (see `classifySurfaceCards`), sets no `variant` or
3835
- * `border` of its own and is not nested inside an interactive panel becomes
3836
- * `variant: "section"` (a heading plus content without a box). Operations
3837
- * other than updateComponents pass through unchanged.
3838
- *
3839
- * @param operations - The operations of one surface.
3840
- * @returns The operations with informational cards set to `variant: "section"`.
3841
- * When no card changes, it returns the same array.
3842
- *
3843
- * @example
3844
- * ```ts
3845
- * const operations = flattenInformationalCards(prepared.operations);
3846
- * ```
3847
- */
3848
- declare function flattenInformationalCards(operations: A2UIMarkdownOperation[], options?: ChildWalkOptions): A2UIMarkdownOperation[];
3849
- /** One block of a segmented surface, in render order. */
3850
- type SurfaceSegment = {
3851
- kind: "markdown";
3852
- markdown: string;
3853
- } | {
3854
- kind: "surface";
3855
- components: Record<string, unknown>[];
3856
- };
3857
- /**
3858
- * Markdown mode: split a surface into markdown and surface segments so that
3859
- * only real UI renders as A2UI and everything else is the chat's markdown.
3860
- *
3861
- * From `root`, descend through single-child vertical containers (Column,
3862
- * column Box, informational Card) to the first one with several children:
3863
- * the stack. Its children are partitioned, in order, into runs of prose and
3864
- * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal
3865
- * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:
3866
- * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →
3867
- * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →
3868
- * `- …` (or `1. …` for `marker: "number"`, `**label** — description` for
3869
- * described items), and a `Divider` between two prose blocks → `---`.
3870
- *
3871
- * Not prose: `{path}`-bound text or items, a Text with inline children, a
3872
- * List with `children`/icons/actions, a template entry, a component with an
3873
- * `accessibility` envelope, and a child whose component has not streamed
3874
- * yet. Separators with no text beside them stay in
3875
- * the surface. An interactive Card (see `classifySurfaceCards`) is never
3876
- * entered.
3877
- *
3878
- * Each prose run becomes a markdown segment; each UI run becomes a surface
3879
- * segment whose `root` is a copy of the stack (its other props kept, `child`
3880
- * dropped) with only that run's `children`, followed by every component
3881
- * reachable from them. When nothing is prose the input comes back as the one
3882
- * surface segment (same array); when everything is (or `root` itself is),
3883
- * there are only markdown segments.
3884
- *
3885
- * Pure and linear in the number of components, so it runs on every stream
3886
- * update.
3887
- *
3888
- * @param components - The components of one surface, root included.
3889
- * @returns The segments in render order.
3890
- *
3891
- * @example
3892
- * ```ts
3893
- * for (const segment of segmentSurfaceProse(components)) {
3894
- * if (segment.kind === "markdown") renderMarkdown(segment.markdown);
3895
- * else renderSurface(segment.components);
3896
- * }
3897
- * ```
3898
- */
3899
- declare function segmentSurfaceProse(components: Record<string, unknown>[], options?: ChildWalkOptions): SurfaceSegment[];
3900
- //#endregion
3901
- export { A2UIMarkdownOperation, A2UI_FENCE_LANGUAGE, ActionConfig, ActionCreator, ActionFromCreator, ActionFromCreators, ActionGroupConfig, ActionGroupResult, AgentRegistry, AgentThreadLockedError, AnyAction, ChildIdsOf, ChildWalkOptions, ContextStore, CopilotKitCore, type CopilotKitCoreAddAgentParams, type CopilotKitCoreCatalogComponent, CopilotKitCoreConfig, type CopilotKitCoreConnectAgentParams, CopilotKitCoreContinuationHandoff, CopilotKitCoreErrorCode, CopilotKitCoreFriendsAccess, CopilotKitCoreGetSuggestionsResult, type CopilotKitCoreGetToolParams, type CopilotKitCoreRegisterProxiedAgentParams, type CopilotKitCoreRegisterProxiedAgentResult, type CopilotKitCoreRunAgentParams, type CopilotKitCoreRunToolParams, type CopilotKitCoreRunToolResult, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreStopAgentParams, CopilotKitCoreSubscriber, CopilotKitCoreSubscription, CopilotKitHeaderResolutionError, type CopilotKitHeadersSource, type CopilotKitMessageFilter, CopilotRuntimeTransport, DispatchingEffect, DispatchingEffectOptions, DynamicSuggestionsConfig, Effect, EmptyActionConfig, FrontendTool, FrontendToolHandlerContext, FrontendToolReconnectBehavior, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, InspectorActiveThreadPayload, type InspectorMetadataV1, InspectorStopViewingPayload, InspectorViewThreadPayload, InspectorViewThreadResultPayload, IntelligenceAgent, IntelligenceAgentConfig, IntelligenceReplayFailedError, type IntelligenceRuntimeInfo, type JsonValue, type LearningConfig, type LegacyLearningConfig, MEMORY_ERROR_REGISTRY, MarkdownSegment, Memory, MemoryChanges, MemoryError, type MemoryErrorCategory, type MemoryErrorCode, type MemoryErrorRegistryEntry, MemoryKind, MemoryRealtimeStatus, MemoryScope, NewMemory, NonDispatchingEffect, NonDispatchingEffectOptions, type OpenThreadRegistration, PropsActionConfig, ProxiedCopilotRuntimeAgent, ProxiedCopilotRuntimeAgentConfig, Reducer, RunCompletionAware, type RunErrorPhase, RunHandler, type RuntimeLicenseStatus, type RuntimeMode, ScopedContext, ScopedProperties, Selector, type StartResult, StateManager, StaticSuggestionsConfig, Store, StoreLifecycleAction, SubscribeToAgentOptions, SubscribeToAgentSubscriber, Suggestion, SuggestionAvailability, SuggestionEngine, SuggestionsConfig, SurfaceSegment, type ThreadEndpointRuntimeInfo, ThreadRunActivityNotification, ToolCallStatus, type TrajectoryStartOptions, WebMCPModelContext, WebMCPRegistry, WebMCPToolAnnotations, WebMCPToolConfig, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵCopilotKitFeature, ɵGenerativeUIDebugFunction, ɵGenerativeUIDebugPromptSection, ɵGenerativeUIDebugRun, ɵGenerativeUIDebugSnapshot, ɵGenerativeUIDebugSource, ɵGenerativeUIDebugSurface, ɵInterruptDecision, ɵInterruptEvent, ɵInterruptState, ɵInterruptToolResult, ɵMAX_SOCKET_RETRIES, ɵMemoryEnvironment, ɵMemoryMetadataEvent, ɵMemoryRuntimeContext, ɵMemoryState, ɵMemoryStore, ɵPendingInterrupt, ɵPhoenixChannelLike, ɵPhoenixChannelOptions, ɵPhoenixChannelSession, ɵPhoenixJoinOutcome, ɵPhoenixPushLike, ɵPhoenixSocketLike, ɵPhoenixSocketOptions, ɵPhoenixSocketSession, ɵPhoenixSocketSignal, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵThread, ɵThreadEnvironment, ɵThreadMetadataEvent, ɵThreadRuntimeContext, ɵThreadSelectors, ɵThreadStore, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };
3902
- //# sourceMappingURL=index.d.mts.map
1
+ import { $ as extractCompleteArrayItems, $n as AgentThreadLockedError, $t as ɵselectMemoriesError, A as createThreadStore, An as ActionGroupResult, Ar as FrontendToolHandlerContext, At as ɵgetAgentInterruptState, B as ɵselectFetchMoreError, Bn as Selector, Br as ThreadEndpointRuntimeInfo, Bt as createMemoryStore, C as ɵGenerativeUIDebugFunction, Cn as ɵphoenixChannel$, Cr as ɵRUNTIME_PROBE_TIMEOUT_MS, Ct as onInspectorViewThreadResult, D as ɵGenerativeUIDebugSource, Dn as ActionFromCreator, Dr as CopilotRuntimeTransport, Dt as ɵInterruptToolResult, E as ɵGenerativeUIDebugSnapshot, En as ActionCreator, Er as CopilotKitMessageFilter, Et as ɵInterruptState, F as ɵThreadMetadataEvent, Fn as EmptyActionConfig, Fr as RuntimeMode, Ft as MemoryChanges, G as ɵselectThreadsError, Gn as createReducer, Gr as LegacyLearningConfig, Gt as ɵMemoryStore, H as ɵselectIsFetchingNextPage, Hn as StoreLifecycleAction, Hr as WebMCPToolAnnotations, Ht as ɵMemoryMetadataEvent, I as ɵThreadRuntimeContext, In as NonDispatchingEffect, Ir as StaticSuggestionsConfig, It as MemoryKind, J as A2UIMarkdownOperation, Jn as empty, Jt as ɵmemoryDomainEvents, K as ɵselectThreadsIsLoading, Kn as createSelector, Kr as OpenThreadRegistration, Kt as ɵmapMemoryMetadataEvent, L as ɵThreadSelectors, Ln as NonDispatchingEffectOptions, Lr as Suggestion, Lt as MemoryRealtimeStatus, M as ɵTHREAD_REQUEST_TIMEOUT_MS, Mn as DispatchingEffect, Mr as InspectorMetadataV1, Mt as ɵCopilotKitFeature, N as ɵThread, Nn as DispatchingEffectOptions, Nr as IntelligenceRuntimeInfo, Nt as ɵisCopilotKitFeature, O as ɵGenerativeUIDebugSurface, On as ActionFromCreators, Or as DynamicSuggestionsConfig, Ot as ɵPendingInterrupt, P as ɵThreadEnvironment, Pn as Effect, Pr as RuntimeLicenseStatus, Pt as Memory, Q as classifySurfaceCards, Qn as select, Qt as ɵselectMemoriesAvailable, R as ɵThreadStore, Rn as PropsActionConfig, Rr as SuggestionAvailability, Rt as MemoryScope, S as ɵwithHeaderDefaults, Sn as ɵobservePhoenixSocketSignals$, Sr as CopilotKitCoreRegisterProxiedAgentResult, St as onInspectorViewThread, T as ɵGenerativeUIDebugRun, Tn as ActionConfig, Tr as ProxiedCopilotRuntimeAgentConfig, Tt as ɵInterruptEvent, U as ɵselectIsMutating, Un as createActionGroup, Ur as WebMCPToolConfig, Ut as ɵMemoryRuntimeContext, V as ɵselectHasNextPage, Vn as Store, Vr as ToolCallStatus, Vt as ɵMemoryEnvironment, W as ɵselectThreads, Wn as createEffect, Wr as LearningConfig, Wt as ɵMemoryState, X as ChildWalkOptions, Xn as on, Xt as ɵmemoryRestEvents, Y as ChildIdsOf, Yn as ofType, Yt as ɵmemoryReducer, Z as SurfaceSegment, Zn as props, Zt as ɵselectMemories, _ as StartResult, _n as ɵPhoenixSocketSignal, _r as ContextStore, _t as emitInspectorViewThread, a as isAbortError, an as MemoryErrorCategory, ar as completePartialMarkdown, at as segmentSurfaceProse, b as CopilotKitHeaderResolutionError, bn as ɵobservePhoenixJoinOutcome$, br as CopilotKitCoreAddAgentParams, bt as onInspectorActiveThread, c as CopilotKitCoreErrorCode, cn as isRetryableStatus, cr as CopilotKitCoreGetToolParams, ct as splitA2UIMarkdown, d as CopilotKitCoreRuntimeConnectionStatus, dn as ɵPhoenixChannelSession, dr as CopilotKitCoreRunToolResult, dt as InspectorStopViewingPayload, en as ɵselectMemoriesIsLoading, er as IntelligenceAgent, et as extractFenceOperations, f as CopilotKitCoreStopAgentParams, fn as ɵPhoenixJoinOutcome, fr as RunHandler, ft as InspectorViewThreadPayload, g as ScopedProperties, gn as ɵPhoenixSocketSession, gr as StateManager, gt as emitInspectorStopViewing, h as JsonValue, hn as ɵPhoenixSocketOptions, hr as CopilotKitCoreContinuationHandoff, ht as emitInspectorActiveThread, i as SuggestionEngine, in as MemoryError, ir as ɵisHttpAgent, it as prepareSurfaceOperations, j as ɵMAX_SOCKET_RETRIES, jn as AnyAction, jr as FrontendToolReconnectBehavior, jt as ɵCOPILOTKIT_FEATURES, k as ThreadRunActivityNotification, kn as ActionGroupConfig, kr as FrontendTool, kt as ɵclearAgentInterruptState, l as CopilotKitCoreFriendsAccess, ln as ɵPhoenixChannelLike, lr as CopilotKitCoreRunAgentParams, lt as INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, m as CopilotKitCoreSubscription, mn as ɵPhoenixSocketLike, mr as parseToolArguments, mt as createInspectorThreadRequestId, n as WebMCPRegistry, nn as ɵselectMemoriesRealtimeStatus, nr as RunCompletionAware, nt as flattenInformationalCards, o as CopilotKitCore, on as MemoryErrorCode, or as CopilotKitCoreCatalogComponent, ot as A2UI_FENCE_LANGUAGE, p as CopilotKitCoreSubscriber, pn as ɵPhoenixPushLike, pr as ensureObjectArgs, pt as InspectorViewThreadResultPayload, q as ɵthreadAdapterEvents, qn as createStore, qr as TrajectoryStartOptions, qt as ɵmemoryAdapterEvents, r as getWebMCPModelContext, rn as MEMORY_ERROR_REGISTRY, rr as isRunCompletionAware, rt as getMarkdownOperationSurfaceId, s as CopilotKitCoreConfig, sn as MemoryErrorRegistryEntry, sr as CopilotKitCoreConnectAgentParams, st as MarkdownSegment, t as WebMCPModelContext, tn as ɵselectMemoriesIsMutating, tr as IntelligenceAgentConfig, tt as extractStringField, u as CopilotKitCoreGetSuggestionsResult, un as ɵPhoenixChannelOptions, ur as CopilotKitCoreRunToolParams, ut as InspectorActiveThreadPayload, v as SubscribeToAgentOptions, vn as ɵjoinPhoenixChannel$, vr as ScopedContext, vt as emitInspectorViewThreadResult, w as ɵGenerativeUIDebugPromptSection, wn as ɵphoenixSocket$, wr as ProxiedCopilotRuntimeAgent, wt as ɵInterruptDecision, x as CopilotKitHeadersSource, xn as ɵobservePhoenixSocketHealth$, xr as CopilotKitCoreRegisterProxiedAgentParams, xt as onInspectorStopViewing, y as SubscribeToAgentSubscriber, yn as ɵobservePhoenixEvent$, yr as AgentRegistry, yt as isInspectorThreadBridgeEnabled, z as ɵcreateThreadSelectors, zn as Reducer, zr as SuggestionsConfig, zt as NewMemory } from "./index-BC1dzn_F.mjs";
2
+ export { A2UIMarkdownOperation, A2UI_FENCE_LANGUAGE, ActionConfig, ActionCreator, ActionFromCreator, ActionFromCreators, ActionGroupConfig, ActionGroupResult, AgentRegistry, AgentThreadLockedError, AnyAction, ChildIdsOf, ChildWalkOptions, ContextStore, CopilotKitCore, CopilotKitCoreAddAgentParams, CopilotKitCoreCatalogComponent, CopilotKitCoreConfig, CopilotKitCoreConnectAgentParams, CopilotKitCoreContinuationHandoff, CopilotKitCoreErrorCode, CopilotKitCoreFriendsAccess, CopilotKitCoreGetSuggestionsResult, CopilotKitCoreGetToolParams, CopilotKitCoreRegisterProxiedAgentParams, CopilotKitCoreRegisterProxiedAgentResult, CopilotKitCoreRunAgentParams, CopilotKitCoreRunToolParams, CopilotKitCoreRunToolResult, CopilotKitCoreRuntimeConnectionStatus, CopilotKitCoreStopAgentParams, CopilotKitCoreSubscriber, CopilotKitCoreSubscription, CopilotKitHeaderResolutionError, CopilotKitHeadersSource, CopilotKitMessageFilter, CopilotRuntimeTransport, DispatchingEffect, DispatchingEffectOptions, DynamicSuggestionsConfig, Effect, EmptyActionConfig, FrontendTool, FrontendToolHandlerContext, FrontendToolReconnectBehavior, INSPECTOR_THREAD_BRIDGE_PLUGIN_ID, InspectorActiveThreadPayload, InspectorMetadataV1, InspectorStopViewingPayload, InspectorViewThreadPayload, InspectorViewThreadResultPayload, IntelligenceAgent, IntelligenceAgentConfig, IntelligenceRuntimeInfo, JsonValue, LearningConfig, LegacyLearningConfig, MEMORY_ERROR_REGISTRY, MarkdownSegment, Memory, MemoryChanges, MemoryError, MemoryErrorCategory, MemoryErrorCode, MemoryErrorRegistryEntry, MemoryKind, MemoryRealtimeStatus, MemoryScope, NewMemory, NonDispatchingEffect, NonDispatchingEffectOptions, OpenThreadRegistration, PropsActionConfig, ProxiedCopilotRuntimeAgent, ProxiedCopilotRuntimeAgentConfig, Reducer, RunCompletionAware, RunHandler, RuntimeLicenseStatus, RuntimeMode, ScopedContext, ScopedProperties, Selector, StartResult, StateManager, StaticSuggestionsConfig, Store, StoreLifecycleAction, SubscribeToAgentOptions, SubscribeToAgentSubscriber, Suggestion, SuggestionAvailability, SuggestionEngine, SuggestionsConfig, SurfaceSegment, ThreadEndpointRuntimeInfo, ThreadRunActivityNotification, ToolCallStatus, TrajectoryStartOptions, WebMCPModelContext, WebMCPRegistry, WebMCPToolAnnotations, WebMCPToolConfig, classifySurfaceCards, completePartialMarkdown, createActionGroup, createEffect, createInspectorThreadRequestId, createReducer, createSelector, createStore, emitInspectorActiveThread, emitInspectorStopViewing, emitInspectorViewThread, emitInspectorViewThreadResult, empty, ensureObjectArgs, extractCompleteArrayItems, extractFenceOperations, extractStringField, flattenInformationalCards, getMarkdownOperationSurfaceId, getWebMCPModelContext, isAbortError, isInspectorThreadBridgeEnabled, isRunCompletionAware, ofType, on, onInspectorActiveThread, onInspectorStopViewing, onInspectorViewThread, onInspectorViewThreadResult, parseToolArguments, prepareSurfaceOperations, props, segmentSurfaceProse, select, splitA2UIMarkdown, ɵCOPILOTKIT_FEATURES, ɵCopilotKitFeature, ɵGenerativeUIDebugFunction, ɵGenerativeUIDebugPromptSection, ɵGenerativeUIDebugRun, ɵGenerativeUIDebugSnapshot, ɵGenerativeUIDebugSource, ɵGenerativeUIDebugSurface, ɵInterruptDecision, ɵInterruptEvent, ɵInterruptState, ɵInterruptToolResult, ɵMAX_SOCKET_RETRIES, ɵMemoryEnvironment, ɵMemoryMetadataEvent, ɵMemoryRuntimeContext, ɵMemoryState, ɵMemoryStore, ɵPendingInterrupt, ɵPhoenixChannelLike, ɵPhoenixChannelOptions, ɵPhoenixChannelSession, ɵPhoenixJoinOutcome, ɵPhoenixPushLike, ɵPhoenixSocketLike, ɵPhoenixSocketOptions, ɵPhoenixSocketSession, ɵPhoenixSocketSignal, ɵRUNTIME_PROBE_TIMEOUT_MS, ɵTHREAD_REQUEST_TIMEOUT_MS, ɵThread, ɵThreadEnvironment, ɵThreadMetadataEvent, ɵThreadRuntimeContext, ɵThreadSelectors, ɵThreadStore, ɵclearAgentInterruptState, createMemoryStore as ɵcreateMemoryStore, ɵcreateThreadSelectors, createThreadStore as ɵcreateThreadStore, ɵgetAgentInterruptState, ɵisCopilotKitFeature, ɵisHttpAgent, isRetryableStatus as ɵisRetryableMemoryStatus, ɵjoinPhoenixChannel$, ɵmapMemoryMetadataEvent, ɵmemoryAdapterEvents, ɵmemoryDomainEvents, ɵmemoryReducer, ɵmemoryRestEvents, ɵobservePhoenixEvent$, ɵobservePhoenixJoinOutcome$, ɵobservePhoenixSocketHealth$, ɵobservePhoenixSocketSignals$, ɵphoenixChannel$, ɵphoenixSocket$, ɵselectFetchMoreError, ɵselectHasNextPage, ɵselectIsFetchingNextPage, ɵselectIsMutating, ɵselectMemories, ɵselectMemoriesAvailable, ɵselectMemoriesError, ɵselectMemoriesIsLoading, ɵselectMemoriesIsMutating, ɵselectMemoriesRealtimeStatus, ɵselectThreads, ɵselectThreadsError, ɵselectThreadsIsLoading, ɵthreadAdapterEvents, ɵwithHeaderDefaults };