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