@copilotkit/core 1.84.1 → 1.84.2-canary.1793807121

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["switchMap","switchMapOperator","isAbortError","#applyMessageFilter","switchMap","#connectViaDelegate","#connectViaHttp","#runViaDelegate","#runViaHttp","#prepareOutboundMessages","isAbortError","isAbortError","randomUUID","randomUUID","#responses","#pending","#replace","#sealed","#adoptedContent","#respond","#decide","randomUUID","isAbortError","randomUUID","observeOn","REQUEST_TIMEOUT_MS","MAX_SOCKET_RETRIES","switchMap","randomUUID","ɵcreateMemoryStore","switchMap","on"],"sources":["../src/utils/http-agent.ts","../src/utils/connect-replay.ts","../src/utils/phoenix-observable.ts","../src/intelligence-agent.ts","../src/utils/runtime-info-error.ts","../src/core/message-filter.ts","../src/agent.ts","../src/utils/abort-error.ts","../src/utils/runtime-request.ts","../src/utils/single-route-resource-request.ts","../src/core/header-source.ts","../src/core/agent-registry.ts","../src/core/agent-scope.ts","../src/core/context-store.ts","../src/core/suggestion-engine.ts","../src/core/tool-result-content.ts","../src/core/tool-schema.ts","../src/interrupt-state.ts","../src/core/webmcp.ts","../src/core/run-handler.ts","../src/core/state-manager.ts","../src/core/thread-store-registry.ts","../src/core/trajectory-connection.ts","../src/core/learning-bridge.ts","../src/utils/micro-redux.ts","../src/memory-errors.ts","../src/memory.ts","../src/core/core.ts","../src/types.ts","../src/utils/markdown.ts","../src/threads.ts","../src/features.ts","../src/inspector-thread-bridge.ts","../src/a2ui-markdown/fence-parser.ts","../src/a2ui-markdown/operations.ts"],"sourcesContent":["import { HttpAgent } from \"@ag-ui/client\";\n\n/**\n * Whether an agent is an `HttpAgent`, including one built from another copy of\n * `@ag-ui/client` (an app that pins its own 0.x version next to CopilotKit's\n * 1.0, for example). `instanceof` is false across package copies, which made\n * CopilotKit silently skip headers and abort wiring for those agents. The\n * fallback checks the public fields CopilotKit uses, which every published\n * `HttpAgent` has.\n */\nexport function ɵisHttpAgent(agent: unknown): agent is HttpAgent {\n if (agent instanceof HttpAgent) return true;\n if (typeof agent !== \"object\" || agent === null) return false;\n const candidate = agent as Record<string, unknown>;\n return (\n typeof candidate.url === \"string\" &&\n typeof candidate.headers === \"object\" &&\n candidate.headers !== null &&\n candidate.abortController instanceof AbortController &&\n typeof candidate.runAgent === \"function\"\n );\n}\n","import type {\n AbstractAgent,\n AgentSubscriber,\n BaseEvent,\n RunAgentInput,\n RunAgentParameters,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport {\n AGUIConnectNotImplementedError,\n CompatibilityBoundary,\n EventType,\n randomUUID,\n structuredClone_,\n transformChunks,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { EMPTY, Subject, defer, lastValueFrom } from \"rxjs\";\nimport { catchError, finalize, takeUntil, tap } from \"rxjs/operators\";\n\n/** Internal connection callbacks; HTTP connections keep their EOF behavior. */\nexport interface ConnectionReplayLifecycle {\n onReplayStarted?: () => void;\n onReplayFinished?: () => void;\n}\n\n/**\n * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline\n * with the `verifyEvents` step omitted.\n *\n * `verifyEvents` enforces AG-UI's *single run* lifecycle rules: exactly one\n * RUN_STARTED opening the stream, no events after a terminal RUN_FINISHED /\n * RUN_ERROR. Those rules are correct for `/run`, but a `/connect` response is a\n * replay of a thread's history and can legitimately carry several past runs\n * back to back — including a run that ended in RUN_ERROR followed by a later\n * RUN_STARTED. Verifying a replay against single-run rules makes hydration of\n * an existing thread fail outright:\n *\n * Cannot send event type 'RUN_STARTED': The run has already errored with\n * 'RUN_ERROR'. No further events can be sent.\n *\n * The AG-UI 1.0 compatibility boundary still runs first, so stored 0.x history\n * is translated (THINKING_* events, `binary` parts, legacy nulls) exactly as in\n * the base pipeline. `enforceEvents` is omitted too: a replay is stored\n * history, and one event that the 1.0 schema rejects (the Intelligence gateway\n * replays RUN_STARTED without `runId`, for example) must not stop the whole\n * thread from hydrating. That keeps the leniency this path had before 1.0.\n *\n * Connection-local replay hooks track the phase before applying events. An\n * explicitly live RUN_ERROR clears busy without closing the connection;\n * historical errors remain data. Connections without hooks retain the existing\n * completion behavior.\n *\n * Apart from the above, this mirrors the base `AbstractAgent.connectAgent`\n * implementation, so callers keep the same subscriber notifications, detach\n * semantics, and `{ result, newMessages }` return shape.\n *\n * TODO: Remove this in favour of the base implementation once AG-UI's\n * AbstractAgent supports opting out of `verifyEvents` for transports whose\n * connection life-cycle isn't a single run AND preserves the connection-local\n * replay lifecycle and running-state behavior below. Skipping verification alone\n * is insufficient. As of `@ag-ui/client@1.0.1`\n * `connectAgent(parameters?, subscriber?)` takes no such option.\n *\n * @param agent - The agent whose `connect()` stream should be consumed.\n * @param parameters - Run parameters, forwarded to `prepareRunAgentInput`.\n * @param subscriber - Optional one-shot subscriber for this connect call.\n */\nexport async function ɵconnectWithoutEventVerification(\n agent: AbstractAgent,\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n connect?: (\n input: RunAgentInput,\n lifecycle: ConnectionReplayLifecycle,\n ) => Observable<BaseEvent>,\n): Promise<RunAgentResult> {\n // Access protected/private members through a type escape hatch — they are\n // set and read by the base class and must be managed identically to the\n // original implementation. `any` is required because these fields are\n // private in AbstractAgent, and intersecting private+public members of the\n // same name produces `never`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const self = agent as any;\n let finalizeRun = () => {\n agent.isRunning = false;\n };\n\n try {\n agent.isRunning = true;\n agent.agentId = agent.agentId ?? randomUUID();\n\n const input = self.prepareRunAgentInput(parameters);\n let result: RunAgentResult[\"result\"];\n const previousMessageIds = new Set(agent.messages.map((m) => m.id));\n // Record the phase when an error arrives: subscriber callbacks may run\n // asynchronously after replay_complete has already changed the phase.\n let isReplaying = true;\n const liveErrors = new WeakSet<BaseEvent>();\n const subscribers: AgentSubscriber[] = [\n {\n onRunStartedEvent: () => {\n agent.isRunning = true;\n },\n onRunErrorEvent: ({ event }) => {\n if (liveErrors.has(event)) agent.isRunning = false;\n },\n onRunFinishedEvent: (event) => {\n if (event.outcome === \"success\") {\n result = event.result;\n }\n },\n },\n ...agent.subscribers,\n subscriber ?? {},\n ];\n\n const activeRunDetach$ = new Subject<void>();\n self.activeRunDetach$ = activeRunDetach$;\n let resolveCompletion: (() => void) | undefined;\n self.activeRunCompletionPromise = new Promise<void>((resolve) => {\n resolveCompletion = resolve;\n });\n let detached = false;\n let finalized = false;\n const detachSubscription = activeRunDetach$.subscribe(() => {\n detached = true;\n });\n finalizeRun = () => {\n if (finalized) return;\n finalized = true;\n detachSubscription.unsubscribe();\n if (self.activeRunDetach$ === activeRunDetach$) {\n agent.isRunning = false;\n self.activeRunCompletionPromise = undefined;\n self.activeRunDetach$ = undefined;\n // Keep AG-UI's callback timing. A finalizer can await the next run.\n void self.onFinalize(input, subscribers);\n }\n resolveCompletion?.();\n resolveCompletion = undefined;\n };\n\n // Initialization can await subscribers that return state mutations.\n // Publish teardown first, then wait for those mutations before releasing it.\n await self.onInitialize(input, subscribers);\n if (detached) return { result: undefined, newMessages: [] };\n\n // Only an explicitly live error changes busy state. Connection lifetime\n // remains owned by the transport (Intelligence idle or HTTP EOF).\n const lifecycle: ConnectionReplayLifecycle = {\n onReplayStarted: () => {\n isReplaying = true;\n agent.isRunning = true;\n },\n onReplayFinished: () => {\n isReplaying = false;\n },\n };\n const source$ = defer(() =>\n // The boundary is a middleware; hand it a stand-in agent whose run() is\n // this connect stream, as AG-UI's own connect operator does internally.\n new CompatibilityBoundary().run(input, {\n run: () =>\n connect\n ? connect(input, lifecycle)\n : (self.connect(input) as Observable<BaseEvent>),\n } as unknown as AbstractAgent),\n ).pipe(\n // NOTE: enforceEvents is intentionally omitted here. See JSDoc above.\n tap((event) => {\n if (!isReplaying && event.type === EventType.RUN_ERROR) {\n liveErrors.add(event);\n }\n }),\n // transformChunks reassembles partial/streamed messages — still needed.\n transformChunks(self.debugLogger),\n // NOTE: verifyEvents is intentionally omitted here. See JSDoc above.\n takeUntil(activeRunDetach$),\n );\n\n const applied$ = self.apply(input, source$, subscribers);\n const processed$ = self.processApplyEvents(input, applied$, subscribers);\n\n await lastValueFrom(\n processed$.pipe(\n catchError((error: unknown) => {\n if (self.activeRunDetach$ !== activeRunDetach$) return EMPTY;\n agent.isRunning = false;\n // An agent that doesn't implement connect() is not an error worth\n // surfacing: the base pipeline swallows it, and callers rely on that.\n // `CopilotKitCore` awaits `detachActiveRun()` before every run, which\n // only resolves because this path still reaches the finalize block\n // below (see the historical note in run-handler.ts). Routing it\n // through onError would also fire run-failure callbacks on every\n // subscriber for a benign condition.\n if (error instanceof AGUIConnectNotImplementedError) {\n return EMPTY;\n }\n return self.onError(input, error, subscribers);\n }),\n finalize(() => finalizeRun()),\n ),\n { defaultValue: undefined },\n );\n\n const newMessages = structuredClone_(agent.messages).filter(\n (m) => !previousMessageIds.has(m.id),\n );\n return { result, newMessages };\n } finally {\n finalizeRun();\n }\n}\n","import { Socket } from \"phoenix\";\nimport { EMPTY, NEVER, Observable, concat, defer, of, throwError } from \"rxjs\";\nimport {\n filter,\n finalize,\n mergeMap,\n scan,\n shareReplay,\n switchMap,\n take,\n} from \"rxjs/operators\";\n\n/**\n * Minimal Phoenix push contract used by the observable adapters.\n */\nexport interface ɵPhoenixPushLike {\n receive(\n status: string,\n callback: (payload?: unknown) => unknown,\n ): ɵPhoenixPushLike;\n}\n\n/**\n * Minimal Phoenix channel contract used by the observable adapters.\n */\nexport interface ɵPhoenixChannelLike {\n on(event: string, callback: (payload: unknown) => void): number;\n off(event: string, ref?: number): void;\n onError?(callback: (reason?: unknown) => void): unknown;\n join(params?: Record<string, unknown>): ɵPhoenixPushLike;\n push?(event: string, payload: unknown): ɵPhoenixPushLike;\n leave(): void;\n}\n\n/**\n * Minimal Phoenix socket contract used by the observable adapters.\n */\nexport interface ɵPhoenixSocketLike {\n connect(): void;\n disconnect(): void;\n channel(topic: string, params?: Record<string, unknown>): ɵPhoenixChannelLike;\n onError(callback: (error?: unknown) => void): unknown;\n onOpen(callback: () => void): unknown;\n}\n\n/**\n * Socket lifecycle notifications exposed by {@link ɵphoenixSocket$}.\n */\nexport type ɵPhoenixSocketSignal =\n | { type: \"open\" }\n | { type: \"error\"; error?: unknown };\n\n/**\n * Terminal outcomes of a Phoenix channel join attempt.\n */\nexport type ɵPhoenixJoinOutcome =\n | { type: \"joined\" }\n | { type: \"error\"; response?: unknown }\n | { type: \"timeout\" };\n\n/**\n * Active Phoenix socket session plus its derived lifecycle stream.\n */\nexport interface ɵPhoenixSocketSession {\n socket: ɵPhoenixSocketLike;\n signals$: Observable<ɵPhoenixSocketSignal>;\n}\n\n/**\n * Active Phoenix channel session plus its derived join-outcome stream.\n */\nexport interface ɵPhoenixChannelSession {\n channel: ɵPhoenixChannelLike;\n joinOutcome$: Observable<ɵPhoenixJoinOutcome>;\n}\n\n/**\n * Options for creating a cold Phoenix socket session stream.\n */\nexport interface ɵPhoenixSocketOptions {\n url: string;\n options?: Record<string, unknown>;\n}\n\n/**\n * Options for creating a cold Phoenix channel session stream from a socket stream.\n */\nexport interface ɵPhoenixChannelOptions {\n socket$: Observable<ɵPhoenixSocketSession>;\n topic: string;\n params?: Record<string, unknown>;\n leaveOnUnsubscribe?: boolean;\n}\n\n/**\n * Adapt Phoenix socket open/error callbacks into an observable signal stream.\n *\n * The returned observable is shared and replayable by the caller when needed,\n * but this helper itself does not own socket connection teardown.\n */\nfunction ɵcreatePhoenixSocketSignals$(\n socket: ɵPhoenixSocketLike,\n): Observable<ɵPhoenixSocketSignal> {\n return new Observable<ɵPhoenixSocketSignal>((observer) => {\n socket.onOpen(() => observer.next({ type: \"open\" }));\n socket.onError((error) => observer.next({ type: \"error\", error }));\n });\n}\n\n/**\n * Adapt a Phoenix channel join attempt into a single-outcome observable.\n */\nfunction ɵcreatePhoenixJoinOutcome$(\n channel: ɵPhoenixChannelLike,\n): Observable<ɵPhoenixJoinOutcome> {\n return new Observable<ɵPhoenixJoinOutcome>((observer) => {\n channel\n .join()\n .receive(\"ok\", () => {\n observer.next({ type: \"joined\" });\n observer.complete();\n })\n .receive(\"error\", (response?: unknown) => {\n observer.next({ type: \"error\", response });\n observer.complete();\n })\n .receive(\"timeout\", () => {\n observer.next({ type: \"timeout\" });\n observer.complete();\n });\n });\n}\n\n/**\n * Create a cold Phoenix socket session.\n *\n * The socket is constructed and connected on subscription, and disconnected on\n * teardown. Each subscription creates an isolated socket instance.\n *\n * Heartbeats default to every 15s: Phoenix's own 30s default matches common\n * reverse-proxy WebSocket idle timeouts (e.g. Azure Application Gateway), which\n * would drop the socket during a quiet run. Callers may override it.\n */\nexport function ɵphoenixSocket$(\n options: ɵPhoenixSocketOptions,\n): Observable<ɵPhoenixSocketSession> {\n return defer(() => {\n const socket = new Socket(options.url, {\n heartbeatIntervalMs: 15_000,\n ...options.options,\n } as ConstructorParameters<typeof Socket>[1]) as ɵPhoenixSocketLike;\n const signals$ = ɵcreatePhoenixSocketSignals$(socket).pipe(\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n\n socket.connect();\n\n return concat(\n of({\n socket,\n signals$,\n }),\n NEVER,\n ).pipe(finalize(() => socket.disconnect()));\n });\n}\n\n/**\n * Create a cold Phoenix channel session from a socket session stream.\n *\n * A channel is created and joined for each active socket session. If the\n * upstream socket session changes, the previous channel is left before the\n * next one becomes active.\n */\nexport function ɵphoenixChannel$(\n options: ɵPhoenixChannelOptions,\n): Observable<ɵPhoenixChannelSession> {\n return options.socket$.pipe(\n switchMap(({ socket }) =>\n defer(() => {\n const channel = socket.channel(options.topic, options.params);\n const joinOutcome$ = ɵcreatePhoenixJoinOutcome$(channel).pipe(\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n\n return concat(\n of({\n channel,\n joinOutcome$,\n }),\n NEVER,\n ).pipe(\n finalize(() => {\n if (options.leaveOnUnsubscribe !== false) {\n channel.leave();\n }\n }),\n );\n }),\n ),\n );\n}\n\n/**\n * Observe a named Phoenix channel event as an observable payload stream.\n */\nexport function ɵobservePhoenixEvent$<T>(\n channel: ɵPhoenixChannelLike,\n eventName: string,\n): Observable<T> {\n return new Observable<T>((observer) => {\n const ref = channel.on(eventName, (payload) => observer.next(payload as T));\n\n return () => {\n channel.off(eventName, ref);\n };\n });\n}\n\n/**\n * Flatten channel sessions into their join-outcome stream.\n */\nexport function ɵobservePhoenixJoinOutcome$(\n channel$: Observable<ɵPhoenixChannelSession>,\n): Observable<ɵPhoenixJoinOutcome> {\n return channel$.pipe(switchMap((session) => session.joinOutcome$));\n}\n\n/**\n * Complete when a channel joins successfully, or error if the join fails.\n */\nexport function ɵjoinPhoenixChannel$(\n channel$: Observable<ɵPhoenixChannelSession>,\n): Observable<never> {\n return ɵobservePhoenixJoinOutcome$(channel$).pipe(\n take(1),\n mergeMap((outcome) => {\n if (outcome.type === \"joined\") {\n return EMPTY;\n }\n\n throw outcome.type === \"timeout\"\n ? new Error(\"Timed out joining channel\")\n : new Error(\n `Failed to join channel: ${JSON.stringify(outcome.response)}`,\n );\n }),\n );\n}\n\n/**\n * Flatten socket sessions into their lifecycle signal stream.\n */\nexport function ɵobservePhoenixSocketSignals$(\n socket$: Observable<ɵPhoenixSocketSession>,\n): Observable<ɵPhoenixSocketSignal> {\n return socket$.pipe(switchMap((session) => session.signals$));\n}\n\n/**\n * Error after a socket emits the configured number of consecutive error\n * signals, resetting the counter after each successful open signal.\n */\nexport function ɵobservePhoenixSocketHealth$(\n socketSignals$: Observable<ɵPhoenixSocketSignal>,\n maxConsecutiveErrors: number,\n): Observable<never> {\n return socketSignals$.pipe(\n scan(\n (consecutiveErrors, signal) =>\n signal.type === \"open\" ? 0 : consecutiveErrors + 1,\n 0,\n ),\n filter((consecutiveErrors) => consecutiveErrors >= maxConsecutiveErrors),\n take(1),\n mergeMap((consecutiveErrors) =>\n throwError(\n () =>\n new Error(\n `WebSocket connection failed after ${consecutiveErrors} consecutive errors`,\n ),\n ),\n ),\n );\n}\n","import type { ConnectionReplayLifecycle } from \"./utils/connect-replay\";\nimport type {\n RunAgentInput,\n RunAgentParameters,\n RunAgentResult,\n AgentSubscriber,\n BaseEvent,\n} from \"@ag-ui/client\";\nimport { AbstractAgent, EventType } from \"@ag-ui/client\";\n\nimport {\n EMPTY,\n Notification,\n combineLatest,\n defer,\n dematerialize,\n merge,\n of,\n switchMap,\n throwError,\n} from \"rxjs\";\nimport type { ObservableNotification, Observable } from \"rxjs\";\nimport {\n catchError,\n delay,\n endWith,\n filter,\n finalize,\n ignoreElements,\n map,\n mergeMap,\n startWith,\n share,\n shareReplay,\n switchMap as switchMapOperator,\n take,\n takeUntil,\n tap,\n} from \"rxjs/operators\";\nimport {\n phoenixExponentialBackoff,\n stripIntelligenceRoutingFields,\n} from \"@copilotkit/shared\";\nimport { ɵconnectWithoutEventVerification } from \"./utils/connect-replay\";\nimport {\n ɵphoenixChannel$,\n ɵphoenixSocket$,\n ɵjoinPhoenixChannel$,\n ɵobservePhoenixSocketSignals$,\n ɵobservePhoenixSocketHealth$,\n ɵobservePhoenixEvent$,\n} from \"./utils/phoenix-observable\";\nimport type {\n ɵPhoenixChannelLike,\n ɵPhoenixChannelSession,\n ɵPhoenixPushLike,\n ɵPhoenixSocketLike,\n ɵPhoenixSocketSession,\n} from \"./utils/phoenix-observable\";\n\n/**\n * Structural Phoenix socket/channel contracts used by this agent, derived from\n * the minimal `*Like` interfaces in {@link ./utils/phoenix-observable}.\n */\ntype Socket = ɵPhoenixSocketLike;\n\ninterface Channel extends ɵPhoenixChannelLike {\n push(event: string, payload: unknown): ɵPhoenixPushLike;\n}\n\nconst globalFetch: typeof fetch = (...args) => fetch(...args);\n\nconst CLIENT_AG_UI_EVENT = \"ag_ui_event\";\nconst REPLAY_COMPLETE_EVENT = \"replay_complete\";\nconst REPLAY_FAILED_EVENT = \"replay_failed\";\nconst STREAM_IDLE_EVENT = \"stream_idle\";\nconst STOP_RUN_EVENT = \"stop_run\";\nconst CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS = 100;\nconst CONNECT_IDLE_WARNING_MS = 30_000;\n// Credential refreshes allowed in a row for sockets that never opened. Past this,\n// the run fails instead of waiting on a realtime endpoint that is not answering.\nconst MAX_UNOPENED_CREDENTIAL_REFRESHES = 2;\n\ninterface IntelligenceAgentSharedState {\n lastSeenEventIds: Map<string, string>;\n}\n\n/** Control-frame cursor state for one channel join. */\ninterface ControlCursorState {\n /** The last `latestEventId` that this join saved as the reconnect cursor. */\n applied: string | null;\n /** True after `replay_failed`. The gateway then repeats the prior cursor on purpose. */\n replayFailed: boolean;\n}\n\ninterface RealtimeConnectionInfo {\n clientUrl: string;\n topic: string;\n}\n\ninterface ThreadJoinCredentials {\n threadId: string;\n runId: string | null;\n joinToken: string;\n realtime: RealtimeConnectionInfo;\n}\n\ninterface McpResourceReadResponse {\n kind: \"mcp-resource-read\";\n threadId: string;\n runId: string;\n result: unknown;\n}\n\nfunction isMcpResourceRead(input: RunAgentInput): boolean {\n const forwardedProps = input.forwardedProps as\n | Record<string, unknown>\n | undefined;\n const request = forwardedProps?.__proxiedMCPRequest;\n return (\n forwardedProps?.__copilotkitMcpResourceReadOnly === true &&\n typeof request === \"object\" &&\n request !== null &&\n (request as { method?: unknown }).method === \"resources/read\"\n );\n}\n\nexport class AgentThreadLockedError extends Error {\n constructor(threadId?: string) {\n super(threadId ? `Thread ${threadId} is locked` : \"Thread is locked\");\n this.name = \"AgentThreadLockedError\";\n }\n}\n\n/**\n * Typed contract for agents that expose the completion promise of their\n * currently in-flight run.\n *\n * `IntelligenceAgent` resolves this promise once a run's observable pipeline\n * finalizes (see {@link IntelligenceAgent.connectAgent}). Consumers (e.g. the\n * v2 `CopilotChat` send-serialization path) await it to let an in-flight run —\n * notably an interrupt RESUME — finish before dispatching a new run, instead\n * of pre-empting it.\n *\n * The base `AbstractAgent` from `@ag-ui/client` only declares this property\n * privately, so it is reachable only through this contract plus the\n * {@link isRunCompletionAware} type guard. This keeps callers off `as unknown`\n * casts while still degrading safely for agents that don't implement it.\n */\nexport interface RunCompletionAware {\n /**\n * Resolves when the active run's pipeline finalizes (completes, errors, or is\n * detached). `undefined` when no run is in flight.\n */\n readonly activeRunCompletionPromise?: Promise<void>;\n}\n\n/**\n * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes\n * an `activeRunCompletionPromise` property, so callers can await an in-flight\n * run without an `as unknown as` cast. Returns false for agents that don't\n * implement the contract, letting the caller skip the await and degrade safely.\n */\nexport function isRunCompletionAware(\n agent: unknown,\n): agent is RunCompletionAware {\n return (\n typeof agent === \"object\" &&\n agent !== null &&\n \"activeRunCompletionPromise\" in agent\n );\n}\n\nexport interface IntelligenceAgentConfig {\n /** Phoenix websocket URL, e.g. \"ws://localhost:4000/socket\" */\n url: string;\n /** Runtime base URL, e.g. \"http://localhost:4000\" */\n runtimeUrl: string;\n /** HTTP transport for run/connect requests. Defaults to REST. */\n transport?: \"rest\" | \"single\";\n /** Agent identifier for REST endpoints */\n agentId: string;\n /** Optional params sent on socket connect (e.g. auth token) */\n socketParams?: Record<string, string>;\n /** Optional headers sent with REST requests */\n headers?: Record<string, string>;\n /** Optional credentials mode for fetch requests */\n credentials?: RequestCredentials;\n fetch?: typeof fetch;\n}\n\nexport class IntelligenceAgent extends AbstractAgent {\n private config: IntelligenceAgentConfig;\n private socket: Socket | null = null;\n private activeChannel: Channel | null = null;\n private canonicalRunId: string | null = null;\n private sharedState: IntelligenceAgentSharedState;\n\n constructor(\n config: IntelligenceAgentConfig,\n sharedState: IntelligenceAgentSharedState = {\n lastSeenEventIds: new Map<string, string>(),\n },\n ) {\n super();\n this.config = config;\n this.sharedState = sharedState;\n }\n\n /**\n * Headers sent with the REST join requests (`/connect`, `/run`).\n *\n * Deliberately a public accessor pair rather than a plain read of `config`.\n * `ProxiedCopilotRuntimeAgent` builds its delegate once and caches it for the\n * proxy's lifetime, so a header that changes later (a tenant switch, a\n * rotated bearer) would otherwise never reach the gateway. The accessor is\n * what closes that gap: `syncDelegate` refreshes the delegate before every\n * join, and its `hasHeaders` probe is an `\"headers\" in agent` check — which a\n * prototype accessor satisfies but a `private config` does not.\n *\n * The setter replaces the config object instead of mutating it because\n * `clone()` hands the same config reference to the copy. An in-place write\n * would therefore have a per-thread clone's headers land on the original's\n * config too. The join path itself would survive that (`syncDelegate`\n * rewrites the headers just before every join), but the re-acquisition inside\n * an already-running pipeline does not go through `syncDelegate` — so a\n * clone's tenant could ride out on the original's socket-error refresh. That\n * is the same cross-tenant leak this accessor exists to prevent.\n */\n get headers(): Record<string, string> | undefined {\n return this.config.headers;\n }\n\n set headers(headers: Record<string, string> | undefined) {\n this.config = { ...this.config, headers };\n }\n\n /** Credentials mode for the REST join requests. Live for the same reason as {@link headers}. */\n get credentials(): RequestCredentials | undefined {\n return this.config.credentials;\n }\n\n set credentials(credentials: RequestCredentials | undefined) {\n this.config = { ...this.config, credentials };\n }\n\n clone(): IntelligenceAgent {\n return new IntelligenceAgent(this.config, this.sharedState);\n }\n\n /**\n * Override of AbstractAgent.connectAgent that removes the `verifyEvents` step.\n *\n * IntelligenceAgent uses long-lived WebSocket connections rather than\n * request-scoped SSE streams. When connecting to replay historical messages\n * for an existing thread, the connection semantics don't map to a single\n * agent run start/stop cycle: the replayed events may omit the\n * RUN_STARTED/RUN_FINISHED bookends, or carry events from several past runs,\n * either of which makes `verifyEvents` stall or error out.\n *\n * See {@link ɵconnectWithoutEventVerification} for the pipeline itself, which\n * the self-hosted `/connect` path shares for the same reason.\n */\n override async connectAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n // A run already in flight owns the canonical run id; reuse it so the\n // replay is attributed to that run rather than minting a new one.\n const effectiveParameters =\n parameters?.runId || !this.canonicalRunId\n ? parameters\n : {\n ...parameters,\n runId: this.canonicalRunId,\n };\n\n return ɵconnectWithoutEventVerification(\n this,\n effectiveParameters,\n subscriber,\n (input, lifecycle) => this.connect(input, lifecycle),\n );\n }\n\n abortRun(): void {\n if (this.activeChannel && this.canonicalRunId) {\n // Defer cleanup until the push is acknowledged so socket.disconnect()\n // doesn't clear the push buffer before the stop signal is sent.\n // The 5-second fallback handles the case where the socket is down and\n // Phoenix never flushes the buffered push (its .receive(\"timeout\") only\n // fires for pushes that were actually sent but not replied to).\n // detachActiveRun() gracefully tears down the connectAgent() pipeline;\n // cleanup() follows as a safety net for the run() path.\n const fallback = setTimeout(() => clear(), 5_000);\n const clear = () => {\n clearTimeout(fallback);\n void this.detachActiveRun();\n this.cleanup();\n };\n\n this.activeChannel\n .push(STOP_RUN_EVENT, { run_id: this.canonicalRunId })\n .receive(\"ok\", clear)\n .receive(\"error\", clear)\n .receive(\"timeout\", clear);\n } else {\n void this.detachActiveRun();\n this.cleanup();\n }\n }\n\n /**\n * Trigger the run via REST, then join the realtime thread channel and relay\n * server-pushed AG-UI events to the Observable subscriber.\n */\n run(input: RunAgentInput): Observable<BaseEvent> {\n if (!isMcpResourceRead(input)) {\n this.threadId = input.threadId;\n this.canonicalRunId = input.runId;\n }\n\n return defer(() => this.requestJoinCredentials$(\"run\", input)).pipe(\n switchMap((credentials) => {\n if (credentials === null) {\n return throwError(\n () => new Error(\"REST run request returned no credentials\"),\n );\n }\n\n if (\"kind\" in credentials) {\n return of(\n {\n type: EventType.RUN_STARTED,\n threadId: credentials.threadId,\n runId: credentials.runId,\n } as BaseEvent,\n {\n type: EventType.RUN_FINISHED,\n threadId: credentials.threadId,\n runId: credentials.runId,\n result: credentials.result,\n } as BaseEvent,\n );\n }\n\n const canonicalInput = this.applyCanonicalRunIdentity(\n input,\n credentials,\n { fallbackToInputRunId: true },\n );\n\n return this.observeThread$(canonicalInput, credentials, {\n completeOnRunError: false,\n streamMode: \"run\",\n });\n }),\n );\n }\n\n /**\n * Reconnect to an existing thread by fetching websocket credentials and\n * joining the realtime thread channel.\n */\n /**\n * Reconnect to an existing thread by fetching websocket credentials\n * and joining the realtime thread channel.\n *\n * Note: this method does NOT clear the replay cursor. Whether to\n * request a full historical replay vs. resume from\n * `lastSeenEventId` is a decision the caller (typically\n * `RunHandler.connectAgent`) makes by calling\n * {@link clearReconnectCursor} ahead of time on a fresh thread\n * restore. Same-thread churn re-connects preserve the cursor so the\n * gateway only streams events past it instead of replaying the\n * entire history every time the chat re-opens a socket.\n */\n protected connect(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent> {\n this.threadId = input.threadId;\n this.canonicalRunId = null;\n const replayCursor = this.getReconnectCursor(input);\n\n return defer(() =>\n this.requestJoinCredentials$(\"connect\", input, replayCursor),\n ).pipe(\n switchMap((credentials) => {\n if (credentials === null) {\n lifecycle?.onReplayStarted?.();\n lifecycle?.onReplayFinished?.();\n return EMPTY;\n }\n\n const canonicalInput = this.applyCanonicalRunIdentity(\n input,\n credentials,\n { fallbackToInputRunId: false },\n );\n\n return this.observeThread$(canonicalInput, credentials, {\n completeOnRunError: false,\n streamMode: \"connect\",\n replayCursor,\n lifecycle,\n });\n }),\n );\n }\n\n /**\n * Tear down a specific channel + socket pair that belongs to one pipeline.\n * Only nulls instance references when they still point to the owned resource,\n * so a concurrent pipeline's resources are never clobbered.\n */\n private cleanupOwned(\n ownChannel: Channel | null,\n ownSocket: Socket | null,\n ): void {\n if (ownChannel) {\n ownChannel.leave();\n if (this.activeChannel === ownChannel) {\n this.activeChannel = null;\n }\n }\n if (ownSocket) {\n ownSocket.disconnect();\n if (this.socket === ownSocket) {\n this.socket = null;\n }\n }\n this.canonicalRunId = null;\n }\n\n private cleanup(): void {\n this.cleanupOwned(this.activeChannel, this.socket);\n }\n\n private requestJoinCredentials$(\n mode: \"run\",\n input: RunAgentInput,\n ): Observable<ThreadJoinCredentials | McpResourceReadResponse>;\n private requestJoinCredentials$(\n mode: \"connect\",\n input: RunAgentInput,\n replayCursor?: string | null,\n ): Observable<ThreadJoinCredentials | null>;\n private requestJoinCredentials$(\n mode: \"run\" | \"connect\",\n input: RunAgentInput,\n replayCursor?: string | null,\n ): Observable<ThreadJoinCredentials | McpResourceReadResponse | null> {\n return defer(async () => {\n try {\n const requestFetch = this.config.fetch ?? globalFetch;\n const body = {\n ...input,\n ...(mode === \"connect\"\n ? {\n lastSeenEventId:\n replayCursor === undefined\n ? this.getReconnectCursor(input)\n : replayCursor,\n }\n : {}),\n };\n const single = this.config.transport === \"single\";\n const response = await requestFetch(\n single ? this.config.runtimeUrl : this.buildRuntimeUrl(mode),\n {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n // Post the whole RunAgentInput rather than naming each field, so a\n // protocol field such as `resume` cannot be dropped here again.\n body: JSON.stringify(\n single\n ? {\n method: `agent/${mode}`,\n params: { agentId: this.config.agentId },\n body,\n }\n : body,\n ),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n },\n );\n\n if (response.status === 204 && mode === \"connect\") {\n return null;\n }\n\n if (response.status === 409 && mode === \"run\") {\n throw new AgentThreadLockedError(input.threadId);\n }\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(\n text || response.statusText || String(response.status),\n );\n }\n\n const payload: unknown = await response.json();\n if (\n mode === \"run\" &&\n isMcpResourceRead(input) &&\n typeof payload === \"object\" &&\n payload !== null &&\n (payload as { kind?: unknown }).kind === \"mcp-resource-read\"\n ) {\n const resource = payload as Partial<McpResourceReadResponse>;\n if (\n typeof resource.threadId !== \"string\" ||\n !resource.threadId ||\n typeof resource.runId !== \"string\" ||\n !resource.runId\n ) {\n throw new Error(\"invalid MCP resource response identity\");\n }\n return {\n kind: \"mcp-resource-read\" as const,\n threadId: resource.threadId,\n runId: resource.runId,\n result: resource.result,\n };\n }\n return this.normalizeJoinCredentials(payload, input);\n } catch (error) {\n if (error instanceof AgentThreadLockedError) {\n throw error;\n }\n throw new Error(\n `REST ${mode} request failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n private normalizeJoinCredentials(\n payload: unknown,\n input: RunAgentInput,\n ): ThreadJoinCredentials {\n const envelope =\n payload && typeof payload === \"object\"\n ? (payload as Record<string, unknown>)\n : null;\n const realtime =\n envelope?.realtime && typeof envelope.realtime === \"object\"\n ? (envelope.realtime as Record<string, unknown>)\n : null;\n\n if (typeof envelope?.joinToken !== \"string\" || !envelope.joinToken) {\n throw new Error(\"missing joinToken\");\n }\n\n if (typeof realtime?.clientUrl !== \"string\" || !realtime.clientUrl) {\n throw new Error(\"missing realtime.clientUrl\");\n }\n\n if (typeof realtime.topic !== \"string\" || !realtime.topic) {\n throw new Error(\"missing realtime.topic\");\n }\n\n return {\n threadId:\n typeof envelope.threadId === \"string\" && envelope.threadId\n ? envelope.threadId\n : input.threadId,\n runId:\n typeof envelope.runId === \"string\" && envelope.runId\n ? envelope.runId\n : null,\n joinToken: envelope.joinToken,\n realtime: {\n clientUrl: realtime.clientUrl,\n topic: realtime.topic,\n },\n };\n }\n\n private observeThread$(\n input: RunAgentInput,\n credentials: ThreadJoinCredentials,\n options: {\n completeOnRunError: boolean;\n streamMode: \"run\" | \"connect\";\n lifecycle?: ConnectionReplayLifecycle;\n channelMode?: \"run\" | \"connect\";\n replayCursor?: string | null;\n unopenedRefreshes?: number;\n },\n ): Observable<BaseEvent> {\n const { unopenedRefreshes: previousUnopened = 0, ...sessionOptions } =\n options;\n return defer(() => {\n let socketOpened = false;\n return this.observeThreadSession$(input, credentials, {\n ...sessionOptions,\n onSocketOpen: () => {\n socketOpened = true;\n },\n }).pipe(\n catchError((error) => {\n if (!this.isSocketReconnectExhaustedError(error)) {\n return throwError(() => error);\n }\n\n // A session whose socket opened was a real connection that dropped, so\n // it restarts the count. Sessions that never open mean the realtime\n // endpoint is unavailable, and fresh credentials will not fix that.\n // Only a run is capped: a developer is waiting on its turn. A connect\n // restores history in the background, and nothing retries it after it\n // fails, so it keeps reconnecting until the endpoint recovers.\n const unopenedRefreshes = socketOpened ? 0 : previousUnopened + 1;\n if (\n options.streamMode === \"run\" &&\n unopenedRefreshes > MAX_UNOPENED_CREDENTIAL_REFRESHES\n ) {\n return throwError(\n () =>\n new Error(\n `Realtime connection to ${credentials.realtime.clientUrl} never opened ` +\n `in ${unopenedRefreshes} connection attempts. ` +\n `The realtime endpoint is unavailable.`,\n ),\n );\n }\n\n const replayCursor = this.getReconnectCursor(input);\n return this.requestJoinCredentials$(\n \"connect\",\n input,\n replayCursor,\n ).pipe(\n switchMap((refreshedCredentials) =>\n refreshedCredentials === null\n ? EMPTY\n : this.observeThread$(\n this.applyCanonicalRunIdentity(\n input,\n refreshedCredentials,\n {\n fallbackToInputRunId: options.streamMode === \"run\",\n },\n ),\n refreshedCredentials,\n {\n ...sessionOptions,\n channelMode: \"connect\",\n replayCursor,\n unopenedRefreshes,\n },\n ),\n ),\n );\n }),\n );\n });\n }\n\n private observeThreadSession$(\n input: RunAgentInput,\n credentials: ThreadJoinCredentials,\n options: {\n completeOnRunError: boolean;\n streamMode: \"run\" | \"connect\";\n lifecycle?: ConnectionReplayLifecycle;\n channelMode?: \"run\" | \"connect\";\n replayCursor?: string | null;\n onSocketOpen?: () => void;\n },\n ): Observable<BaseEvent> {\n return defer(() => {\n options.lifecycle?.onReplayStarted?.();\n // Capture references to the socket and channel created by THIS pipeline\n // so the finalize closure only tears down its own resources. Without\n // this, a fire-and-forget detachActiveRun() from run-handler can race:\n // the old pipeline's deferred cleanup reads from `this.socket` /\n // `this.activeChannel`, which by then may already point to the NEW\n // pipeline's resources — destroying the live connection and preventing\n // the stop signal from ever reaching the backend.\n let ownSocket: Socket | null = null;\n let ownChannel: Channel | null = null;\n\n // Silence after replay may mean a long-running agent or an unavailable\n // thread-lock lookup. Diagnose it without declaring an active run idle.\n let replayFinished = false;\n let warnedAboutIdle = false;\n let idleWarning: ReturnType<typeof setTimeout> | undefined;\n const clearIdleWarning = () => {\n clearTimeout(idleWarning);\n idleWarning = undefined;\n };\n const scheduleIdleWarning = () => {\n clearIdleWarning();\n if (\n options.streamMode !== \"connect\" ||\n !replayFinished ||\n warnedAboutIdle\n )\n return;\n idleWarning = setTimeout(() => {\n warnedAboutIdle = true;\n this.debugLogger?.lifecycle(\n \"INTELLIGENCE\",\n \"No progress or stream_idle for 30 seconds after replay_complete; the run may still be active or its status unavailable.\",\n { threadId: input.threadId },\n );\n }, CONNECT_IDLE_WARNING_MS);\n };\n\n const socket$ = ɵphoenixSocket$({\n url: credentials.realtime.clientUrl,\n options: {\n params: {\n ...this.config.socketParams,\n join_token: credentials.joinToken,\n },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(\n tap(({ socket }) => {\n ownSocket = socket as Socket;\n this.socket = ownSocket;\n }),\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n const params = this.createThreadChannelParams(\n input,\n options.channelMode ?? options.streamMode,\n options.replayCursor,\n );\n const channel$ = ɵphoenixChannel$({\n socket$,\n topic: credentials.realtime.topic,\n params,\n }).pipe(\n tap(({ channel }) => {\n ownChannel = channel as Channel;\n this.activeChannel = ownChannel;\n }),\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n const reconnectCursor = this.readDurableEventId(\n options.replayCursor ?? this.getReconnectCursor(input),\n );\n let latestObservedReplayCursor: string | null = null;\n const threadEvents$ = this.observeThreadEvents$(\n input.threadId,\n channel$,\n options,\n ).pipe(\n tap((payload) => {\n latestObservedReplayCursor =\n this.readEventId(payload) ?? latestObservedReplayCursor;\n scheduleIdleWarning();\n }),\n share(),\n );\n const controlCursor: ControlCursorState = {\n applied: null,\n replayFailed: false,\n };\n const replayFailed$ = channel$.pipe(\n switchMapOperator(({ channel }) =>\n this.observeChannelEvent$<unknown>(channel, REPLAY_FAILED_EVENT),\n ),\n tap(() => {\n controlCursor.replayFailed = true;\n }),\n );\n // Controls are scoped to each replay epoch, not cached across rejoin.\n const replayComplete$ = this.observeControlEvent$(\n input.threadId,\n channel$,\n REPLAY_COMPLETE_EVENT,\n controlCursor,\n ).pipe(\n // Notify before idle completion can unsubscribe other observers.\n tap(() => {\n replayFinished = true;\n scheduleIdleWarning();\n options.lifecycle?.onReplayFinished?.();\n }),\n share(),\n );\n const streamIdle$ = this.observeControlEvent$(\n input.threadId,\n channel$,\n STREAM_IDLE_EVENT,\n controlCursor,\n ).pipe(share());\n const replayRestart$ = merge(\n this.observeControlEvent$(\n input.threadId,\n channel$,\n \"phx_error\",\n controlCursor,\n ),\n ɵobservePhoenixSocketSignals$(socket$).pipe(\n filter((signal) => signal.type === \"error\"),\n ),\n ).pipe(\n tap(() => {\n replayFinished = false;\n warnedAboutIdle = false;\n clearIdleWarning();\n options.lifecycle?.onReplayStarted?.();\n }),\n share(),\n );\n const streamIdleCompletion$ =\n options.streamMode === \"connect\"\n ? replayRestart$.pipe(\n startWith(null),\n switchMap(() =>\n merge(\n combineLatest([\n replayComplete$.pipe(take(1)),\n streamIdle$.pipe(take(1)),\n ]),\n streamIdle$.pipe(\n take(1),\n filter((payload) =>\n this.canFallbackCompleteConnect(\n payload,\n reconnectCursor,\n latestObservedReplayCursor,\n ),\n ),\n delay(CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS),\n tap(() => {\n this.debugLogger?.lifecycle(\n \"INTELLIGENCE\",\n \"Completing connection on stream_idle fallback without replay_complete.\",\n {\n threadId: input.threadId,\n fallbackMs: CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS,\n },\n );\n }),\n ),\n ),\n ),\n take(1),\n shareReplay({ bufferSize: 1, refCount: true }),\n )\n : EMPTY;\n const threadCompleted$ = threadEvents$.pipe(\n ignoreElements(),\n endWith(null),\n take(1),\n );\n const terminal$ = merge(threadCompleted$, streamIdleCompletion$);\n\n return merge(\n // Install replay/idle observers before joining the channel.\n replayFailed$.pipe(ignoreElements(), takeUntil(terminal$)),\n replayComplete$.pipe(ignoreElements(), takeUntil(terminal$)),\n this.joinThreadChannel$(channel$),\n this.observeSocketHealth$(socket$, options.onSocketOpen).pipe(\n takeUntil(terminal$),\n ),\n threadEvents$.pipe(takeUntil(streamIdleCompletion$)),\n streamIdleCompletion$.pipe(\n ignoreElements(),\n takeUntil(threadCompleted$),\n ),\n ).pipe(\n finalize(() => {\n clearIdleWarning();\n this.cleanupOwned(ownChannel, ownSocket);\n }),\n );\n });\n }\n\n private joinThreadChannel$(\n channel$: Observable<ɵPhoenixChannelSession>,\n ): Observable<never> {\n return ɵjoinPhoenixChannel$(channel$);\n }\n\n private observeSocketHealth$(\n socket$: Observable<ɵPhoenixSocketSession>,\n onSocketOpen?: () => void,\n ): Observable<never> {\n return ɵobservePhoenixSocketHealth$(\n ɵobservePhoenixSocketSignals$(socket$).pipe(\n tap((signal) => {\n if (signal.type === \"open\") onSocketOpen?.();\n }),\n ),\n 5,\n );\n }\n\n private observeThreadEvents$(\n threadId: string,\n channel$: Observable<ɵPhoenixChannelSession>,\n options: { completeOnRunError: boolean; streamMode: \"run\" | \"connect\" },\n ): Observable<BaseEvent> {\n return channel$.pipe(\n switchMapOperator(({ channel }) =>\n this.observeChannelEvent$<BaseEvent>(channel, CLIENT_AG_UI_EVENT),\n ),\n tap((payload) => {\n this.updateLastSeenEventId(threadId, payload);\n }),\n // Only the run stream goes through AG-UI 1.0 enforcement, which would\n // strip these fields with a warning each. Replays stay as sent.\n map((payload) =>\n options.streamMode === \"run\"\n ? stripIntelligenceRoutingFields(payload)\n : payload,\n ),\n mergeMap(\n (payload) =>\n this.createThreadNotifications(payload, {\n completeOnRunError: options.completeOnRunError,\n completeOnRunFinished: options.streamMode === \"run\",\n errorOnRunError: options.streamMode === \"run\",\n }) as ObservableNotification<BaseEvent>[],\n ),\n dematerialize(),\n );\n }\n\n private observeControlEvent$(\n threadId: string,\n channel$: Observable<ɵPhoenixChannelSession>,\n eventName: string,\n controlCursor: ControlCursorState,\n ): Observable<unknown> {\n return channel$.pipe(\n switchMapOperator(({ channel }) =>\n this.observeChannelEvent$<unknown>(channel, eventName),\n ),\n tap((payload) =>\n this.updateLastSeenEventIdFromControl(threadId, payload, controlCursor),\n ),\n );\n }\n\n private observeChannelEvent$<T>(\n channel: ɵPhoenixChannelLike,\n eventName: string,\n ): Observable<T> {\n return ɵobservePhoenixEvent$<T>(channel, eventName);\n }\n\n private createThreadNotifications(\n payload: BaseEvent,\n options: {\n completeOnRunError: boolean;\n completeOnRunFinished: boolean;\n errorOnRunError: boolean;\n },\n ): Array<Notification<BaseEvent>> {\n if (payload.type === EventType.RUN_FINISHED) {\n return options.completeOnRunFinished\n ? [Notification.createNext(payload), Notification.createComplete()]\n : [Notification.createNext(payload)];\n }\n\n if (payload.type === EventType.RUN_ERROR) {\n const errorMessage =\n (payload as BaseEvent & { message?: string }).message ?? \"Run error\";\n\n return options.completeOnRunError\n ? [Notification.createNext(payload), Notification.createComplete()]\n : options.errorOnRunError\n ? [\n Notification.createNext(payload),\n Notification.createError(new Error(errorMessage)),\n ]\n : [Notification.createNext(payload)];\n }\n\n return [Notification.createNext(payload)];\n }\n\n private buildRuntimeUrl(mode: \"run\" | \"connect\"): string {\n const path = `${this.config.runtimeUrl}/agent/${encodeURIComponent(this.config.agentId)}/${mode}`;\n const origin =\n typeof window !== \"undefined\" && window.location\n ? window.location.origin\n : \"http://localhost\";\n\n return new URL(path, new URL(this.config.runtimeUrl, origin)).toString();\n }\n\n private createThreadChannelParams(\n input: RunAgentInput,\n streamMode: \"run\" | \"connect\",\n replayCursor?: string | null,\n ): Record<string, unknown> {\n return streamMode === \"run\"\n ? {\n stream_mode: \"run\",\n run_id: input.runId,\n }\n : {\n stream_mode: \"connect\",\n last_seen_event_id:\n replayCursor === undefined\n ? this.getReconnectCursor(input)\n : replayCursor,\n };\n }\n\n private getLastSeenEventId(threadId: string): string | null {\n return this.sharedState.lastSeenEventIds.get(threadId) ?? null;\n }\n\n private getReconnectCursor(input: RunAgentInput): string | null {\n return this.getLastSeenEventId(input.threadId);\n }\n\n /**\n * Drop the cached `lastSeenEventId` cursor for `threadId` so the\n * next connect to that topic asks the gateway for a full historical\n * replay (rather than resuming). Public because\n * `RunHandler.connectAgent` calls it on a detected thread switch\n * to rebuild local state from scratch, and skips it on same-thread\n * churn so the gateway can resume.\n */\n public clearReconnectCursor(threadId: string): void {\n this.sharedState.lastSeenEventIds.delete(threadId);\n }\n\n private updateLastSeenEventId(threadId: string, payload: BaseEvent): void {\n const eventId = this.readEventId(payload);\n if (!eventId) {\n return;\n }\n\n this.advanceLastSeenEventId(threadId, eventId);\n }\n\n private updateLastSeenEventIdFromControl(\n threadId: string,\n payload: unknown,\n controlCursor: ControlCursorState,\n ): void {\n const eventId = this.readControlEventId(payload);\n if (!eventId) {\n return;\n }\n\n // An older gateway repeats the join's history checkpoint on every control\n // frame, also on stream_idle after live events moved past it. A repeat is\n // stale and must not replace the newer event cursor, or the next join\n // replays those live events again. After replay_failed the gateway repeats\n // the prior cursor on purpose, so the next join retries the failed history.\n if (eventId === controlCursor.applied && !controlCursor.replayFailed) {\n return;\n }\n\n controlCursor.applied = eventId;\n this.advanceLastSeenEventId(threadId, eventId);\n }\n\n private advanceLastSeenEventId(threadId: string, eventId: string): void {\n this.sharedState.lastSeenEventIds.set(threadId, eventId);\n }\n\n private readEventId(payload: BaseEvent): string | null {\n const metadata = (payload as BaseEvent & { metadata?: unknown }).metadata;\n if (!metadata || typeof metadata !== \"object\") {\n return null;\n }\n\n const eventMetadata = metadata as { cpki_event_id?: unknown };\n return this.readDurableEventId(eventMetadata.cpki_event_id);\n }\n\n private readControlEventId(payload: unknown): string | null {\n if (!payload || typeof payload !== \"object\") {\n return null;\n }\n\n const controlPayload = payload as {\n latestEventId?: unknown;\n latest_event_id?: unknown;\n };\n const latestEventId =\n controlPayload.latestEventId ?? controlPayload.latest_event_id;\n return this.readDurableEventId(latestEventId);\n }\n\n private readDurableEventId(eventId: unknown): string | null {\n if (typeof eventId !== \"string\" || eventId.trim() === \"\") {\n return null;\n }\n\n return eventId.startsWith(\"cpki_ingested\") ? null : eventId;\n }\n\n private canFallbackCompleteConnect(\n streamIdlePayload: unknown,\n reconnectCursor: string | null,\n latestObservedReplayCursor: string | null,\n ): boolean {\n const idleCursor = this.readControlEventId(streamIdlePayload);\n if (!idleCursor) {\n return true;\n }\n\n return (\n idleCursor === reconnectCursor ||\n idleCursor === latestObservedReplayCursor\n );\n }\n\n private applyCanonicalRunIdentity(\n input: RunAgentInput,\n credentials: ThreadJoinCredentials,\n options: { fallbackToInputRunId: boolean },\n ): RunAgentInput {\n this.threadId = credentials.threadId;\n const runId =\n credentials.runId ?? (options.fallbackToInputRunId ? input.runId : null);\n this.canonicalRunId = runId;\n\n return {\n ...input,\n threadId: credentials.threadId,\n ...(runId === null ? {} : { runId }),\n };\n }\n\n private isSocketReconnectExhaustedError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"WebSocket connection failed after\")\n );\n }\n}\n","/**\n * Build the error for a failed runtime `/info` response, folding in whatever\n * explanation the runtime sent back.\n *\n * The status alone cannot distinguish a wrong `runtimeUrl` from a transport\n * mismatch, so the runtime answers the latter with a body naming the cause\n * (see the handler's `single_route_envelope_against_multi_route_runtime`\n * diagnostic). Discarding that body — as every `/info` caller used to — left\n * the developer with a bare 404 and nothing to act on (OSS-882).\n *\n * A body that isn't JSON, or carries no string `message`, contributes nothing:\n * the status is then the whole error.\n */\nexport async function runtimeInfoError(\n response: Response,\n): Promise<RuntimeInfoRequestError> {\n const base = `Runtime info request failed with status ${response.status}`;\n\n let detail: string | undefined;\n try {\n const body: unknown = await response.clone().json();\n const message = (body as { message?: unknown } | null)?.message;\n if (typeof message === \"string\" && message.trim().length > 0) {\n detail = message.trim();\n }\n } catch {\n // Unparseable or already-consumed body — fall back to the status.\n }\n\n const error = new Error(\n detail ? `${base}: ${detail}` : base,\n ) as RuntimeInfoRequestError;\n error.runtimeInfoStatus = response.status;\n return error;\n}\n\nexport interface RuntimeInfoRequestError extends Error {\n runtimeInfoStatus: number;\n}\n\nexport function isRuntimeInfoRequestError(\n error: unknown,\n): error is RuntimeInfoRequestError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as { runtimeInfoStatus?: unknown }).runtimeInfoStatus ===\n \"number\"\n );\n}\n","import type { Message } from \"@ag-ui/client\";\n\n/**\n * Rewrites the message list a runtime agent sends on each run.\n *\n * CopilotKit sends the whole thread on every request. When the backend already\n * stores the conversation (a LangGraph checkpointer, a Mastra memory store, a\n * Strands `SessionManager`, an Agent Framework chat history provider), that\n * history is dead weight: the payload grows without bound, and an agent that\n * merges the inbound list with its own store can show the model every turn\n * twice. See https://github.com/CopilotKit/CopilotKit/issues/1482.\n *\n * The filter runs on the outbound payload only. It never touches the messages\n * the UI renders, so trimming here does not shorten the visible transcript.\n *\n * Return the messages to send. Returning an empty array is valid and means\n * \"send nothing but the run metadata\".\n *\n * @param messages - The thread as the client holds it, in order, with\n * `activity`-role messages already removed.\n * @param context - Which agent is about to run.\n */\nexport type CopilotKitMessageFilter = (\n messages: Message[],\n context: { agentId: string },\n) => Message[];\n\n/**\n * The string ids of a message's tool calls.\n *\n * Malformed entries are ignored rather than thrown on, matching\n * {@link ɵkeepToolResultsWithCalls}: a null or primitive entry, or an entry\n * without a string `id`, opens no pair instead of failing the repair.\n */\nfunction toolCallIdsOf(message: Message): string[] {\n const calls = (message as { toolCalls?: unknown }).toolCalls;\n if (!Array.isArray(calls)) return [];\n const ids: string[] = [];\n for (const call of calls) {\n if (typeof call !== \"object\" || call === null) continue;\n const id = (call as { id?: unknown }).id;\n if (typeof id === \"string\" && id) ids.push(id);\n }\n return ids;\n}\n\nfunction resultCallIdOf(message: Message): string | undefined {\n if (message.role !== \"tool\") return undefined;\n return (message as { toolCallId?: string }).toolCallId;\n}\n\n/**\n * Repair the tool-call pairs a filter broke.\n *\n * Every provider rejects a half pair. A tool result whose call is gone reads as\n * a reply to nothing, and an assistant tool call whose result is gone leaves\n * the turn unanswered — the failure reporters hit on #1482 when a trimmed\n * history landed mid-HITL and Anthropic answered \"a tool result is expected\".\n * A filter written as `messages.slice(-1)` cannot know this, so the repair runs\n * for every filter rather than being something each caller opts into.\n *\n * Both repairs restore, never discard, and both are anchored on the untrimmed\n * thread:\n *\n * - A kept tool result whose assistant call was trimmed away gets that call put\n * back in front of it. Dropping the result instead would be protocol-safe and\n * semantically wrong: on a human-in-the-loop turn the result IS the new\n * information, and a backend that already holds the call would be asked to\n * resume with nothing.\n * - A kept assistant call whose result was trimmed gets that result restored,\n * placed directly after the call.\n *\n * Restoring a call pulls in every result for that call, not only the one the\n * filter kept. Providers reject an assistant turn with a parallel tool call\n * left unanswered, so a half-answered set is as invalid as a missing one.\n *\n * A call with no result anywhere in `full` is left alone. That is an open call\n * (a pending frontend tool, an unanswered interrupt), not a broken pair. A\n * result whose call is nowhere in `full` is left alone too: it was already\n * unpaired before the filter ran, so it is not this function's to fix.\n *\n * The filter's own ordering is preserved. Restorations are the only insertions,\n * and messages the filter synthesized (absent from `full`) pass through\n * untouched.\n */\nexport function ɵrepairToolCallPairs(\n kept: Message[],\n full: Message[],\n): Message[] {\n // Pair each result with the nearest unmatched call before it. Providers\n // often reuse call ids across turns, so an id alone cannot identify a pair.\n // The untrimmed thread supplies the order the filter may have removed.\n const pendingIssuersByCallId = new Map<string, Message[]>();\n const issuerIdToResultsByCallId = new Map<string, Map<string, Message[]>>();\n const resultIdToIssuer = new Map<string, Message>();\n for (const message of full) {\n for (const callId of toolCallIdsOf(message)) {\n push(pendingIssuersByCallId, callId, message);\n }\n const resultCallId = resultCallIdOf(message);\n if (resultCallId !== undefined) {\n const pendingIssuers = pendingIssuersByCallId.get(resultCallId);\n const issuer = pendingIssuers?.pop();\n if (issuer) {\n resultIdToIssuer.set(message.id, issuer);\n let resultsByCallId = issuerIdToResultsByCallId.get(issuer.id);\n if (!resultsByCallId) {\n resultsByCallId = new Map();\n issuerIdToResultsByCallId.set(issuer.id, resultsByCallId);\n }\n push(resultsByCallId, resultCallId, message);\n }\n }\n }\n\n const repaired: Message[] = [];\n const emitted = new Set<string>();\n const expandedMessages = new Set<Message>();\n\n const emit = (message: Message) => {\n if (emitted.has(message.id)) return;\n emitted.add(message.id);\n repaired.push(message);\n };\n\n /** Emit an assistant turn together with every result it is owed. */\n const emitWithResults = (message: Message) => {\n emit(message);\n if (expandedMessages.has(message)) return;\n expandedMessages.add(message);\n const resultsByCallId = issuerIdToResultsByCallId.get(message.id);\n for (const callId of toolCallIdsOf(message)) {\n for (const result of resultsByCallId?.get(callId) ?? []) emit(result);\n }\n };\n\n for (const message of kept) {\n const resultCallId = resultCallIdOf(message);\n if (resultCallId === undefined) {\n emitWithResults(message);\n continue;\n }\n\n const issuer = resultIdToIssuer.get(message.id);\n if (issuer) {\n // Emits the issuer first, then this result along with its siblings.\n emitWithResults(issuer);\n continue;\n }\n emit(message);\n }\n\n return repaired;\n}\n\n/**\n * Move each detached tool result to sit behind the assistant call that issued\n * it — usually back to an earlier call, and forward only when no earlier call\n * has its id and exactly one call in the list does — and change nothing else.\n * Used for unfiltered sends, and on a configured filter's output only when\n * {@link ɵrepairToolCallPairs}, which filtered sends go through otherwise,\n * throws.\n *\n * The client store can detach a tool result from its call on its own: when a\n * backend's `MESSAGES_SNAPSHOT` carries a tool message under a different id\n * than the streamed `TOOL_CALL_RESULT`, the `@ag-ui/client` merge drops the\n * copy placed after its call and appends the snapshot's copy at the end,\n * leaving `assistant(tool_call), assistant(text), tool(result)`. A backend that\n * rebuilds its state from that payload discards every result it cannot pair.\n *\n * The pairing rule mirrors the `@ag-ui/client` snapshot pass\n * (ag-ui-protocol/ag-ui#3114):\n *\n * - Everything is by list position. The same object or id appearing twice is\n * two independent slots, including an assistant call the merge duplicated,\n * so a duplicated call can be left unanswered. Nothing is dropped,\n * deduplicated, or added, and only tool-role messages ever change position.\n * - Transparent entries are `activity` and `reasoning` messages and anything\n * that is not a plain object (`null`, arrays, primitives). They are never\n * the anchor, never separate a call from its result, and stay in place.\n * Reasoning stored between a call and its result is the next step's: in a\n * multi-step turn whose calls share one assistant message, Mastra leaves\n * `assistant(c1, c2), tool(c1), reasoning, tool(c2)`. Moving the result in\n * front of it leaves the reasoning trailing, and Mastra drops it.\n * - The anchor is the last non-transparent message so far that is not `tool`.\n * Each tool call an assistant issues opens a slot for its call id, and a\n * result pairs with slots for its `toolCallId` alone. `subagentRunId` is\n * ignored: results CopilotKit creates itself (frontend tool results,\n * interrupt responses) do not carry one, and on a result it names the run\n * that executed the tool, which may differ from the run that issued the\n * call. Known limitation: a parent call and a subagent call that reuse one\n * id are indistinguishable, so their drifted results can be swapped.\n * - Pass 1, left to right: a result with an open slot issued at the anchor is\n * in place; it takes that slot and stays put. A result with an open slot\n * issued earlier is detached. A result with no slot for its id issued\n * earlier at all is early. Any other result — every earlier slot for its id\n * already answered — stays put. Detached results take no slot in this\n * pass: they could only ever take a slot issued before the current anchor,\n * which no later in-place result can want.\n * - Pass 2, backward, per id: the detached results, from the newest back,\n * each take the newest still-open slot issued before them; one that finds\n * none stays put. So when several results for a reused id (providers reuse\n * `call_0` every turn) are all detached, they keep their stored order\n * across the calls, and a later turn's lone result goes to the later call\n * rather than to an earlier one that was abandoned.\n * - Pass 3, forward, per id: an early result moves forward only when its id\n * is unambiguous — exactly one call slot in the whole list has it, that\n * slot is issued after the result, and it is still open after passes 1-2.\n * The first early result for the id, left to right, takes it; any other\n * early result for that id stays put. This repairs a result whose call\n * was re-issued after it (a snapshot that re-ids the assistant message but\n * keeps the result's id). With a reused id (providers reuse `call_0` every\n * turn) nothing moves forward: in `[t0, t1, a1(c), user, a2(c)]` nothing\n * says t1 answers a2, and a2 may be a pending call (a frontend tool, an\n * interrupt, a human-in-the-loop call waiting on the user). Only early\n * results move forward: an extra result for a call that is already\n * answered never does.\n * - A moved result goes behind its issuer, after the tool and transparent\n * entries already following it, but in front of any reasoning among those\n * transparent entries: reasoning belongs to the message after it, so a\n * moved result never lands between a reasoning message and its owner.\n * Results moved behind one issuer keep their stored order. Any other\n * message between a call and its result separates them, so a\n * backward-moved result moves before it and a forward-moved result moves\n * past it.\n * - The rule cannot tell a duplicate result from a detached one. A second\n * result for an already-answered call moves back to an older still-open\n * slot for its id if there is one, even across user turns; it never moves\n * forward.\n * - Malformed entries are ignored rather than thrown on. Non-array\n * `toolCalls`, call entries without a string `id`, and results without a\n * string `toolCallId` open or take no slot.\n *\n * Returns `messages` itself when nothing moved.\n */\nexport function ɵkeepToolResultsWithCalls(messages: Message[]): Message[] {\n type Slot = { issuer: number; open: boolean };\n // Per call id, the slots its calls opened, in stored order.\n const slots = new Map<string, Slot[]>();\n // Per call id, how many of its slots are still open.\n const openCount = new Map<string, number>();\n const close = (callId: string, slot: Slot) => {\n slot.open = false;\n openCount.set(callId, openCount.get(callId)! - 1);\n };\n // Per call id, the detached results, in stored order.\n const detached = new Map<string, number[]>();\n // Per call id, the results with no slot for their id issued before them at\n // all, in stored order: the only results that may move forward.\n const early = new Map<string, number[]>();\n let anchor = -1;\n\n for (let index = 0; index < messages.length; index++) {\n const message: unknown = messages[index];\n if (isTransparent(message)) continue;\n const role = roleOf(message);\n\n if (role !== \"tool\") {\n anchor = index;\n const calls =\n role === \"assistant\"\n ? (message as { toolCalls?: unknown }).toolCalls\n : undefined;\n if (!Array.isArray(calls)) continue;\n for (const call of calls) {\n if (typeof call !== \"object\" || call === null) continue;\n const callId = (call as { id?: unknown }).id;\n if (typeof callId !== \"string\") continue;\n push(slots, callId, { issuer: index, open: true });\n openCount.set(callId, (openCount.get(callId) ?? 0) + 1);\n }\n continue;\n }\n\n const callId = (message as { toolCallId?: unknown }).toolCallId;\n if (typeof callId !== \"string\") continue;\n const forId = slots.get(callId);\n if (!forId) {\n push(early, callId, index);\n continue;\n }\n\n // Slots open in stored order and the anchor is the newest issuer, so the\n // anchor's slots sit at the tail: scan only those.\n let atAnchor: Slot | undefined;\n for (let s = forId.length - 1; s >= 0; s--) {\n const slot = forId[s]!;\n if (slot.issuer !== anchor) break;\n if (slot.open) atAnchor = slot;\n }\n if (atAnchor) {\n close(callId, atAnchor);\n continue;\n }\n // Every earlier slot for this id already answered: an extra or stale\n // result. It stays, so it cannot answer a later pending call.\n if (openCount.get(callId)! > 0) push(detached, callId, index);\n }\n\n const movedBehind = new Map<number, number[]>();\n const moved = new Set<number>();\n const take = (callId: string, slot: Slot, index: number) => {\n close(callId, slot);\n moved.add(index);\n push(movedBehind, slot.issuer, index);\n };\n\n for (const [callId, results] of detached) {\n const forId = slots.get(callId)!;\n // Results go newest first and each needs a slot issued before it, so the\n // newest usable slot only ever moves left: one cursor per id keeps the\n // pass linear even when every turn reuses the same id.\n let s = forId.length - 1;\n for (let r = results.length - 1; r >= 0; r--) {\n const index = results[r]!;\n while (s >= 0 && (!forId[s]!.open || forId[s]!.issuer >= index)) s--;\n // One that finds none had an earlier call for its id, so it stays.\n if (s < 0) break;\n take(callId, forId[s]!, index);\n }\n }\n\n for (const [callId, results] of early) {\n // Only an unambiguous id moves forward: exactly one call slot for it in\n // the whole list. With a reused id (providers reuse `call_0` every turn)\n // nothing says which later call an early result answers, and guessing\n // can answer a pending human-in-the-loop call with another turn's\n // result. Every slot is issued after an early result (none came before\n // it), so the one slot only has to be still open; the first early\n // result takes it and the rest stay put.\n const forId = slots.get(callId);\n if (forId?.length !== 1 || !forId[0]!.open) continue;\n take(callId, forId[0]!, results[0]!);\n }\n\n if (moved.size === 0) return messages;\n\n const result: Message[] = [];\n let openIssuer = -1;\n const flush = () => {\n const behind = movedBehind.get(openIssuer);\n if (!behind) return;\n // Converters give a reasoning message to the message after it, so the\n // moved results go in front of any reasoning among the transparent\n // entries at the tail, never between a reasoning message and its owner.\n // Activity is stripped before sending, so it is looked past too.\n let at = result.length;\n for (let tail = result.length - 1; tail >= 0; tail--) {\n if (!isTransparent(result[tail])) break;\n if (roleOf(result[tail]) === \"reasoning\") at = tail;\n }\n // Collected id by id, and within an id in pass order; emit them in\n // stored order.\n result.splice(\n at,\n 0,\n ...[...behind]\n .sort((a, b) => a - b)\n .map((index) => messages[index] as Message),\n );\n };\n for (let index = 0; index < messages.length; index++) {\n if (moved.has(index)) continue;\n const message: unknown = messages[index];\n if (!isTransparent(message) && roleOf(message) !== \"tool\") {\n flush();\n openIssuer = index;\n }\n result.push(message as Message);\n }\n flush();\n return result;\n}\n\nfunction push<K, T>(map: Map<K, T[]>, key: K, value: T): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/**\n * Activity and reasoning messages and anything that is not a plain object\n * (`null`, arrays, primitives) never anchor or separate.\n */\nfunction isTransparent(message: unknown): boolean {\n return (\n typeof message !== \"object\" ||\n message === null ||\n Array.isArray(message) ||\n (message as { role?: unknown }).role === \"activity\" ||\n (message as { role?: unknown }).role === \"reasoning\"\n );\n}\n\nfunction roleOf(message: unknown): unknown {\n if (typeof message !== \"object\" || message === null) return undefined;\n return (message as { role?: unknown }).role;\n}\n","import type {\n AbstractAgent,\n AgentCapabilities,\n AgentSubscriber,\n BaseEvent,\n HttpAgentConfig,\n Message,\n RunAgentInput,\n RunAgentParameters,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport {\n EventType,\n HttpAgent,\n runHttpRequest,\n structuredClone_,\n transformHttpEventStream,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { EMPTY, defer, from, of } from \"rxjs\";\nimport {\n catchError,\n concatMap,\n concatWith,\n finalize,\n switchMap,\n} from \"rxjs/operators\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport type {\n IntelligenceRuntimeInfo,\n RuntimeInfo,\n RuntimeMode,\n ResolvedDebugConfig,\n} from \"@copilotkit/shared\";\nimport { IntelligenceAgent } from \"./intelligence-agent\";\nimport type { CopilotRuntimeTransport } from \"./types\";\nimport { runtimeInfoError } from \"./utils/runtime-info-error\";\nimport type { RuntimeRequestInit } from \"./utils/runtime-request\";\nimport type { ConnectionReplayLifecycle } from \"./utils/connect-replay\";\nimport { ɵconnectWithoutEventVerification } from \"./utils/connect-replay\";\nimport type { CopilotKitMessageFilter } from \"./core/message-filter\";\nimport {\n ɵkeepToolResultsWithCalls,\n ɵrepairToolCallPairs,\n} from \"./core/message-filter\";\n\ntype ResolvedRuntimeMode = RuntimeMode | \"pending\";\n\ninterface RunnableAgent {\n connect(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent>;\n run(input: RunAgentInput): Observable<BaseEvent>;\n}\n\nfunction hasHeaders(\n agent: AbstractAgent,\n): agent is AbstractAgent & { headers?: Record<string, string> } {\n return \"headers\" in agent;\n}\n\nfunction hasCredentials(\n agent: AbstractAgent,\n): agent is AbstractAgent & { credentials?: RequestCredentials } {\n return \"credentials\" in agent;\n}\n\nfunction isZodError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n (error as { name: string }).name === \"ZodError\"\n );\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException || error instanceof Error) &&\n (error as Error).name === \"AbortError\"\n );\n}\n\nfunction withAbortErrorHandling(\n observable: Observable<BaseEvent>,\n): Observable<BaseEvent> {\n return observable.pipe(\n catchError((error) => {\n if (isZodError(error) || isAbortError(error)) {\n return EMPTY;\n }\n throw error;\n }),\n );\n}\n\nexport interface ProxiedCopilotRuntimeAgentConfig extends Omit<\n HttpAgentConfig,\n \"url\"\n> {\n runtimeUrl?: string;\n transport?: CopilotRuntimeTransport;\n credentials?: RequestCredentials;\n runtimeMode?: ResolvedRuntimeMode;\n intelligence?: IntelligenceRuntimeInfo;\n capabilities?: AgentCapabilities;\n debug?: ResolvedDebugConfig;\n /**\n * When set, runtime requests (HTTP path, single-route envelope, intelligence\n * delegate) are routed to this agent on the runtime instead of `agentId`.\n * The local `agentId` remains the registry key used for subscriber\n * bookkeeping; only outbound routing is overridden.\n */\n runtimeAgentId?: string;\n /**\n * Rewrites the outbound message list on every run. See\n * {@link CopilotKitMessageFilter}. Not applied in Intelligence mode.\n */\n messageFilter?: CopilotKitMessageFilter;\n}\n\nexport class ProxiedCopilotRuntimeAgent extends HttpAgent {\n runtimeUrl?: string;\n credentials?: RequestCredentials;\n // `readonly` because `super.url` is baked at construction; mutating\n // `runtimeAgentId` post-construction would desync the REST `run` URL\n // (already captured) from `routedAgentId()` (consulted per-call by\n // stop/connect/single-route paths).\n readonly runtimeAgentId?: string;\n private transport: CopilotRuntimeTransport;\n /**\n * The runtime URL exactly as the caller supplied it. `runtimeUrl` is the\n * slash-stripped form used for path joins; the single-route endpoint (run,\n * connect, stop, info envelopes) is this verbatim value, because a trailing\n * slash can select a different proxy location.\n */\n private readonly runtimeEndpointUrl?: string;\n private singleEndpointUrl?: string;\n private runtimeMode: ResolvedRuntimeMode;\n private intelligence?: IntelligenceRuntimeInfo;\n private _capabilities?: AgentCapabilities;\n private delegate?: AbstractAgent;\n private runtimeInfoPromise?: Promise<void>;\n private connectionAttempt?: object;\n private _messageFilter?: CopilotKitMessageFilter;\n /**\n * The HTTP `run` this agent started and has not yet seen finish, as the\n * exact `{ threadId, runId }` it POSTed. `abortRun` narrows `/stop` to this\n * run only while `threadId` still matches: `threadId` is a public field the\n * host may reassign under a live run, and a runId from another thread must\n * not be sent as if it were this thread's. Released when the run stream\n * finalizes, cleared on `connect` (a reconnected thread may run under a\n * runId this client never saw) and never copied by `clone`. Without a\n * provable active run the stop stays thread-wide.\n */\n private activeRun?: { threadId: string; runId: string };\n\n constructor(config: ProxiedCopilotRuntimeAgentConfig) {\n const normalizedRuntimeUrl = config.runtimeUrl\n ? config.runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n const transport = config.transport ?? \"auto\";\n const routedId = config.runtimeAgentId ?? config.agentId ?? \"\";\n // The single endpoint is the caller's URL exactly as given: a trailing\n // slash can select a different proxy location, so it must survive. Only\n // the path joins (`/agent/…`, `/info`) use the slash-stripped form.\n const runUrl =\n transport === \"single\"\n ? (config.runtimeUrl ?? \"\")\n : `${normalizedRuntimeUrl ?? config.runtimeUrl}/agent/${encodeURIComponent(routedId)}/run`;\n\n if (!runUrl) {\n throw new Error(\n \"ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.\",\n );\n }\n\n super({\n ...config,\n url: runUrl,\n });\n this.runtimeUrl = normalizedRuntimeUrl ?? config.runtimeUrl;\n this.runtimeEndpointUrl = config.runtimeUrl;\n this.credentials = config.credentials;\n this.runtimeAgentId = config.runtimeAgentId;\n this.transport = transport;\n this.runtimeMode = config.runtimeMode ?? RUNTIME_MODE_SSE;\n this.intelligence = config.intelligence;\n this._capabilities = config.capabilities;\n this._messageFilter = config.messageFilter;\n if (config.debug) {\n this.debug = config.debug;\n }\n if (this.transport === \"single\") {\n this.singleEndpointUrl = this.runtimeEndpointUrl;\n }\n }\n\n /**\n * Adopt the runtime mode a fresh `/info` just reported.\n *\n * A live proxy outlives the runtime configuration that minted it: a\n * redeploy, an env-var change or a rollback can flip `intelligence` → `sse`\n * under a page that is already open. The registry preserves the proxy across\n * that re-sync on purpose — it is backing an open conversation — so the new\n * mode is pushed onto the instance here instead of replacing it.\n *\n * Without this the mode was decided once, at construction, and `run()` kept\n * taking the delegate path against a runtime serving plain SSE, where\n * `response.json()` on a `text/event-stream` body throws for the rest of the\n * page's life. See #7130.\n *\n * A delegate built for the old mode is torn down: it speaks a protocol the\n * runtime no longer serves, and it may be holding a websocket open. The\n * memoized `/info` promise goes with it — it answered for the old\n * configuration, so a later `ensureRuntimeConfiguration()` must re-ask\n * rather than treat that answer as current.\n *\n * Only `wsUrl` is compared on the Intelligence metadata, because that is the\n * one field the delegate bakes in at construction.\n */\n adoptRuntimeMode(\n runtimeMode: ResolvedRuntimeMode,\n intelligence: IntelligenceRuntimeInfo | undefined,\n ): void {\n const unchanged =\n this.runtimeMode === runtimeMode &&\n this.intelligence?.wsUrl === intelligence?.wsUrl;\n\n this.runtimeMode = runtimeMode;\n this.intelligence = intelligence;\n\n if (unchanged) {\n return;\n }\n this.connectionAttempt = undefined;\n this.runtimeInfoPromise = undefined;\n const staleDelegate = this.delegate;\n this.delegate = undefined;\n if (staleDelegate) {\n staleDelegate.abortRun();\n }\n // SSE also owns a pipeline, even though it has no delegate.\n void this.detachActiveRun();\n }\n\n /**\n * The agent id used for outbound runtime requests — `runtimeAgentId` when\n * set (manually-registered proxy), otherwise `agentId` (registry id\n * matches runtime id). Subscriber bookkeeping keeps using `agentId`\n * directly.\n *\n * Throws when both are unset: a proxy reaching an HTTP path with no\n * routable id is a bug, and a missing id would otherwise produce a\n * malformed `/agent//run` or `/agent/undefined/connect` URL silently.\n */\n private routedAgentId(): string {\n const id = this.runtimeAgentId ?? this.agentId;\n if (!id) {\n throw new Error(\n \"ProxiedCopilotRuntimeAgent: cannot make a runtime request without an agentId or runtimeAgentId.\",\n );\n }\n return id;\n }\n\n get capabilities(): AgentCapabilities | undefined {\n return this._capabilities;\n }\n\n /**\n * The filter applied to the outbound message list on every run.\n *\n * Registry-owned. `AgentRegistry` writes it whenever the core-level filter\n * changes, so an agent discovered before the app configured one still picks\n * it up — and so a value written here by hand is replaced on the registry's\n * next sweep. Configure it through `CopilotKitCore` instead.\n */\n get messageFilter(): CopilotKitMessageFilter | undefined {\n return this._messageFilter;\n }\n\n set messageFilter(filter: CopilotKitMessageFilter | undefined) {\n this._messageFilter = filter;\n }\n\n /**\n * Build the outbound payload, keeping every tool result with the call that\n * issued it.\n *\n * - **No filter** (or a filter whose output is unusable, which falls back to\n * the full thread): `ɵkeepToolResultsWithCalls` re-places tool results\n * that drifted from their call and changes nothing else. The client store\n * can detach them on its own when a `MESSAGES_SNAPSHOT` re-ids a tool\n * message, and a backend that rebuilds state from such a payload drops\n * every result it cannot pair.\n * - **Filter**: `ɵrepairToolCallPairs(kept, full)` restores the call or the\n * results a filter trimmed. Its known limitations are tracked in\n * https://github.com/CopilotKit/CopilotKit/issues/7891.\n * - **Filter repair throws**: the filter's output goes through\n * `ɵkeepToolResultsWithCalls` instead, keeping its trimming and\n * redaction; if that throws too, the output is sent as is.\n *\n * **Called from the HTTP paths only, and that placement is the Intelligence\n * exemption.** An earlier revision applied the filter in\n * `prepareRunAgentInput`, which runs before the runtime mode is resolved:\n * with the default `\"auto\"` transport, or on a proxy still `\"pending\"` its\n * first `/info`, `run()` prepared the input, *then* resolved the mode, then\n * handed that already-filtered input to `#runViaDelegate` — so a managed\n * runtime received a truncated thread despite the exemption. Filtering here\n * makes that unreachable by construction: `#runViaHttp` and\n * `#connectViaHttp` are only entered once the mode is known not to be\n * Intelligence. Do not move this back up the call chain.\n *\n * The managed runtime is the store of record for the thread — the threads\n * drawer and the Slack transcript read from it — so a client-side truncation\n * there has a blast radius nobody asked for. Every reporter on #1482 is\n * self-hosted.\n *\n * `prepareRunAgentInput` has already deep-cloned the thread and stripped\n * `activity` messages by the time the input reaches here, so the filter\n * cannot reach the messages the UI renders no matter what it does with the\n * array it is handed. The filter gets a *second* deep clone on top of that,\n * because `input.messages` is also the repair baseline and the untrimmed\n * fallback: sharing the message objects let a filter that rewrote the tool\n * call id of an assistant message it dropped hide that issuer from the\n * repair, and the kept tool result then went out orphaned — a payload the\n * provider rejects, which is exactly the failure this whole mechanism\n * exists to prevent.\n */\n #prepareOutboundMessages(input: RunAgentInput): RunAgentInput {\n const full = input.messages;\n const kept = this.#applyMessageFilter(full);\n\n // The pairing step is a best-effort fix-up, so it is guarded on its own\n // and kept apart from the filter call: a bug here is reported as the\n // repair failing, never as the app's filter failing. A successful filter\n // repair changes more than pairing: it can add stored calls and results,\n // reorder messages, drop messages that share an id or results under a\n // reused call id, and replace a filter's edited copies with the stored\n // originals (see above). If the repair throws, the payload goes out as\n // it would have without it — the input unchanged when nothing was\n // filtered, the filter's output with only drifted results moved when a\n // filter ran.\n const agentId = this.agentId ?? \"\";\n try {\n const messages =\n kept === undefined\n ? ɵkeepToolResultsWithCalls(full)\n : ɵrepairToolCallPairs(kept, full);\n return { ...input, messages };\n } catch (error) {\n if (kept === undefined) {\n console.warn(\n `ProxiedCopilotRuntimeAgent: tool-call repair failed for agent \"${agentId}\"; sending the message history unrepaired instead.`,\n error,\n );\n return input;\n }\n try {\n const messages = ɵkeepToolResultsWithCalls(kept);\n console.warn(\n `ProxiedCopilotRuntimeAgent: tool-call repair failed for agent \"${agentId}\"; sending the filtered message history with only drifted tool results moved instead.`,\n error,\n );\n return { ...input, messages };\n } catch (moveError) {\n console.warn(\n `ProxiedCopilotRuntimeAgent: tool-call repair failed for agent \"${agentId}\"; sending the filtered message history unrepaired instead.`,\n error,\n moveError,\n );\n return { ...input, messages: kept };\n }\n }\n }\n\n /**\n * Run the configured filter. Returns `undefined` when there is no filter,\n * copying the thread for it fails, or the filter's output cannot be used,\n * meaning \"send the full thread\".\n *\n * A filter that throws, returns a non-array, or returns an array with an\n * entry that is not a message object (a hole or a nested array included)\n * falls back to the untrimmed thread rather than failing the run. Trimming\n * is an optimization, and taking the user's message down with it would be\n * the worse outcome; the warning is what surfaces the bug.\n */\n #applyMessageFilter(full: Message[]): Message[] | undefined {\n const filter = this._messageFilter;\n if (!filter) return undefined;\n\n // Copied outside the filter's guard, so a thread that cannot be cloned is\n // reported as that, not as the app's filter failing.\n let copy: Message[];\n try {\n copy = structuredClone_(full);\n } catch (error) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: could not copy the message history for messageFilter; sending the full message history instead.\",\n error,\n );\n return undefined;\n }\n\n let kept: unknown;\n try {\n kept = filter(copy, { agentId: this.agentId ?? \"\" });\n } catch (error) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.\",\n error,\n );\n return undefined;\n }\n if (!Array.isArray(kept)) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.\",\n );\n return undefined;\n }\n // An index loop, not `every`: `every` skips the holes of a sparse array.\n for (let index = 0; index < kept.length; index++) {\n const entry: unknown = kept[index];\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: messageFilter returned an entry that is not a message; sending the full message history instead.\",\n );\n return undefined;\n }\n }\n return kept as Message[];\n }\n\n override requestInit(input: RunAgentInput): RequestInit {\n const baseInit = super.requestInit(input);\n return {\n ...baseInit,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n };\n }\n\n async getCapabilities(): Promise<AgentCapabilities> {\n return this._capabilities ?? {};\n }\n\n override async detachActiveRun(): Promise<void> {\n this.connectionAttempt = undefined;\n this.isRunning = false;\n const delegateDetach = this.delegate?.detachActiveRun();\n const proxyDetach = super.detachActiveRun();\n await Promise.all([delegateDetach, proxyDetach]);\n }\n\n abortRun(): void {\n if (this.delegate) {\n this.syncDelegate(this.delegate);\n this.delegate.abortRun();\n // Also detach the proxy's own runAgent pipeline so the proxy's\n // isRunning resets and onRunFinalized fires even if the delegate's\n // observable doesn't propagate a clean completion.\n void this.detachActiveRun();\n return;\n }\n\n if (!this.agentId || !this.threadId) {\n return;\n }\n\n if (typeof fetch === \"undefined\") {\n return;\n }\n\n const routedId = this.routedAgentId();\n const runId =\n this.activeRun?.threadId === this.threadId\n ? this.activeRun.runId\n : undefined;\n\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n return;\n }\n\n const headers = new Headers({\n ...this.headers,\n \"Content-Type\": \"application/json\",\n });\n void this.fetch(this.singleEndpointUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n method: \"agent/stop\",\n params: {\n agentId: routedId,\n threadId: this.threadId,\n },\n ...(runId === undefined ? {} : { body: { runId } }),\n }),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n // A stop is fire-and-forget: its failure shouldn't arm the runtime\n // reachability watchdog or trigger a reachability probe.\n ɵruntimeRequest: { nonCritical: true },\n } as RuntimeRequestInit).catch((error) => {\n console.error(\"ProxiedCopilotRuntimeAgent: stop request failed\", error);\n });\n return;\n }\n\n if (!this.runtimeUrl) {\n return;\n }\n\n const stopPath = `${this.runtimeUrl}/agent/${encodeURIComponent(routedId)}/stop/${encodeURIComponent(this.threadId)}`;\n const origin =\n typeof window !== \"undefined\" && window.location\n ? window.location.origin\n : \"http://localhost\";\n const base = new URL(this.runtimeUrl, origin);\n const stopUrl = new URL(stopPath, base);\n\n void this.fetch(stopUrl.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n ...(runId === undefined ? {} : { body: JSON.stringify({ runId }) }),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n // A stop is fire-and-forget: its failure shouldn't arm the runtime\n // reachability watchdog or trigger a reachability probe.\n ɵruntimeRequest: { nonCritical: true },\n } as RuntimeRequestInit).catch((error) => {\n console.error(\"ProxiedCopilotRuntimeAgent: stop request failed\", error);\n });\n }\n\n override async connectAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n const detached = this.detachActiveRun();\n const connection = {};\n const threadId = this.threadId;\n this.connectionAttempt = connection;\n const isCurrentConnection = () =>\n this.connectionAttempt === connection && this.threadId === threadId;\n await detached;\n if (!isCurrentConnection()) return { result: undefined, newMessages: [] };\n await this.ensureRuntimeConfiguration();\n if (!isCurrentConnection()) return { result: undefined, newMessages: [] };\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) {\n // A self-hosted `/connect` response replays the thread's history, so it\n // can carry several past runs — including one that ended in RUN_ERROR\n // followed by a later RUN_STARTED. The base pipeline's `verifyEvents`\n // step enforces single-run lifecycle rules and rejects that stream\n // outright, so an existing thread never hydrates (#4943).\n return ɵconnectWithoutEventVerification(\n this,\n parameters,\n subscriber,\n (input, lifecycle) => this.connect(input, lifecycle),\n );\n }\n\n // Ensure the delegate exists and is synced with the proxy's current state.\n await this.resolveDelegate();\n if (!isCurrentConnection()) return { result: undefined, newMessages: [] };\n const delegate = this.delegate!;\n\n // Subscribe a bridging observer FIRST so it fires before the forwarded\n // UI subscribers. This keeps proxy.messages in sync with the delegate\n // in real-time — otherwise the UI re-renders (triggered by the\n // forwarded onMessagesChanged) but reads stale proxy.messages because\n // the final sync only happens after connectAgent resolves.\n const bridgeSub = delegate.subscribe({\n onMessagesChanged: () => {\n if (!isCurrentConnection()) return;\n this.setMessages([...delegate.messages]);\n },\n onStateChanged: () => {\n if (!isCurrentConnection()) return;\n this.setState({ ...delegate.state });\n },\n // Mirror isRunning so the proxy reflects the delegate's run lifecycle.\n // Without this, UI components read proxy.isRunning (always false) even\n // though the delegate is actively running, causing the stop button to\n // never appear.\n onRunInitialized: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = true;\n },\n onRunFinalized: () => {\n if (!isCurrentConnection()) return;\n this.pendingInterrupts = structuredClone_(delegate.pendingInterrupts);\n this.isRunning = false;\n },\n // Local exception (network error, deserialization failure, etc.)\n onRunFailed: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = false;\n },\n // The connect pipeline updates the delegate before forwarding events:\n // live errors clear busy, historical errors keep replay busy, and a\n // successor run can start while the same connection keeps listening.\n onRunErrorEvent: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = delegate.isRunning;\n },\n onRunStartedEvent: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = delegate.isRunning;\n },\n });\n\n // Forward the proxy's subscribers to the delegate so that UI hooks\n // (e.g. useAgent's onMessagesChanged) receive real-time updates as\n // the delegate processes events during connectAgent.\n const forwardedSubs = [\n ...this.subscribers,\n ...(subscriber ? [subscriber] : []),\n ].map((subscriber) =>\n delegate.subscribe(\n new Proxy(subscriber, {\n get(target, property, receiver) {\n const callback = Reflect.get(target, property, receiver);\n if (typeof callback !== \"function\") return callback;\n return (...args: unknown[]) =>\n isCurrentConnection()\n ? Reflect.apply(callback, target, args)\n : undefined;\n },\n }),\n ),\n );\n\n try {\n const result = await delegate.connectAgent(parameters);\n\n // Final sync to guarantee the proxy reflects the delegate's end state.\n if (isCurrentConnection()) {\n this.setMessages([...delegate.messages]);\n this.setState({ ...delegate.state });\n this.pendingInterrupts = structuredClone_(delegate.pendingInterrupts);\n }\n\n return result;\n } finally {\n // Ensure the proxy's isRunning is reset — the bridging subscription\n // may have already handled this, but if the delegate threw before\n // firing onRunFinalized the proxy would be stuck in isRunning=true.\n if (isCurrentConnection()) this.isRunning = false;\n // Remove forwarded subscribers to avoid duplicate notifications on\n // subsequent calls (they'll be re-forwarded next time).\n bridgeSub.unsubscribe();\n for (const sub of forwardedSubs) {\n sub.unsubscribe();\n }\n }\n }\n\n connect(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent> {\n if (\n this.runtimeMode === \"pending\" ||\n (this.transport === \"auto\" &&\n this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE)\n ) {\n return defer(() => from(this.ensureRuntimeConfiguration())).pipe(\n switchMap(() => this.connect(input, lifecycle)),\n );\n }\n if (this.runtimeMode === RUNTIME_MODE_INTELLIGENCE) {\n return this.#connectViaDelegate(input, lifecycle);\n }\n return this.#connectViaHttp(input);\n }\n\n public run(input: RunAgentInput): Observable<BaseEvent> {\n if (\n this.runtimeMode === \"pending\" ||\n (this.transport === \"auto\" &&\n this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE)\n ) {\n return defer(() => from(this.ensureRuntimeConfiguration())).pipe(\n switchMap(() => this.run(input)),\n );\n }\n if (this.runtimeMode === RUNTIME_MODE_INTELLIGENCE) {\n return this.#runViaDelegate(input);\n }\n return this.#runViaHttp(input);\n }\n\n #connectViaDelegate(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent> {\n return defer(() => from(this.resolveDelegate())).pipe(\n switchMap((delegate) =>\n withAbortErrorHandling(delegate.connect(input, lifecycle)),\n ),\n );\n }\n\n #connectViaHttp(unfiltered: RunAgentInput): Observable<BaseEvent> {\n const input = this.#prepareOutboundMessages(unfiltered);\n this.activeRun = undefined;\n const routedId = this.routedAgentId();\n let httpEvents: ReturnType<typeof runHttpRequest>;\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n throw new Error(\"Single endpoint transport requires a runtimeUrl\");\n }\n\n const requestInit = this.createSingleRouteRequestInit(\n input,\n \"agent/connect\",\n {\n agentId: routedId,\n },\n );\n httpEvents = runHttpRequest(() =>\n this.fetch(this.singleEndpointUrl!, requestInit),\n );\n } else {\n const connectUrl = `${this.runtimeUrl}/agent/${routedId}/connect`;\n const connectRequestInit = this.requestInit(input);\n httpEvents = runHttpRequest(() =>\n this.fetch(connectUrl, connectRequestInit),\n );\n }\n\n const replay = defer(() => {\n let replayStarted = false;\n const emptyHistory = [\n { type: EventType.MESSAGES_SNAPSHOT, messages: [] },\n { type: EventType.STATE_SNAPSHOT, snapshot: {} },\n ];\n return transformHttpEventStream(httpEvents).pipe(\n concatMap((event) => {\n if (replayStarted) return of(event);\n replayStarted = true;\n // Reset through the event pipeline because it captures the old view.\n // Keep that view until the first replay event arrives.\n return from([...emptyHistory, event]);\n }),\n concatWith(defer(() => (replayStarted ? EMPTY : from(emptyHistory)))),\n );\n });\n // A failed or aborted request must not become a successful empty replay.\n return withAbortErrorHandling(replay);\n }\n\n #runViaDelegate(input: RunAgentInput): Observable<BaseEvent> {\n return defer(() => from(this.resolveDelegate())).pipe(\n switchMap((delegate) => withAbortErrorHandling(delegate.run(input))),\n );\n }\n\n #runViaHttp(unfiltered: RunAgentInput): Observable<BaseEvent> {\n const input = this.#prepareOutboundMessages(unfiltered);\n const activeRun = { threadId: input.threadId, runId: input.runId };\n // Hold this run's identity for as long as its stream lives. The identity\n // check keeps a late-finalizing stream from releasing a newer run.\n const trackActiveRun = (source: Observable<BaseEvent>) => {\n this.activeRun = activeRun;\n return source.pipe(\n finalize(() => {\n if (this.activeRun === activeRun) this.activeRun = undefined;\n }),\n );\n };\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n throw new Error(\"Single endpoint transport requires a runtimeUrl\");\n }\n\n const requestInit = this.createSingleRouteRequestInit(\n input,\n \"agent/run\",\n {\n agentId: this.routedAgentId(),\n },\n );\n const httpEvents = runHttpRequest(() =>\n this.fetch(this.singleEndpointUrl!, requestInit),\n );\n return trackActiveRun(\n withAbortErrorHandling(transformHttpEventStream(httpEvents)),\n );\n }\n\n return trackActiveRun(withAbortErrorHandling(super.run(input)));\n }\n\n public override clone(): ProxiedCopilotRuntimeAgent {\n const cloned = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this.runtimeEndpointUrl ?? this.runtimeUrl,\n agentId: this.agentId,\n runtimeAgentId: this.runtimeAgentId,\n description: this.description,\n headers: { ...this.headers },\n credentials: this.credentials,\n transport: this.transport,\n runtimeMode: this.runtimeMode,\n intelligence: this.intelligence,\n capabilities: this._capabilities,\n debug: this.debug,\n fetch: this.fetch,\n messageFilter: this._messageFilter,\n });\n cloned.threadId = this.threadId;\n cloned.setState(this.state);\n cloned.setMessages(this.messages);\n cloned.pendingInterrupts = structuredClone_(this.pendingInterrupts);\n if (this.delegate) {\n const clonedDelegate: AbstractAgent = this.delegate.clone();\n cloned.delegate = clonedDelegate;\n cloned.syncDelegate(clonedDelegate);\n }\n return cloned;\n }\n\n /** Run presentation-only MCP reads on a separate client agent so their\n * lifecycle cannot replace an in-flight approval's detach/completion state. */\n public async ɵrunMcpResourceRead(\n parameters: RunAgentParameters,\n ): Promise<RunAgentResult> {\n const request = (\n parameters.forwardedProps as Record<string, unknown> | undefined\n )?.__proxiedMCPRequest;\n if (\n typeof request !== \"object\" ||\n request === null ||\n (request as { method?: unknown }).method !== \"resources/read\"\n ) {\n throw new Error(\"Only MCP resources/read can use the read-only path\");\n }\n await this.ensureRuntimeConfiguration();\n // Only the renderer's dedicated read path opts into the direct response.\n // Other MCP callers still receive the normal realtime run protocol.\n const resourceParameters = {\n ...parameters,\n forwardedProps: {\n ...parameters.forwardedProps,\n __copilotkitMcpResourceReadOnly: true,\n },\n };\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) {\n return this.runAgent(resourceParameters);\n }\n const resourceAgent = this.clone();\n // A resource read does not resume the conversation. Only its disposable\n // client skips the pending-interrupt gate; the original agent and ordinary\n // clones must retain every approval for the next conversation run.\n resourceAgent.pendingInterrupts = [];\n return resourceAgent.runAgent(resourceParameters);\n }\n\n /**\n * Drop the delegate's cached `lastSeenEventId` for this thread so\n * the next connect requests a full historical replay from the\n * gateway. Used by `RunHandler.connectAgent` on a detected thread\n * switch (the chat moved between threads, so its local\n * messages/state are about to be cleared and need rebuilding from\n * the gateway). Skipped on same-thread churn re-connects so the\n * gateway can resume from the cursor instead.\n *\n * No-op for non-Intelligence runtime modes — the HTTP transport\n * doesn't replay.\n */\n public clearReplayCursor(threadId: string): void {\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) return;\n const delegate = this.delegate as\n | { clearReconnectCursor?: (id: string) => void }\n | null\n | undefined;\n delegate?.clearReconnectCursor?.(threadId);\n }\n\n private async resolveDelegate(): Promise<RunnableAgent> {\n await this.ensureRuntimeConfiguration();\n\n if (!this.delegate) {\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) {\n throw new Error(\"A delegate is only created for Intelligence mode\");\n }\n this.delegate = this.createIntelligenceDelegate();\n }\n\n this.syncDelegate(this.delegate);\n\n // AbstractAgent declares connect() as protected, but concrete delegates\n // (IntelligenceAgent, HttpAgent) expose both connect() and run() publicly.\n return this.delegate as unknown as RunnableAgent;\n }\n\n /** Resolve transport and runtime mode before the first outbound request. */\n private async ensureRuntimeConfiguration(): Promise<void> {\n if (\n this.runtimeMode === RUNTIME_MODE_INTELLIGENCE ||\n (this.runtimeMode !== \"pending\" && this.transport !== \"auto\")\n ) {\n return;\n }\n\n if (!this.runtimeUrl) {\n throw new Error(\"Runtime URL is not set\");\n }\n\n const runtimeInfoPromise =\n this.runtimeInfoPromise ??\n this.fetchRuntimeInfo().then((runtimeInfo) => {\n if (this.runtimeInfoPromise !== runtimeInfoPromise) return;\n this.runtimeMode = runtimeInfo.mode ?? RUNTIME_MODE_SSE;\n this.intelligence = runtimeInfo.intelligence;\n });\n this.runtimeInfoPromise = runtimeInfoPromise;\n\n try {\n await runtimeInfoPromise;\n } catch (error) {\n if (this.runtimeInfoPromise === runtimeInfoPromise) {\n this.runtimeInfoPromise = undefined;\n }\n throw error;\n }\n }\n\n private async fetchRuntimeInfo(): Promise<RuntimeInfo> {\n const headers: Record<string, string> = {\n ...this.headers,\n };\n\n if (this.transport === \"auto\") {\n return this.fetchRuntimeInfoAutoDetect(headers);\n }\n\n let init: RequestInit;\n let url: string;\n\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n throw new Error(\"Single endpoint transport requires a runtimeUrl\");\n }\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n url = this.singleEndpointUrl;\n init = { method: \"POST\", body: JSON.stringify({ method: \"info\" }) };\n } else {\n url = `${this.runtimeUrl}/info`;\n init = {};\n }\n\n const response = await this.fetch(url, {\n ...init,\n headers,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n return (await response.json()) as RuntimeInfo;\n }\n\n private async fetchRuntimeInfoAutoDetect(\n headers: Record<string, string>,\n ): Promise<RuntimeInfo> {\n // Try REST first (GET /info)\n try {\n const response = await this.fetch(`${this.runtimeUrl}/info`, {\n headers: { ...headers },\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n // Only treat a successful (2xx) response as a valid REST runtime.\n // 404/405 means the endpoint doesn't exist; other non-2xx errors\n // (500, 403, etc.) should also fall through to single-endpoint.\n if (response.status >= 200 && response.status < 300) {\n this.transport = \"rest\";\n return (await response.json()) as RuntimeInfo;\n }\n } catch {\n // REST failed — fall through to single-endpoint attempt\n }\n\n // Try single-endpoint (POST with { method: \"info\" })\n const singleHeaders = { ...headers };\n if (!singleHeaders[\"Content-Type\"]) {\n singleHeaders[\"Content-Type\"] = \"application/json\";\n }\n const endpointUrl = this.runtimeEndpointUrl ?? this.runtimeUrl!;\n const response = await this.fetch(endpointUrl, {\n method: \"POST\",\n headers: singleHeaders,\n body: JSON.stringify({ method: \"info\" }),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n this.transport = \"single\";\n this.singleEndpointUrl = endpointUrl;\n return (await response.json()) as RuntimeInfo;\n }\n\n private createSingleRouteRequestInit(\n input: RunAgentInput,\n method: string,\n params?: Record<string, string>,\n ): RequestInit {\n if (!this.agentId) {\n throw new Error(\n \"ProxiedCopilotRuntimeAgent requires agentId to make runtime requests\",\n );\n }\n\n const baseInit = super.requestInit(input);\n const headers = new Headers(baseInit.headers ?? {});\n headers.set(\"Content-Type\", \"application/json\");\n headers.set(\"Accept\", headers.get(\"Accept\") ?? \"text/event-stream\");\n\n let originalBody: unknown = undefined;\n if (typeof baseInit.body === \"string\") {\n try {\n originalBody = JSON.parse(baseInit.body);\n } catch (error) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport\",\n error,\n );\n }\n }\n\n const envelope: Record<string, unknown> = { method };\n\n if (params && Object.keys(params).length > 0) {\n envelope.params = params;\n }\n\n if (originalBody !== undefined) {\n envelope.body = originalBody;\n }\n\n return {\n ...baseInit,\n headers,\n body: JSON.stringify(envelope),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n };\n }\n\n private createIntelligenceDelegate(): AbstractAgent {\n const routedId = this.routedAgentId();\n if (!this.runtimeUrl || !routedId || !this.intelligence?.wsUrl) {\n throw new Error(\n \"Intelligence mode requires runtimeUrl, agentId, and intelligence websocket metadata\",\n );\n }\n\n const single = this.transport === \"single\";\n\n return new IntelligenceAgent({\n url: this.intelligence.wsUrl,\n // Single-route posts to the endpoint itself, so it needs the caller's URL\n // verbatim: a trailing slash can select a different proxy location\n // (issue #7028). REST needs the slash-stripped form, because it joins\n // `/agent/:id/:mode` onto it.\n runtimeUrl: single\n ? (this.runtimeEndpointUrl ?? this.runtimeUrl)\n : this.runtimeUrl,\n transport: single ? \"single\" : \"rest\",\n agentId: routedId,\n headers: { ...this.headers },\n credentials: this.credentials,\n fetch: this.fetch as typeof fetch,\n });\n }\n\n private syncDelegate(delegate: AbstractAgent): void {\n // Delegate is the IntelligenceAgent that talks to the runtime — it must\n // use the routed id so that requests reach the right runtime agent.\n delegate.agentId = this.routedAgentId();\n delegate.description = this.description;\n delegate.threadId = this.threadId;\n delegate.debugLogger = this.debugLogger;\n delegate.setMessages(this.messages);\n delegate.setState(this.state);\n delegate.pendingInterrupts = structuredClone_(this.pendingInterrupts);\n\n if (hasHeaders(delegate)) {\n delegate.headers = { ...this.headers };\n }\n\n if (hasCredentials(delegate)) {\n delegate.credentials = this.credentials;\n }\n }\n}\n","const ABORT_MESSAGES: ReadonlySet<string> = new Set([\n \"Fetch is aborted\",\n \"signal is aborted without reason\",\n \"component unmounted\",\n]);\n\nexport function isAbortError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (name === \"AbortError\") {\n return true;\n }\n return typeof message === \"string\" && ABORT_MESSAGES.has(message);\n}\n","export const RUNTIME_REQUEST_WATCHDOG_MS = 10_000;\n\nexport interface RuntimeRequestMeta {\n nonCritical?: boolean;\n selfBounded?: boolean;\n timedOut?: boolean;\n}\n\nexport interface RuntimeRequestInit extends RequestInit {\n ɵruntimeRequest?: RuntimeRequestMeta;\n}\n\nexport function runtimeRequestMeta(\n init?: RequestInit,\n): RuntimeRequestMeta | undefined {\n return (init as RuntimeRequestInit | undefined)?.ɵruntimeRequest;\n}\n","interface SingleRouteResourceRequest {\n input: RequestInfo | URL;\n init: RequestInit;\n}\n\n/** Returns true when a path belongs to an Intelligence resource API. */\nfunction isIntelligenceResourcePath(path: string): boolean {\n return (\n path === \"/threads\" ||\n path.startsWith(\"/threads/\") ||\n path === \"/memories\" ||\n path.startsWith(\"/memories/\") ||\n path === \"/annotate\"\n );\n}\n\n/** Reads a JSON resource body without changing invalid JSON error behavior. */\nasync function readResourceBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n headers: Headers,\n method: string,\n): Promise<unknown | undefined> {\n if (method === \"GET\" || method === \"HEAD\") return undefined;\n\n let text: string | undefined;\n if (init?.body != null) {\n text = await new Response(init.body).text();\n } else if (input instanceof Request) {\n text = await input.clone().text();\n }\n if (!text) return undefined;\n\n if (headers.get(\"content-type\")?.toLowerCase().includes(\"application/json\")) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n }\n return text;\n}\n\n/**\n * Converts one Runtime resource fetch into a single-route JSON envelope.\n * Requests outside the mounted Runtime or outside its resource APIs pass\n * through unchanged.\n */\nexport async function createSingleRouteResourceRequest(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n runtimeUrl: string,\n): Promise<SingleRouteResourceRequest | null> {\n const baseUrl =\n typeof window !== \"undefined\" && window.location?.href\n ? window.location.href\n : \"http://localhost\";\n const runtime = new URL(runtimeUrl, baseUrl);\n const inputUrl =\n input instanceof Request\n ? input.url\n : input instanceof URL\n ? input.href\n : input;\n const target = new URL(inputUrl, baseUrl);\n const runtimePath = runtime.pathname.replace(/\\/$/, \"\");\n if (target.origin !== runtime.origin) return null;\n if (!target.pathname.startsWith(`${runtimePath}/`)) return null;\n\n const resourcePath = target.pathname.slice(runtimePath.length);\n if (!isIntelligenceResourcePath(resourcePath)) return null;\n\n const method = (\n init?.method ?? (input instanceof Request ? input.method : \"GET\")\n ).toUpperCase();\n const headers = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n );\n const body = await readResourceBody(input, init, headers, method);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const requestDefaults: RequestInit =\n input instanceof Request\n ? {\n cache: input.cache,\n credentials: input.credentials,\n integrity: input.integrity,\n keepalive: input.keepalive,\n mode: input.mode,\n redirect: input.redirect,\n referrer: input.referrer,\n referrerPolicy: input.referrerPolicy,\n signal: input.signal,\n }\n : {};\n\n return {\n input: runtimeUrl,\n init: {\n ...requestDefaults,\n ...init,\n method: \"POST\",\n headers,\n body: JSON.stringify({\n method: \"resource/request\",\n params: {\n path: `${resourcePath}${target.search}`,\n httpMethod: method,\n },\n ...(body === undefined ? {} : { body }),\n }),\n },\n };\n}\n","export type HeaderRecordInput = Record<string, string | null | undefined>;\n\n/**\n * What `headers` accepts: a record, a sync builder, or an async builder. A\n * builder runs once per request, when the request is sent. See #1937.\n */\nexport type CopilotKitHeadersSource =\n | HeaderRecordInput\n | (() => HeaderRecordInput)\n | (() => Promise<HeaderRecordInput>);\n\nexport class CopilotKitHeaderResolutionError extends Error {\n override readonly name = \"CopilotKitHeaderResolutionError\";\n constructor(cause: unknown) {\n // Fixed message on purpose: never echo header values.\n super(\"[CopilotKit] Failed to resolve request headers\", { cause });\n }\n}\n\nexport function isHeaderResolutionError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 5 && current; depth++) {\n if (current instanceof CopilotKitHeaderResolutionError) return true;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\nexport function isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Normalize a header map to a `Record<string, string>` with no `null` or\n * `undefined` values. Dropping an entry is how a header is cleared.\n */\nexport function normalizeHeaders(\n headers: HeaderRecordInput,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(headers).filter(\n (entry): entry is [string, string] => entry[1] != null,\n ),\n );\n}\n\n/** Same keys, same values (order-independent). */\nfunction shallowEqualRecord(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((key) => a[key] === b[key]);\n}\n\nfunction isHeaderRecordInput(value: unknown): value is HeaderRecordInput {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Owns the headers source for one core. Resolution is synchronous for a\n * record or a sync builder, so those callers never pay an extra await.\n */\nexport class HeaderSourceResolver {\n private source: CopilotKitHeadersSource = {};\n private sourceGeneration = 0;\n private snapshot: Record<string, string> = {};\n private inFlight?: {\n generation: number;\n promise: Promise<Record<string, string>>;\n };\n\n constructor(\n private readonly onFailure: (\n error: CopilotKitHeaderResolutionError,\n ) => void,\n ) {}\n\n /** The last resolved headers. Not necessarily current for a builder. */\n get headers(): Record<string, string> {\n return this.snapshot;\n }\n\n /** Bumped on every accepted `setSource`, never by a new token. */\n get generation(): number {\n return this.sourceGeneration;\n }\n\n /**\n * Returns false when a builder with the same identity is set again, or\n * when a record replaces another record with equal normalized values (a\n * caller re-passing an equivalent literal on every re-render must not\n * bump the generation). A record replacing a builder, a builder replacing\n * a record, and a new builder function all still count as a change.\n */\n setSource(source: CopilotKitHeadersSource): boolean {\n if (typeof source === \"function\" && source === this.source) return false;\n const nextSnapshot =\n typeof source === \"function\" ? {} : normalizeHeaders(source);\n if (\n typeof source !== \"function\" &&\n typeof this.source !== \"function\" &&\n shallowEqualRecord(nextSnapshot, this.snapshot)\n ) {\n return false;\n }\n this.source = source;\n this.sourceGeneration += 1;\n this.inFlight = undefined;\n // A builder hasn't run yet, so the previous source's snapshot must not\n // survive the switch — otherwise a stale value (e.g. the old user's\n // Authorization) would be re-applied to agents and broadcast as current.\n this.snapshot = nextSnapshot;\n return true;\n }\n\n resolve(): Record<string, string> | Promise<Record<string, string>> {\n const source = this.source;\n if (typeof source !== \"function\") return this.snapshot;\n const generation = this.sourceGeneration;\n if (this.inFlight?.generation === generation) return this.inFlight.promise;\n\n let value: HeaderRecordInput | Promise<HeaderRecordInput>;\n try {\n value = source();\n } catch (error) {\n throw this.fail(error);\n }\n if (!isPromiseLike(value)) return this.accept(value, generation);\n\n const promise: Promise<Record<string, string>> = Promise.resolve(value)\n .then(\n (resolved) => this.accept(resolved, generation),\n (error: unknown) => {\n throw this.fail(error);\n },\n )\n .finally(() => {\n if (this.inFlight?.promise === promise) this.inFlight = undefined;\n });\n this.inFlight = { generation, promise };\n return promise;\n }\n\n private accept(value: unknown, generation: number): Record<string, string> {\n if (!isHeaderRecordInput(value)) {\n throw this.fail(\n new TypeError(\"headers builder must return an object of header values\"),\n );\n }\n const normalized = normalizeHeaders(value);\n if (generation === this.sourceGeneration) {\n // Keep the previous snapshot's identity when nothing actually changed,\n // so `core.headers` (and anything keyed on it, e.g. a React dep array)\n // only sees a new reference when a header value really changed.\n if (!shallowEqualRecord(normalized, this.snapshot)) {\n this.snapshot = normalized;\n }\n return this.snapshot;\n }\n return normalized;\n }\n\n private fail(cause: unknown): CopilotKitHeaderResolutionError {\n if (cause instanceof CopilotKitHeaderResolutionError) return cause;\n const error = new CopilotKitHeaderResolutionError(cause);\n this.onFailure(error);\n return error;\n }\n}\n\nconst PROTOCOL_HEADERS = new Set([\"content-type\", \"accept\"]);\n\n/**\n * Put fresh core headers on top of a request's headers, keeping the input's\n * shape. Core beats an agent's own headers (#5635). A site's Content-Type and\n * Accept are never overridden, matching every site's existing spread order.\n */\nexport function ɵoverlayCoreHeaders(\n existing: HeadersInit | undefined,\n core: Record<string, string>,\n): HeadersInit {\n if (existing instanceof Headers) {\n const headers = new Headers(existing);\n for (const [key, value] of Object.entries(core)) {\n if (PROTOCOL_HEADERS.has(key.toLowerCase()) && headers.has(key)) continue;\n headers.set(key, value);\n }\n return headers;\n }\n const base: Record<string, string> = Array.isArray(existing)\n ? Object.fromEntries(existing)\n : { ...existing };\n const keyByLower = new Map(\n Object.keys(base).map((k) => [k.toLowerCase(), k]),\n );\n for (const [key, value] of Object.entries(core)) {\n const existingKey = keyByLower.get(key.toLowerCase());\n if (existingKey !== undefined) {\n if (PROTOCOL_HEADERS.has(key.toLowerCase())) continue;\n delete base[existingKey];\n }\n base[key] = value;\n }\n return base;\n}\n\n/** Reject with the signal's AbortError if it aborts before `value` settles. */\nexport async function abortable<T>(\n value: T | Promise<T>,\n signal: AbortSignal | null | undefined,\n): Promise<T> {\n if (!signal || !isPromiseLike(value)) return value;\n if (signal.aborted) throw abortError(signal);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n Promise.resolve(value).then(\n (v) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(e);\n },\n );\n });\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\n/**\n * Add default headers (e.g. the public API key) to a source, only where the\n * source left the key unset or empty. The single shared replacement for the\n * React, Vue and Angular providers' own merges.\n */\nexport function ɵwithHeaderDefaults(\n source: CopilotKitHeadersSource,\n defaults: Record<string, string>,\n): CopilotKitHeadersSource {\n if (Object.keys(defaults).length === 0) return source;\n const fill = (headers: HeaderRecordInput): HeaderRecordInput => {\n const out: HeaderRecordInput = { ...headers };\n for (const [key, value] of Object.entries(defaults)) {\n if (!out[key]) out[key] = value;\n }\n return out;\n };\n if (typeof source !== \"function\") return fill(source);\n // The wrapper's return type tracks its argument (sync stays sync, async\n // stays async), but that dependency isn't expressible in\n // `CopilotKitHeadersSource`'s shape, so the cast below stands in for it.\n return (() => {\n const value = source();\n return isPromiseLike(value)\n ? Promise.resolve(value).then((resolved) =>\n isHeaderRecordInput(resolved) ? fill(resolved) : resolved,\n )\n : isHeaderRecordInput(value)\n ? fill(value)\n : value;\n }) as CopilotKitHeadersSource;\n}\n","import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { HttpAgent } from \"@ag-ui/client\";\nimport { ɵisHttpAgent } from \"../utils/http-agent\";\nimport type {\n RuntimeInfo,\n RuntimeMode,\n RuntimeLicenseStatus,\n RuntimeEntitlementResponse,\n IntelligenceRuntimeInfo,\n InspectorMetadataV1,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport {\n logger,\n parseInspectorMetadataV1,\n RUNTIME_MODE_SSE,\n resolveDebugConfig,\n} from \"@copilotkit/shared\";\nimport { ProxiedCopilotRuntimeAgent } from \"../agent\";\nimport type { CopilotKitCore, CopilotKitCoreFriendsAccess } from \"./core\";\nimport {\n CopilotKitCoreErrorCode,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"./core\";\nimport type { CopilotRuntimeTransport } from \"../types\";\nimport {\n isRuntimeInfoRequestError,\n runtimeInfoError,\n} from \"../utils/runtime-info-error\";\nimport { isAbortError } from \"../utils/abort-error\";\nimport type { RuntimeRequestMeta } from \"../utils/runtime-request\";\nimport {\n RUNTIME_REQUEST_WATCHDOG_MS,\n runtimeRequestMeta,\n} from \"../utils/runtime-request\";\nimport { createSingleRouteResourceRequest } from \"../utils/single-route-resource-request\";\nimport {\n abortable,\n isHeaderResolutionError,\n isPromiseLike,\n ɵoverlayCoreHeaders,\n} from \"./header-source\";\n\ntype ResolvedCopilotRuntimeTransport = Exclude<CopilotRuntimeTransport, \"auto\">;\n\ntype RuntimeInfoFetchResult = {\n runtimeInfo: RuntimeInfo;\n resolvedTransport: ResolvedCopilotRuntimeTransport;\n};\n\n/** Maximum wait for optional Inspector metadata before degrading to absence. */\nconst INSPECTOR_METADATA_REQUEST_TIMEOUT_MS = 5_000;\n\nexport const ɵRUNTIME_PROBE_TIMEOUT_MS = 5_000;\n\ntype RuntimeRequestOutcome = \"ok\" | \"failed\" | \"aborted\" | \"ignored\";\n\nfunction classifyRuntimeRequestFailure(\n error: unknown,\n meta: RuntimeRequestMeta | undefined,\n): RuntimeRequestOutcome {\n if (meta?.nonCritical) {\n return \"ignored\";\n }\n if (isAbortError(error) && !meta?.timedOut) {\n return \"aborted\";\n }\n return \"failed\";\n}\n\ninterface RuntimeConnectionOptions {\n preserveOnFailure?: boolean;\n recovery?: boolean;\n}\n\n/** Build case-insensitive JSON headers without mutating the Core snapshot. */\nfunction withJsonContentType(headers: Record<string, string>): Headers {\n const requestHeaders = new Headers(headers);\n if (!requestHeaders.has(\"content-type\")) {\n requestHeaders.set(\"content-type\", \"application/json\");\n }\n return requestHeaders;\n}\n\nconst RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5_000;\n\ninterface RuntimeConnectionAttempt {\n key: string;\n generation: number;\n}\n\ninterface RuntimeAgentConnection {\n runtimeUrl: string;\n /** The caller-supplied URL the proxy was built with (trailing slash intact). */\n endpointUrl?: string;\n transport: CopilotRuntimeTransport;\n}\n\nexport interface CopilotKitCoreAddAgentParams {\n id: string;\n agent: AbstractAgent;\n}\n\n/**\n * Parameters for registering a proxied agent against an existing runtime agent.\n */\nexport interface CopilotKitCoreRegisterProxiedAgentParams {\n /**\n * The local registry id under which the proxy is registered. Used by\n * `useAgent`, state-manager subscriptions, and all subscriber bookkeeping.\n * Must not collide with any existing local or runtime-discovered agent id.\n */\n agentId: string;\n /**\n * The id of the runtime agent that this proxy routes outbound HTTP requests\n * to. Invisible to subscribers — only affects URL paths and single-route\n * envelopes.\n */\n runtimeAgentId: string;\n}\n\nexport interface CopilotKitCoreRegisterProxiedAgentResult {\n agent: ProxiedCopilotRuntimeAgent;\n unregister: () => void;\n}\n\n/**\n * Manages agent registration, lifecycle, and runtime connectivity for CopilotKitCore.\n * Handles both local development agents and remote runtime agents.\n */\nexport class AgentRegistry {\n private _agents: Record<string, AbstractAgent> = {};\n private localAgents: Record<string, AbstractAgent> = {};\n private remoteAgents: Record<string, AbstractAgent> = {};\n\n private readonly mintedThreadIds = new WeakMap<AbstractAgent, string>();\n\n private _runtimeUrl?: string;\n /** The runtime URL as the caller supplied it; the single-route endpoint uses it verbatim. */\n private _runtimeEndpointUrl?: string;\n // Tracks an in-flight `/info` connection so concurrent calls targeting the\n // same runtime (url + requested transport) collapse to a single request\n // instead of each firing their own. See #5801.\n private _connectionInFlight?: {\n attempt: RuntimeConnectionAttempt;\n promise: Promise<void>;\n };\n private _runtimeConnectionGeneration = 0;\n private _activeRuntimeConnectionAttempt?: RuntimeConnectionAttempt;\n private _runtimeEntitlementRetryTimer?: ReturnType<typeof setTimeout>;\n private _runtimeEntitlementRetryAttemptedKey?: string;\n private _runtimeEntitlementRetryPendingKey?: string;\n private _runtimeVersion?: string;\n private _runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n private _runtimeTransport: CopilotRuntimeTransport = \"auto\";\n // The transport MODE last requested via `setRuntimeTransport` (e.g. \"auto\").\n // Distinct from `_runtimeTransport`, which auto-detect overwrites with the\n // RESOLVED value (\"rest\"/\"single\"). The idempotency guard compares against\n // this so re-applying the same mode (the provider effect re-applies \"auto\"\n // on every render) is a no-op instead of re-running the /info handshake.\n private _requestedTransport: CopilotRuntimeTransport = \"auto\";\n private _audioFileTranscriptionEnabled: boolean = false;\n private _runtimeMode: RuntimeMode = RUNTIME_MODE_SSE;\n private _intelligence?: IntelligenceRuntimeInfo;\n private _threadEndpoints?: ThreadEndpointRuntimeInfo;\n private _singleRouteResourceOperations = false;\n private _suggestions?: boolean;\n private _inspectorLearning: boolean = false;\n private _inspectorMetadata?: InspectorMetadataV1;\n private _inspectorMetadataSupported: boolean = false;\n private inspectorMetadataRefreshReady: boolean = false;\n private inspectorMetadataConnectionGeneration: number = 0;\n private inspectorMetadataGeneration: number = 0;\n private inspectorMetadataHeadersGeneration: number = 0;\n private inspectorMetadataCredentialsGeneration: number = 0;\n private inspectorMetadataAbortController?: AbortController;\n private inspectorMetadataNotificationQueue: Promise<void> = Promise.resolve();\n private _a2uiEnabled: boolean = false;\n private _a2uiAgents?: string[];\n private _openGenerativeUIEnabled: boolean = false;\n private _licenseStatus?: RuntimeLicenseStatus;\n private _runtimeEntitlements?: RuntimeEntitlementResponse;\n private _telemetryDisabled: boolean = false;\n private remoteAgentConnections = new WeakMap<\n ProxiedCopilotRuntimeAgent,\n RuntimeAgentConnection\n >();\n\n private runtimeFetch?: typeof fetch;\n private runtimeProbeInFlight: boolean = false;\n private runtimeProbeToken: number = 0;\n private runtimeProbeAbortController?: AbortController;\n private runtimeRecoveryRunning: boolean = false;\n private runtimeRecoveryPending: boolean = false;\n private runtimeHealthGeneration: number = 0;\n\n /**\n * The headers each HttpAgent was constructed with, captured on the first\n * `applyHeadersToAgent` call for that agent (which, for agents the registry\n * owns, happens at registration before any core headers are applied). Core\n * headers are merged ON TOP of this baseline so that headers configured\n * directly on an agent (e.g. an `Authorization` for a self-hosted backend)\n * survive registration instead of being silently replaced. The baseline is\n * captured once and never re-captured, so a later direct mutation of\n * `agent.headers` is not folded into it. See #5635.\n */\n private agentOwnHeaders = new WeakMap<HttpAgent, Record<string, string>>();\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Get all agents as a readonly record\n */\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this._agents;\n }\n\n get runtimeUrl(): string | undefined {\n return this._runtimeUrl;\n }\n\n get runtimeVersion(): string | undefined {\n return this._runtimeVersion;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this._runtimeConnectionStatus;\n }\n\n get runtimeTransport(): CopilotRuntimeTransport {\n return this._runtimeTransport;\n }\n\n get audioFileTranscriptionEnabled(): boolean {\n return this._audioFileTranscriptionEnabled;\n }\n\n get runtimeMode(): RuntimeMode {\n return this._runtimeMode;\n }\n\n get intelligence(): IntelligenceRuntimeInfo | undefined {\n return this._intelligence;\n }\n\n get threadEndpoints(): ThreadEndpointRuntimeInfo | undefined {\n return this._threadEndpoints;\n }\n\n get suggestions(): boolean | undefined {\n return this._suggestions;\n }\n\n get inspectorLearning(): boolean {\n return this._inspectorLearning;\n }\n\n get inspectorMetadata(): InspectorMetadataV1 | undefined {\n return this._inspectorMetadata;\n }\n\n get a2uiEnabled(): boolean {\n return this._a2uiEnabled;\n }\n\n /**\n * Agent ids the runtime applies A2UI to (#5369). `undefined` means A2UI\n * applies to every agent — or is disabled entirely; check `a2uiEnabled`.\n */\n get a2uiAgents(): string[] | undefined {\n return this._a2uiAgents;\n }\n\n get openGenerativeUIEnabled(): boolean {\n return this._openGenerativeUIEnabled;\n }\n\n get licenseStatus(): RuntimeLicenseStatus | undefined {\n return this._licenseStatus;\n }\n\n /** Structured Runtime entitlement authority advertised by `/info`. */\n get runtimeEntitlements(): RuntimeEntitlementResponse | undefined {\n return this._runtimeEntitlements;\n }\n\n get runtimeEntitlementRetryPending(): boolean {\n return (\n this._runtimeEntitlementRetryPendingKey === this.runtimeConnectionKey()\n );\n }\n\n get telemetryDisabled(): boolean {\n return this._telemetryDisabled;\n }\n\n /**\n * Initialize agents from configuration\n */\n initialize(agents: Record<string, AbstractAgent>): void {\n this.localAgents = this.assignAgentIds(agents);\n this.applyHeadersToAgents(this.localAgents);\n this.applyCredentialsToAgents(this.localAgents);\n this.applyMessageFilterToAgents(this.localAgents);\n this.applyRuntimeFetchToAgents(this.localAgents);\n this._agents = this.localAgents;\n }\n\n /**\n * Set the runtime URL and update connection\n */\n setRuntimeUrl(\n runtimeUrl: string | undefined,\n options?: { deferConnection?: boolean },\n ): void {\n const normalizedRuntimeUrl = runtimeUrl\n ? runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n const runtimeEndpointUrl = runtimeUrl || undefined;\n\n if (\n this._runtimeUrl === normalizedRuntimeUrl &&\n this._runtimeEndpointUrl === runtimeEndpointUrl\n ) {\n return;\n }\n\n this.invalidateInspectorMetadataConnection();\n this.abandonRuntimeHealthProbe();\n this.resetRuntimeEntitlementRetry();\n // Runtime authority is scoped to the target that advertised it. Clear it\n // before subscribers observe the replacement target connecting.\n this._licenseStatus = undefined;\n this._runtimeEntitlements = undefined;\n this._singleRouteResourceOperations = false;\n this._runtimeUrl = normalizedRuntimeUrl;\n this._runtimeEndpointUrl = runtimeEndpointUrl;\n\n // Deferred construction (see CopilotKitCore.connect / #5801): record the URL\n // so getters/hooks see it synchronously, but do NOT start the `/info` fetch\n // here. The host starts it from a commit-phase effect via `connect()`, so\n // renders discarded before commit never issue a request.\n if (options?.deferConnection) {\n return;\n }\n\n void this.updateRuntimeConnection({\n preserveOnFailure: this.hasLiveRuntimeKnowledgeToProtect(),\n });\n }\n\n /**\n * Start the initial runtime connection if it has not been started yet.\n *\n * Backs {@link CopilotKitCore.connect}. Idempotent: it only kicks off a fetch\n * when a `runtimeUrl` is set and the connection is still `Disconnected` (its\n * state before any connect attempt). `updateRuntimeConnection` flips the\n * status to `Connecting` synchronously, so a second call — e.g. React\n * StrictMode double-invoking the mount effect — bails here. A genuine config\n * change still reconnects through `setRuntimeUrl`/`setRuntimeTransport`. See\n * #5801.\n */\n connectRuntime(): void {\n if (typeof window === \"undefined\") {\n return;\n }\n if (!this._runtimeUrl) {\n return;\n }\n if (\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Disconnected\n ) {\n return;\n }\n void this.updateRuntimeConnection();\n }\n\n setRuntimeTransport(runtimeTransport: CopilotRuntimeTransport): void {\n // Guard on the requested MODE, not the resolved value: after auto-detect\n // writes `_runtimeTransport = \"rest\"`, re-applying the same requested\n // \"auto\" must not be treated as a change (otherwise every provider\n // re-render re-runs the /info handshake and rebuilds agents).\n if (this._requestedTransport === runtimeTransport) {\n return;\n }\n\n this.invalidateInspectorMetadataConnection();\n this.abandonRuntimeHealthProbe();\n this.resetRuntimeEntitlementRetry();\n this._requestedTransport = runtimeTransport;\n this._runtimeTransport = runtimeTransport;\n this._singleRouteResourceOperations = false;\n void this.updateRuntimeConnection({\n preserveOnFailure: this.hasLiveRuntimeKnowledgeToProtect(),\n });\n }\n\n private hasLiveRuntimeKnowledgeToProtect(): boolean {\n if (Object.keys(this.remoteAgents).length === 0) {\n return false;\n }\n return (\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n );\n }\n\n private reconcileRecoveredAgents(\n reported: Record<string, AbstractAgent>,\n ): Record<string, AbstractAgent> {\n const merged = { ...this.remoteAgents, ...reported };\n if (Object.keys(reported).length === 0) {\n return merged;\n }\n for (const [id, agent] of Object.entries(merged)) {\n if (Object.prototype.hasOwnProperty.call(reported, id)) {\n continue;\n }\n if (this.carriesConversationState(agent)) {\n continue;\n }\n delete merged[id];\n }\n return merged;\n }\n\n private carriesConversationState(agent: AbstractAgent): boolean {\n if (agent.messages.length > 0) {\n return true;\n }\n const mintedThreadId = this.mintedThreadIds.get(agent);\n return mintedThreadId === undefined || agent.threadId !== mintedThreadId;\n }\n\n private abandonRuntimeHealthProbe(): void {\n this.runtimeProbeToken += 1;\n this.runtimeProbeInFlight = false;\n this.runtimeHealthGeneration += 1;\n this.runtimeProbeAbortController?.abort();\n this.runtimeProbeAbortController = undefined;\n }\n\n /**\n * Set all agents at once (for development use)\n */\n setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void {\n // Validate all agents before making any changes\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent) {\n this.validateAndAssignAgentId(id, agent);\n }\n });\n this.localAgents = agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this.applyHeadersToAgents(this._agents);\n this.applyCredentialsToAgents(this._agents);\n this.applyMessageFilterToAgents(this._agents);\n this.applyRuntimeFetchToAgents(this._agents);\n void this.notifyAgentsChanged();\n }\n\n /**\n * Add a single agent (for development use)\n */\n addAgent__unsafe_dev_only({ id, agent }: CopilotKitCoreAddAgentParams): void {\n this.validateAndAssignAgentId(id, agent);\n this.localAgents[id] = agent;\n this.applyHeadersToAgent(agent);\n this.applyCredentialsToAgent(agent);\n this.applyRuntimeFetchToAgent(agent);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n }\n\n /**\n * Remove an agent by ID (for development use)\n */\n removeAgent__unsafe_dev_only(id: string): void {\n delete this.localAgents[id];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n }\n\n /**\n * Register a proxied agent that routes outbound runtime requests to an\n * existing runtime agent (`runtimeAgentId`) while exposing a distinct local\n * registry id (`agentId`). Throws if `agentId` is already taken by either a\n * local or runtime-discovered agent.\n *\n * Use this to mount multiple frontend agents against a single runtime\n * agent (e.g. a chat-1 / chat-2 pair both proxying to \"default\") without\n * implicit per-thread cloning. The returned `unregister` removes the proxy\n * from the registry and emits `onAgentsChanged`.\n */\n registerProxiedAgent({\n agentId,\n runtimeAgentId,\n }: CopilotKitCoreRegisterProxiedAgentParams): CopilotKitCoreRegisterProxiedAgentResult {\n // Use hasOwnProperty rather than `in`: `in` walks the prototype chain,\n // so an agentId of \"__proto__\", \"constructor\", \"toString\" etc. would\n // falsely test as already-registered.\n if (Object.prototype.hasOwnProperty.call(this._agents, agentId)) {\n throw new Error(\n `CopilotKitCore.registerProxiedAgent: agentId \"${agentId}\" is already registered. ` +\n `Pick a different agentId, or unregister the existing agent first.`,\n );\n }\n\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const debug = friends.debug;\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this._runtimeEndpointUrl ?? this._runtimeUrl,\n agentId,\n runtimeAgentId,\n transport: this._runtimeTransport,\n credentials: friends.credentials,\n // If runtime info has already synced, mirror its mode/intelligence so\n // the proxy doesn't have to re-resolve. Otherwise stay \"pending\" until\n // /info lands.\n runtimeMode: this._runtimeUrl\n ? this._runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ? this._runtimeMode\n : \"pending\"\n : RUNTIME_MODE_SSE,\n intelligence: this._intelligence,\n debug: debug ? resolveDebugConfig(debug) : undefined,\n messageFilter: friends.messageFilter,\n });\n this.applyHeadersToAgent(agent);\n this.applyRuntimeFetchToAgent(agent);\n\n this.localAgents[agentId] = agent;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n\n return {\n agent,\n unregister: () => {\n // Only unregister if the same instance is still in place — guards\n // against double-unregister or against unregistering after a\n // subsequent register replaced the slot.\n if (this.localAgents[agentId] === agent) {\n delete this.localAgents[agentId];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n }\n },\n };\n }\n\n /**\n * Get an agent by ID\n */\n getAgent(id: string): AbstractAgent | undefined {\n if (id in this._agents) {\n return this._agents[id] as AbstractAgent;\n }\n\n // Silently return undefined if we're still loading runtime agents\n if (\n this.runtimeUrl !== undefined &&\n (this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n return undefined;\n }\n\n console.warn(`Agent ${id} not found`);\n return undefined;\n }\n\n /**\n * Shared core-and-own-header merge for a single agent. Captures the\n * agent's construction-time headers once (the per-agent baseline in\n * `agentOwnHeaders`), then either keeps only that baseline — a\n * `ProxiedCopilotRuntimeAgent`, whose core headers are added by\n * `ɵruntimeFetch` when each request is actually sent instead, so a key the\n * builder stops returning can never ride along from a stale copy baked\n * onto the agent (see #1937) — or merges `coreHeaders` on top of it (any\n * other `HttpAgent`; core wins on a key conflict, see #5635).\n */\n private applyHeaderRecordToAgent(\n agent: HttpAgent,\n coreHeaders: Record<string, string>,\n ): void {\n // On every apply we rebuild from this baseline so re-applying core\n // headers (e.g. via setHeaders) never loses the agent's own headers.\n if (!this.agentOwnHeaders.has(agent)) {\n this.agentOwnHeaders.set(agent, { ...agent.headers });\n }\n const own = this.agentOwnHeaders.get(agent)!;\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.headers = { ...own };\n this.applyRuntimeFetchToAgent(agent);\n return;\n }\n agent.headers = { ...own, ...coreHeaders };\n }\n\n /**\n * Apply the last resolved header snapshot to an agent, merged ON TOP of\n * the agent's own construction-time headers. Non-`HttpAgent` agents are\n * left untouched because only `HttpAgent` carries a `headers` field. See\n * #5635.\n *\n * Never invokes the headers builder — safe to call from anywhere (dev-only\n * registration helpers, a React effect that re-runs on every render)\n * without risking a synchronous throw or an unhandled async rejection from\n * a user-supplied builder. Use `prepareAgentHeadersForRun` (friends-only)\n * on the run/connect path, where a builder failure can be awaited and\n * reported once.\n */\n applyHeadersToAgent(agent: AbstractAgent): void {\n if (!ɵisHttpAgent(agent)) return;\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n this.applyHeaderRecordToAgent(agent, friends.headers);\n }\n\n /**\n * Apply the last resolved header snapshot to every agent, without\n * triggering a builder call per agent. Used by `initialize` and\n * `setHeaders`; a run re-applies with fresh headers anyway (see\n * `prepareAgentHeadersForRun`).\n */\n applyHeadersToAgents(agents: Record<string, AbstractAgent>): void {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n Object.values(agents).forEach((agent) => {\n if (ɵisHttpAgent(agent)) {\n this.applyHeaderRecordToAgent(agent, friends.headers);\n }\n });\n }\n\n /**\n * Resolve headers fresh and apply them to `agent` right before a run or\n * connect actually sends (#1937) — the resolving counterpart to\n * `applyHeadersToAgent`. Friends-only: only the run handler should call\n * this, since resolving can invoke a user-supplied builder that throws\n * synchronously or returns a rejecting promise. Resolution is synchronous\n * for a record or a sync builder; this returns a promise only when an\n * async builder must be awaited first, and callers that need the write to\n * have landed before continuing must await a returned promise.\n *\n * A `ProxiedCopilotRuntimeAgent` never invokes the builder here: its core\n * headers are added by `ɵruntimeFetch` at send time instead, so only its\n * own headers are (re)applied.\n */\n prepareAgentHeadersForRun(agent: AbstractAgent): void | Promise<void> {\n if (!ɵisHttpAgent(agent)) return;\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n this.applyHeaderRecordToAgent(agent, {});\n return;\n }\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const resolved = friends.resolveHeaders();\n if (isPromiseLike(resolved)) {\n return Promise.resolve(resolved).then((headers) => {\n this.applyHeaderRecordToAgent(agent, headers);\n });\n }\n this.applyHeaderRecordToAgent(agent, resolved);\n }\n\n /**\n * Apply current credentials to an agent\n */\n applyCredentialsToAgent(agent: AbstractAgent): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.credentials = (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).credentials;\n }\n }\n\n /**\n * Apply current credentials to all agents\n */\n applyCredentialsToAgents(agents: Record<string, AbstractAgent>): void {\n Object.values(agents).forEach((agent) => {\n this.applyCredentialsToAgent(agent);\n });\n }\n\n /**\n * Carry the mode a fresh `/info` reported onto a proxy this re-sync kept.\n *\n * `canReuseRuntimeAgent` deliberately ignores the mode: a preserved proxy is\n * backing an open conversation, and replacing the instance to change one\n * field would drop it. The mode is therefore pushed onto the survivor here,\n * the same way headers and credentials are. Without it the mode was fixed at\n * construction, so a runtime that flipped `intelligence` → `sse` under an\n * open page left every later run on the delegate path. See #7130.\n */\n applyRuntimeModeToAgent(\n agent: AbstractAgent,\n runtimeInfo: RuntimeInfo,\n ): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.adoptRuntimeMode(\n runtimeInfo.mode ?? RUNTIME_MODE_SSE,\n runtimeInfo.intelligence,\n );\n }\n }\n\n /**\n * Apply the core's message filter to an agent.\n *\n * The test is the class, not which bucket the agent is registered in: every\n * `ProxiedCopilotRuntimeAgent` gets the core filter, whether it came from\n * `/info` or from `registerProxiedAgent` (which files its proxy under\n * `localAgents`). Agents of any other class are left untouched — an\n * `AbstractAgent` the app built has no such hook, and its owner already has\n * the AG-UI middleware seam.\n *\n * This is the sole writer of `agent.messageFilter` in normal operation. The\n * public setter exists for the registry and for tests; a value written\n * directly onto an agent is replaced the next time the registry sweeps, the\n * same way per-agent credentials are.\n */\n applyMessageFilterToAgent(agent: AbstractAgent): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.messageFilter = (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).messageFilter;\n }\n }\n\n /**\n * Apply the core's message filter to all agents\n */\n applyMessageFilterToAgents(agents: Record<string, AbstractAgent>): void {\n Object.values(agents).forEach((agent) => {\n this.applyMessageFilterToAgent(agent);\n });\n }\n\n /** Preserve the exact configured URL when posting to a single endpoint. */\n get runtimeEndpointUrl(): string | undefined {\n return this._runtimeEndpointUrl;\n }\n\n createRuntimeFetch(): typeof fetch {\n if (!this.runtimeFetch) {\n this.runtimeFetch = (async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const coreHeaders = await abortable(\n friends.resolveHeaders(),\n init?.signal,\n );\n const requestHeaders = ɵoverlayCoreHeaders(\n init?.headers ??\n (input instanceof Request ? input.headers : undefined),\n coreHeaders,\n );\n init = { ...init, headers: requestHeaders };\n const meta = () => runtimeRequestMeta(init);\n const watchdog = this.armRuntimeRequestWatchdog(meta());\n try {\n const singleRouteRequest =\n this._runtimeTransport === \"single\" &&\n this._singleRouteResourceOperations &&\n this._runtimeUrl\n ? await createSingleRouteResourceRequest(\n input,\n init,\n // The endpoint itself is the POST target here, so it has to be\n // the caller's URL verbatim - a trailing slash can select a\n // different proxy location. `_runtimeUrl` is the slash-stripped\n // form kept for path joins (issue #7028).\n this._runtimeEndpointUrl ?? this._runtimeUrl,\n )\n : null;\n const response = singleRouteRequest\n ? await fetch(singleRouteRequest.input, singleRouteRequest.init)\n : await fetch(input, init);\n watchdog.clear();\n this.handleRuntimeRequestOutcome(\n response.ok ? \"ok\" : meta()?.nonCritical ? \"ignored\" : \"failed\",\n watchdog.checked,\n );\n return response;\n } catch (error) {\n watchdog.clear();\n this.handleRuntimeRequestOutcome(\n classifyRuntimeRequestFailure(error, meta()),\n watchdog.checked,\n );\n throw error;\n }\n }) as typeof fetch;\n }\n return this.runtimeFetch;\n }\n\n private armRuntimeRequestWatchdog(meta: RuntimeRequestMeta | undefined): {\n clear: () => void;\n checked: () => boolean;\n } {\n if (\n typeof window === \"undefined\" ||\n meta?.nonCritical ||\n meta?.selfBounded\n ) {\n return { clear: () => {}, checked: () => false };\n }\n let checked = false;\n const timeoutId = setTimeout(() => {\n checked = this.handleRuntimeRequestOutcome(\"failed\");\n }, RUNTIME_REQUEST_WATCHDOG_MS);\n return {\n clear: () => clearTimeout(timeoutId),\n checked: () => checked,\n };\n }\n\n applyRuntimeFetchToAgent(agent: AbstractAgent): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.fetch = this.createRuntimeFetch();\n }\n }\n\n applyRuntimeFetchToAgents(agents: Record<string, AbstractAgent>): void {\n Object.values(agents).forEach((agent) => {\n this.applyRuntimeFetchToAgent(agent);\n });\n }\n\n /** Refresh metadata after the Core header snapshot changes. */\n handleHeadersChanged(): void {\n this.inspectorMetadataHeadersGeneration += 1;\n this.setInspectorMetadata(undefined);\n void this.refreshInspectorMetadata();\n }\n\n /** Refresh metadata after the Core credentials mode changes. */\n handleCredentialsChanged(): void {\n this.inspectorMetadataCredentialsGeneration += 1;\n this.setInspectorMetadata(undefined);\n void this.refreshInspectorMetadata();\n }\n\n /**\n * Fetch trusted inspector metadata independently from runtime discovery.\n * Optional-route failures degrade to absent metadata and never affect the\n * runtime connection state.\n */\n async refreshInspectorMetadata(): Promise<void> {\n const generation = ++this.inspectorMetadataGeneration;\n this.inspectorMetadataAbortController?.abort();\n this.inspectorMetadataAbortController = undefined;\n\n if (\n !this._inspectorMetadataSupported ||\n !this.inspectorMetadataRefreshReady ||\n !this.runtimeUrl ||\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n this.setInspectorMetadata(undefined);\n return;\n }\n\n const runtimeUrl = this.runtimeUrl;\n const requestedTransport = this._requestedTransport;\n const resolvedTransport = this._runtimeTransport;\n const headersGeneration = this.inspectorMetadataHeadersGeneration;\n const credentialsGeneration = this.inspectorMetadataCredentialsGeneration;\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n\n // Resolve before creating the AbortController: a builder failure here\n // must degrade to absent metadata (like any other optional-route\n // failure) without ever leaving a dangling, never-aborted controller.\n // Resolution is synchronous for a record or a sync builder — only await\n // when it's actually async (there's no AbortSignal yet to make this\n // abortable), so a sync source never pays an extra microtask tick here.\n let headers: Record<string, string>;\n try {\n const resolved = friends.resolveHeaders();\n headers = {\n ...(isPromiseLike(resolved) ? await resolved : resolved),\n };\n } catch {\n if (generation === this.inspectorMetadataGeneration) {\n this.setInspectorMetadata(undefined);\n }\n return;\n }\n // A concurrent refresh (e.g. from setHeaders/setCredentials) may have\n // superseded this call while the builder above was pending — without\n // this check, a slower earlier call would still send a request with\n // stale headers and could replace the newer call's AbortController.\n if (generation !== this.inspectorMetadataGeneration) {\n return;\n }\n const credentials = friends.credentials;\n const abortController = new AbortController();\n this.inspectorMetadataAbortController = abortController;\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let rejectForAbort: ((reason: Error) => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectForAbort = reject;\n });\n const handleAbort = () => {\n rejectForAbort?.(new Error(\"Inspector metadata request aborted\"));\n };\n abortController.signal.addEventListener(\"abort\", handleAbort, {\n once: true,\n });\n const timeout = new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(() => {\n timedOut = true;\n reject(new Error(\"Inspector metadata request timed out\"));\n abortController.abort();\n }, INSPECTOR_METADATA_REQUEST_TIMEOUT_MS);\n });\n\n let nextMetadata: InspectorMetadataV1 | undefined;\n try {\n const request = (async () => {\n const response =\n resolvedTransport === \"single\"\n ? await this.fetchInspectorMetadataSingle({\n runtimeUrl: this.singleEndpointUrlFor(runtimeUrl),\n headers,\n credentials,\n signal: abortController.signal,\n })\n : await this.fetchInspectorMetadataRest({\n runtimeUrl,\n headers,\n credentials,\n signal: abortController.signal,\n });\n\n if (response.status === 204 || !response.ok) {\n return undefined;\n }\n return parseInspectorMetadataV1(await response.json());\n })();\n nextMetadata = await Promise.race([request, aborted, timeout]);\n } catch {\n nextMetadata = undefined;\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n abortController.signal.removeEventListener(\"abort\", handleAbort);\n }\n\n if (\n !this.isInspectorMetadataRequestCurrent({\n generation,\n runtimeUrl,\n requestedTransport,\n resolvedTransport,\n headersGeneration,\n credentialsGeneration,\n signal: abortController.signal,\n allowAbortedSignal: timedOut,\n })\n ) {\n return;\n }\n\n this.inspectorMetadataAbortController = undefined;\n this.setInspectorMetadata(nextMetadata);\n }\n\n private async fetchInspectorMetadataRest({\n runtimeUrl,\n headers,\n credentials,\n signal,\n }: {\n runtimeUrl: string;\n headers: Record<string, string>;\n credentials: RequestCredentials | undefined;\n signal: AbortSignal;\n }): Promise<Response> {\n return fetch(`${runtimeUrl}/inspector-metadata`, {\n method: \"GET\",\n headers,\n ...(credentials ? { credentials } : {}),\n signal,\n });\n }\n\n private async fetchInspectorMetadataSingle({\n runtimeUrl,\n headers,\n credentials,\n signal,\n }: {\n runtimeUrl: string;\n headers: Record<string, string>;\n credentials: RequestCredentials | undefined;\n signal: AbortSignal;\n }): Promise<Response> {\n return fetch(runtimeUrl, {\n method: \"POST\",\n headers: withJsonContentType(headers),\n body: JSON.stringify({ method: \"inspector/metadata\" }),\n ...(credentials ? { credentials } : {}),\n signal,\n });\n }\n\n private isInspectorMetadataRequestCurrent({\n generation,\n runtimeUrl,\n requestedTransport,\n resolvedTransport,\n headersGeneration,\n credentialsGeneration,\n signal,\n allowAbortedSignal = false,\n }: {\n generation: number;\n runtimeUrl: string;\n requestedTransport: CopilotRuntimeTransport;\n resolvedTransport: CopilotRuntimeTransport;\n headersGeneration: number;\n credentialsGeneration: number;\n signal: AbortSignal;\n allowAbortedSignal?: boolean;\n }): boolean {\n return (\n (allowAbortedSignal || !signal.aborted) &&\n generation === this.inspectorMetadataGeneration &&\n runtimeUrl === this.runtimeUrl &&\n requestedTransport === this._requestedTransport &&\n resolvedTransport === this._runtimeTransport &&\n headersGeneration === this.inspectorMetadataHeadersGeneration &&\n credentialsGeneration === this.inspectorMetadataCredentialsGeneration &&\n this._inspectorMetadataSupported &&\n this.inspectorMetadataRefreshReady &&\n this._runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n );\n }\n\n private invalidateInspectorMetadataConnection(): void {\n this._inspectorMetadataSupported = false;\n this._inspectorLearning = false;\n this.inspectorMetadataRefreshReady = false;\n this.inspectorMetadataConnectionGeneration += 1;\n this.inspectorMetadataGeneration += 1;\n this.inspectorMetadataAbortController?.abort();\n this.inspectorMetadataAbortController = undefined;\n this.setInspectorMetadata(undefined);\n }\n\n /**\n * Publish one state transition without making refreshes wait on subscribers.\n * Each queued callback closes over its readonly snapshot so reentrant changes\n * cannot replace the value that an older publication is still delivering.\n */\n private setInspectorMetadata(\n inspectorMetadata: InspectorMetadataV1 | undefined,\n ): void {\n if (\n JSON.stringify(this._inspectorMetadata) ===\n JSON.stringify(inspectorMetadata)\n ) {\n return;\n }\n\n this._inspectorMetadata = inspectorMetadata;\n const snapshot = inspectorMetadata;\n this.inspectorMetadataNotificationQueue =\n this.inspectorMetadataNotificationQueue\n .then(() => this.notifyInspectorMetadataChanged(snapshot))\n .catch((error: unknown) => {\n console.error(\n \"Subscriber onInspectorMetadataChanged queue error:\",\n error,\n );\n });\n }\n\n private setRuntimeConnectionStatus(\n status: CopilotKitCoreRuntimeConnectionStatus,\n ): void {\n this._runtimeConnectionStatus = status;\n this.runtimeHealthGeneration += 1;\n }\n\n private handleRuntimeRequestOutcome(\n outcome: RuntimeRequestOutcome,\n alreadyChecked: () => boolean = () => false,\n ): boolean {\n if (outcome === \"aborted\" || outcome === \"ignored\") {\n return false;\n }\n if (outcome === \"failed\" && alreadyChecked()) {\n return false;\n }\n if (typeof window === \"undefined\") {\n return false;\n }\n if (!this._runtimeUrl) {\n return false;\n }\n\n if (outcome === \"ok\") {\n this.runtimeHealthGeneration += 1;\n if (this.runtimeRecoveryRunning) {\n this.runtimeRecoveryPending = true;\n }\n if (\n this._runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Error\n ) {\n void this.recoverRuntimeConnection();\n }\n return false;\n }\n\n if (\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n return false;\n }\n if (this.runtimeProbeInFlight) {\n return false;\n }\n void this.probeRuntimeReachability();\n return true;\n }\n\n private async fetchRuntimeInfoWithTimeout(\n abortController: AbortController,\n runtimeUrl = this.runtimeUrl,\n runtimeTransport = this._runtimeTransport,\n ): Promise<RuntimeInfoFetchResult> {\n if (!runtimeUrl) {\n throw new Error(\"Runtime URL is not set\");\n }\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const request = this.fetchRuntimeInfo(\n runtimeUrl,\n runtimeTransport,\n abortController.signal,\n );\n void request.catch(() => {});\n try {\n const timedOut = new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(() => {\n abortController.abort();\n reject(\n new Error(\n `Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`,\n ),\n );\n }, ɵRUNTIME_PROBE_TIMEOUT_MS);\n });\n return await Promise.race([request, timedOut]);\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n }\n }\n\n private async probeRuntimeReachability(): Promise<void> {\n const generation = this.runtimeHealthGeneration;\n const token = ++this.runtimeProbeToken;\n this.runtimeProbeInFlight = true;\n const abortController = new AbortController();\n this.runtimeProbeAbortController = abortController;\n try {\n await this.fetchRuntimeInfoWithTimeout(abortController);\n } catch (error) {\n if (generation !== this.runtimeHealthGeneration) {\n return;\n }\n await this.markRuntimeUnreachable(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n if (this.runtimeProbeAbortController === abortController) {\n this.runtimeProbeAbortController = undefined;\n }\n if (this.runtimeProbeToken === token) {\n this.runtimeProbeInFlight = false;\n }\n }\n }\n\n private async markRuntimeUnreachable(error: Error): Promise<void> {\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n\n if (isHeaderResolutionError(error)) {\n logger.warn(\n `Could not resolve request headers for the identification request (${this._runtimeUrl}/info). Check the headers builder passed to CopilotKit.`,\n );\n return;\n }\n\n const runtimeStatus = isRuntimeInfoRequestError(error)\n ? error.runtimeInfoStatus\n : undefined;\n logger.warn(\n runtimeStatus === undefined\n ? `Runtime did not answer the identification request (${this._runtimeUrl}/info): ${error.message}. The runtime appears to be unreachable.`\n : `Runtime answered the identification request with status ${runtimeStatus} (${this._runtimeUrl}/info): ${error.message}. The runtime is reachable but refused the request — check credentials and authorisation before addresses and ports.`,\n );\n await (this.core as unknown as CopilotKitCoreFriendsAccess).emitError({\n error,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl: this._runtimeUrl,\n reason: runtimeStatus === undefined ? \"no-answer\" : \"answered\",\n ...(runtimeStatus === undefined ? {} : { runtimeStatus }),\n },\n });\n }\n\n private async recoverRuntimeConnection(): Promise<void> {\n if (this.runtimeRecoveryRunning) {\n this.runtimeRecoveryPending = true;\n return;\n }\n this.runtimeRecoveryRunning = true;\n try {\n do {\n this.runtimeRecoveryPending = false;\n await this.updateRuntimeConnection({\n preserveOnFailure: true,\n recovery: true,\n });\n } while (\n this.runtimeRecoveryPending &&\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n );\n } finally {\n this.runtimeRecoveryRunning = false;\n this.runtimeRecoveryPending = false;\n }\n }\n\n /**\n * Update runtime connection and fetch remote agents\n */\n private async updateRuntimeConnection(\n options?: RuntimeConnectionOptions,\n ): Promise<void> {\n // Skip fetching on the server (SSR)\n if (typeof window === \"undefined\") {\n return;\n }\n\n // In-flight guard: if a connection to the same target (runtime url +\n // requested transport) is already running, reuse it instead of starting a\n // second `/info` request. A change to a different target supersedes it. See\n // #5801.\n const key = this.runtimeConnectionKey();\n const inFlight = this._connectionInFlight;\n if (\n inFlight &&\n inFlight.attempt.key === key &&\n this.isCurrentRuntimeConnection(inFlight.attempt)\n ) {\n return inFlight.promise;\n }\n\n const attempt = {\n key,\n generation: ++this._runtimeConnectionGeneration,\n };\n this._activeRuntimeConnectionAttempt = attempt;\n const promise = this.performRuntimeConnection({\n attempt,\n runtimeUrl: this._runtimeUrl,\n transport: this._runtimeTransport,\n options,\n });\n this._connectionInFlight = { attempt, promise };\n void promise.finally(() => {\n if (this._connectionInFlight?.promise === promise) {\n this._connectionInFlight = undefined;\n }\n });\n return promise;\n }\n\n /** Return the stable key that scopes connection and entitlement retries. */\n private runtimeConnectionKey(): string {\n // The endpoint URL is part of the identity: a change that only adds or\n // drops the trailing slash targets a different single-route endpoint.\n return `${this._runtimeEndpointUrl ?? this._runtimeUrl ?? \"\"}::${this._requestedTransport}`;\n }\n\n /** Return whether a proxy still targets this Runtime connection. */\n private canReuseRuntimeAgent(\n agent: ProxiedCopilotRuntimeAgent,\n runtimeUrl: string | undefined,\n transport: CopilotRuntimeTransport,\n ): boolean {\n if (!runtimeUrl) {\n return false;\n }\n const connection = this.remoteAgentConnections.get(agent);\n return (\n connection?.runtimeUrl === runtimeUrl.replace(/\\/$/, \"\") &&\n connection.endpointUrl === this._runtimeEndpointUrl &&\n connection.transport === transport\n );\n }\n\n /** Return whether an async attempt still owns the active Runtime state. */\n private isCurrentRuntimeConnection(\n attempt: RuntimeConnectionAttempt,\n ): boolean {\n return (\n this._activeRuntimeConnectionAttempt?.generation === attempt.generation &&\n this.runtimeConnectionKey() === attempt.key\n );\n }\n\n /** Cancel a pending entitlement retry and allow a new target to retry. */\n private resetRuntimeEntitlementRetry(): void {\n if (this._runtimeEntitlementRetryTimer !== undefined) {\n clearTimeout(this._runtimeEntitlementRetryTimer);\n this._runtimeEntitlementRetryTimer = undefined;\n }\n this._runtimeEntitlementRetryAttemptedKey = undefined;\n this._runtimeEntitlementRetryPendingKey = undefined;\n }\n\n /** Schedule one retry after Runtime's short failed-entitlement cache. */\n private updateRuntimeEntitlementRetry(\n runtimeEntitlements: RuntimeEntitlementResponse | undefined,\n attempt: RuntimeConnectionAttempt,\n ): void {\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n const { key } = attempt;\n if (\n runtimeEntitlements?.status === \"ready\" ||\n runtimeEntitlements?.error.retryable !== true\n ) {\n this.resetRuntimeEntitlementRetry();\n return;\n }\n if (this._runtimeEntitlementRetryTimer !== undefined) {\n return;\n }\n if (this._runtimeEntitlementRetryAttemptedKey === key) {\n this._runtimeEntitlementRetryPendingKey = undefined;\n return;\n }\n\n this._runtimeEntitlementRetryAttemptedKey = key;\n this._runtimeEntitlementRetryPendingKey = key;\n this._runtimeEntitlementRetryTimer = setTimeout(() => {\n this._runtimeEntitlementRetryTimer = undefined;\n void this.executeRuntimeEntitlementRetry(attempt).catch(\n (error: unknown) => {\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to retry runtime info (${this.runtimeUrl}/info): ${message}`,\n );\n },\n );\n }, RUNTIME_ENTITLEMENT_RETRY_DELAY_MS);\n }\n\n /** Start the bounded retry after the original connection has settled. */\n private async executeRuntimeEntitlementRetry(\n attempt: RuntimeConnectionAttempt,\n ): Promise<void> {\n const inFlight = this._connectionInFlight;\n if (inFlight?.attempt.generation === attempt.generation) {\n await inFlight.promise;\n }\n if (!this._runtimeUrl || !this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n await this.updateRuntimeConnection();\n }\n\n private async performRuntimeConnection({\n attempt,\n runtimeUrl,\n transport,\n options,\n }: {\n attempt: RuntimeConnectionAttempt;\n runtimeUrl: string | undefined;\n transport: CopilotRuntimeTransport;\n options?: RuntimeConnectionOptions;\n }): Promise<void> {\n const { key } = attempt;\n if (!runtimeUrl) {\n this.invalidateInspectorMetadataConnection();\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n );\n this._runtimeVersion = undefined;\n this._audioFileTranscriptionEnabled = false;\n this._runtimeMode = RUNTIME_MODE_SSE;\n this._intelligence = undefined;\n this._threadEndpoints = undefined;\n this._singleRouteResourceOperations = false;\n this._suggestions = undefined;\n this._inspectorLearning = false;\n this._a2uiEnabled = false;\n this._a2uiAgents = undefined;\n this._openGenerativeUIEnabled = false;\n this._licenseStatus = undefined;\n this._runtimeEntitlements = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n );\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n await this.notifyAgentsChanged();\n return;\n }\n\n const inspectorMetadataConnectionGeneration =\n this.inspectorMetadataConnectionGeneration;\n\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Connecting,\n );\n const runtimeHealthGeneration = this.runtimeHealthGeneration;\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Connecting,\n );\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n\n try {\n if (\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration\n ) {\n return;\n }\n const { runtimeInfo: runtimeInfoResponse, resolvedTransport } =\n options?.recovery\n ? await this.fetchRuntimeInfoWithTimeout(\n new AbortController(),\n runtimeUrl,\n transport,\n )\n : await this.fetchRuntimeInfo(runtimeUrl, transport);\n if (\n !this.isCurrentRuntimeConnection(attempt) ||\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration\n ) {\n return;\n }\n\n this._runtimeTransport = resolvedTransport;\n const { version, ...runtimeInfo } = runtimeInfoResponse;\n\n const credentials = (this.core as unknown as CopilotKitCoreFriendsAccess)\n .credentials;\n const rawDebug = (this.core as unknown as CopilotKitCoreFriendsAccess)\n .debug;\n const agents: Record<string, AbstractAgent> = Object.fromEntries(\n Object.entries(runtimeInfo.agents).map(\n ([id, { description, capabilities }]) => {\n // Preserve a live proxy only when its baked request routes still\n // match this connection. A new Runtime URL or resolved transport\n // needs a new proxy so agent traffic cannot keep using the old\n // target.\n const existing = Object.prototype.hasOwnProperty.call(\n this.remoteAgents,\n id,\n )\n ? this.remoteAgents[id]\n : undefined;\n if (\n existing instanceof ProxiedCopilotRuntimeAgent &&\n this.canReuseRuntimeAgent(\n existing,\n runtimeUrl,\n this._runtimeTransport,\n )\n ) {\n this.applyHeadersToAgent(existing);\n this.applyCredentialsToAgent(existing);\n this.applyMessageFilterToAgent(existing);\n this.applyRuntimeFetchToAgent(existing);\n this.applyRuntimeModeToAgent(existing, runtimeInfoResponse);\n return [id, existing];\n }\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this._runtimeEndpointUrl ?? runtimeUrl,\n agentId: id, // Runtime agents always have their ID set correctly\n description: description,\n transport: this._runtimeTransport,\n credentials,\n runtimeMode: runtimeInfoResponse.mode ?? RUNTIME_MODE_SSE,\n intelligence: runtimeInfoResponse.intelligence,\n capabilities,\n debug: rawDebug ? resolveDebugConfig(rawDebug) : undefined,\n messageFilter: (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).messageFilter,\n });\n this.applyHeadersToAgent(agent);\n this.applyRuntimeFetchToAgent(agent);\n this.mintedThreadIds.set(agent, agent.threadId);\n if (options?.preserveOnFailure === true && existing) {\n agent.threadId = existing.threadId;\n agent.setState(existing.state);\n agent.setMessages([...existing.messages]);\n }\n this.remoteAgentConnections.set(agent, {\n runtimeUrl,\n endpointUrl: this._runtimeEndpointUrl,\n transport: this._runtimeTransport,\n });\n return [id, agent];\n },\n ),\n );\n\n this.remoteAgents = options?.recovery\n ? this.reconcileRecoveredAgents(agents)\n : agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Connected,\n );\n this._runtimeVersion = version;\n this._audioFileTranscriptionEnabled =\n runtimeInfoResponse.audioFileTranscriptionEnabled ?? false;\n this._runtimeMode = runtimeInfoResponse.mode ?? RUNTIME_MODE_SSE;\n this._intelligence = runtimeInfoResponse.intelligence;\n this._singleRouteResourceOperations =\n resolvedTransport === \"single\" &&\n runtimeInfoResponse.singleRoute?.resourceOperations === true;\n this._threadEndpoints = this._singleRouteResourceOperations\n ? runtimeInfoResponse.singleRoute?.threadEndpoints\n : runtimeInfoResponse.threadEndpoints;\n this._suggestions = runtimeInfoResponse.suggestions;\n this._inspectorLearning = runtimeInfoResponse.inspectorLearning === true;\n this._inspectorMetadataSupported =\n runtimeInfoResponse.inspectorMetadata === true;\n this.inspectorMetadataRefreshReady = false;\n if (!this._inspectorMetadataSupported) {\n this.setInspectorMetadata(undefined);\n }\n const a2uiInfo = runtimeInfoResponse.a2ui;\n this._a2uiEnabled =\n a2uiInfo?.enabled ?? runtimeInfoResponse.a2uiEnabled ?? false;\n this._a2uiAgents = a2uiInfo?.enabled ? a2uiInfo.agents : undefined;\n this._openGenerativeUIEnabled =\n runtimeInfoResponse.openGenerativeUIEnabled ?? false;\n this._licenseStatus = runtimeInfoResponse.licenseStatus;\n this._runtimeEntitlements = runtimeInfoResponse.runtimeEntitlements;\n this.updateRuntimeEntitlementRetry(\n runtimeInfoResponse.runtimeEntitlements,\n attempt,\n );\n this._telemetryDisabled = runtimeInfoResponse.telemetryDisabled ?? false;\n\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Connected,\n );\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n await this.notifyAgentsChanged();\n if (\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration ||\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n return;\n }\n this.inspectorMetadataRefreshReady = true;\n if (this._inspectorMetadataSupported) {\n void this.refreshInspectorMetadata();\n }\n } catch (error) {\n if (\n !this.isCurrentRuntimeConnection(attempt) ||\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration\n ) {\n return;\n }\n const boundedEntitlementRetryFailed =\n this._runtimeEntitlementRetryTimer === undefined &&\n this._runtimeEntitlementRetryAttemptedKey === key &&\n this._runtimeEntitlementRetryPendingKey === key;\n if (boundedEntitlementRetryFailed) {\n this._runtimeEntitlementRetryPendingKey = undefined;\n }\n if (options?.preserveOnFailure) {\n if (\n options?.recovery &&\n runtimeHealthGeneration !== this.runtimeHealthGeneration\n ) {\n return;\n }\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n } else {\n this.invalidateInspectorMetadataConnection();\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n this._runtimeVersion = undefined;\n this._audioFileTranscriptionEnabled = false;\n this._runtimeMode = RUNTIME_MODE_SSE;\n this._intelligence = undefined;\n this._threadEndpoints = undefined;\n this._singleRouteResourceOperations = false;\n this._suggestions = undefined;\n this._inspectorLearning = false;\n this._a2uiEnabled = false;\n this._a2uiAgents = undefined;\n this._openGenerativeUIEnabled = false;\n // A failed bounded retry must settle the authority that caused it. Keep\n // that retryable result so consumers can distinguish terminal denial\n // from the initial loading window. Other connection failures still\n // clear stale Runtime authority.\n if (!boundedEntitlementRetryFailed) {\n this._licenseStatus = undefined;\n this._runtimeEntitlements = undefined;\n }\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n await this.notifyAgentsChanged();\n }\n\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to load runtime info (${runtimeUrl}/info): ${message}`,\n );\n const runtimeError =\n error instanceof Error ? error : new Error(String(error));\n await (this.core as unknown as CopilotKitCoreFriendsAccess).emitError({\n error: runtimeError,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl,\n },\n });\n }\n }\n\n private async fetchRuntimeInfo(\n runtimeUrl: string,\n runtimeTransport: CopilotRuntimeTransport,\n signal?: AbortSignal,\n ): Promise<RuntimeInfoFetchResult> {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const credentials = friends.credentials;\n // Resolution is synchronous for a record or a sync builder — only await\n // when it's actually async, so a sync source never pays an extra\n // microtask tick here.\n const resolved = friends.resolveHeaders();\n const resolvedHeaders = isPromiseLike(resolved)\n ? await abortable(resolved, signal)\n : resolved;\n const headers: Record<string, string> = {\n ...resolvedHeaders,\n };\n\n if (runtimeTransport === \"single\") {\n return {\n runtimeInfo: await this.fetchRuntimeInfoSingle(\n this.singleEndpointUrlFor(runtimeUrl),\n headers,\n credentials,\n signal,\n ),\n resolvedTransport: \"single\",\n };\n }\n\n if (runtimeTransport === \"auto\") {\n return this.fetchRuntimeInfoAutoDetect(\n runtimeUrl,\n headers,\n credentials,\n signal,\n );\n }\n\n // REST transport\n const response = await fetch(`${runtimeUrl}/info`, {\n headers,\n ...(credentials ? { credentials } : {}),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n return {\n runtimeInfo: (await response.json()) as RuntimeInfo,\n resolvedTransport: \"rest\",\n };\n }\n\n /**\n * The URL a single-route request targets: the runtime URL as the caller\n * supplied it. `runtimeUrl` is the slash-stripped form used for path joins;\n * a trailing slash can select a different proxy location, so the endpoint\n * itself keeps it.\n */\n private singleEndpointUrlFor(runtimeUrl: string): string {\n return this._runtimeEndpointUrl !== undefined &&\n this._runtimeUrl === runtimeUrl\n ? this._runtimeEndpointUrl\n : runtimeUrl;\n }\n\n private async fetchRuntimeInfoSingle(\n runtimeUrl: string,\n headers: Record<string, string>,\n credentials: RequestCredentials | undefined,\n signal?: AbortSignal,\n ): Promise<RuntimeInfo> {\n const response = await fetch(runtimeUrl, {\n method: \"POST\",\n headers: withJsonContentType(headers),\n body: JSON.stringify({ method: \"info\" }),\n ...(credentials ? { credentials } : {}),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n return (await response.json()) as RuntimeInfo;\n }\n\n /**\n * Auto-detect transport by trying REST first, then falling back to single-endpoint.\n * The caller commits the detected transport only after confirming this\n * connection attempt is still current.\n */\n private async fetchRuntimeInfoAutoDetect(\n runtimeUrl: string,\n headers: Record<string, string>,\n credentials: RequestCredentials | undefined,\n signal?: AbortSignal,\n ): Promise<RuntimeInfoFetchResult> {\n // Try REST first (GET /info)\n try {\n const response = await fetch(`${runtimeUrl}/info`, {\n headers: { ...headers },\n ...(credentials ? { credentials } : {}),\n ...(signal ? { signal } : {}),\n });\n // Only treat a successful (2xx) response as a valid REST runtime.\n // 404/405 means the endpoint doesn't exist; other non-2xx errors\n // (500, 403, etc.) should also fall through to single-endpoint.\n if (response.status >= 200 && response.status < 300) {\n return {\n runtimeInfo: (await response.json()) as RuntimeInfo,\n resolvedTransport: \"rest\",\n };\n }\n // Non-2xx — try single-endpoint below\n } catch {\n // REST failed (network error, etc.) — fall through to single-endpoint attempt\n }\n\n const runtimeInfo = await this.fetchRuntimeInfoSingle(\n this.singleEndpointUrlFor(runtimeUrl),\n { ...headers },\n credentials,\n signal,\n );\n return { runtimeInfo, resolvedTransport: \"single\" };\n }\n\n /**\n * Assign agent IDs to a record of agents\n */\n private assignAgentIds(\n agents: Record<string, AbstractAgent>,\n ): Record<string, AbstractAgent> {\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent) {\n this.validateAndAssignAgentId(id, agent);\n }\n });\n return agents;\n }\n\n /**\n * Validate and assign an agent ID\n */\n private validateAndAssignAgentId(\n registrationId: string,\n agent: AbstractAgent,\n ): void {\n if (agent.agentId && agent.agentId !== registrationId) {\n throw new Error(\n `Agent registration mismatch: Agent with ID \"${agent.agentId}\" cannot be registered under key \"${registrationId}\". ` +\n `The agent ID must match the registration key or be undefined.`,\n );\n }\n if (!agent.agentId) {\n agent.agentId = registrationId;\n }\n }\n\n /**\n * Notify subscribers of runtime status changes\n */\n private async notifyRuntimeStatusChanged(\n status: CopilotKitCoreRuntimeConnectionStatus,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this.core,\n status,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\",\n );\n }\n\n /**\n * Notify subscribers of agent changes\n */\n private async notifyAgentsChanged(): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this.core,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\",\n );\n }\n\n private async notifyInspectorMetadataChanged(\n inspectorMetadata: InspectorMetadataV1 | undefined,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onInspectorMetadataChanged?.({\n copilotkit: this.core,\n inspectorMetadata,\n }),\n \"Subscriber onInspectorMetadataChanged error:\",\n );\n }\n}\n","/**\n * True when an entry scoped to `agentIds` goes to a run of `agentId`. An\n * entry without `agentIds` goes to every agent; an entry with them does not\n * go to a run without an agent id. Internal, not exported.\n */\nexport function isForAgent(\n agentIds: readonly string[] | undefined,\n agentId: string | undefined,\n): boolean {\n return (\n agentIds === undefined ||\n (agentId !== undefined && agentIds.includes(agentId))\n );\n}\n","import type { Context } from \"@ag-ui/client\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport type { CopilotKitCore } from \"./core\";\nimport type { CopilotKitCoreFriendsAccess } from \"./core\";\nimport { isForAgent } from \"./agent-scope\";\n\n/**\n * A context entry with optional per-agent scoping.\n * When `agentIds` is set, the entry is forwarded only to runs of those agents;\n * when omitted, the entry is forwarded to every agent run.\n */\nexport interface ScopedContext extends Context {\n agentIds?: string[];\n}\n\n/**\n * Manages context storage and lifecycle for CopilotKitCore.\n * Context represents additional information available to agents during execution.\n */\nexport class ContextStore {\n private _context: Record<string, ScopedContext> = {};\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Get all context entries as a readonly record\n */\n get context(): Readonly<Record<string, ScopedContext>> {\n return this._context;\n }\n\n /**\n * Add a new context entry. Pass `agentIds` to restrict the entry to runs of\n * specific agents (#5369); omit it for context every agent should receive.\n * @returns The ID of the created context entry\n */\n addContext({ description, value, agentIds }: ScopedContext): string {\n const id = randomUUID();\n this._context[id] = {\n description,\n value,\n ...(agentIds ? { agentIds } : {}),\n };\n void this.notifySubscribers();\n return id;\n }\n\n /**\n * Build the context array for a run of the given agent: entries scoped to\n * other agents are dropped, and the scoping metadata is stripped so only\n * protocol-shaped `{ description, value }` entries go over the wire.\n */\n getContextForAgent(agentId?: string): Context[] {\n return Object.values(this._context)\n .filter((entry) => isForAgent(entry.agentIds, agentId))\n .map(({ description, value }) => ({ description, value }));\n }\n\n /**\n * Remove a context entry by ID\n */\n removeContext(id: string): void {\n delete this._context[id];\n void this.notifySubscribers();\n }\n\n /**\n * Notify all subscribers of context changes\n */\n private async notifySubscribers(): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this.core,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\",\n );\n }\n}\n","import type { AbstractAgent, Message, Tool } from \"@ag-ui/client\";\nimport { HttpAgent } from \"@ag-ui/client\";\nimport { ProxiedCopilotRuntimeAgent } from \"../agent\";\nimport { randomUUID, partialJSONParse } from \"@copilotkit/shared\";\nimport type { CopilotKitCore } from \"./core\";\nimport type { CopilotKitCoreGetSuggestionsResult } from \"./core\";\nimport type { CopilotKitCoreFriendsAccess } from \"./core\";\nimport type {\n DynamicSuggestionsConfig,\n StaticSuggestionsConfig,\n Suggestion,\n SuggestionsConfig,\n} from \"../types\";\n\n/**\n * The minimal cancellation surface a running suggestion generation exposes.\n * Both a cloned `AbstractAgent` (via `abortRun`) and the stateless fetch shim\n * (which aborts an `AbortController`) satisfy this, so `clearSuggestions` can\n * cancel either uniformly.\n */\ninterface AbortableSuggestionRun {\n abortRun(): void;\n}\n\n/**\n * Manages suggestion generation, streaming, and lifecycle for CopilotKitCore.\n * Handles both dynamic (AI-generated) and static suggestions.\n */\nexport class SuggestionEngine {\n private _suggestionsConfig: Record<string, SuggestionsConfig> = {};\n private _suggestions: Record<string, Record<string, Suggestion[]>> = {};\n private _runningSuggestions: Record<string, AbortableSuggestionRun[]> = {};\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Initialize with suggestion configs\n */\n initialize(suggestionsConfig: SuggestionsConfig[]): void {\n for (const config of suggestionsConfig) {\n this._suggestionsConfig[randomUUID()] = config;\n }\n }\n\n /**\n * Add a suggestion configuration\n * @returns The ID of the created config\n */\n addSuggestionsConfig(config: SuggestionsConfig): string {\n const id = randomUUID();\n this._suggestionsConfig[id] = config;\n void this.notifySuggestionsConfigChanged();\n return id;\n }\n\n /**\n * Remove a suggestion configuration by ID\n */\n removeSuggestionsConfig(id: string): void {\n delete this._suggestionsConfig[id];\n void this.notifySuggestionsConfigChanged();\n }\n\n /**\n * Reload suggestions for a specific agent\n * This triggers generation of new suggestions based on current configs\n */\n public reloadSuggestions(agentId: string): void {\n this.clearSuggestions(agentId);\n\n // The agent may legitimately be missing here (e.g. runtime info still loading,\n // or the consumer agent is configured but not yet registered) — static suggestions\n // don't need it, only dynamic generation does. Treat that case as \"no messages yet\"\n // and process static configs anyway.\n const agent = (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).getAgent(agentId);\n\n const messageCount = agent?.messages?.length ?? 0;\n let hasAnySuggestions = false;\n\n for (const config of Object.values(this._suggestionsConfig)) {\n // Check if config applies to this agent\n if (\n config.consumerAgentId !== undefined &&\n config.consumerAgentId !== \"*\" &&\n config.consumerAgentId !== agentId\n ) {\n continue;\n }\n\n // Check availability based on message count\n if (!this.shouldShowSuggestions(config, messageCount)) {\n continue;\n }\n\n const suggestionId = randomUUID();\n\n if (isDynamicSuggestionsConfig(config)) {\n // Dynamic suggestions need a real agent (provider + consumer messages).\n // Skip when the agent isn't ready yet — `reloadSuggestions` will be\n // called again once it is.\n if (!agent) {\n continue;\n }\n if (!hasAnySuggestions) {\n hasAnySuggestions = true;\n void this.notifySuggestionsStartedLoading(agentId);\n }\n void this.generateSuggestions(suggestionId, config, agentId);\n } else if (isStaticSuggestionsConfig(config)) {\n this.addStaticSuggestions(suggestionId, config, agentId);\n }\n }\n }\n\n /**\n * Clear all suggestions for a specific agent\n */\n public clearSuggestions(agentId: string): void {\n const runningAgents = this._runningSuggestions[agentId];\n if (runningAgents) {\n for (const agent of runningAgents) {\n agent.abortRun();\n }\n delete this._runningSuggestions[agentId];\n }\n this._suggestions[agentId] = {};\n\n void this.notifySuggestionsChanged(agentId, []);\n }\n\n /**\n * Get current suggestions for an agent\n */\n public getSuggestions(agentId: string): CopilotKitCoreGetSuggestionsResult {\n const suggestions = Object.values(this._suggestions[agentId] ?? {}).flat();\n const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;\n return { suggestions, isLoading };\n }\n\n /**\n * Generate suggestions by running a provider agent and extracting the\n * `copilotkitSuggest` tool call from its streamed messages.\n *\n * Two transports, one set of mechanics: both seed an agent with the\n * consumer's messages + state and the instruction, then `runAgent` with\n * forced `copilotkitSuggest` tool choice, parsing suggestions as messages\n * stream in via `onMessagesChanged`.\n *\n * - **Stateless** (runtime advertises `suggestions` and transport isn't\n * `single`): a stock `HttpAgent` pointed at `/agent/:id/suggest`. That\n * endpoint runs the provider directly and streams AG-UI SSE **without**\n * persisting a thread, and a plain `HttpAgent` only ever speaks REST SSE —\n * it never routes through the Intelligence websocket delegate (which would\n * persist a thread). This is the path that removes the thread flood.\n * - **Fallback** (capability absent → old runtime, or `single` transport):\n * clone the provider agent and run it client-side, as before.\n *\n * Gated to non-`single` transports because this client only builds the\n * multi-route `/agent/:id/suggest` URL; single-route deployments (not the\n * persisting-thread/Intelligence case) fall through to the clone fallback.\n */\n private async generateSuggestions(\n suggestionId: string,\n config: DynamicSuggestionsConfig,\n consumerAgentId: string,\n ): Promise<void> {\n // The cancellable handle for this generation, removed from the running set\n // in `finally`. `abortRun` flips `aborted` before cancelling the underlying\n // agent so the `catch` can distinguish a deliberate clear/reload from a real\n // failure — some engines (undici, some React Native) reject an aborted run\n // with a non-\"AbortError\" error that `isAbortError` alone would misclassify.\n let runHandle: AbortableSuggestionRun | undefined = undefined;\n let aborted = false;\n try {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const resolvedProviderAgentId = config.providerAgentId ?? \"default\";\n const suggestionsProviderAgent = friends.getAgent(\n resolvedProviderAgentId,\n );\n if (!suggestionsProviderAgent) {\n throw new Error(\n `Suggestions provider agent not found: ${resolvedProviderAgentId}`,\n );\n }\n const suggestionsConsumerAgent = friends.getAgent(consumerAgentId);\n if (!suggestionsConsumerAgent) {\n throw new Error(\n `Suggestions consumer agent not found: ${consumerAgentId}`,\n );\n }\n\n const instructionContent = [\n `Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \\`copilotkitSuggest\\` tool.`,\n `Provide at least ${config.minSuggestions ?? 1} and at most ${\n config.maxSuggestions ?? 3\n } suggestions.`,\n `The user has the following tools available: ${JSON.stringify(\n friends.buildFrontendTools(consumerAgentId),\n )}.`,\n ` ${config.instructions}`,\n ].join(\"\\n\");\n\n // Initialize suggestion storage for this agent/suggestion combo\n this._suggestions[consumerAgentId] = {\n ...this._suggestions[consumerAgentId],\n [suggestionId]: [],\n };\n\n // Deep-clone the consumer's messages + state so the suggestion run sees\n // the same context a real turn would, without sharing mutable references.\n const seededMessages: Message[] = JSON.parse(\n JSON.stringify(suggestionsConsumerAgent.messages),\n );\n const seededState: unknown = JSON.parse(\n JSON.stringify(suggestionsConsumerAgent.state ?? {}),\n );\n\n const useStateless =\n this.core.suggestions === true &&\n this.core.runtimeTransport !== \"single\";\n\n let suggestionAgent: AbstractAgent;\n // Tracks the stateless HttpAgent (when built) so its headers can be\n // resolved fresh right before the request is sent, without widening\n // `suggestionAgent`'s type below.\n let statelessAgent: HttpAgent | undefined;\n if (useStateless) {\n const suggestUrl = `${this.core.runtimeUrl}/agent/${encodeURIComponent(\n resolvedProviderAgentId,\n )}/suggest`;\n const credentials = this.core.credentials;\n statelessAgent = new HttpAgent({\n agentId: resolvedProviderAgentId,\n url: suggestUrl,\n // `HttpAgentConfig` has no `credentials` field; inject it via a fetch\n // wrapper so cookie-based / self-hosted auth still rides along on the\n // `/suggest` request.\n ...(credentials\n ? {\n fetch: (url: string, requestInit: RequestInit) =>\n fetch(url, { ...requestInit, credentials }),\n }\n : {}),\n });\n suggestionAgent = statelessAgent;\n } else {\n suggestionAgent = suggestionsProviderAgent.clone();\n // A suggestion run gets a brand-new thread id, so no backend store can\n // fill in history the client withheld. An app-level `messageFilter`\n // trimmed for a persisted conversation would therefore leave the\n // provider with only the tail of the seeded context and generate\n // suggestions about nothing. The seeded messages ARE the context here.\n if (suggestionAgent instanceof ProxiedCopilotRuntimeAgent) {\n suggestionAgent.messageFilter = undefined;\n }\n }\n\n suggestionAgent.threadId = suggestionId;\n suggestionAgent.setMessages(seededMessages);\n suggestionAgent.setState(seededState);\n\n runHandle = {\n abortRun: () => {\n aborted = true;\n suggestionAgent.abortRun();\n },\n };\n // Registered before the header resolution below (which can await) so\n // `isLoading` flips true in the same tick this generation starts,\n // matching the pre-#1937 timing: a caller inspecting it right after\n // `reloadSuggestions()` must see the run as already in flight.\n this._runningSuggestions[consumerAgentId] = [\n ...(this._runningSuggestions[consumerAgentId] ?? []),\n runHandle,\n ];\n\n if (statelessAgent) {\n // Resolved fresh (not the last snapshot) so a builder's current\n // token rides along on this stateless request, applied right before\n // the request is sent (#1937).\n statelessAgent.headers = { ...(await this.core.resolveHeaders()) };\n } else {\n // A clone of a plain `HttpAgent` carries the source agent's headers\n // from its last run, so apply fresh ones the way a normal run does.\n // A proxied runtime agent adds core headers at send time instead.\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).prepareAgentHeadersForRun(suggestionAgent);\n }\n\n // `clearSuggestions`/`abortRun` may have run while the header\n // resolution above was in flight. `HttpAgent.runAgent` always installs\n // a fresh `AbortController` for the run it starts, so an abort issued\n // against the (now-discarded) pre-run instance would NOT stop the\n // request below from being sent, and a completed run would write stale\n // suggestions into whatever the current turn has become. `finally`\n // still performs its cleanup on this early return.\n if (aborted) return;\n\n suggestionAgent.addMessage({\n id: suggestionId,\n role: \"user\",\n content: instructionContent,\n });\n\n await suggestionAgent.runAgent(\n {\n context: friends.getContextForAgent(consumerAgentId),\n forwardedProps: {\n ...friends.getPropertiesForAgent(consumerAgentId),\n toolChoice: {\n type: \"function\",\n function: { name: \"copilotkitSuggest\" },\n },\n },\n tools: [SUGGEST_TOOL],\n },\n {\n onMessagesChanged: ({ messages }) => {\n this.extractSuggestions(\n messages,\n suggestionId,\n consumerAgentId,\n true,\n );\n },\n },\n );\n } catch (error) {\n // An abort is expected when suggestions are cleared/reloaded mid-flight;\n // swallow it quietly rather than surfacing it as a failure. `isAbortError`\n // is the primary (name-based) check; `aborted` covers engines that reject\n // an aborted run with a differently-named error (or a `TypeError`).\n if (!isAbortError(error) && !aborted) {\n console.warn(\"Error generating suggestions:\", error);\n }\n } finally {\n // Finalize suggestions by marking them as no longer loading\n this.finalizeSuggestions(suggestionId, consumerAgentId);\n\n // Remove this run from the running set. `runHandle` may be undefined when\n // generation threw before it was assigned (e.g. provider/consumer agent\n // lookup failed); still perform cleanup so the loading balance holds. If\n // no runs remain for this consumer, emit finished-loading — otherwise a\n // subscriber that saw `started` would hang in the loading state.\n const runningAgents = this._runningSuggestions[consumerAgentId];\n const remaining = runHandle\n ? (runningAgents ?? []).filter((a) => a !== runHandle)\n : (runningAgents ?? []);\n\n if (remaining.length === 0) {\n delete this._runningSuggestions[consumerAgentId];\n await this.notifySuggestionsFinishedLoading(consumerAgentId);\n } else {\n this._runningSuggestions[consumerAgentId] = remaining;\n }\n }\n }\n\n /**\n * Finalize suggestions by marking them as no longer loading\n */\n private finalizeSuggestions(\n suggestionId: string,\n consumerAgentId: string,\n ): void {\n const agentSuggestions = this._suggestions[consumerAgentId];\n const currentSuggestions = agentSuggestions?.[suggestionId];\n\n if (\n agentSuggestions &&\n currentSuggestions &&\n currentSuggestions.length > 0\n ) {\n // Filter out empty suggestions and mark remaining as no longer loading\n const finalizedSuggestions = currentSuggestions\n .filter(\n (suggestion) => suggestion.title !== \"\" || suggestion.message !== \"\",\n )\n .map((suggestion) => ({\n ...suggestion,\n isLoading: false,\n }));\n\n if (finalizedSuggestions.length > 0) {\n agentSuggestions[suggestionId] = finalizedSuggestions;\n } else {\n delete agentSuggestions[suggestionId];\n }\n\n // Get all aggregated suggestions for this agent\n const allSuggestions = Object.values(\n this._suggestions[consumerAgentId] ?? {},\n ).flat();\n\n void this.notifySuggestionsChanged(\n consumerAgentId,\n allSuggestions,\n \"finalized\",\n );\n }\n }\n\n /**\n * Extract suggestions from messages (called during streaming)\n */\n extractSuggestions(\n messages: readonly Message[],\n suggestionId: string,\n consumerAgentId: string,\n isRunning: boolean,\n ): void {\n const idx = messages.findIndex((message) => message.id === suggestionId);\n if (idx == -1) {\n return;\n }\n\n const suggestions: Suggestion[] = [];\n const newMessages = messages.slice(idx + 1);\n\n for (const message of newMessages) {\n if (message.role === \"assistant\" && message.toolCalls) {\n for (const toolCall of message.toolCalls) {\n if (toolCall.function.name === \"copilotkitSuggest\") {\n // Join all argument chunks into a single string for parsing\n // arguments can be either a string or an array of strings\n const fullArgs = Array.isArray(toolCall.function.arguments)\n ? toolCall.function.arguments.join(\"\")\n : toolCall.function.arguments;\n const parsed = partialJSONParse(fullArgs);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n \"suggestions\" in parsed\n ) {\n const parsedSuggestions = (parsed as any).suggestions;\n if (Array.isArray(parsedSuggestions)) {\n for (const item of parsedSuggestions) {\n if (item && typeof item === \"object\" && \"title\" in item) {\n suggestions.push({\n title: item.title ?? \"\",\n message: item.message ?? \"\",\n // Defaults to false; only the trailing item is flipped to\n // true below, and only while a streaming run is in flight.\n isLoading: false,\n });\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Set isLoading for the last suggestion if still running\n if (isRunning && suggestions.length > 0) {\n suggestions[suggestions.length - 1]!.isLoading = true;\n }\n\n const agentSuggestions = this._suggestions[consumerAgentId];\n if (agentSuggestions) {\n agentSuggestions[suggestionId] = suggestions;\n\n // Get all aggregated suggestions for this agent\n const allSuggestions = Object.values(\n this._suggestions[consumerAgentId] ?? {},\n ).flat();\n\n void this.notifySuggestionsChanged(\n consumerAgentId,\n allSuggestions,\n \"suggestions changed\",\n );\n }\n }\n\n /**\n * Notify subscribers of suggestions config changes\n */\n private async notifySuggestionsConfigChanged(): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsConfigChanged?.({\n copilotkit: this.core,\n suggestionsConfig: this._suggestionsConfig,\n }),\n \"Subscriber onSuggestionsConfigChanged error:\",\n );\n }\n\n /**\n * Notify subscribers of suggestions changes\n */\n private async notifySuggestionsChanged(\n agentId: string,\n suggestions: Suggestion[],\n context: string = \"\",\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsChanged?.({\n copilotkit: this.core,\n agentId,\n suggestions,\n }),\n `Subscriber onSuggestionsChanged error: ${context}`,\n );\n }\n\n /**\n * Notify subscribers that suggestions started loading\n */\n private async notifySuggestionsStartedLoading(\n agentId: string,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsStartedLoading?.({\n copilotkit: this.core,\n agentId,\n }),\n \"Subscriber onSuggestionsStartedLoading error:\",\n );\n }\n\n /**\n * Notify subscribers that suggestions finished loading\n */\n private async notifySuggestionsFinishedLoading(\n agentId: string,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsFinishedLoading?.({\n copilotkit: this.core,\n agentId,\n }),\n \"Subscriber onSuggestionsFinishedLoading error:\",\n );\n }\n\n /**\n * Check if suggestions should be shown based on availability and message count\n */\n private shouldShowSuggestions(\n config: SuggestionsConfig,\n messageCount: number,\n ): boolean {\n const availability = config.available;\n\n // Default behavior if no availability specified\n if (!availability) {\n if (isDynamicSuggestionsConfig(config)) {\n return messageCount > 0; // Default: after-first-message\n } else {\n return messageCount === 0; // Default: before-first-message\n }\n }\n\n switch (availability) {\n case \"disabled\":\n return false;\n case \"before-first-message\":\n return messageCount === 0;\n case \"after-first-message\":\n return messageCount > 0;\n case \"always\":\n return true;\n default:\n return false;\n }\n }\n\n /**\n * Add static suggestions directly without AI generation\n */\n private addStaticSuggestions(\n suggestionId: string,\n config: StaticSuggestionsConfig,\n consumerAgentId: string,\n ): void {\n // Mark all as not loading since they're static\n const suggestions = config.suggestions.map((s) => ({\n ...s,\n isLoading: false,\n }));\n\n // Store suggestions\n this._suggestions[consumerAgentId] = {\n ...this._suggestions[consumerAgentId],\n [suggestionId]: suggestions,\n };\n\n // Notify subscribers\n const allSuggestions = Object.values(\n this._suggestions[consumerAgentId] ?? {},\n ).flat();\n\n void this.notifySuggestionsChanged(\n consumerAgentId,\n allSuggestions,\n \"static suggestions added\",\n );\n }\n}\n\n/**\n * Detects an `AbortController`-driven cancellation so the stateless path can\n * treat it as an expected (non-error) outcome on clear/reload.\n */\nexport function isAbortError(error: unknown): boolean {\n // Detect purely by name: a `DOMException` is NOT `instanceof Error` in Safari\n // and older engines, so gating on `instanceof Error` would misclassify a real\n // user abort as a failure in the browser (this package runs client-side).\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"name\" in error &&\n (error as { name?: unknown }).name === \"AbortError\"\n );\n}\n\n/**\n * Type guard for dynamic suggestions config\n */\nfunction isDynamicSuggestionsConfig(\n config: SuggestionsConfig,\n): config is DynamicSuggestionsConfig {\n return \"instructions\" in config;\n}\n\n/**\n * Type guard for static suggestions config\n */\nfunction isStaticSuggestionsConfig(\n config: SuggestionsConfig,\n): config is StaticSuggestionsConfig {\n return \"suggestions\" in config;\n}\n\n/**\n * The tool definition for AI-generated suggestions\n */\nconst SUGGEST_TOOL: Tool = {\n name: \"copilotkitSuggest\",\n description: \"Suggest what the user could say next\",\n parameters: {\n type: \"object\",\n properties: {\n suggestions: {\n type: \"array\",\n description: \"List of suggestions shown to the user as buttons.\",\n items: {\n type: \"object\",\n properties: {\n title: {\n type: \"string\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence \" +\n \"and will be sent as an instruction to the AI.\",\n },\n },\n required: [\"title\", \"message\"],\n },\n },\n },\n required: [\"suggestions\"],\n },\n};\n","import type { ContentPart } from \"@ag-ui/client\";\n\n/**\n * Single authority for the forwarded-to-client sentinel used by StateManager\n * and RunHandler.\n */\nexport const FORWARDED_TO_CLIENT = \"Forwarded to client\";\n\nexport function normalizeToolResultContent(content: unknown): string | null {\n if (typeof content === \"string\") return content.trim();\n\n if (Array.isArray(content)) {\n const text = content\n .flatMap((part) => {\n if (typeof part === \"string\") return [part];\n if (\n part &&\n typeof part === \"object\" &&\n \"text\" in part &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return [(part as { text: string }).text];\n }\n return [];\n })\n .join(\"\")\n .trim();\n return text.length > 0 ? text : null;\n }\n\n if (\n content &&\n typeof content === \"object\" &&\n \"text\" in content &&\n typeof (content as { text?: unknown }).text === \"string\"\n ) {\n return (content as { text: string }).text.trim();\n }\n\n return null;\n}\n\nexport function isForwardedToClientPlaceholder(content: unknown): boolean {\n return normalizeToolResultContent(content) === FORWARDED_TO_CLIENT;\n}\n\nconst MEDIA_PART_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\nfunction isOptionalString(value: unknown): boolean {\n return value === undefined || typeof value === \"string\";\n}\n\nfunction isPartSource(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const source = value as Record<string, unknown>;\n if (typeof source.value !== \"string\") return false;\n switch (source.type) {\n case \"data\":\n return typeof source.mimeType === \"string\";\n case \"url\":\n return isOptionalString(source.mimeType);\n case \"file\":\n return (\n isOptionalString(source.provider) && isOptionalString(source.mimeType)\n );\n default:\n return false;\n }\n}\n\n/**\n * Mirrors `ContentPartSchema` from `@ag-ui/core/schemas`. The runtime parses\n * the request with that schema, and one invalid part there fails the whole run.\n * Core does not import the schema because the UMD build has no global for it.\n * A test checks this function against the schema.\n */\nexport function isContentPart(value: unknown): value is ContentPart {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const part = value as Record<string, unknown>;\n if (!isOptionalString(part.id) || part.metadata === null) return false;\n if (part.type === \"text\") return typeof part.text === \"string\";\n return (\n typeof part.type === \"string\" &&\n MEDIA_PART_TYPES.has(part.type) &&\n isPartSource(part.source)\n );\n}\n\n/**\n * Converts what a frontend tool handler returned into tool message content.\n * A non-empty array of AG-UI content parts passes through unchanged, so an\n * image reaches the model as media. Everything else becomes a string, as before.\n *\n * `text` is the string form, for surfaces typed as `result: string`\n * (`runTool`, `onToolExecutionEnd`). For content parts it is the JSON text they\n * received before. It is computed here, so a part that cannot be serialized\n * throws inside the caller's handler error boundary.\n */\nexport function toToolResultContent(result: unknown): {\n content: string | ContentPart[];\n text: string;\n} {\n if (result === undefined || result === null) return { content: \"\", text: \"\" };\n if (typeof result === \"string\") return { content: result, text: result };\n const text = JSON.stringify(result);\n if (\n Array.isArray(result) &&\n result.length > 0 &&\n result.every(isContentPart)\n ) {\n return { content: result, text };\n }\n return { content: text, text };\n}\n","import { schemaToJsonSchema } from \"@copilotkit/shared\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { FrontendTool } from \"../types\";\n\n/**\n * Empty tool schema constant\n */\nconst EMPTY_TOOL_SCHEMA = {\n type: \"object\",\n properties: {},\n} as const satisfies Record<string, unknown>;\n\n/**\n * Create a JSON schema from a tool's parameters\n */\nexport function createToolSchema(\n tool: FrontendTool<any>,\n): Record<string, unknown> {\n if (!tool.parameters) {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const rawSchema = schemaToJsonSchema(tool.parameters, {\n zodToJsonSchema: (schema, options) =>\n zodToJsonSchema(\n schema as Parameters<typeof zodToJsonSchema>[0],\n options as Parameters<typeof zodToJsonSchema>[1],\n ),\n });\n\n if (!rawSchema || typeof rawSchema !== \"object\") {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const { $schema: _$schema, ...schema } = rawSchema as Record<string, unknown>;\n\n if (typeof schema.type !== \"string\") {\n schema.type = \"object\";\n }\n if (typeof schema.properties !== \"object\" || schema.properties === null) {\n schema.properties = {};\n }\n\n stripAdditionalProperties(schema);\n return schema;\n}\n\n/**\n * Remove every `additionalProperties` key from a JSON schema tree, in place.\n * Some LLM providers reject schemas that carry it.\n */\nfunction stripAdditionalProperties(schema: unknown): void {\n if (!schema || typeof schema !== \"object\") {\n return;\n }\n\n if (Array.isArray(schema)) {\n schema.forEach(stripAdditionalProperties);\n return;\n }\n\n const record = schema as Record<string, unknown>;\n\n if (record.additionalProperties !== undefined) {\n delete record.additionalProperties;\n }\n\n for (const value of Object.values(record)) {\n stripAdditionalProperties(value);\n }\n}\n","import { buildResumeArray, isInterruptExpired } from \"@ag-ui/client\";\nimport type {\n AbstractAgent,\n Interrupt,\n ResumeEntry,\n Message,\n} from \"@ag-ui/client\";\n\nimport { isForwardedToClientPlaceholder } from \"./core/tool-result-content\";\n\ntype ResumeResponse =\n | { status: \"resolved\"; payload?: unknown }\n | { status: \"cancelled\" };\n\n/** @internal Application authors must not depend on this contract. */\nexport interface ɵInterruptEvent<TValue = unknown> {\n name: string;\n value: TValue;\n}\n\n/** @internal Application authors must not depend on this contract. */\nexport type ɵPendingInterrupt<TValue = unknown> =\n | { kind: \"legacy\"; event: ɵInterruptEvent<TValue> }\n | { kind: \"standard\"; interrupts: readonly Interrupt[] };\n\n/** @internal Application authors must not depend on this contract. */\nexport interface ɵInterruptToolResult {\n toolCallId: string;\n content: Extract<Message, { role: \"tool\" }>[\"content\"];\n}\n\n/** @internal Application authors must not depend on this contract. */\nexport type ɵInterruptDecision =\n | { kind: \"ignored\" }\n | { kind: \"waiting\" }\n | { kind: \"dismiss\" }\n | {\n kind: \"expired\";\n interrupt: Interrupt;\n }\n | {\n kind: \"legacy-resume\";\n payload: unknown;\n interruptValue: unknown;\n }\n | {\n kind: \"resume\";\n resume: ResumeEntry[];\n toolResults: ɵInterruptToolResult[];\n };\n\n/** Serialize a newly answered frontend call for the canonical message history. */\nfunction toolResultContent(response: ResumeResponse): string {\n if (response.status === \"cancelled\") {\n return JSON.stringify({ status: \"cancelled\" });\n }\n return JSON.stringify(response.payload ?? { status: \"resolved\" });\n}\n\n/**\n * @internal Framework-neutral interrupt response state shared by framework\n * adapters. Application authors must not depend on this API.\n */\nexport class ɵInterruptState<TValue = unknown> {\n readonly #responses: Record<string, ResumeResponse> = Object.create(null);\n #adoptedContent = new Map<string, ɵInterruptToolResult[\"content\"]>();\n #pending: ɵPendingInterrupt<TValue> | null = null;\n #sealed = false;\n\n /** Return the active normalized interrupt without exposing mutable state. */\n get pending(): ɵPendingInterrupt<TValue> | null {\n const pending = this.#pending;\n if (pending?.kind === \"standard\") {\n return { kind: \"standard\", interrupts: [...pending.interrupts] };\n }\n return pending;\n }\n\n /** Replace the current interrupt with a legacy custom-event interrupt. */\n setLegacy(event: ɵInterruptEvent<TValue>): void {\n this.#replace({ kind: \"legacy\", event });\n }\n\n /** Replace the current interrupt with an AG-UI standard interrupt set. */\n setStandard(interrupts: readonly Interrupt[]): void {\n const ids = new Set<string>();\n const callIds = new Set<string>();\n for (const interrupt of interrupts) {\n if (ids.has(interrupt.id))\n throw new Error(`Duplicate interrupt id: ${interrupt.id}`);\n ids.add(interrupt.id);\n if (interrupt.reason === \"tool_call\" && interrupt.toolCallId) {\n if (callIds.has(interrupt.toolCallId))\n throw new Error(\n `Duplicate interrupt tool call: ${interrupt.toolCallId}`,\n );\n callIds.add(interrupt.toolCallId);\n }\n }\n this.#replace({ kind: \"standard\", interrupts: [...interrupts] });\n }\n\n /** Clear all pending interrupt data and accumulated responses. */\n clear(): void {\n this.#pending = null;\n this.#sealed = false;\n this.#adoptedContent.clear();\n for (const id of Object.keys(this.#responses)) delete this.#responses[id];\n }\n\n /** Record a resolved response and return the next framework action. */\n resolve(\n payload?: unknown,\n interruptId?: string,\n messages: readonly Message[] = [],\n ): ɵInterruptDecision {\n const pending = this.#pending;\n if (!pending || this.#sealed) return { kind: \"ignored\" };\n if (pending.kind === \"legacy\") {\n this.#sealed = true;\n return {\n kind: \"legacy-resume\",\n payload,\n interruptValue: pending.event.value,\n };\n }\n return this.#respond(\n pending.interrupts,\n interruptId,\n {\n status: \"resolved\",\n payload,\n },\n messages,\n );\n }\n\n /** Record a cancelled response and return the next framework action. */\n cancel(\n interruptId?: string,\n messages: readonly Message[] = [],\n ): ɵInterruptDecision {\n const pending = this.#pending;\n if (!pending || this.#sealed) return { kind: \"ignored\" };\n if (pending.kind === \"legacy\") {\n this.#sealed = true;\n return { kind: \"dismiss\" };\n }\n return this.#respond(\n pending.interrupts,\n interruptId,\n {\n status: \"cancelled\",\n },\n messages,\n );\n }\n\n /** Reject ambiguous assistant definitions before executing or answering a call. */\n validateToolCalls(messages: readonly Message[]): void {\n if (this.#pending?.kind !== \"standard\") return;\n const pendingCalls = new Set(\n this.#pending.interrupts\n .filter((interrupt) => interrupt.reason === \"tool_call\")\n .map((interrupt) => interrupt.toolCallId),\n );\n const seen = new Set<string>();\n for (const message of messages) {\n if (message.role !== \"assistant\") continue;\n for (const call of message.toolCalls ?? []) {\n if (!pendingCalls.has(call.id)) continue;\n if (seen.has(call.id))\n throw new Error(`Duplicate tool call definition: ${call.id}`);\n seen.add(call.id);\n }\n }\n }\n\n /** Let UI adapters ignore answers for exactly one successful frontend result. */\n isCompletedToolCall(\n interruptId: string | undefined,\n messages: readonly Message[],\n ): boolean {\n const pending = this.#pending;\n if (pending?.kind !== \"standard\") return false;\n const id = interruptId ?? pending.interrupts[0]?.id;\n const interrupt = pending.interrupts.find((entry) => entry.id === id);\n if (interrupt?.reason !== \"tool_call\" || !interrupt.toolCallId)\n return false;\n // Do not hide duplicate results: resolve/cancel still reaches #decide's error.\n const results = messages.filter(\n (message) =>\n message.role === \"tool\" &&\n message.toolCallId === interrupt.toolCallId &&\n !isForwardedToClientPlaceholder(message.content),\n );\n const result = results[0];\n return (\n results.length === 1 &&\n result?.role === \"tool\" &&\n result.error === undefined\n );\n }\n\n /** Resume only when saved frontend results answer every pending interrupt. */\n resumeWithToolResults(messages: readonly Message[]): ɵInterruptDecision {\n const pending = this.#pending;\n if (pending?.kind !== \"standard\" || this.#sealed)\n return { kind: \"ignored\" };\n return this.#decide(pending.interrupts, { ...this.#responses }, messages);\n }\n\n /** Start a new batch with no decisions retained from the preceding run. */\n #replace(pending: ɵPendingInterrupt<TValue>): void {\n this.clear();\n this.#pending = pending;\n }\n\n /** Record one explicit answer and reconcile it with saved frontend results. */\n #respond(\n interrupts: readonly Interrupt[],\n interruptId: string | undefined,\n response: ResumeResponse,\n messages: readonly Message[],\n ): ɵInterruptDecision {\n const id = interruptId ?? interrupts[0]?.id;\n if (!id || !interrupts.some((interrupt) => interrupt.id === id)) {\n return { kind: \"ignored\" };\n }\n return this.#decide(\n interrupts,\n { ...this.#responses, [id]: response },\n messages,\n );\n }\n\n /** Claim a complete batch once, preserving saved results and partial answers. */\n #decide(\n interrupts: readonly Interrupt[],\n responses: Record<string, ResumeResponse>,\n messages: readonly Message[],\n ): ɵInterruptDecision {\n this.validateToolCalls(messages);\n const completed = new Set<string>();\n // Stage adoption until every response validates, so a rejected decision\n // cannot leave cached content out of sync with accumulated responses.\n const adoptedContent = new Map(this.#adoptedContent);\n for (const interrupt of interrupts) {\n if (interrupt.reason !== \"tool_call\" || !interrupt.toolCallId) continue;\n const results = messages.filter(\n (message): message is Extract<Message, { role: \"tool\" }> =>\n message.role === \"tool\" &&\n message.toolCallId === interrupt.toolCallId &&\n !isForwardedToClientPlaceholder(message.content),\n );\n if (results.length > 1)\n throw new Error(`Duplicate tool results for ${interrupt.toolCallId}`);\n const result = results[0];\n if (!result && !adoptedContent.has(interrupt.id)) continue;\n const response = Object.prototype.hasOwnProperty.call(\n responses,\n interrupt.id,\n )\n ? responses[interrupt.id]\n : undefined;\n if (result?.role === \"tool\" && result.error !== undefined) {\n // Failure history remains intact; only an explicit decision can recover\n // this call. Do not append a second result for the same call ID.\n adoptedContent.delete(interrupt.id);\n completed.add(interrupt.id);\n continue;\n }\n const content = result\n ? result.content\n : adoptedContent.get(interrupt.id)!;\n if (\n response &&\n (response.status !== \"resolved\" ||\n (!sameValue(response.payload, content) &&\n toolResultContent(response) !== content))\n ) {\n throw new Error(\n `Interrupt response conflicts with existing tool result for ${interrupt.toolCallId}`,\n );\n }\n // Preserve actual result bytes, including the empty string. Never create\n // another tool message for a call already answered by a frontend handler.\n responses[interrupt.id] = { status: \"resolved\", payload: content };\n adoptedContent.set(interrupt.id, content);\n if (result) completed.add(interrupt.id);\n }\n Object.assign(this.#responses, responses);\n this.#adoptedContent = adoptedContent;\n if (\n !interrupts.every((interrupt) =>\n Object.prototype.hasOwnProperty.call(responses, interrupt.id),\n )\n ) {\n return { kind: \"waiting\" };\n }\n\n const expired = interrupts.find(\n (interrupt) =>\n responses[interrupt.id]?.status !== \"cancelled\" &&\n isInterruptExpired(interrupt),\n );\n if (expired) {\n this.#sealed = true;\n return { kind: \"expired\", interrupt: expired };\n }\n\n const mutableInterrupts = [...interrupts];\n const resume = buildResumeArray(mutableInterrupts, responses);\n const toolResults = mutableInterrupts.flatMap((interrupt) => {\n if (\n !interrupt.toolCallId ||\n interrupt.reason !== \"tool_call\" ||\n completed.has(interrupt.id)\n )\n return [];\n return [\n {\n toolCallId: interrupt.toolCallId,\n content: adoptedContent.has(interrupt.id)\n ? adoptedContent.get(interrupt.id)!\n : toolResultContent(responses[interrupt.id]!),\n },\n ];\n });\n this.#sealed = true;\n return { kind: \"resume\", resume, toolResults };\n }\n}\n\n/** Compare JSON protocol values without depending on object key insertion order. */\nfunction sameValue(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (!left || !right || typeof left !== \"object\" || typeof right !== \"object\")\n return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => sameValue(value, right[index]))\n );\n }\n const a = left as Record<string, unknown>;\n const b = right as Record<string, unknown>;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(\n (key) =>\n Object.prototype.hasOwnProperty.call(b, key) &&\n sameValue(a[key], b[key]),\n )\n );\n}\n\nconst agentInterruptStates = new WeakMap<\n AbstractAgent,\n {\n threadId: string;\n interrupts: readonly Interrupt[];\n state: ɵInterruptState;\n }\n>();\n\n/** @internal Share decisions and the single resume claim for an agent's pending batch. */\nexport function ɵgetAgentInterruptState(\n agent: AbstractAgent,\n interrupts: readonly Interrupt[] = agent.pendingInterrupts,\n): ɵInterruptState {\n const current = agentInterruptStates.get(agent);\n if (\n current &&\n current.threadId === agent.threadId &&\n current.state.pending &&\n sameValue(current.interrupts, interrupts)\n )\n return current.state;\n const state = new ɵInterruptState();\n state.setStandard(interrupts);\n agentInterruptStates.set(agent, {\n threadId: agent.threadId,\n interrupts: structuredClone(interrupts),\n state,\n });\n return state;\n}\n\n/** @internal A new run owns a new batch, even if the server reuses interrupt IDs. */\nexport function ɵclearAgentInterruptState(agent: AbstractAgent): void {\n agentInterruptStates.delete(agent);\n}\n","import type { ToolCall } from \"@ag-ui/client\";\nimport { logger, randomUUID } from \"@copilotkit/shared\";\nimport type { FrontendTool, WebMCPToolAnnotations } from \"../types\";\nimport { createToolSchema } from \"./tool-schema\";\n\n/**\n * The subset of the WebMCP `ModelContext` API\n * (https://webmachinelearning.github.io/webmcp/) that the registry depends on.\n * Kept structural so the code works against the real browser API and test\n * doubles alike. Aborting the registration signal unregisters the tool.\n */\nexport interface WebMCPModelContext {\n registerTool(\n tool: {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n options: { signal?: AbortSignal },\n ) => Promise<unknown>;\n annotations?: WebMCPToolAnnotations;\n },\n options: { signal: AbortSignal },\n ): Promise<undefined>;\n}\n\n/**\n * Return the page's `document.modelContext`, or null when WebMCP is not\n * available (SSR, React Native, browsers without the API enabled).\n */\nexport function getWebMCPModelContext(): WebMCPModelContext | null {\n if (typeof document === \"undefined\") {\n return null;\n }\n const modelContext = (\n document as Document & { modelContext?: WebMCPModelContext }\n ).modelContext;\n return modelContext ?? null;\n}\n\ninterface WebMCPRegistryEntry {\n tool: FrontendTool<any>;\n controller: AbortController;\n}\n\n/**\n * Keeps a set of frontend tools registered on the page's WebMCP model context.\n *\n * `sync(desired)` reconciles the registrations with the desired set: tools that\n * are gone (or were re-registered with a new tool object) are unregistered by\n * aborting their registration signal, and new tools are registered with an\n * `execute` that delegates to the frontend tool's own handler.\n *\n * All WebMCP-API constraints live here so callers only supply the desired set:\n * a tool without a description is skipped with a warning (the spec rejects\n * empty descriptions), and failures from `registerTool` (duplicate name,\n * unsupported context, ...) are warned rather than thrown.\n */\nexport class WebMCPRegistry {\n private entries = new Map<string, WebMCPRegistryEntry>();\n private warnedNames = new Set<string>();\n\n /** Names currently kept registered on the model context. */\n get registeredNames(): string[] {\n return [...this.entries.keys()];\n }\n\n /** Reconcile the registered tools with the desired set. */\n sync(desired: Map<string, FrontendTool<any>>): void {\n const modelContext = getWebMCPModelContext();\n if (!modelContext) {\n return;\n }\n\n for (const [name, entry] of [...this.entries]) {\n if (desired.get(name) !== entry.tool) {\n entry.controller.abort();\n this.entries.delete(name);\n }\n }\n\n for (const [name, tool] of desired) {\n if (this.entries.has(name)) {\n continue;\n }\n if (!tool.description) {\n this.warnOnce(\n name,\n `Skipping WebMCP registration for tool '${name}': WebMCP requires a description.`,\n );\n continue;\n }\n\n const controller = new AbortController();\n this.entries.set(name, { tool, controller });\n modelContext\n .registerTool(\n this.buildModelContextTool(\n tool as FrontendTool<any> & { description: string },\n ),\n { signal: controller.signal },\n )\n .catch((error) => {\n // Registration failed (duplicate name, insecure context, permission\n // policy, ...). Drop the bookkeeping; the browser never registered.\n // Only delete while this is still the active registration: an\n // aborted registration can reject after a newer one already replaced\n // it, and that replacement's bookkeeping must survive.\n if (this.entries.get(name)?.controller !== controller) {\n return;\n }\n this.entries.delete(name);\n const message =\n error instanceof Error ? error.message : String(error);\n this.warnOnce(\n name,\n `WebMCP registration failed for tool '${name}': ${message}`,\n );\n });\n }\n }\n\n /**\n * Build the WebMCP model-context tool for a frontend tool. The `execute`\n * callback delegates to the frontend tool's own handler, so a browser agent\n * call runs the same application code as an agent call.\n */\n private buildModelContextTool(\n tool: FrontendTool<any> & { description: string },\n ): {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n options: { signal?: AbortSignal },\n ) => Promise<unknown>;\n annotations?: WebMCPToolAnnotations;\n } {\n const annotations =\n typeof tool.webmcp === \"object\" ? tool.webmcp.annotations : undefined;\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: createToolSchema(tool),\n execute: async (args, options) => {\n if (!tool.handler) {\n // Mirrors core's empty tool result for a display-only tool.\n return \"\";\n }\n const toolCall: ToolCall = {\n id: randomUUID(),\n type: \"function\",\n function: {\n name: tool.name,\n arguments: JSON.stringify(args ?? {}),\n },\n };\n return await tool.handler(args as any, {\n toolCall,\n signal: options?.signal,\n });\n },\n ...(annotations ? { annotations } : {}),\n };\n }\n\n /** Log `message` once per tool name. Repeated syncs must not spam the log. */\n private warnOnce(name: string, message: string): void {\n if (this.warnedNames.has(name)) {\n return;\n }\n this.warnedNames.add(name);\n logger.warn(`[CopilotKit] ${message}`);\n }\n}\n","import type {\n AbstractAgent,\n AgentSubscriber,\n Message,\n RunAgentResult,\n ResumeEntry,\n Tool,\n ToolCall,\n ContentPart,\n} from \"@ag-ui/client\";\nimport {\n randomUUID,\n logger,\n THREAD_ALREADY_RUNNING_ERROR_CODE,\n} from \"@copilotkit/shared\";\nimport type { CopilotKitCore, CopilotKitCoreFriendsAccess } from \"./core\";\nimport { CopilotKitCoreErrorCode } from \"./core\";\nimport { AgentThreadLockedError } from \"../intelligence-agent\";\nimport type { FrontendTool } from \"../types\";\nimport { isAbortError } from \"../utils/abort-error\";\nimport type { CopilotKitCoreContinuationHandoff } from \"./state-manager\";\nimport {\n isForwardedToClientPlaceholder,\n toToolResultContent,\n} from \"./tool-result-content\";\nimport { createToolSchema } from \"./tool-schema\";\nimport {\n ɵgetAgentInterruptState,\n ɵclearAgentInterruptState,\n} from \"../interrupt-state\";\nimport { WebMCPRegistry } from \"./webmcp\";\n\n/**\n * Live approvals cancelled by stopping their own run, keyed by the handler's\n * signal. The value reports whether that stop is still current: no reconnect\n * has started and the thread is unchanged, so nothing will restore the call.\n *\n * Kept here rather than in `AbortSignal.reason`: React Native's global\n * `AbortController` is the `abort-controller@3` polyfill, whose `abort()`\n * takes no reason and whose signals never expose one.\n */\nconst liveHITLStops = new WeakMap<AbortSignal, () => boolean>();\n\n// Explicitly stopping a live approval must retain its error result. History\n// restoration and thread-switch cancellation instead discard the old result.\n/**\n * The message a failed tool call reports. An error thrown with an empty\n * message still means the call failed, so it gets a fallback rather than an\n * empty string, which everything downstream reads as success.\n */\nfunction toolFailureMessage(error: Error): string {\n return error.message || \"Tool call failed\";\n}\n\nfunction discardAbortedResult(\n signal: AbortSignal | undefined,\n discardOnAbort: boolean,\n errorMessage?: string,\n): boolean {\n return !!(\n discardOnAbort &&\n signal?.aborted &&\n !(liveHITLStops.get(signal)?.() && errorMessage)\n );\n}\n\nexport interface CopilotKitCoreRunAgentParams {\n agent: AbstractAgent;\n forwardedProps?: Record<string, unknown>;\n /**\n * Optional caller-supplied run identifier forwarded to the underlying AG-UI\n * agent. When omitted, the agent creates one.\n */\n runId?: string;\n /**\n * Per-interrupt responses addressing every open AG-UI interrupt from the\n * previous run. Forwarded to the agent as the standard `resume` array.\n */\n resume?: ResumeEntry[];\n}\n\nexport interface CopilotKitCoreConnectAgentParams {\n agent: AbstractAgent;\n}\n\nexport interface CopilotKitCoreGetToolParams {\n toolName: string;\n agentId?: string;\n}\n\n/**\n * Parameters for programmatic tool execution via `copilotkit.runTool()`.\n */\nexport interface CopilotKitCoreRunToolParams {\n /** Name of the registered frontend tool to execute. */\n name: string;\n /** Optional agent ID. If omitted, uses the default agent lookup. */\n agentId?: string;\n /** Parameters to pass to the tool handler. */\n parameters?: Record<string, unknown>;\n /**\n * Whether to trigger an LLM follow-up after tool execution.\n * - `false` (default): execute tool, add messages to history, done.\n * - `\"generate\"`: after execution, trigger another agent run so the LLM responds to the tool result.\n * - Any other string: add a user message with this text, then trigger another agent run.\n */\n followUp?: string | false;\n}\n\n/**\n * Result of programmatic tool execution via `copilotkit.runTool()`.\n */\nexport interface CopilotKitCoreRunToolResult {\n /** The unique ID of the tool call. */\n toolCallId: string;\n /** The stringified result from the tool handler. */\n result: string;\n /** Error message if the handler failed. */\n error?: string;\n}\n\n/**\n * Internal result from the shared tool handler execution logic.\n */\ninterface ExecuteToolHandlerResult {\n /** The tool message content: a string, or content parts from the handler. */\n content: string | ContentPart[];\n /** The string form of `content`, for surfaces typed as `result: string`. */\n result: string;\n error?: string;\n isArgumentError: boolean;\n}\n\n/**\n * A registered A2UI catalog component, as exposed to the inspector via\n * `CopilotKitCore.catalogComponents`. `schema` is an opaque JSON-schema-ish\n * value (the built catalog's Zod schema or a serialized form); the inspector\n * treats it as unknown. `description` is optional because the built\n * `ComponentApi` does not carry descriptions.\n */\nexport interface CopilotKitCoreCatalogComponent {\n name: string;\n description?: string;\n schema: unknown;\n}\n\n/** How many recent runs keep their request ID for a later approval resume. */\nconst MAX_REMEMBERED_REQUEST_IDS = 100;\n\n/**\n * Absolute safety cap on the depth of recursive follow-up runs triggered by\n * `processAgentResult`. Without this, any scenario that keeps\n * `needsFollowUp = true` (e.g. the LLM repeatedly calling the same tool, a\n * backend that errors after receiving tool results, or input processors that\n * reprocess tool messages) would loop indefinitely, silently consuming API\n * quota and potentially DOS'ing the backend.\n *\n * The cap is deliberately high so that legitimate multi-step agent workflows\n * (search → fill form → confirm → update → send email, etc.) are never\n * affected; it only trips on runaway recursion.\n */\nconst MAX_FOLLOW_UP_DEPTH = 100;\n\n/**\n * Name of the catch-all frontend tool. A tool registered under this name\n * handles any tool call that has no exact match (see `executeWildcardTool`),\n * and is never advertised to the agent.\n */\nconst WILDCARD_TOOL_NAME = \"*\";\n\n/**\n * Handles agent execution, tool calling, and agent connectivity for CopilotKitCore.\n * Manages the complete lifecycle of agent runs including tool execution and follow-ups.\n */\nexport class RunHandler {\n /**\n * Tools owned by the framework provider, replaced wholesale by\n * {@link initialize} and {@link setTools} whenever the provider re-syncs its\n * props or runtime feature flags.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _propTools: FrontendTool<any>[] = [];\n\n /**\n * Tools registered imperatively via {@link addTool} — `useFrontendTool`,\n * `useHumanInTheLoop`, and direct `core.addTool()` callers. Held separately\n * from {@link _propTools} so a provider re-sync cannot wipe them: they shared\n * one array before, so the `/info` response flipping `openGenerativeUI` (or\n * any other provider-prop change) silently dropped every hook-registered\n * tool (#4952). Key = `capabilityKey(name, agentId)`.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _hookTools: Map<string, FrontendTool<any>> = new Map();\n\n /**\n * Memoized merge of both buckets, invalidated on every registry write.\n *\n * This is about identity, not speed: `tools` is public and used to return the\n * same array instance until something mutated the registry, so consumers can\n * hold it or use it as an effect dependency. Rebuilding the merge on every\n * read would hand out a new array each time.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _cachedMergedTools: FrontendTool<any>[] | null = null;\n\n /**\n * The full list of A2UI catalog components registered by the provider.\n * Order is preserved for display in the inspector.\n */\n private _catalogComponents: CopilotKitCoreCatalogComponent[] = [];\n\n /**\n * Names of catalog components the caller has explicitly disabled. A name\n * absent from this set is enabled (default). Survives re-registration so a\n * catalog identity change does not silently re-enable a disabled component.\n */\n private _disabledCatalogComponents: Set<string> = new Set();\n\n /**\n * Keys of frontend tools explicitly disabled at runtime via the Inspector's\n * Capabilities tool (`setToolEnabled`). Kept independently of each tool's own\n * `available` flag so a hook re-registering the tool (which resets\n * `available`) does not clobber the override. Key = `capabilityKey(name, agentId)`.\n */\n private _disabledToolKeys = new Set<string>();\n\n /**\n * Registry keys already reported by {@link warnOnMissingToolParameters}.\n * Development only, and per instance rather than per module so tests and\n * multiple cores stay independent. Deliberately NOT cleared by\n * {@link removeTool}: `useFrontendTool` tears down and re-registers on every\n * dependency change, so clearing it would turn one warning into one per\n * render. Key = `capabilityKey(name, agentId)`.\n */\n private _warnedMissingToolParameters = new Set<string>();\n\n /**\n * Abort controllers of each agent's in-flight run chains (a run plus its\n * recursive follow-ups), recording whether a chain, including its tool\n * execution, was aborted via `stopAgent()` or `agent.abortRun()`. Every run\n * that is not a follow-up gets a fresh controller, so a run started after\n * Stop is not born aborted while the stopped chain is still settling. Keyed\n * by agent so that stopping one agent never cancels another agent's run on\n * the same core.\n */\n private _runAbortControllers = new WeakMap<\n AbstractAgent,\n Set<AbortController>\n >();\n\n /**\n * Per-agent `runAgent` depth (in-flight runs plus their recursive\n * follow-ups), so that the `agent.abortRun()` intercept is installed while\n * any of the agent's runs is in flight and removed once none is, and so\n * that runaway follow-up chains trip `MAX_FOLLOW_UP_DEPTH`.\n */\n private _runDepths = new WeakMap<AbstractAgent, number>();\n\n /**\n * Each agent's own `abortRun`, saved while RunHandler's intercept is\n * installed. Restored only once none of the agent's runs is in flight, so an\n * overlapping run keeps the intercept after an earlier run finishes.\n */\n private _originalAbortRuns = new WeakMap<AbstractAgent, () => void>();\n\n /**\n * The request each agent's in-flight run belongs to. Its follow-up runs\n * send the same ID, so Intelligence counts the chain as one request.\n */\n private _activeRequestIds = new WeakMap<AbstractAgent, string>();\n\n /**\n * Request IDs of recent logical runs, so an approval that resumes a paused\n * run sends the ID of the request that paused. Oldest entries go first.\n */\n private _requestIdByRun = new Map<string, string>();\n\n /**\n * Keeps tools that opt in via `webmcp` registered on the page's WebMCP model\n * context (`document.modelContext`), in addition to the normal agent\n * registration. Reconciled on every tool registry mutation.\n */\n private _webmcpRegistry = new WebMCPRegistry();\n\n /**\n * Tracks the threadId of the most recent `connectAgent` call so we\n * can distinguish a fresh thread restore (different threadId than\n * last time — chat is rebuilding state from scratch, must clear\n * messages/state and ask the gateway for a full replay) from a\n * same-thread churn re-connect (effect-dep churn or transient\n * disconnect — local messages/state are still meaningful, must\n * preserve them and let the gateway resume from\n * `lastSeenEventId`).\n *\n * Tyler's bug fired because every `connectAgent` was treated as a\n * fresh restore, which forced the gateway to replay the full\n * thread history on every churn re-connect and amplified the\n * downstream churn into duplicate `cpki_event_id` rows in the\n * inspector and intermittent \"Message not found\" toasts.\n */\n private _lastConnectedThreadIdsByAgent = new Map<string, string | null>();\n private _lastActiveThreadIdsByAgent = new Map<string, string | null>();\n private _anonymousAgentIds = new WeakMap<AbstractAgent, string>();\n private _nextAnonymousAgentId = 0;\n\n /** Prevent reconnects from starting an interaction already executing locally. */\n private _executingToolCalls = new WeakMap<AbstractAgent, Set<string>>();\n\n private _connectionGenerations = new WeakMap<AbstractAgent, object>();\n private _runGenerations = new WeakMap<AbstractAgent, object>();\n\n private _interactionAbortControllers = new WeakMap<\n AbstractAgent,\n {\n threadId: string | null;\n controllers: Set<AbortController>;\n }\n >();\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Abort the current run. Called by `CopilotKitCore.stopAgent()` to signal\n * that in-flight tool handlers should stop and `processAgentResult` should\n * not start a follow-up run.\n */\n abortCurrentRun(agent: AbstractAgent): void {\n this.abortAgentRuns(agent);\n const replay = this._interactionAbortControllers.get(agent);\n if (replay) {\n for (const controller of replay.controllers) controller.abort();\n this._interactionAbortControllers.delete(agent);\n // Cancellation is cooperative: an old handler may never settle. Let a\n // reconnect restore it without waiting for its execution marker to clear.\n this._executingToolCalls.delete(agent);\n }\n }\n\n private abortAgentRuns(agent: AbstractAgent): void {\n for (const controller of this._runAbortControllers.get(agent) ?? []) {\n controller.abort();\n }\n }\n\n /** Signal of the agent's most recently started in-flight run, if any. */\n private latestRunSignal(agent: AbstractAgent): AbortSignal | undefined {\n let latest: AbortController | undefined;\n for (const controller of this._runAbortControllers.get(agent) ?? []) {\n latest = controller;\n }\n return latest?.signal;\n }\n\n /**\n * Typed access to CopilotKitCore's internal (\"friend\") methods.\n * Centralises the single unavoidable cast so call-sites stay clean.\n */\n private get _internal(): CopilotKitCoreFriendsAccess {\n return this.core as unknown as CopilotKitCoreFriendsAccess;\n }\n\n /**\n * Return a stable restore-tracking key for the logical agent being\n * connected. Named agents share their last-thread marker across proxy\n * instances; anonymous agents fall back to object identity.\n */\n private getConnectRestoreKey(agent: AbstractAgent): string {\n if (agent.agentId) {\n return `agent:${agent.agentId}`;\n }\n\n const existing = this._anonymousAgentIds.get(agent);\n if (existing) {\n return existing;\n }\n\n const anonymousId = `anonymous:${this._nextAnonymousAgentId}`;\n this._nextAnonymousAgentId += 1;\n this._anonymousAgentIds.set(agent, anonymousId);\n return anonymousId;\n }\n\n /**\n * Get all tools as a readonly array: provider-owned tools in registration\n * order, with imperatively-added tools appended and taking precedence over a\n * provider tool of the same name + agentId.\n */\n get tools(): Readonly<FrontendTool<any>[]> {\n if (this._hookTools.size === 0) {\n return this._propTools;\n }\n if (this._cachedMergedTools) {\n return this._cachedMergedTools;\n }\n // Merge: hook entries override prop entries with the same key. Overriding\n // an existing key keeps the prop entry's position, so provider order is\n // preserved and only genuinely new hook tools land at the end.\n const merged = new Map<string, FrontendTool<any>>();\n for (const tool of this._propTools) {\n merged.set(this.capabilityKey(tool.name, tool.agentId), tool);\n }\n for (const [key, tool] of this._hookTools) {\n merged.set(key, tool);\n }\n this._cachedMergedTools = Array.from(merged.values());\n return this._cachedMergedTools;\n }\n\n /**\n * Initialize with tools\n */\n initialize(tools: FrontendTool<any>[]): void {\n // Copied, like `setTools` does: the merged view is memoized, so holding the\n // caller's array would let an in-place mutation of it go unnoticed. (It\n // also used to be mutated from this side — `addTool` pushed straight onto\n // the array the provider passed in.)\n this._propTools = [...tools];\n this._cachedMergedTools = null;\n this.warnOnMissingToolParameters(this._propTools);\n this.syncWebMCP();\n }\n\n /**\n * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),\n * and shadows a provider tool of the same name + agentId.\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>,\n ): void {\n const key = this.capabilityKey(tool.name, tool.agentId);\n\n // Only a competing imperative registration is a conflict. A provider tool\n // of the same name is shadowed rather than treated as a duplicate — hooks\n // mount after the provider and are the more specific registration.\n if (this._hookTools.has(key)) {\n logger.warn(\n `Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`,\n );\n return;\n }\n\n this._hookTools.set(key, tool);\n this._cachedMergedTools = null;\n this.warnOnMissingToolParameters([tool]);\n this.syncWebMCP();\n }\n\n /**\n * Report, once per tool and at development time only, a tool registered with\n * no `parameters` schema.\n *\n * `createToolSchema` substitutes `{ type: \"object\", properties: {} }` for a\n * missing `parameters` and returns silently, and `parameters` is optional on\n * `FrontendTool`, so nothing — not the compiler, not the runtime — tells the\n * developer that the model was handed a tool with nothing to fill in. It then\n * calls the tool with no arguments. `useComponent`, `useFrontendTool` and\n * `useHumanInTheLoop` all funnel into {@link addTool}; the provider's `tools`\n * prop funnels into {@link initialize} and {@link setTools}.\n *\n * A parameterless tool is legitimate (a HITL confirm dialog, say), so this\n * stays a warning rather than an error. An explicit empty schema\n * (`parameters: z.object({})`) is the way to say \"takes none on purpose\": it\n * satisfies the check below and `createToolSchema` reduces it to the same\n * advertised `{ type: \"object\", properties: {} }` that omitting `parameters`\n * produces, so silencing the warning costs nothing on the wire.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private warnOnMissingToolParameters(tools: FrontendTool<any>[]): void {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n for (const tool of tools) {\n if (tool.parameters) {\n continue;\n }\n const key = this.capabilityKey(tool.name, tool.agentId);\n if (this._warnedMissingToolParameters.has(key)) {\n continue;\n }\n this._warnedMissingToolParameters.add(key);\n logger.warn(\n `Tool has no parameters schema: '${tool.name}' for agent '${tool.agentId || \"global\"}'. ` +\n `The model is told it takes no arguments and will call it with none. ` +\n `Add \\`parameters\\` (a Zod or Standard Schema object) if it should ` +\n `receive arguments, or \\`parameters: z.object({})\\` to declare that it ` +\n `takes none and silence this warning.`,\n );\n }\n }\n\n /**\n * Remove a tool by name and optionally by agentId\n */\n removeTool(id: string, agentId?: string): void {\n this._hookTools.delete(this.capabilityKey(id, agentId));\n this._propTools = this._propTools.filter((tool) => {\n // Remove tool if both name and agentId match\n if (agentId !== undefined) {\n return !(tool.name === id && tool.agentId === agentId);\n }\n // If no agentId specified, only remove global tools with matching name\n return !(tool.name === id && !tool.agentId);\n });\n this._cachedMergedTools = null;\n this.syncWebMCP();\n }\n\n /**\n * Get a tool by name and optionally by agentId.\n * If agentId is provided, it will first look for an agent-specific tool,\n * then fall back to a global tool with the same name.\n */\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n const { toolName, agentId } = params;\n const tools = this.tools;\n\n // If agentId is provided, first look for agent-specific tool\n if (agentId) {\n const agentTool = tools.find(\n (tool) => tool.name === toolName && tool.agentId === agentId,\n );\n if (agentTool) {\n return agentTool;\n }\n }\n\n // Fall back to global tool (no agentId)\n return tools.find((tool) => tool.name === toolName && !tool.agentId);\n }\n\n /**\n * Set all provider-owned tools at once. Replaces the previous provider set;\n * tools registered via {@link addTool} are unaffected.\n */\n setTools(tools: FrontendTool<any>[]): void {\n this._propTools = [...tools];\n this._cachedMergedTools = null;\n this.warnOnMissingToolParameters(this._propTools);\n this.syncWebMCP();\n }\n\n /**\n * Return the registered A2UI catalog components (readonly).\n */\n get catalogComponents(): ReadonlyArray<CopilotKitCoreCatalogComponent> {\n return this._catalogComponents;\n }\n\n /**\n * Replace the registered catalog component list. Preserves the disabled set\n * (by name) so re-registration does not re-enable disabled components.\n */\n setCatalogComponents(components: CopilotKitCoreCatalogComponent[]): void {\n this._catalogComponents = [...components];\n }\n\n /**\n * Enable or disable a catalog component by name.\n */\n setCatalogComponentEnabled(name: string, enabled: boolean): void {\n if (enabled) {\n this._disabledCatalogComponents.delete(name);\n } else {\n this._disabledCatalogComponents.add(name);\n }\n }\n\n /**\n * Whether a catalog component is enabled. Unknown names default to enabled.\n */\n isCatalogComponentEnabled(name: string): boolean {\n return !this._disabledCatalogComponents.has(name);\n }\n\n /**\n * Connect an agent (establish initial connection)\n */\n async connectAgent({\n agent,\n }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult> {\n const connection = {};\n this._connectionGenerations.set(agent, connection);\n const incomingThreadId = agent.threadId ?? null;\n const previousReplay = this._interactionAbortControllers.get(agent);\n if (previousReplay && previousReplay.threadId !== incomingThreadId) {\n for (const controller of previousReplay.controllers) controller.abort();\n this._interactionAbortControllers.delete(agent);\n // Old handlers retain their own set until they settle. They must not\n // prevent a fresh restoration when navigating back to this thread.\n this._executingToolCalls.delete(agent);\n }\n try {\n const restoreKey = this.getConnectRestoreKey(agent);\n const previousThreadId = this._lastActiveThreadIdsByAgent.get(restoreKey);\n const isFreshRestore =\n incomingThreadId !==\n (previousThreadId ??\n this._lastConnectedThreadIdsByAgent.get(restoreKey) ??\n null);\n\n // Detach any active run before connecting to avoid previous runs\n // interfering. This stays unconditional — both fresh restores and\n // churn re-connects need the previous socket torn down before a new\n // one can open.\n await agent.detachActiveRun();\n if (\n this._connectionGenerations.get(agent) !== connection ||\n (agent.threadId ?? null) !== incomingThreadId\n ) {\n return { result: undefined, newMessages: [] };\n }\n this._lastConnectedThreadIdsByAgent.set(restoreKey, incomingThreadId);\n this._lastActiveThreadIdsByAgent.set(restoreKey, incomingThreadId);\n\n // State reset + replay-cursor clear are gated on actually moving\n // to a different thread. On same-thread churn, the local\n // messages/state are still the right view of the thread, and the\n // gateway can resume from `lastSeenEventId` instead of replaying\n // the full history.\n if (isFreshRestore) {\n agent.setMessages([]);\n agent.setState({});\n if (\n previousThreadId !== undefined &&\n previousThreadId !== incomingThreadId\n ) {\n agent.pendingInterrupts = [];\n }\n const cursorAware = agent as {\n clearReconnectCursor?: (id: string) => void;\n clearReplayCursor?: (id: string) => void;\n };\n if (incomingThreadId) {\n if (typeof cursorAware.clearReplayCursor === \"function\") {\n cursorAware.clearReplayCursor(incomingThreadId);\n }\n if (typeof cursorAware.clearReconnectCursor === \"function\") {\n cursorAware.clearReconnectCursor(incomingThreadId);\n }\n }\n }\n\n // Re-apply current headers (merged on top of the agent's own headers)\n // so the token in effect right now is what this connect carries — not\n // a value resolved earlier (#1937).\n const headersApplied = this._internal.prepareAgentHeadersForRun(agent);\n if (headersApplied) await headersApplied;\n\n // Notify subscribers (e.g. the inspector) about the agent that is about\n // to run. Per-thread clones are not in the agent registry, so\n // onAgentsChanged never fires for them and they would otherwise be\n // invisible to subscribers.\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentRunStarted?.({\n copilotkit: this.core,\n agent,\n }),\n \"Subscriber onAgentRunStarted error:\",\n );\n if (\n this._connectionGenerations.get(agent) !== connection ||\n (agent.threadId ?? null) !== incomingThreadId\n ) {\n return { result: undefined, newMessages: [] };\n }\n\n const runAgentResult = await agent.connectAgent(\n {\n forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),\n tools: this.buildFrontendTools(agent.agentId),\n context: this._internal.getContextForAgent(agent.agentId),\n },\n this.createAgentErrorSubscriber(agent),\n );\n\n // Connecting ends when history is restored, not when a human answers.\n // Keeping this promise open would block run-activity reconnects while\n // another client answers the same interaction.\n if (\n this._connectionGenerations.get(agent) !== connection ||\n (agent.threadId ?? null) !== incomingThreadId\n )\n return runAgentResult;\n const controller = new AbortController();\n const replay = this._interactionAbortControllers.get(agent) ?? {\n threadId: incomingThreadId,\n controllers: new Set<AbortController>(),\n };\n replay.controllers.add(controller);\n this._interactionAbortControllers.set(agent, replay);\n void this.processAgentResult({\n runAgentResult,\n agent,\n toolExecutionMode: \"restore\",\n connectionGeneration: connection,\n signal: controller.signal,\n })\n .catch(async (error: unknown) => {\n await this._internal.emitError({\n error: error instanceof Error ? error : new Error(String(error)),\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context: { agentId: agent.agentId, threadId: incomingThreadId },\n });\n })\n .finally(() => {\n replay.controllers.delete(controller);\n if (\n replay.controllers.size === 0 &&\n this._interactionAbortControllers.get(agent) === replay\n ) {\n this._interactionAbortControllers.delete(agent);\n }\n });\n return runAgentResult;\n } catch (error) {\n const connectError =\n error instanceof Error ? error : new Error(String(error));\n // Silently ignore abort errors (e.g. from navigation during active\n // requests).\n if (!isAbortError(connectError)) {\n const context: Record<string, any> = {};\n if (agent.agentId) {\n context.agentId = agent.agentId;\n }\n if (incomingThreadId) {\n context.threadId = incomingThreadId;\n }\n await this._internal.emitError({\n error: connectError,\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context,\n });\n }\n return { result: undefined, newMessages: [] };\n }\n }\n\n /**\n * Run an agent\n */\n async runAgent(\n { agent, forwardedProps, resume, runId }: CopilotKitCoreRunAgentParams,\n continuationHandoff?: CopilotKitCoreContinuationHandoff,\n /**\n * Set only by `processAgentResult` for a recursive follow-up: the\n * controller of the run being followed up, which the follow-up shares.\n */\n followUpOf?: AbortController,\n ): Promise<RunAgentResult> {\n this._connectionGenerations.set(agent, {});\n this._runGenerations.set(agent, {});\n ɵclearAgentInterruptState(agent);\n // Agent ID is guaranteed to be set by validateAndAssignAgentId\n if (agent.agentId) {\n void this._internal.suggestionEngine.clearSuggestions(agent.agentId);\n }\n\n // Re-apply current headers (merged on top of the agent's own headers) so\n // the token in effect right now is what this run carries — not a value\n // resolved earlier (#1937).\n try {\n const headersApplied = this._internal.prepareAgentHeadersForRun(agent);\n if (headersApplied) await headersApplied;\n } catch {\n // Already reported as HEADER_RESOLUTION_FAILED by the resolver.\n continuationHandoff?.cancel();\n return { result: undefined, newMessages: [] };\n }\n\n // Detach any active run (e.g. a long-lived connectAgent pipeline) before\n // starting a new run. We await the detach to ensure the previous pipeline\n // has fully finalized — its activeRunCompletionPromise resolves once the\n // observable finalize block runs, which happens synchronously after the\n // takeUntil signal completes the chain. This prevents a race where the new\n // runAgent() overwrites activeRunDetach$ / activeRunCompletionPromise before\n // the old pipeline can clean up, causing dropped runs.\n //\n // Historical note: an earlier version used fire-and-forget (`void`) here\n // because awaiting caused a deadlock when connectAgent's\n // ConnectNotImplementedError cleanup was still in-flight. That deadlock\n // was resolved in @ag-ui/client ≥0.0.42 where the catchError path\n // (ConnectNotImplementedError → EMPTY) always runs the finalize block,\n // so the completion promise now resolves reliably.\n if (agent.detachActiveRun) {\n try {\n await agent.detachActiveRun();\n } catch (error) {\n continuationHandoff?.cancel();\n throw error;\n }\n }\n\n const resumedRunId = this._internal.stateManager.getContinuationRunId(\n agent,\n {\n threadId: agent.threadId,\n resume,\n forwardedProps,\n },\n );\n const logicalHandoff =\n continuationHandoff ??\n (resumedRunId\n ? this._internal.stateManager.markNextRunAsContinuation(\n agent,\n resumedRunId,\n )\n : undefined);\n\n // Every run that is not a recursive follow-up gets its own controller;\n // follow-ups share the controller of the run they continue. Whether a\n // call is a follow-up is passed explicitly rather than inferred from the\n // depth, because a run started after Stop, while the stopped run's tool\n // handlers are still settling, must not inherit the aborted controller.\n const isFollowUp = followUpOf !== undefined;\n const controller = followUpOf ?? new AbortController();\n // The depth is claimed in the same synchronous step as the intercept\n // decision, so two runs started in one tick cannot both see depth 0.\n const depth = this._runDepths.get(agent) ?? 0;\n this._runDepths.set(agent, depth + 1);\n\n // A follow-up or a resume continues the request that started it. Anything\n // else is a new request.\n const continuedRunId =\n resumedRunId ?? (continuationHandoff ? runId : undefined);\n const requestId =\n (continuationHandoff ? this._activeRequestIds.get(agent) : undefined) ??\n (continuedRunId !== undefined\n ? this._requestIdByRun.get(continuedRunId)\n : undefined) ??\n randomUUID();\n\n if (!isFollowUp) {\n const controllers =\n this._runAbortControllers.get(agent) ?? new Set<AbortController>();\n controllers.add(controller);\n this._runAbortControllers.set(agent, controllers);\n }\n\n if (depth === 0) {\n // Intercept agent.abortRun() so that calling it directly (not via\n // stopAgent) also aborts in-flight tool execution and prevents\n // follow-up runs.\n const originalAbortRun = agent.abortRun;\n this._originalAbortRuns.set(agent, originalAbortRun);\n agent.abortRun = () => {\n this.abortAgentRuns(agent);\n originalAbortRun.call(agent);\n };\n }\n\n const previousRequestId = this._activeRequestIds.get(agent);\n this._activeRequestIds.set(agent, requestId);\n\n try {\n if (depth === 0) {\n // Notify subscribers (e.g. the inspector) about the agent that is\n // about to run. Per-thread clones are not in the agent registry, so\n // onAgentsChanged never fires for them and they would otherwise be\n // invisible to subscribers. Fired once while the agent has runs in\n // flight; follow-ups and overlapping runs reuse the same instance and\n // need no re-notification.\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentRunStarted?.({\n copilotkit: this.core,\n agent,\n }),\n \"Subscriber onAgentRunStarted error:\",\n );\n }\n\n let logicalRunId = resumedRunId ?? runId;\n const agentSubscriber = this.createAgentErrorSubscriber(\n agent,\n controller.signal,\n );\n let started = false;\n const onRunStartedEvent = agentSubscriber.onRunStartedEvent;\n const onRunInitialized = agentSubscriber.onRunInitialized;\n agentSubscriber.onRunInitialized = async (params) => {\n this._lastActiveThreadIdsByAgent.set(\n this.getConnectRestoreKey(agent),\n params.input.threadId,\n );\n logicalHandoff?.bind(params.input);\n return onRunInitialized?.(params);\n };\n agentSubscriber.onRunStartedEvent = async (params) => {\n started = true;\n // A continuation keeps reporting under the run it continues; only an\n // ordinary run adopts the id the transport assigned it.\n if (!logicalHandoff) {\n logicalRunId = params.input.runId;\n }\n return onRunStartedEvent?.(params);\n };\n // An internal continuation (a human-in-the-loop tool resolved and this is\n // the recursive follow-up) deliberately does NOT pin the originating run\n // id on the wire. Pinning it made the transport treat the follow-up as a\n // resumption of a run it had already completed: it re-delivered that\n // run's applied half — duplicating every tool call already on the\n // message, each duplicate carrying empty arguments — and the follow-up's\n // own tool call never reached client state, so its card never rendered.\n //\n // One logical run is still what everything downstream sees: the state\n // manager re-stamps the continuation's events onto `runId` (passed to\n // markNextRunAsContinuation), and `logicalRunId` below keeps the result\n // reported under it. So external tracing still gets a single run without\n // the wire having to lie about which invocation this is.\n const pinRunIdOnWire = runId !== undefined && !continuationHandoff;\n const agentRunInput = {\n forwardedProps: {\n ...this._internal.getPropertiesForAgent(agent.agentId),\n ...forwardedProps,\n __copilotkitRequestId: requestId,\n },\n ...(resume !== undefined ? { resume } : {}),\n ...(pinRunIdOnWire ? { runId } : {}),\n tools: this.buildFrontendTools(agent.agentId),\n context: this._internal.getContextForAgent(agent.agentId),\n };\n const runAgentResult = await agent.runAgent(\n agentRunInput,\n agentSubscriber,\n );\n if (!started) {\n logicalHandoff?.cancel();\n }\n if (logicalRunId !== undefined) {\n this.rememberRequestId(logicalRunId, requestId);\n }\n return await this.processAgentResult({\n runAgentResult,\n agent,\n runId: logicalRunId,\n runController: controller,\n });\n } catch (error) {\n logicalHandoff?.cancel();\n const runError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agent.agentId) {\n context.agentId = agent.agentId;\n }\n await this._internal.emitError({\n error: runError,\n code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,\n context,\n });\n return { result: undefined, newMessages: [] };\n } finally {\n const remainingDepth = (this._runDepths.get(agent) ?? 1) - 1;\n this._runDepths.set(agent, remainingDepth);\n // Drop this chain's controller once the chain ends, so a finished,\n // aborted run does not mark later errors as user-aborted.\n if (!isFollowUp) {\n const controllers = this._runAbortControllers.get(agent);\n controllers?.delete(controller);\n if (controllers?.size === 0) this._runAbortControllers.delete(agent);\n }\n // Restore the original abortRun only once none of the agent's runs is\n // in flight: an overlapping run on the same agent still needs it.\n if (remainingDepth === 0) {\n const originalAbortRun = this._originalAbortRuns.get(agent);\n if (originalAbortRun) {\n agent.abortRun = originalAbortRun;\n this._originalAbortRuns.delete(agent);\n }\n }\n if (previousRequestId === undefined) {\n this._activeRequestIds.delete(agent);\n } else {\n this._activeRequestIds.set(agent, previousRequestId);\n }\n }\n }\n\n private rememberRequestId(runId: string, requestId: string): void {\n this._requestIdByRun.delete(runId);\n this._requestIdByRun.set(runId, requestId);\n if (this._requestIdByRun.size > MAX_REMEMBERED_REQUEST_IDS) {\n const oldest = this._requestIdByRun.keys().next().value;\n if (oldest !== undefined) this._requestIdByRun.delete(oldest);\n }\n }\n\n /**\n * Process agent result and execute tools\n */\n private async processAgentResult({\n runAgentResult,\n agent,\n runId,\n toolExecutionMode = \"all\",\n runController,\n signal = runController?.signal,\n connectionGeneration,\n }: {\n runAgentResult: RunAgentResult;\n agent: AbstractAgent;\n runId?: string;\n toolExecutionMode?: \"all\" | \"restore\";\n /** Controller of the run that produced this result; follow-ups share it. */\n runController?: AbortController;\n signal?: AbortSignal;\n connectionGeneration?: object;\n }): Promise<RunAgentResult> {\n const { newMessages } = runAgentResult;\n // Agent ID is guaranteed to be set by validateAndAssignAgentId\n const agentId = agent.agentId!;\n\n let needsFollowUp = false;\n // Same-thread reconnects leave an executing handler in charge of its\n // eventual follow-up; a new explicit run still supersedes that ownership.\n let ownsHandlerFollowUp = false;\n const runGeneration = this._runGenerations.get(agent);\n\n const threadId = agent.threadId;\n const interruptState = agent.pendingInterrupts?.length\n ? ɵgetAgentInterruptState(agent)\n : undefined;\n interruptState?.validateToolCalls(agent.messages);\n const executing = this._executingToolCalls.get(agent) ?? new Set<string>();\n this._executingToolCalls.set(agent, executing);\n\n // Reconnect deltas omit messages hydrated by earlier replays. Restore only\n // the latest user turn: an unanswered call before a later user message is\n // historical, not permission to resume work. Keep every assistant message\n // in that turn, and snapshot because handlers insert results.\n const messagesToProcess =\n toolExecutionMode === \"restore\"\n ? agent.messages.filter(\n (message) =>\n message.role === \"assistant\" &&\n this.isInLatestUserTurn(agent.messages, message.id),\n )\n : newMessages;\n\n // One restoration pass owns the pending sequence. Skipping only the first\n // executing call would start later calls concurrently and replace a HITL\n // hook's response resolver. A saved remote answer releases this barrier.\n if (\n toolExecutionMode === \"restore\" &&\n messagesToProcess.some(\n (message) =>\n message.role === \"assistant\" &&\n message.toolCalls?.some(\n (call) =>\n executing.has(JSON.stringify([threadId, call.id])) &&\n !agent.messages.some(\n (result) =>\n result.role === \"tool\" &&\n result.toolCallId === call.id &&\n !this.isFrontendPlaceholderResult(result),\n ),\n ),\n )\n ) {\n return runAgentResult;\n }\n\n for (const message of messagesToProcess) {\n if (message.role === \"assistant\") {\n for (const toolCall of message.toolCalls || []) {\n const tool = this.getTool({\n toolName: toolCall.function.name,\n agentId: agent.agentId,\n });\n\n let wildcardTool: FrontendTool<any> | undefined;\n const getWildcardTool = () => {\n if (tool || wildcardTool) {\n return wildcardTool;\n }\n wildcardTool = this.getTool({\n toolName: WILDCARD_TOOL_NAME,\n agentId: agent.agentId,\n });\n return wildcardTool;\n };\n\n const executableTool = tool ?? getWildcardTool();\n const executionKey = JSON.stringify([threadId, toolCall.id]);\n if (\n signal?.aborted ||\n agent.threadId !== threadId ||\n (toolExecutionMode === \"restore\" &&\n !this.isInLatestUserTurn(agent.messages, message.id)) ||\n executing.has(executionKey)\n ) {\n continue;\n }\n\n const existingResultIndex = newMessages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n );\n // Live messages may contain a remote answer received while an\n // earlier handler awaited input; never replace it with stale replay.\n let existingResult =\n agent.messages.find(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n ) ?? newMessages[existingResultIndex];\n\n // Reusing a completed result is not handler execution. Passive tools\n // may resume saved successes but must keep unanswered placeholders.\n if (\n existingResult &&\n !this.isFrontendPlaceholderResult(existingResult)\n ) {\n if (\n executableTool &&\n executableTool.followUp !== false &&\n agent.pendingInterrupts?.some(\n (interrupt) =>\n interrupt.reason === \"tool_call\" &&\n interrupt.toolCallId === toolCall.id,\n )\n )\n needsFollowUp = true;\n continue;\n }\n // Handlerless frontend tools (e.g. chart components) must recreate\n // missing empty results using their original call IDs. Handlers still\n // run only for HITL prompts or an explicit \"resume-pending\" opt-in,\n // so restoring history never repeats other tools' side effects.\n if (\n toolExecutionMode === \"restore\" &&\n (!executableTool ||\n (executableTool.handler &&\n executableTool.type !== \"human-in-the-loop\" &&\n executableTool.reconnectBehavior !== \"resume-pending\"))\n ) {\n continue;\n }\n if (\n existingResult &&\n this.isFrontendPlaceholderResult(existingResult) &&\n (toolExecutionMode === \"restore\" || executableTool?.handler)\n ) {\n if (existingResultIndex !== -1)\n newMessages.splice(existingResultIndex, 1);\n existingResult = undefined;\n\n const agentMsgIdx = agent.messages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n );\n if (agentMsgIdx !== -1) {\n agent.messages.splice(agentMsgIdx, 1);\n }\n }\n\n if (!existingResult) {\n executing.add(executionKey);\n // Live HITL handlers need the same thread-switch cancellation as\n // restored ones, so returning to this thread can open a fresh UI.\n const interactionController =\n toolExecutionMode === \"all\" &&\n executableTool?.type === \"human-in-the-loop\"\n ? new AbortController()\n : undefined;\n const interactions = this._interactionAbortControllers.get(\n agent,\n ) ?? {\n threadId: threadId ?? null,\n controllers: new Set<AbortController>(),\n };\n const abortInteraction = () => {\n if (!interactionController) return;\n const stopConnectionGeneration =\n this._connectionGenerations.get(agent);\n liveHITLStops.set(\n interactionController.signal,\n () =>\n this._connectionGenerations.get(agent) ===\n stopConnectionGeneration && agent.threadId === threadId,\n );\n interactionController.abort();\n };\n if (interactionController) {\n interactions.controllers.add(interactionController);\n this._interactionAbortControllers.set(agent, interactions);\n signal?.addEventListener(\"abort\", abortInteraction, {\n once: true,\n });\n if (signal?.aborted) abortInteraction();\n }\n const executionSignal = interactionController?.signal ?? signal;\n const discardOnAbort =\n toolExecutionMode === \"restore\" || !!interactionController;\n try {\n if (tool) {\n const followUp = await this.executeSpecificTool(\n tool,\n toolCall,\n message,\n agent,\n agentId,\n executionSignal,\n discardOnAbort,\n toolExecutionMode === \"restore\",\n );\n if (followUp) {\n ownsHandlerFollowUp ||= !!tool.handler;\n needsFollowUp = true;\n }\n } else {\n const fallbackTool = getWildcardTool();\n if (fallbackTool) {\n const followUp = await this.executeWildcardTool(\n fallbackTool,\n toolCall,\n message,\n agent,\n agentId,\n executionSignal,\n discardOnAbort,\n toolExecutionMode === \"restore\",\n );\n if (followUp) {\n ownsHandlerFollowUp ||= !!fallbackTool.handler;\n needsFollowUp = true;\n }\n }\n }\n } finally {\n executing.delete(executionKey);\n if (interactionController) {\n signal?.removeEventListener(\"abort\", abortInteraction);\n interactions.controllers.delete(interactionController);\n if (\n interactions.controllers.size === 0 &&\n this._interactionAbortControllers.get(agent) === interactions\n ) {\n this._interactionAbortControllers.delete(agent);\n }\n }\n }\n if (interactionController?.signal.aborted) return runAgentResult;\n }\n }\n }\n }\n\n if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) {\n // Circuit breaker: bail out instead of recursing once the follow-up\n // chain exceeds an absolute safety cap. `_runDepths` holds this agent's\n // current depth of nested runAgent calls (it is incremented in runAgent and\n // decremented in its finally block), so a runaway loop — repeated\n // identical tool calls, a backend that keeps erroring after tool\n // results, reprocessed tool messages, etc. — eventually trips this\n // guard rather than looping forever and exhausting API quota.\n if ((this._runDepths.get(agent) ?? 0) >= MAX_FOLLOW_UP_DEPTH) {\n logger.warn(\n `[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent \"${agentId}\". ` +\n `Stopping recursive follow-up runs to prevent an infinite loop. ` +\n `This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly ` +\n `calling the same tool). Consider setting \"followUp: false\" on the offending tool.`,\n );\n } else {\n // Yield to the framework scheduler before the follow-up run so that any\n // deferred state updates (e.g. React useEffect in useAgentContext) can\n // complete and write fresh values into the context store before runAgent\n // reads it. The base implementation is a no-op; React overrides this.\n await this._internal.waitForPendingFrameworkUpdates();\n if (\n signal?.aborted ||\n agent.threadId !== threadId ||\n this._runGenerations.get(agent) !== runGeneration ||\n (connectionGeneration &&\n !ownsHandlerFollowUp &&\n this._connectionGenerations.get(agent) !== connectionGeneration) ||\n (interruptState && ɵgetAgentInterruptState(agent) !== interruptState)\n )\n return runAgentResult;\n\n if (\n toolExecutionMode === \"restore\" &&\n !messagesToProcess.some((message) =>\n this.isInLatestUserTurn(agent.messages, message.id),\n )\n ) {\n return runAgentResult;\n }\n let resume: ResumeEntry[] | undefined;\n if (agent.pendingInterrupts?.length) {\n // The shared state requires an explicit decision for failed results,\n // including Stop, while retaining decisions made before handlers finish.\n const decision = ɵgetAgentInterruptState(agent).resumeWithToolResults(\n agent.messages,\n );\n // A completed frontend call is not permission to answer a native\n // approval or a child question. Keep the full interrupt set pending.\n if (decision.kind !== \"resume\") return runAgentResult;\n resume = decision.resume;\n for (const result of decision.toolResults) {\n agent.addMessage({ id: randomUUID(), role: \"tool\", ...result });\n }\n }\n const continuationHandoff =\n this._internal.stateManager.markNextRunAsContinuation(agent, runId);\n return await this.runAgent(\n {\n agent,\n ...(runId !== undefined ? { runId } : {}),\n ...(resume ? { resume } : {}),\n },\n continuationHandoff,\n runController,\n );\n }\n }\n\n void this._internal.suggestionEngine.reloadSuggestions(agentId);\n\n return runAgentResult;\n }\n\n /** A later user message supersedes pending work from an older turn. */\n private isInLatestUserTurn(messages: Message[], messageId: string): boolean {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"user\") return false;\n if (message?.id === messageId) return true;\n }\n return false;\n }\n\n /** Locate a missing result before saved results for later calls in its batch. */\n private toolResultInsertionIndex(\n messages: Message[],\n messageIndex: number,\n toolCallId: string,\n ): number {\n const parent = messages[messageIndex];\n const calls = parent?.role === \"assistant\" ? (parent.toolCalls ?? []) : [];\n const callIndex = calls.findIndex((call) => call.id === toolCallId);\n let insertAt = messageIndex + 1;\n while (insertAt < messages.length) {\n const result = messages[insertAt];\n if (result?.role !== \"tool\") break;\n const resultIndex = calls.findIndex(\n (call) => call.id === result.toolCallId,\n );\n // Results from earlier batches may follow this assistant in replayed\n // history. Preserve their position; only stop for a later sibling call.\n if (resultIndex > callIndex) break;\n insertAt++;\n }\n return insertAt;\n }\n\n /** Identify transport placeholders that must not count as completed answers. */\n private isFrontendPlaceholderResult(message: Message): boolean {\n return (\n message.role === \"tool\" && isForwardedToClientPlaceholder(message.content)\n );\n }\n\n /**\n * Shared handler execution logic used by executeSpecificTool, executeWildcardTool, and runTool.\n * Handles arg parsing, subscriber notifications, handler invocation, result stringification,\n * and error handling.\n */\n private async executeToolHandler({\n tool,\n toolCall,\n agent,\n agentId,\n handlerArgs,\n toolType,\n messageId,\n signal = this.latestRunSignal(agent),\n discardOnAbort = false,\n isReplay = false,\n }: {\n tool: FrontendTool<any>;\n toolCall: { id: string; function: { name: string; arguments: string } };\n agent: AbstractAgent;\n agentId: string;\n handlerArgs: unknown;\n toolType: string;\n messageId?: string;\n signal?: AbortSignal;\n discardOnAbort?: boolean;\n isReplay?: boolean;\n }): Promise<ExecuteToolHandlerResult> {\n let toolCallResult: string | ContentPart[] = \"\";\n let toolCallText = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n\n let parsedArgs: unknown;\n try {\n parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(parseError);\n isArgumentError = true;\n await this._internal.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: handlerArgs,\n toolType,\n ...(messageId ? { messageId } : {}),\n },\n });\n }\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId,\n toolName: toolCall.function.name,\n args: parsedArgs,\n }),\n \"Subscriber onToolExecutionStart error:\",\n );\n\n if (!errorMessage) {\n try {\n const result = await tool.handler!(parsedArgs as any, {\n toolCall: toolCall as any,\n agent,\n signal,\n ...(isReplay ? { isReplay } : {}),\n });\n ({ content: toolCallResult, text: toolCallText } =\n toToolResultContent(result));\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(handlerError);\n if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) {\n await this._internal.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs,\n toolType,\n ...(messageId ? { messageId } : {}),\n },\n });\n }\n }\n }\n\n if (errorMessage) {\n toolCallResult = toolCallText = `Error: ${errorMessage}`;\n }\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallText,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\",\n );\n\n return {\n content: toolCallResult,\n result: toolCallText,\n error: errorMessage,\n isArgumentError,\n };\n }\n\n /**\n * Execute a specific tool\n */\n private async executeSpecificTool(\n tool: FrontendTool<any>,\n toolCall: ToolCall,\n message: Message,\n agent: AbstractAgent,\n agentId: string,\n signal?: AbortSignal,\n discardOnAbort = false,\n isReplay = false,\n ): Promise<boolean> {\n const threadId = agent.threadId;\n // Check if tool is constrained to a specific agent\n if (tool?.agentId && tool.agentId !== agent.agentId) {\n // Tool is not available for this agent, skip it\n return false;\n }\n\n let handlerResult: ExecuteToolHandlerResult = {\n content: \"\",\n result: \"\",\n error: undefined,\n isArgumentError: false,\n };\n\n if (tool?.handler) {\n handlerResult = await this.executeToolHandler({\n tool,\n toolCall,\n agent,\n agentId,\n handlerArgs: toolCall.function.arguments,\n toolType: \"specific\",\n messageId: message.id,\n signal,\n discardOnAbort,\n isReplay,\n });\n }\n\n {\n const messageIndex = agent.messages.findIndex((m) => m.id === message.id);\n if (\n discardAbortedResult(signal, discardOnAbort, handlerResult.error) ||\n agent.threadId !== threadId ||\n messageIndex === -1 ||\n (isReplay && !this.isInLatestUserTurn(agent.messages, message.id)) ||\n agent.messages.some(\n (m) =>\n m.role === \"tool\" &&\n m.toolCallId === toolCall.id &&\n !this.isFrontendPlaceholderResult(m),\n )\n ) {\n // The interaction was removed, the thread changed, or another client\n // already answered. Do not insert a stale answer or start a follow-up.\n return false;\n }\n const insertAt = this.toolResultInsertionIndex(\n agent.messages,\n messageIndex,\n toolCall.id,\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: handlerResult.content,\n ...(handlerResult.error ? { error: handlerResult.error } : {}),\n };\n agent.messages.splice(insertAt, 0, toolMessage);\n\n if (!handlerResult.error && tool?.followUp !== false) {\n return true; // Needs follow-up\n }\n }\n\n return false;\n }\n\n /**\n * Execute a wildcard tool.\n * Wildcard tools receive args wrapped as `{toolName, args}`, which differs from\n * specific tools, so this method keeps its own arg-wrapping logic rather than\n * delegating to `executeToolHandler`.\n */\n private async executeWildcardTool(\n wildcardTool: FrontendTool<any>,\n toolCall: ToolCall,\n message: Message,\n agent: AbstractAgent,\n agentId: string,\n signal?: AbortSignal,\n discardOnAbort = false,\n isReplay = false,\n ): Promise<boolean> {\n const threadId = agent.threadId;\n // Check if wildcard tool is constrained to a specific agent\n if (wildcardTool?.agentId && wildcardTool.agentId !== agent.agentId) {\n // Wildcard tool is not available for this agent, skip it\n return false;\n }\n\n let toolCallResult: string | ContentPart[] = \"\";\n let toolCallText = \"\";\n let errorMessage: string | undefined;\n\n if (wildcardTool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = parseToolArguments(\n toolCall.function.arguments,\n toolCall.function.name,\n );\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(parseError);\n await this._internal.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n\n const wildcardArgs = {\n toolName: toolCall.function.name,\n args: parsedArgs,\n };\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId: agentId,\n toolName: toolCall.function.name,\n args: wildcardArgs,\n }),\n \"Subscriber onToolExecutionStart error:\",\n );\n\n if (!errorMessage) {\n try {\n const result = await wildcardTool.handler(wildcardArgs as any, {\n toolCall,\n agent,\n // Use the same execution signal as named tools, including the\n // replay-specific signal when restoring a wildcard HITL handler.\n signal,\n ...(isReplay ? { isReplay } : {}),\n });\n ({ content: toolCallResult, text: toolCallText } =\n toToolResultContent(result));\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(handlerError);\n if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) {\n await this._internal.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs: wildcardArgs,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n }\n }\n\n if (errorMessage) {\n toolCallResult = toolCallText = `Error: ${errorMessage}`;\n }\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId: agentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallText,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\",\n );\n }\n\n {\n const messageIndex = agent.messages.findIndex((m) => m.id === message.id);\n if (\n discardAbortedResult(signal, discardOnAbort, errorMessage) ||\n agent.threadId !== threadId ||\n messageIndex === -1 ||\n (isReplay && !this.isInLatestUserTurn(agent.messages, message.id)) ||\n agent.messages.some(\n (m) =>\n m.role === \"tool\" &&\n m.toolCallId === toolCall.id &&\n !this.isFrontendPlaceholderResult(m),\n )\n ) {\n // The interaction was removed, the thread changed, or another client\n // already answered. Do not insert a stale answer or start a follow-up.\n return false;\n }\n const insertAt = this.toolResultInsertionIndex(\n agent.messages,\n messageIndex,\n toolCall.id,\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n ...(errorMessage ? { error: errorMessage } : {}),\n };\n agent.messages.splice(insertAt, 0, toolMessage);\n\n if (!errorMessage && wildcardTool?.followUp !== false) {\n return true; // Needs follow-up\n }\n }\n\n return false;\n }\n\n /**\n * Programmatically execute a registered frontend tool without going through an LLM turn.\n * The handler runs, render components show up in the UI, and both the tool call and\n * result messages are added to `agent.messages`.\n */\n async runTool(\n params: CopilotKitCoreRunToolParams,\n ): Promise<CopilotKitCoreRunToolResult> {\n const { name, agentId, parameters = {}, followUp = false } = params;\n\n // 1. Look up the tool\n const tool = this.getTool({ toolName: name, agentId });\n if (!tool) {\n const error = new Error(`Tool not found: ${name}`);\n await this._internal.emitError({\n error,\n code: CopilotKitCoreErrorCode.TOOL_NOT_FOUND,\n context: { toolName: name, agentId },\n });\n throw error;\n }\n\n // 2. Look up the agent\n const resolvedAgentId = agentId ?? \"default\";\n const agent = this._internal.getAgent(resolvedAgentId);\n if (!agent) {\n const error = new Error(`Agent not found: ${resolvedAgentId}`);\n await this._internal.emitError({\n error,\n code: CopilotKitCoreErrorCode.AGENT_NOT_FOUND,\n context: { agentId: resolvedAgentId },\n });\n throw error;\n }\n\n // 3. Create assistant message with tool call\n const toolCallId = randomUUID();\n const assistantToolCall = {\n id: toolCallId,\n type: \"function\" as const,\n function: {\n name,\n arguments: JSON.stringify(parameters),\n },\n };\n const assistantMessage: Message = {\n id: randomUUID(),\n role: \"assistant\",\n content: \"\",\n toolCalls: [assistantToolCall],\n };\n\n // 4. Push assistant message into agent's messages\n agent.messages.push(assistantMessage);\n\n // 5. Execute the tool handler (if it has one)\n let handlerResult: ExecuteToolHandlerResult = {\n content: \"\",\n result: \"\",\n error: undefined,\n isArgumentError: false,\n };\n\n if (tool.handler) {\n handlerResult = await this.executeToolHandler({\n tool,\n toolCall: assistantToolCall,\n agent,\n agentId: resolvedAgentId,\n handlerArgs: parameters,\n toolType: \"runTool\",\n });\n }\n\n // 6. Create and insert tool result message\n const toolResultMessage: Message = {\n id: randomUUID(),\n role: \"tool\",\n toolCallId,\n content: handlerResult.content,\n ...(handlerResult.error ? { error: handlerResult.error } : {}),\n };\n\n const assistantIndex = agent.messages.findIndex(\n (m) => m.id === assistantMessage.id,\n );\n if (assistantIndex !== -1) {\n agent.messages.splice(assistantIndex + 1, 0, toolResultMessage);\n } else {\n // Fallback: push to end if assistant message was removed\n agent.messages.push(toolResultMessage);\n }\n\n // 7. Handle followUp (only if no error)\n if (!handlerResult.error && followUp !== false) {\n if (typeof followUp === \"string\" && followUp !== \"generate\") {\n // Custom text: add a user message first\n const userMessage: Message = {\n id: randomUUID(),\n role: \"user\",\n content: followUp,\n };\n agent.messages.push(userMessage);\n }\n // Yield to the framework scheduler so deferred state updates (e.g. React\n // useEffect in useAgentContext) can complete before the follow-up run reads\n // the context store. Mirrors the same yield in processAgentResult.\n await this._internal.waitForPendingFrameworkUpdates();\n // Trigger agent run for both \"generate\" and custom text\n await this.runAgent({ agent });\n }\n\n // 8. Return result\n return {\n toolCallId,\n result: handlerResult.result,\n error: handlerResult.error,\n };\n }\n\n /** Stable identity for a tool override: agent-scope + name (NUL-separated). */\n private capabilityKey(name: string, agentId?: string): string {\n return `${agentId ?? \"\"}\\u0000${name}`;\n }\n\n /**\n * Enable/disable a registered frontend tool at runtime without unregistering\n * it. A disabled tool is omitted from {@link buildFrontendTools}, so the agent\n * never receives it. Unlike the per-tool `available` flag, this override\n * survives the tool being re-registered.\n */\n setToolEnabled(name: string, enabled: boolean, agentId?: string): void {\n const key = this.capabilityKey(name, agentId);\n if (enabled) {\n this._disabledToolKeys.delete(key);\n } else {\n this._disabledToolKeys.add(key);\n }\n this.syncWebMCP();\n }\n\n /** Whether a tool is currently enabled (not overridden off). Defaults true. */\n isToolEnabled(name: string, agentId?: string): boolean {\n return !this._disabledToolKeys.has(this.capabilityKey(name, agentId));\n }\n\n /**\n * Build frontend tools for an agent\n */\n buildFrontendTools(agentId?: string): Tool[] {\n return this.tools\n .filter(\n (tool) =>\n // A wildcard tool is a local catch-all handler (see\n // `executeWildcardTool`), not something the model can call —\n // advertising it would offer the agent a tool named `*`.\n tool.name !== WILDCARD_TOOL_NAME &&\n tool.available !== false &&\n (tool.available as boolean | string | undefined) !== \"disabled\" &&\n (!tool.agentId || tool.agentId === agentId) &&\n this.isToolEnabled(tool.name, tool.agentId),\n )\n .map((tool) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n parameters: createToolSchema(tool),\n }));\n }\n\n /**\n * Reconcile the WebMCP registrations with the current tool registry. Tools\n * opt in via `webmcp: true` or `webmcp: { annotations }`; the same\n * availability rules as `buildFrontendTools` apply. WebMCP tools are\n * page-level, so unlike the agent tool list they are not filtered by\n * agentId — a name collision across agentIds keeps the first registration.\n */\n private syncWebMCP(): void {\n const desired = new Map<string, FrontendTool<any>>();\n const warnedCollisions = new Set<string>();\n for (const tool of this.tools) {\n if (!tool.webmcp) {\n continue;\n }\n if (tool.name === WILDCARD_TOOL_NAME) {\n continue;\n }\n if (\n tool.available === false ||\n (tool.available as boolean | string | undefined) === \"disabled\"\n ) {\n continue;\n }\n if (!this.isToolEnabled(tool.name, tool.agentId)) {\n continue;\n }\n if (desired.has(tool.name)) {\n if (!warnedCollisions.has(tool.name)) {\n warnedCollisions.add(tool.name);\n logger.warn(\n `[CopilotKit] Multiple WebMCP tools share the name '${tool.name}'. ` +\n `Only the first registration is exposed to browser agents.`,\n );\n }\n continue;\n }\n desired.set(tool.name, tool);\n }\n this._webmcpRegistry.sync(desired);\n }\n\n /**\n * Create an agent error subscriber\n */\n private createAgentErrorSubscriber(\n agent: AbstractAgent,\n runSignal?: AbortSignal,\n ): AgentSubscriber {\n const emitAgentError = async (\n error: Error,\n code: CopilotKitCoreErrorCode,\n extraContext: Record<string, any> = {},\n ) => {\n const context: Record<string, any> = { ...extraContext };\n if (agent.agentId) {\n context.agentId = agent.agentId;\n }\n await this._internal.emitError({\n error,\n code,\n context,\n });\n };\n\n return {\n onRunFailed: async ({ error }: { error: Error }) => {\n const code =\n error instanceof AgentThreadLockedError\n ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED\n : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT;\n await emitAgentError(error, code, {\n source: \"onRunFailed\",\n });\n },\n onRunErrorEvent: async ({ event }) => {\n // A user-initiated stop (stopAgent / agent.abortRun) makes the agent\n // emit a terminal RUN_ERROR — often code \"abort\" — as its cancellation\n // signal. That is expected, not a failure: surfacing it would pop an\n // error banner on Stop (#5966, follow-up to #5812). Mirror the\n // local-abort suppression on the runAgent/connectAgent paths and skip\n // it. Prefer the abort controller (the client's own record that it\n // initiated the stop) over the agent-supplied `code`, which is not\n // standardized across agents.\n // Only this run's own signal counts: a connect has none, and another\n // run on the same agent being stopped says nothing about this error.\n const runWasAborted = runSignal?.aborted ?? false;\n if (runWasAborted || event?.code === \"abort\") {\n return;\n }\n\n // The SSE runtime rejected the run because the thread already has\n // one in flight. Report it like Intelligence's 409 so one onError\n // branch covers both transports.\n if (event?.code === THREAD_ALREADY_RUNNING_ERROR_CODE) {\n await emitAgentError(\n new AgentThreadLockedError(agent.threadId),\n CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED,\n { source: \"onRunErrorEvent\", event },\n );\n return;\n }\n\n const eventError =\n event?.rawEvent instanceof Error\n ? event.rawEvent\n : event?.rawEvent?.error instanceof Error\n ? event.rawEvent.error\n : undefined;\n\n const errorMessage =\n typeof event?.rawEvent?.error === \"string\"\n ? event.rawEvent.error\n : (event?.message ?? \"Agent run error\");\n\n const rawError = eventError ?? new Error(errorMessage);\n\n if (event?.code && !(rawError as any).code) {\n (rawError as any).code = event.code;\n }\n\n await emitAgentError(\n rawError,\n CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,\n {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\n },\n );\n },\n };\n }\n}\n\n/**\n * Ensures parsed tool arguments are a plain object.\n * Throws for non-object values so the caller's catch block can emit\n * a structured TOOL_ARGUMENT_PARSE_FAILED error.\n *\n * @internal Exported for testing only.\n */\nexport function ensureObjectArgs(\n parsed: unknown,\n toolName: string,\n): Record<string, unknown> {\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n throw new Error(\n `Tool arguments for ${toolName} parsed to non-object (${typeof parsed})`,\n );\n}\n\n/**\n * Parses raw tool call arguments into a validated object.\n *\n * Some LLM providers (e.g. @ai-sdk/openai-compatible) may send empty string \"\",\n * null, or undefined instead of \"{}\". This function normalises those cases to an\n * empty object so callers don't crash on JSON.parse(\"\").\n *\n * A debug-level warning is emitted when the fallback triggers so silent coercion\n * is observable in logs.\n *\n * @internal Exported for testing only.\n */\nexport function parseToolArguments(\n rawArgs: unknown,\n toolName: string,\n): Record<string, unknown> {\n if (rawArgs === \"\" || rawArgs === null || rawArgs === undefined) {\n logger.debug(\n `[parseToolArguments] Tool \"${toolName}\" received empty/null/undefined arguments — defaulting to {}`,\n );\n return {};\n }\n const parsed = typeof rawArgs === \"string\" ? JSON.parse(rawArgs) : rawArgs;\n return ensureObjectArgs(parsed, toolName);\n}\n","import type {\n AbstractAgent,\n Message,\n State,\n RunAgentInput,\n StateSnapshotEvent,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n TextMessageStartEvent,\n ToolCallResultEvent,\n ToolMessage,\n} from \"@ag-ui/client\";\nimport { randomUUID, structuredClone_ } from \"@ag-ui/client\";\nimport type { CopilotKitCore } from \"./core\";\nimport { isForwardedToClientPlaceholder } from \"./tool-result-content\";\n\nconst isContinuation = (\n input: Pick<RunAgentInput, \"resume\" | \"forwardedProps\">,\n): boolean =>\n input.resume !== undefined ||\n Object.prototype.hasOwnProperty.call(\n (input.forwardedProps as { command?: object } | undefined)?.command ?? {},\n \"resume\",\n );\n\nexport interface CopilotKitCoreContinuationHandoff {\n cancel(): void;\n bind(input: object): void;\n}\n\ninterface PendingContinuation extends CopilotKitCoreContinuationHandoff {\n expectedInput?: object;\n active: boolean;\n /**\n * The logical run id this continuation belongs to. Events arriving on the\n * continuation are re-stamped with it, so the run reads as ONE run to\n * everything downstream (state/message association, external tracing) even\n * though the transport minted a fresh id for the follow-up invocation.\n */\n expectedRunId?: string;\n}\n\n/**\n * Manages state and message tracking by run for CopilotKitCore.\n * Tracks agent state snapshots and message-to-run associations.\n */\nexport class StateManager {\n // State tracking: agentId -> threadId -> runId -> state\n private stateByRun: Map<string, Map<string, Map<string, State>>> = new Map();\n\n // Message tracking: agentId -> threadId -> messageId -> runId\n private messageToRun: Map<string, Map<string, Map<string, string>>> =\n new Map();\n\n // Direct text-start metadata: agentId -> threadId -> messageId -> rawEvent\n private rawEventByMessage: Map<string, Map<string, Map<string, unknown>>> =\n new Map();\n\n // Active run tracking: `agentId:threadId` -> runId (used when messages arrive without input)\n private activeRun: Map<string, string> = new Map();\n\n private agentSubscriptions: Map<\n string,\n { agent: AbstractAgent; unsubscribe: () => void }\n > = new Map();\n\n // Internal follow-ups are marked in memory so the marker never reaches a\n // runtime or becomes user-controlled forwardedProps data.\n private pendingContinuations = new WeakMap<\n AbstractAgent,\n Set<PendingContinuation>\n >();\n\n private interruptedRuns = new WeakMap<\n AbstractAgent,\n Map<string, { runId: string; interruptIds: string[] | null }>\n >();\n\n /** Find the interrupted logical run without consuming its pending answers. */\n getContinuationRunId(\n agent: AbstractAgent,\n input: Pick<RunAgentInput, \"threadId\" | \"resume\" | \"forwardedProps\">,\n ) {\n const pending = this.interruptedRuns.get(agent)?.get(input.threadId);\n if (!pending) return undefined;\n if (pending.interruptIds === null) {\n return input.resume === undefined && isContinuation(input)\n ? pending.runId\n : undefined;\n }\n const submitted = new Set(input.resume?.map((entry) => entry.interruptId));\n const matches =\n submitted.size > 0 &&\n submitted.size === input.resume?.length &&\n submitted.size === pending.interruptIds.length &&\n pending.interruptIds.every((id) => submitted.has(id));\n return matches ? pending.runId : undefined;\n }\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Initialize state tracking for an agent\n */\n initialize(): void {\n // Will be called when CopilotKitCore is initialized\n }\n\n markNextRunAsContinuation(\n agent: AbstractAgent,\n expectedRunId?: string,\n ): CopilotKitCoreContinuationHandoff {\n let pendingForAgent = this.pendingContinuations.get(agent);\n if (!pendingForAgent) {\n pendingForAgent = new Set();\n this.pendingContinuations.set(agent, pendingForAgent);\n }\n\n const pending: PendingContinuation = {\n active: true,\n expectedRunId,\n bind: (input) => {\n if (pending.active) pending.expectedInput = input;\n },\n cancel: () => {\n if (!pending.active) return;\n pending.active = false;\n pendingForAgent!.delete(pending);\n if (pendingForAgent!.size === 0) {\n this.pendingContinuations.delete(agent);\n }\n },\n };\n pendingForAgent.add(pending);\n return pending;\n }\n\n /**\n * Subscribe to an agent's events to track state and messages.\n */\n subscribeToAgent(agent: AbstractAgent): void {\n if (!agent.agentId) {\n return; // Skip agents without IDs\n }\n\n const agentId = agent.agentId;\n\n const existing = this.agentSubscriptions.get(agentId);\n if (existing) {\n if (existing.agent === agent) {\n return;\n }\n existing.unsubscribe();\n this.agentSubscriptions.delete(agentId);\n }\n\n // Subscribe to agent events.\n //\n // Two invariants this subscription must uphold:\n //\n // 1. Revocation: the ag-ui pipeline captures `o = [...agent.subscribers]` at\n // runAgent() start. If this subscription is replaced by a newer one before\n // the pipeline finishes, the old pipeline may still call these callbacks\n // with the old input.runId. `revoked = true` turns them into no-ops once\n // the replacement subscription is in place. Only a replacement revokes —\n // see the same-instance guard above.\n //\n // 2. Run isolation within one subscription: in tests (and edge cases), a new\n // run's events can arrive through the same subscription before the new\n // pipeline is set up. An explicit standard or legacy resume input is a\n // continuation, so only an ordinary new run gets a fresh ID after\n // RUN_FINISHED.\n let revoked = false;\n let subRunId: string | undefined; // runId assigned to the current logical run\n let legacyInterrupted = false;\n let runFinished = false; // true after RUN_FINISHED, reset on next RUN_STARTED\n const pendingResults = new WeakMap<\n RunAgentInput,\n Map<string, ToolCallResultEvent>\n >();\n\n const reconcilePendingResults = (\n historyMessages: readonly Message[],\n input: RunAgentInput,\n ): { messages: Message[] } | undefined => {\n const events = pendingResults.get(input);\n if (!events) return undefined;\n\n const messages = [...historyMessages];\n let changed = false;\n\n for (const event of events.values()) {\n const ownerIndex = messages.findIndex(\n (message) =>\n message.role === \"assistant\" &&\n message.toolCalls?.some(\n (toolCall) => toolCall.id === event.toolCallId,\n ),\n );\n if (ownerIndex < 0) continue;\n\n const matchingIndexes = messages.reduce<number[]>(\n (indexes, message, index) => {\n if (\n message.role === \"tool\" &&\n message.toolCallId === event.toolCallId\n ) {\n indexes.push(index);\n }\n return indexes;\n },\n [],\n );\n const realIndex = matchingIndexes.find(\n (index) => !isForwardedToClientPlaceholder(messages[index]?.content),\n );\n if (realIndex !== undefined) {\n for (const duplicateIndex of matchingIndexes\n .filter((candidateIndex) => candidateIndex !== realIndex)\n .sort((a, b) => b - a)) {\n messages.splice(duplicateIndex, 1);\n changed = true;\n }\n continue;\n }\n\n const placeholderIndex = matchingIndexes.find((index) =>\n isForwardedToClientPlaceholder(messages[index]?.content),\n );\n if (placeholderIndex !== undefined) {\n if (isForwardedToClientPlaceholder(event.content)) {\n for (const duplicateIndex of matchingIndexes\n .slice(1)\n .sort((a, b) => b - a)) {\n messages.splice(duplicateIndex, 1);\n changed = true;\n }\n continue;\n }\n messages[placeholderIndex] = {\n ...messages[placeholderIndex],\n id: event.messageId,\n content: event.content,\n } as ToolMessage;\n changed = true;\n for (const duplicateIndex of matchingIndexes\n .filter(\n (candidateIndex) =>\n candidateIndex !== placeholderIndex &&\n isForwardedToClientPlaceholder(\n messages[candidateIndex]?.content,\n ),\n )\n .sort((a, b) => b - a)) {\n messages.splice(duplicateIndex, 1);\n }\n continue;\n }\n\n const result: ToolMessage = {\n id: event.messageId,\n role: \"tool\",\n toolCallId: event.toolCallId,\n content: event.content,\n };\n let insertIndex = ownerIndex + 1;\n while (messages[insertIndex]?.role === \"tool\") insertIndex++;\n messages.splice(insertIndex, 0, result);\n changed = true;\n }\n\n return changed ? { messages } : undefined;\n };\n\n const clearPendingResults = (input: RunAgentInput): void => {\n pendingResults.delete(input);\n };\n\n const effectiveInput = (input: RunAgentInput): RunAgentInput => ({\n ...input,\n runId: subRunId ?? input.runId,\n });\n\n const { unsubscribe } = agent.subscribe({\n onRunStartedEvent: ({ event, input, state }) => {\n if (revoked) return;\n const pendingForAgent = this.pendingContinuations.get(agent);\n const internalContinuation = [...(pendingForAgent ?? [])].find(\n (pending) => pending.expectedInput === input,\n );\n internalContinuation?.cancel();\n const startedInput = event.input ?? {\n ...input,\n threadId: event.threadId,\n };\n const resumedRunId = this.getContinuationRunId(agent, startedInput);\n this.interruptedRuns.get(agent)?.delete(startedInput.threadId);\n legacyInterrupted = false;\n\n if (internalContinuation) {\n // An internal continuation re-stamps onto the run id it continues, so\n // the follow-up does not have to reuse that id on the wire.\n subRunId =\n internalContinuation.expectedRunId ?? event.runId ?? input.runId;\n } else if (resumedRunId) {\n subRunId = resumedRunId;\n } else if (\n runFinished &&\n input.runId === subRunId &&\n !isContinuation(input) &&\n (event.runId == null || event.runId === subRunId)\n ) {\n // A new logical run's events are arriving through this same (old)\n // subscription. This happens when the test emits events before\n // copilotkit.runAgent() has had a chance to set up the new pipeline:\n // the old pipeline reuses input1.runId for all events, so\n // input.runId equals the previous run's runId. Generate a fresh\n // runId so the new run's state doesn't collide with the old one.\n subRunId = randomUUID();\n } else {\n // A connect replay may contain multiple server runs under one input.runId.\n subRunId = event.runId || input.runId;\n }\n runFinished = false;\n this.handleRunStarted(agent, effectiveInput(input), state);\n },\n onRunFinishedEvent: ({ event, input, state, messages }) => {\n if (revoked) return;\n runFinished = true;\n const effective = effectiveInput(input);\n let interrupted = this.interruptedRuns.get(agent);\n if (event.outcome?.type === \"interrupt\" || legacyInterrupted) {\n if (!interrupted) {\n interrupted = new Map();\n this.interruptedRuns.set(agent, interrupted);\n }\n interrupted.set(event.threadId, {\n runId: effective.runId,\n interruptIds:\n event.outcome?.type === \"interrupt\"\n ? event.outcome.interrupts.map((interrupt) => interrupt.id)\n : null,\n });\n } else {\n interrupted?.delete(event.threadId);\n }\n const mutation = reconcilePendingResults(messages, input);\n clearPendingResults(input);\n this.handleRunFinished(agent, effective, state);\n return mutation;\n },\n onCustomEvent: ({ event }) => {\n if (!revoked && event.name === \"on_interrupt\") legacyInterrupted = true;\n },\n // A run error terminates the run — treat identically to finished for cleanup\n onRunErrorEvent: ({ input, state, messages }) => {\n if (revoked) return;\n runFinished = true;\n const effective = effectiveInput(input);\n const mutation = reconcilePendingResults(messages, input);\n this.handleRunFinished(agent, effective, state);\n return mutation;\n },\n onRunFailed: ({ input, messages }) => {\n if (revoked) return;\n return reconcilePendingResults(messages, input);\n },\n onRunFinalized: ({ input }) => {\n if (revoked) return;\n clearPendingResults(input);\n },\n onToolCallResultEvent: ({ event, input }) => {\n if (revoked) return;\n let events = pendingResults.get(input);\n if (!events) {\n events = new Map();\n pendingResults.set(input, events);\n }\n events.set(event.toolCallId, event);\n },\n onStateSnapshotEvent: ({ event, input, state }) => {\n if (revoked) return;\n this.handleStateSnapshot(agent, event, effectiveInput(input), state);\n },\n onStateDeltaEvent: ({ event, input, state }) => {\n if (revoked) return;\n this.handleStateDelta(agent, event, effectiveInput(input), state);\n },\n onTextMessageStartEvent: ({ event, input }) => {\n if (revoked) return;\n this.handleTextMessageStart(agent, event, effectiveInput(input));\n },\n onMessagesSnapshotEvent: ({ event, input, messages }) => {\n if (revoked) return;\n this.handleMessagesSnapshot(\n agent,\n event,\n effectiveInput(input),\n messages,\n );\n this.pruneRawEvents(\n agent.agentId!,\n input.threadId,\n event.messages,\n effectiveInput(input),\n );\n },\n onNewMessage: ({ message, input }) => {\n if (revoked) return;\n this.handleNewMessage(\n agent,\n message,\n input ? effectiveInput(input) : undefined,\n );\n },\n onMessagesChanged: ({ messages, input }) => {\n if (revoked) return;\n if (!input) {\n this.pruneRawEvents(agent.agentId!, agent.threadId, messages);\n }\n },\n });\n\n this.agentSubscriptions.set(agentId, {\n agent,\n unsubscribe: () => {\n revoked = true;\n this.pendingContinuations.delete(agent);\n this.interruptedRuns.delete(agent);\n unsubscribe();\n },\n });\n }\n\n /**\n * Unsubscribe an agent's subscription.\n */\n unsubscribeFromAgent(agentId: string): void {\n const existing = this.agentSubscriptions.get(agentId);\n if (existing) {\n existing.unsubscribe();\n this.agentSubscriptions.delete(agentId);\n }\n this.rawEventByMessage.delete(agentId);\n }\n\n /**\n * Get state for a specific run\n * Returns a deep copy to prevent external mutations\n */\n getStateByRun(\n agentId: string,\n threadId: string,\n runId: string,\n ): State | undefined {\n const state = this.stateByRun.get(agentId)?.get(threadId)?.get(runId);\n if (!state) return undefined;\n // Return a deep copy to prevent mutations\n return JSON.parse(JSON.stringify(state));\n }\n\n /**\n * Get runId associated with a message\n */\n getRunIdForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): string | undefined {\n return this.messageToRun.get(agentId)?.get(threadId)?.get(messageId);\n }\n\n /**\n * Get direct text-start metadata associated with a message.\n */\n getRawEventForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): unknown {\n const rawEvent = this.rawEventByMessage\n .get(agentId)\n ?.get(threadId)\n ?.get(messageId);\n return rawEvent === undefined ? undefined : structuredClone_(rawEvent);\n }\n\n /**\n * Get all states for an agent's thread\n */\n getStatesForThread(agentId: string, threadId: string): Map<string, State> {\n return this.stateByRun.get(agentId)?.get(threadId) ?? new Map();\n }\n\n /**\n * Get all run IDs for an agent's thread\n */\n getRunIdsForThread(agentId: string, threadId: string): string[] {\n const threadStates = this.stateByRun.get(agentId)?.get(threadId);\n return threadStates ? Array.from(threadStates.keys()) : [];\n }\n\n /**\n * Handle run started event\n */\n private handleRunStarted(\n agent: AbstractAgent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n this.activeRun.set(`${agent.agentId}:${threadId}`, runId);\n // Only persist state when it carries real data. An empty {} from an\n // initial-state-less run would cause getStateByRun to return {} instead\n // of undefined, breaking renderers that rely on undefined to mean \"no\n // state snapshot received yet\".\n if (state && Object.keys(state).length > 0) {\n this.saveState(agent.agentId, threadId, runId, state);\n }\n }\n\n /**\n * Handle run finished event\n */\n private handleRunFinished(\n agent: AbstractAgent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n this.activeRun.delete(`${agent.agentId}:${threadId}`);\n if (state && Object.keys(state).length > 0) {\n this.saveState(agent.agentId, threadId, runId, state);\n }\n }\n\n /**\n * Handle state snapshot event\n */\n private handleStateSnapshot(\n agent: AbstractAgent,\n event: StateSnapshotEvent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n // Merge snapshot into current state\n const mergedState = { ...state, ...event.snapshot };\n this.saveState(agent.agentId, threadId, runId, mergedState);\n }\n\n /**\n * Handle state delta event\n */\n private handleStateDelta(\n agent: AbstractAgent,\n event: StateDeltaEvent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n // State is already updated by the agent, just save it\n this.saveState(agent.agentId, threadId, runId, state);\n }\n\n /**\n * Capture only defined metadata from a normalized direct text-start event.\n */\n private handleTextMessageStart(\n agent: AbstractAgent,\n event: TextMessageStartEvent,\n input: RunAgentInput,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId } = input;\n if (event.rawEvent === undefined) {\n const threadEvents = this.rawEventByMessage\n .get(agent.agentId)\n ?.get(threadId);\n threadEvents?.delete(event.messageId);\n if (threadEvents?.size === 0) {\n this.rawEventByMessage.get(agent.agentId)?.delete(threadId);\n }\n if (this.rawEventByMessage.get(agent.agentId)?.size === 0) {\n this.rawEventByMessage.delete(agent.agentId);\n }\n return;\n }\n\n if (!this.rawEventByMessage.has(agent.agentId)) {\n this.rawEventByMessage.set(agent.agentId, new Map());\n }\n const agentEvents = this.rawEventByMessage.get(agent.agentId)!;\n if (!agentEvents.has(threadId)) {\n agentEvents.set(threadId, new Map());\n }\n agentEvents.get(threadId)!.set(event.messageId, event.rawEvent);\n }\n\n /**\n * Handle messages snapshot event\n */\n private handleMessagesSnapshot(\n agent: AbstractAgent,\n event: MessagesSnapshotEvent,\n input: RunAgentInput,\n _messages: readonly Message[],\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n\n // Cumulative snapshots repeat messages from earlier runs, so only assign\n // messages that do not already have a run association.\n for (const message of event.messages) {\n if (\n this.getRunIdForMessage(agent.agentId, threadId, message.id) ===\n undefined\n ) {\n this.associateMessageWithRun(\n agent.agentId,\n threadId,\n message.id,\n runId,\n );\n }\n }\n }\n\n /**\n * Handle new message event\n */\n private handleNewMessage(\n agent: AbstractAgent,\n message: Message,\n input?: RunAgentInput,\n ): void {\n if (!agent.agentId) return;\n\n if (!input) {\n // ag-ui calls addMessage() without input, so input is undefined here.\n // Fall back to the currently-active run for this agent's thread.\n const threadId = agent.threadId ?? \"\";\n const runId = this.activeRun.get(`${agent.agentId}:${threadId}`);\n if (runId) {\n this.associateMessageWithRun(\n agent.agentId,\n threadId,\n message.id,\n runId,\n );\n }\n return;\n }\n\n const { threadId, runId } = input;\n this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);\n }\n\n /**\n * Save state for a specific run\n */\n private saveState(\n agentId: string,\n threadId: string,\n runId: string,\n state: State,\n ): void {\n // Ensure nested maps exist\n if (!this.stateByRun.has(agentId)) {\n this.stateByRun.set(agentId, new Map());\n }\n const agentStates = this.stateByRun.get(agentId)!;\n\n if (!agentStates.has(threadId)) {\n agentStates.set(threadId, new Map());\n }\n const threadStates = agentStates.get(threadId)!;\n\n // Deep copy the state to prevent mutations\n threadStates.set(runId, JSON.parse(JSON.stringify(state)));\n }\n\n /**\n * Associate a message with a run\n */\n private associateMessageWithRun(\n agentId: string,\n threadId: string,\n messageId: string,\n runId: string,\n ): void {\n // Ensure nested maps exist\n if (!this.messageToRun.has(agentId)) {\n this.messageToRun.set(agentId, new Map());\n }\n const agentMessages = this.messageToRun.get(agentId)!;\n\n if (!agentMessages.has(threadId)) {\n agentMessages.set(threadId, new Map());\n }\n const threadMessages = agentMessages.get(threadId)!;\n\n threadMessages.set(messageId, runId);\n }\n\n private pruneRawEvents(\n agentId: string,\n fallbackThreadId: string | undefined,\n messages: ReadonlyArray<Readonly<Message>>,\n input?: RunAgentInput,\n ): void {\n const threadId = input?.threadId ?? fallbackThreadId;\n if (!threadId) return;\n\n const threadEvents = this.rawEventByMessage.get(agentId)?.get(threadId);\n if (!threadEvents) return;\n\n const messageIds = new Set(messages.map((message) => message.id));\n for (const messageId of threadEvents.keys()) {\n if (!messageIds.has(messageId)) threadEvents.delete(messageId);\n }\n if (threadEvents.size === 0) {\n this.rawEventByMessage.get(agentId)?.delete(threadId);\n }\n if (this.rawEventByMessage.get(agentId)?.size === 0) {\n this.rawEventByMessage.delete(agentId);\n }\n }\n\n /**\n * Clear all state for an agent\n */\n clearAgentState(agentId: string): void {\n const agent = this.agentSubscriptions.get(agentId)?.agent;\n if (agent) this.interruptedRuns.delete(agent);\n this.stateByRun.delete(agentId);\n this.messageToRun.delete(agentId);\n this.rawEventByMessage.delete(agentId);\n }\n\n /**\n * Clear all state for a thread\n */\n clearThreadState(agentId: string, threadId: string): void {\n const agent = this.agentSubscriptions.get(agentId)?.agent;\n if (agent) this.interruptedRuns.get(agent)?.delete(threadId);\n this.stateByRun.get(agentId)?.delete(threadId);\n this.messageToRun.get(agentId)?.delete(threadId);\n this.rawEventByMessage.get(agentId)?.delete(threadId);\n }\n}\n","import { type ɵThreadStore } from \"../threads\";\nimport type { CopilotKitCore } from \"./core\";\nimport { CopilotKitCoreFriendsAccess, CopilotKitCoreSubscriber } from \"./core\";\n\nexport class ThreadStoreRegistry {\n private _stores: Record<string, ɵThreadStore> = {};\n // Cached frozen snapshot of `_stores`. Invalidated to `null` on every\n // `register`/`unregister` so the next `getAll()` rebuilds it. Stable\n // references between mutations matter for `useSyncExternalStore` consumers\n // that compare snapshot identity to decide whether to re-render.\n private _snapshot: Readonly<Record<string, ɵThreadStore>> | null = null;\n\n constructor(private core: CopilotKitCore) {}\n\n register(agentId: string, store: ɵThreadStore): void {\n if (agentId in this._stores) {\n // Capture the previous store before deleting it. `notifyUnregistered`\n // dispatches via `Promise.all` and returns control to this synchronous\n // body before async subscribers resume — by then `this._stores[agentId]`\n // already holds the new store, so the previous store must be forwarded\n // explicitly via the payload. Subscribers MUST NOT call\n // `registry.get(agentId)` from `onThreadStoreUnregistered` to recover\n // the previous store; use the `prevStore` field on the payload instead.\n const prevStore = this._stores[agentId]!;\n delete this._stores[agentId];\n this._snapshot = null;\n this.notifyUnregistered(agentId, prevStore).catch((err) => {\n console.error(\"ThreadStoreRegistry notifyUnregistered failed:\", err);\n });\n }\n this._stores[agentId] = store;\n this._snapshot = null;\n this.notifyRegistered(agentId, store).catch((err) => {\n console.error(\"ThreadStoreRegistry notifyRegistered failed:\", err);\n });\n }\n\n unregister(agentId: string): void {\n if (!(agentId in this._stores)) return;\n // Capture before delete for the same reason as `register()` above.\n const prevStore = this._stores[agentId]!;\n delete this._stores[agentId];\n this._snapshot = null;\n this.notifyUnregistered(agentId, prevStore).catch((err) => {\n console.error(\"ThreadStoreRegistry notifyUnregistered failed:\", err);\n });\n }\n\n get(agentId: string): ɵThreadStore | undefined {\n return this._stores[agentId];\n }\n\n getAll(): Readonly<Record<string, ɵThreadStore>> {\n // Cache a frozen snapshot so consecutive calls return the same reference.\n // `useSyncExternalStore` and other identity-comparing consumers depend on\n // this stability to skip re-renders when nothing has actually changed.\n // `Object.freeze` makes the `Readonly<>` claim true at runtime, not just\n // at the type level — attempts to mutate the snapshot throw in strict\n // mode and are silently ignored in sloppy mode (rather than corrupting\n // the registry). Invalidated to `null` by `register`/`unregister`.\n if (this._snapshot === null) {\n this._snapshot = Object.freeze({ ...this._stores });\n }\n return this._snapshot;\n }\n\n private async notifyRegistered(\n agentId: string,\n store: ɵThreadStore,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber: CopilotKitCoreSubscriber) =>\n subscriber.onThreadStoreRegistered?.({\n copilotkit: this.core,\n agentId,\n store,\n }),\n \"Subscriber onThreadStoreRegistered error:\",\n );\n }\n\n private async notifyUnregistered(\n agentId: string,\n prevStore: ɵThreadStore,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber: CopilotKitCoreSubscriber) =>\n subscriber.onThreadStoreUnregistered?.({\n copilotkit: this.core,\n agentId,\n prevStore,\n }),\n \"Subscriber onThreadStoreUnregistered error:\",\n );\n }\n}\n","import { Socket } from \"phoenix\";\nimport type { Channel } from \"phoenix\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport { phoenixExponentialBackoff } from \"@copilotkit/shared\";\nimport { createTrajectoryCollector } from \"@copilotkit/learning\";\nimport type {\n ConnectionGrant,\n JsonValue,\n StartResult,\n TrajectoryCaptureOptions,\n TrajectoryEvent,\n} from \"@copilotkit/learning\";\nimport type { CopilotKitCore } from \"./core\";\nimport type { CopilotRuntimeTransport } from \"../types\";\nimport { abortable, isPromiseLike } from \"./header-source\";\n\nconst TIMEOUT_MS = 10_000;\nconst BATCH_INTERVAL_MS = 2_000;\nconst MAX_BATCH_EVENTS = 50;\nconst MAX_BATCH_BYTES = 64 * 1024;\nconst MAX_EVENT_BYTES = 16 * 1024;\n\ntype WireEvent = TrajectoryEvent<Record<string, JsonValue>>;\ninterface EventBatch {\n events: WireEvent[];\n dropped: number;\n}\nconst byteLength = (value: unknown) =>\n new TextEncoder().encode(JSON.stringify(value)).byteLength;\nconst reconnectDelay = phoenixExponentialBackoff(1_000, 10_000);\n\n// Fixed client-side hints. Server messages are never shown in the browser.\nconst SETUP_HINTS: Record<string, string> = {\n RUNTIME_REQUIRED:\n \"Set runtimeUrl: capture connects through the CopilotKit runtime.\",\n INTELLIGENCE_RUNTIME_REQUIRED:\n \"Configure the CopilotRuntime with `intelligence` to accept capture.\",\n CONNECTION_FAILED:\n \"Check that the CopilotRuntime is configured with `intelligence` and valid Intelligence credentials, and check the runtime logs.\",\n IDENTITY_REQUIRED:\n \"The runtime could not identify the user. Configure `identifyUser` on the CopilotRuntime and send the app's session with runtime requests.\",\n TRAJECTORIES_NOT_ENABLED:\n \"Trajectories are not enabled for this Intelligence project.\",\n TRAJECTORIES_UNAVAILABLE:\n \"This Intelligence deployment does not serve Trajectory capture.\",\n TRAJECTORIES_ENTITLEMENT_UNAVAILABLE:\n \"Intelligence could not confirm that Trajectories are enabled for this project; try again later.\",\n MARKETPLACE_LICENSE_REQUIRED:\n \"Trajectory capture requires a CopilotKit license for this project.\",\n};\n\ninterface PendingPush {\n timer: ReturnType<typeof setTimeout>;\n finish(code?: string, knownRollback?: boolean, flushNext?: boolean): void;\n}\n\ninterface Connection {\n abort: AbortController;\n timer?: ReturnType<typeof setTimeout>;\n socket?: Socket;\n channel?: Channel;\n socketRefs: string[];\n channelRefs: Array<[string, number]>;\n pending: Set<PendingPush>;\n}\n\ninterface Session {\n trajectoryId: string;\n config: TrajectoryCaptureOptions;\n promise: Promise<StartResult>;\n resolve(result: StartResult): void;\n collector?: ReturnType<typeof createTrajectoryCollector>;\n connection?: Connection;\n retry?: ReturnType<typeof setTimeout>;\n retries: number;\n queue: WireEvent[];\n flushTimer?: ReturnType<typeof setTimeout>;\n dropped: number;\n ready: boolean;\n started: boolean;\n offline: boolean;\n onOffline(): void;\n onOnline(): void;\n /** Threads already linked to this Trajectory. */\n linkedThreads: Set<string>;\n runWatch?: { unsubscribe(): void };\n agentWatches: Map<AbstractAgent, { unsubscribe(): void }>;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\ninterface BatchAcknowledgement {\n highestSeq: number | null;\n accepted: number;\n rejected: number;\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isBatchAcknowledgement(\n value: unknown,\n eventCount: number,\n): value is BatchAcknowledgement {\n return (\n isObject(value) &&\n isNonNegativeInteger(value.accepted) &&\n isNonNegativeInteger(value.rejected) &&\n value.accepted + value.rejected === eventCount &&\n (value.highestSeq === null || isNonNegativeInteger(value.highestSeq)) &&\n (value.accepted === 0 || value.highestSeq !== null)\n );\n}\n\nfunction isGrant(value: unknown): value is ConnectionGrant {\n return (\n isObject(value) &&\n typeof value.joinToken === \"string\" &&\n value.joinToken.length > 0 &&\n isObject(value.realtime) &&\n typeof value.realtime.clientUrl === \"string\" &&\n value.realtime.clientUrl.length > 0 &&\n typeof value.realtime.topic === \"string\" &&\n value.realtime.topic.length > 0\n );\n}\n\n// The Gateway refuses a join with a lowercase reason and no code.\nconst JOIN_REFUSAL_CODES: Record<string, string> = {\n trajectories_unavailable: \"TRAJECTORIES_UNAVAILABLE\",\n trajectories_not_enabled: \"TRAJECTORIES_NOT_ENABLED\",\n entitlement_unavailable: \"TRAJECTORIES_ENTITLEMENT_UNAVAILABLE\",\n marketplace_license_required: \"MARKETPLACE_LICENSE_REQUIRED\",\n};\n\nfunction joinErrorCode(value: unknown): string {\n const reason = isObject(value) ? value.reason : undefined;\n const code =\n typeof reason === \"string\" && Object.hasOwn(JOIN_REFUSAL_CODES, reason)\n ? JOIN_REFUSAL_CODES[reason]\n : undefined;\n return code ?? errorCode(value, \"JOIN_FAILED\");\n}\n\nfunction errorCode(value: unknown, fallback: string): string {\n return isObject(value) &&\n typeof value.code === \"string\" &&\n /^[A-Z][A-Z0-9_]{0,63}$/.test(value.code)\n ? value.code\n : fallback;\n}\n\n/** Owns bounded, connected-only capture batches. Failed batches are never resent. */\nexport class TrajectoryConnection {\n private session: Session | undefined;\n private readonly warned = new Set<string>();\n // Core-scoped high water mark prevents collisions after reconnect or stop/start.\n // Gateway drops a seq it already stored for the Trajectory yet acknowledges it\n // as accepted, and a reload or second tab can reuse the id. Starting at the\n // creation time in microseconds keeps later Cores above earlier ones and\n // stays a safe integer until about 2255. Seqs can still collide only if two\n // Cores start the same Trajectory in one millisecond, or if a Core averages\n // more than 1000 events per millisecond, or if the clock goes back.\n private nextSeq = Math.floor(Date.now()) * 1000;\n\n constructor(\n private readonly core: CopilotKitCore,\n private readonly onChange: () => void,\n ) {}\n\n get trajectoryId(): string | null {\n return this.session?.ready ? this.session.trajectoryId : null;\n }\n\n start(\n trajectoryId: string | undefined,\n config: TrajectoryCaptureOptions,\n ): Promise<StartResult> {\n if (\n this.session &&\n (trajectoryId === undefined || trajectoryId === this.session.trajectoryId)\n ) {\n return this.session.promise;\n }\n this.stop();\n const id = trajectoryId ?? crypto.randomUUID();\n let resolveStart!: (result: StartResult) => void;\n const promise = new Promise<StartResult>((resolve) => {\n resolveStart = resolve;\n });\n const session: Session = {\n trajectoryId: id,\n config,\n promise,\n resolve: resolveStart,\n retries: 0,\n queue: [],\n dropped: 0,\n ready: false,\n started: false,\n offline: typeof navigator !== \"undefined\" && navigator.onLine === false,\n onOffline: () => {\n if (this.session !== session) return;\n session.offline = true;\n if (session.connection)\n this.fail(session, session.connection, \"CONNECTION_LOST\");\n clearTimeout(session.retry);\n session.retry = undefined;\n },\n onOnline: () => {\n if (this.session !== session) return;\n session.offline = false;\n if (!session.connection) {\n clearTimeout(session.retry);\n session.retry = undefined;\n void this.connect(session);\n }\n },\n linkedThreads: new Set(),\n agentWatches: new Map(),\n };\n this.session = session;\n // Runtime creates the Thread before RUN_STARTED reaches the browser, so a\n // link sent from that event names a Thread that Intelligence can store.\n session.runWatch = this.core.subscribe({\n onAgentRunStarted: ({ agent }) => this.watchAgent(session, agent),\n });\n if (\n typeof window !== \"undefined\" &&\n typeof window.addEventListener === \"function\"\n ) {\n window.addEventListener(\"offline\", session.onOffline);\n window.addEventListener(\"online\", session.onOnline);\n }\n if (session.offline) {\n this.report(session, \"CONNECTION_LOST\");\n this.end(session, { status: \"error\", code: \"CONNECTION_LOST\" });\n } else {\n void this.connect(session);\n }\n return promise;\n }\n\n stop(): void {\n const session = this.session;\n if (!session) return;\n // Drain settled input while this session can still enqueue it, before the\n // best-effort transport flush. Stop stays synchronous and never waits for ACK.\n const collector = session.collector;\n session.collector = undefined;\n collector?.stop();\n if (session.ready && session.connection)\n this.flush(session, session.connection);\n this.end(session, { status: \"error\", code: \"CANCELLED\" });\n }\n\n emit(name: string, value: JsonValue): void {\n const session = this.session;\n if (session?.ready) session.collector?.emit(name, value);\n else if (session?.started) {\n // An explicit developer event during recovery is observable loss. Its\n // contents are discarded immediately; only the count survives reconnect.\n this.addDropped(session, 1, false);\n }\n }\n\n private watchAgent(session: Session, agent: AbstractAgent): void {\n if (this.session !== session || session.agentWatches.has(agent)) return;\n session.agentWatches.set(\n agent,\n agent.subscribe({\n onRunStartedEvent: ({ event }) => this.linkThread(session, event),\n }),\n );\n }\n\n /** Sends one `thread.linked` per Thread. A link that cannot be sent waits for the next run. */\n private linkThread(\n session: Session,\n { threadId }: { threadId: string },\n ): void {\n const connection = session.connection;\n if (\n !session.ready ||\n !connection ||\n !threadId ||\n session.linkedThreads.has(threadId)\n )\n return;\n session.linkedThreads.add(threadId);\n // `thread.linked` is a built-in name, so it skips the collector's\n // developer-event check. The host's beforeSend filter still applies.\n const event: TrajectoryEvent = {\n type: \"CUSTOM\",\n name: \"thread.linked\",\n timestamp: Date.now(),\n value: { threadId },\n };\n try {\n const { beforeSend } = session.config;\n const kept = beforeSend === undefined ? event : beforeSend(event);\n if (kept !== null) this.send(session, connection, kept);\n } catch {\n this.report(session, \"INVALID_EVENT\");\n }\n }\n\n private report(session: Session, code: string): void {\n try {\n session.config.onError?.({\n code,\n message: `Trajectory capture: ${code}.`,\n });\n } catch {\n // Telemetry errors, including a host callback, cannot interrupt the app.\n }\n }\n\n private current(session: Session, connection: Connection): boolean {\n return this.session === session && session.connection === connection;\n }\n\n private end(session: Session, result: StartResult): void {\n if (this.session !== session) return;\n this.session = undefined;\n clearTimeout(session.retry);\n session.runWatch?.unsubscribe();\n for (const watch of session.agentWatches.values()) watch.unsubscribe();\n session.agentWatches.clear();\n session.collector?.stop();\n session.ready = false;\n if (session.queue.length > 0) this.report(session, \"EVENTS_DROPPED\");\n this.discardQueue(session);\n if (session.connection) {\n // Stop prevents retry, but cannot prove whether an in-flight event persisted.\n for (const pending of session.connection.pending) {\n pending.finish(\"PERSISTENCE_UNKNOWN\");\n this.report(session, \"PERSISTENCE_UNKNOWN\");\n }\n this.cleanup(session, session.connection);\n }\n if (\n typeof window !== \"undefined\" &&\n typeof window.removeEventListener === \"function\"\n ) {\n window.removeEventListener(\"offline\", session.onOffline);\n window.removeEventListener(\"online\", session.onOnline);\n }\n if (result.status === \"error\" && result.code !== \"CANCELLED\")\n this.warnEnded(session, result.code);\n session.resolve(result);\n this.onChange();\n }\n\n /**\n * Without an app handler, a capture that ends on its own would otherwise fail\n * silently. Each outcome warns once per Core, so StrictMode replays and\n * repeated starts against the same misconfigured Runtime stay quiet.\n */\n private warnEnded(session: Session, code: string): void {\n if (session.config.onError !== undefined) return;\n const summary = session.started\n ? `Trajectory capture stopped (${code}).`\n : `Trajectory capture did not start (${code}).`;\n if (this.warned.has(summary)) return;\n this.warned.add(summary);\n const hint = SETUP_HINTS[code];\n console.warn(\n `[CopilotKit] ${summary}${hint === undefined ? \"\" : ` ${hint}`} Set learning.onError to handle capture errors in the app.`,\n );\n }\n\n private cleanup(session: Session, connection: Connection): void {\n session.connection = undefined;\n clearTimeout(connection.timer);\n connection.abort.abort();\n for (const pending of connection.pending) {\n clearTimeout(pending.timer);\n }\n connection.pending.clear();\n const { socket, channel } = connection;\n try {\n if (channel) {\n for (const [event, ref] of connection.channelRefs)\n channel.off(event, ref);\n // leave() cancels Phoenix's channel rejoin timer and pending join push.\n channel.leave();\n }\n } finally {\n if (socket) {\n socket.off(connection.socketRefs);\n // Phoenix's heartbeat timeout can schedule a reconnect after disconnect\n // returns. Retire this one-use socket; recovery needs a fresh grant.\n socket.connect = () => undefined;\n socket.disconnect();\n }\n }\n }\n\n private fail(\n session: Session,\n connection: Connection,\n code: string,\n retryable = true,\n ): void {\n if (!this.current(session, connection)) return;\n if (session.ready && session.started) {\n // A new start during recovery must await a fresh join, not an old success.\n session.promise = new Promise((resolve) => {\n session.resolve = resolve;\n });\n }\n // Closing capture may drain a pending edit; it must not reach a failed\n // connection or fill a batch while recovery is discarding queued events.\n session.ready = false;\n session.collector?.stop();\n session.collector = undefined;\n this.discardQueue(session);\n // A discarded or unconfirmed link is sent again on the next run.\n session.linkedThreads.clear();\n for (const pending of connection.pending)\n pending.finish(\"PERSISTENCE_UNKNOWN\");\n if (!this.current(session, connection)) return;\n this.cleanup(session, connection);\n this.onChange();\n this.report(session, code);\n if (this.session !== session) return;\n if (!session.started || !retryable) {\n this.end(session, { status: \"error\", code });\n return;\n }\n if (session.offline || this.session !== session) return;\n session.retry = setTimeout(\n () => {\n session.retry = undefined;\n if (this.session === session && !session.offline)\n void this.connect(session);\n },\n reconnectDelay(++session.retries),\n );\n }\n\n private async connect(session: Session): Promise<void> {\n if (this.session !== session || session.offline || session.connection)\n return;\n const connection: Connection = {\n abort: new AbortController(),\n socketRefs: [],\n channelRefs: [],\n pending: new Set(),\n };\n session.connection = connection;\n connection.timer = setTimeout(\n () => this.fail(session, connection, \"CONNECTION_TIMEOUT\"),\n TIMEOUT_MS,\n );\n try {\n const runtimeUrl = this.core.runtimeUrl;\n if (!runtimeUrl) {\n this.fail(session, connection, \"RUNTIME_REQUIRED\", false);\n return;\n }\n // \"auto\" stays unresolved until `/info` answers, and providers start capture\n // right after mount. Wait for detection, or a REST runtime gets a\n // single-endpoint request it cannot route.\n let transport = this.core.runtimeTransport;\n if (transport === \"auto\") {\n transport = await this.detectedTransport(connection.abort.signal);\n if (!this.current(session, connection)) return;\n }\n const rest = transport === \"rest\";\n // Resolved fresh, not the last snapshot: with a builder, `core.headers`\n // is `{}` before the first request and an old token after that (#1937).\n // Only an async builder is awaited, so a sync source still sends in the\n // same tick.\n const resolved = this.core.resolveHeaders();\n const coreHeaders = isPromiseLike(resolved)\n ? await abortable(resolved, connection.abort.signal)\n : resolved;\n if (!this.current(session, connection)) return;\n const response = await fetch(\n rest\n ? `${runtimeUrl}/trajectory/${encodeURIComponent(session.trajectoryId)}/connect`\n : (this.core.ɵruntimeEndpointUrl ?? runtimeUrl),\n {\n method: \"POST\",\n redirect: \"error\",\n signal: connection.abort.signal,\n headers: { ...coreHeaders, \"Content-Type\": \"application/json\" },\n credentials: this.core.credentials,\n body: JSON.stringify(\n rest\n ? {}\n : {\n method: \"trajectory/connect\",\n params: { trajectoryId: session.trajectoryId },\n body: {},\n },\n ),\n },\n );\n if (!this.current(session, connection)) return;\n const payload: unknown = await response.json().catch(() => undefined);\n if (!this.current(session, connection)) return;\n if (!response.ok) {\n this.fail(\n session,\n connection,\n errorCode(payload, \"CONNECTION_FAILED\"),\n response.status >= 500 ||\n response.status === 408 ||\n response.status === 429,\n );\n return;\n }\n if (!isGrant(payload)) {\n this.fail(session, connection, \"INVALID_GRANT\", false);\n return;\n }\n const socket = new Socket(payload.realtime.clientUrl, {\n params: { join_token: payload.joinToken },\n timeout: TIMEOUT_MS,\n });\n connection.socket = socket;\n const lost = () => this.fail(session, connection, \"CONNECTION_LOST\");\n connection.socketRefs.push(socket.onError(lost), socket.onClose(lost));\n const channel = socket.channel(payload.realtime.topic, {});\n connection.channel = channel;\n connection.channelRefs.push(\n [\"phx_error\", channel.onError(lost)],\n [\"phx_close\", channel.onClose(lost)],\n );\n socket.connect();\n if (!this.current(session, connection)) return;\n channel\n .join(TIMEOUT_MS)\n .receive(\"ok\", () => {\n if (!this.current(session, connection)) return;\n try {\n clearTimeout(connection.timer);\n session.ready = true;\n session.retries = 0;\n session.collector = createTrajectoryCollector({\n ...session.config,\n // Exclude SDK transport traffic so capture cannot record its own\n // authorization calls or CopilotKit telemetry and announcements.\n ignoreUrls: [\n ...(session.config.ignoreUrls ?? []),\n ...(this.core.runtimeUrl ? [this.core.runtimeUrl] : []),\n ...(this.core.ɵruntimeEndpointUrl\n ? [this.core.ɵruntimeEndpointUrl]\n : []),\n \"https://telemetry.copilotkit.ai/\",\n \"https://cdn.copilotkit.ai/\",\n ],\n onError: (error) => {\n if (error.code === \"CAPTURE_FAILED\")\n this.fail(session, connection, error.code, false);\n else {\n if (\n error.code === \"INVALID_EVENT\" ||\n error.code === \"EVENT_TOO_LARGE\"\n )\n this.addDropped(session, 1);\n session.config.onError?.(error);\n }\n },\n send: (event) => this.send(session, connection, event),\n });\n session.collector.start();\n if (!this.current(session, connection)) return;\n if (session.dropped > 0) this.scheduleFlush(session, connection);\n session.started = true;\n session.resolve({\n status: \"started\",\n trajectoryId: session.trajectoryId,\n });\n this.onChange();\n } catch {\n this.fail(session, connection, \"CAPTURE_FAILED\", false);\n }\n })\n .receive(\"error\", (joinError: unknown) =>\n this.fail(session, connection, joinErrorCode(joinError)),\n )\n .receive(\"timeout\", () =>\n this.fail(session, connection, \"CONNECTION_TIMEOUT\"),\n );\n } catch {\n this.fail(session, connection, \"CONNECTION_FAILED\");\n }\n }\n\n /** Resolves once auto-detection picks a transport, or with \"auto\" when the attempt is aborted. */\n private detectedTransport(signal: AbortSignal) {\n return new Promise<CopilotRuntimeTransport>((resolve) => {\n const finish = () => {\n subscription.unsubscribe();\n signal.removeEventListener(\"abort\", finish);\n resolve(this.core.runtimeTransport);\n };\n const subscription = this.core.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n if (this.core.runtimeTransport !== \"auto\") finish();\n },\n });\n signal.addEventListener(\"abort\", finish, { once: true });\n });\n }\n\n private addDropped(session: Session, count: number, schedule = true): void {\n session.dropped = Math.min(\n Number.MAX_SAFE_INTEGER,\n session.dropped + count,\n );\n if (schedule && count > 0 && session.ready && session.connection)\n this.scheduleFlush(session, session.connection);\n }\n\n private scheduleFlush(session: Session, connection: Connection): void {\n if (session.flushTimer !== undefined || !this.current(session, connection))\n return;\n session.flushTimer = setTimeout(() => {\n session.flushTimer = undefined;\n this.flush(session, connection);\n }, BATCH_INTERVAL_MS);\n }\n\n private discardQueue(session: Session): void {\n clearTimeout(session.flushTimer);\n session.flushTimer = undefined;\n this.addDropped(session, session.queue.length, false);\n session.queue = [];\n }\n\n private connected(connection: Connection): boolean {\n return (\n connection.socket?.isConnected() === true &&\n connection.channel?.state === \"joined\"\n );\n }\n\n private send(\n session: Session,\n connection: Connection,\n event: TrajectoryEvent,\n ): void {\n if (!this.current(session, connection)) return;\n if (!session.ready) {\n this.addDropped(session, 1, false);\n return;\n }\n if (!this.connected(connection)) {\n this.addDropped(session, 1);\n this.fail(session, connection, \"CONNECTION_LOST\");\n return;\n }\n if (!Number.isSafeInteger(this.nextSeq)) {\n this.addDropped(session, 1);\n this.report(session, \"SEQUENCE_EXHAUSTED\");\n return;\n }\n const original = event.value;\n const fields =\n isObject(original) &&\n !Array.isArray(original) &&\n !Object.hasOwn(original, \"seq\")\n ? (original as Record<string, JsonValue>)\n : { data: original };\n const wire: WireEvent = {\n ...event,\n value: { ...fields, seq: this.nextSeq++ },\n };\n if (byteLength(wire) > MAX_EVENT_BYTES) {\n this.addDropped(session, 1);\n this.report(session, \"EVENT_TOO_LARGE\");\n return;\n }\n // Reserve the maximum dropped-counter width so later local losses cannot\n // grow an already-full payload over the wire limit.\n const fits = () =>\n session.queue.length < MAX_BATCH_EVENTS &&\n byteLength({\n events: [...session.queue, wire],\n dropped: Number.MAX_SAFE_INTEGER,\n }) <= MAX_BATCH_BYTES;\n if (!fits()) this.flush(session, connection);\n if (!this.current(session, connection) || !session.ready) return;\n if (!fits()) {\n this.addDropped(session, 1);\n this.report(session, \"EVENTS_DROPPED\");\n return;\n }\n session.queue.push(wire);\n if (session.queue.length === MAX_BATCH_EVENTS)\n this.flush(session, connection);\n else this.scheduleFlush(session, connection);\n }\n\n private flush(session: Session, connection: Connection): void {\n if (\n !this.current(session, connection) ||\n !session.ready ||\n (session.queue.length === 0 && session.dropped === 0)\n )\n return;\n if (!this.connected(connection)) {\n this.fail(session, connection, \"CONNECTION_LOST\");\n return;\n }\n // One in-flight batch and one bounded queue; never let Phoenix buffer offline.\n if (connection.pending.size > 0) return;\n clearTimeout(session.flushTimer);\n session.flushTimer = undefined;\n const batch: EventBatch = {\n events: session.queue,\n dropped: session.dropped,\n };\n session.queue = [];\n session.dropped = 0;\n let finished = false;\n const pending: PendingPush = {\n timer: setTimeout(\n () => pending.finish(\"PERSISTENCE_UNKNOWN\"),\n TIMEOUT_MS,\n ),\n finish: (code, knownRollback = false, flushNext = true) => {\n if (finished) return;\n finished = true;\n clearTimeout(pending.timer);\n connection.pending.delete(pending);\n // A missing ACK may already be accepted by Redis. Never count uncertainty\n // as a known drop, and never replay a batch or its dropped counter.\n if (knownRollback)\n this.addDropped(session, batch.events.length + batch.dropped, false);\n if (code && this.current(session, connection))\n this.report(session, code);\n if (\n flushNext &&\n this.current(session, connection) &&\n session.ready &&\n (session.queue.length > 0 || (!knownRollback && session.dropped > 0))\n )\n this.flush(session, connection);\n },\n };\n connection.pending.add(pending);\n try {\n connection\n .channel!.push(\"events\", batch, TIMEOUT_MS)\n .receive(\"ok\", (payload: unknown) => {\n // Rejected rows are already counted by Gateway; don't also mark them\n // as client drops. The aggregate reply cannot identify rejected rows.\n pending.finish(\n !isBatchAcknowledgement(payload, batch.events.length)\n ? \"PERSISTENCE_UNKNOWN\"\n : payload.rejected > 0\n ? \"EVENTS_REJECTED\"\n : undefined,\n );\n })\n .receive(\"error\", (payload: unknown) => {\n if (!this.current(session, connection)) return;\n const reason = isObject(payload) ? payload.reason : undefined;\n if (reason === \"unauthorized\" || reason === \"trajectory_mismatch\") {\n // Finish the known rollback without flushing the queued tail onto\n // a channel whose scope has just been refused.\n pending.finish(undefined, true, false);\n this.fail(session, connection, reason.toUpperCase(), false);\n return;\n }\n const rollback =\n typeof reason === \"string\" &&\n [\n \"invalid_batch\",\n \"batch_too_large\",\n \"batch_too_many_events\",\n \"trajectory_over_share\",\n \"trajectory_outbox_full\",\n \"unsupported_event\",\n ].includes(reason);\n // storage_unavailable includes Redis timeouts after a possible write.\n // retryable:true cannot make a repeated dropped counter idempotent.\n pending.finish(\n rollback ? (reason as string).toUpperCase() : \"PERSISTENCE_UNKNOWN\",\n rollback,\n );\n })\n .receive(\"timeout\", () => pending.finish(\"PERSISTENCE_UNKNOWN\"));\n } catch {\n pending.finish(\"PERSISTENCE_UNKNOWN\");\n }\n }\n}\n","import { createCollector } from \"@copilotkit/learning\";\nimport type {\n CaptureOptions,\n Collector,\n CollectorOptions,\n JsonValue,\n StartResult,\n TrajectoryCaptureOptions,\n} from \"@copilotkit/learning\";\nimport type { AbstractAgent, AgentSubscriber, Message } from \"@ag-ui/client\";\nimport type { CopilotKitCore } from \"./core\";\nimport { TrajectoryConnection } from \"./trajectory-connection\";\n\n/** Interaction capture settings for {@link CopilotKitCore}. See `@copilotkit/learning`. */\nexport interface LegacyLearningConfig extends Omit<\n CollectorOptions,\n \"enrich\" | \"capture\"\n> {\n /** Capture modules, plus `agentText: false` to omit message text (included in full by default). */\n capture?: CaptureOptions & { agentText?: boolean };\n}\n\nexport type LearningConfig =\n | LegacyLearningConfig\n | (TrajectoryCaptureOptions & { sink?: undefined });\nexport type TrajectoryStartOptions = {\n trajectoryId?: string;\n /**\n * Used only by explicit custom sinks. Authenticated capture warns and ignores\n * this option; assign Learning Spaces on the server with\n * `getTrajectoryLearningContainerIds` on `CopilotKitIntelligence`.\n */\n learningContainerIds?: string[];\n};\n\n/** Returned by {@link CopilotKitCore.registerOpenThread}. */\nexport interface OpenThreadRegistration {\n /** The view now shows another Thread. */\n update(threadId: string): void;\n /** The view that showed this Thread is gone. */\n unregister(): void;\n}\n\n/** The part of a DOM element the enricher reads. Elements satisfy it. */\ninterface ClosestTarget {\n closest(\n selector: string,\n ): { getAttribute(name: string): string | null } | null;\n}\n\ninterface OpenThread {\n agentId: string;\n threadId: string;\n}\n\ninterface ToolCallOrigin {\n agentId: string;\n threadId: string;\n messageId: string | undefined;\n runId: string | undefined;\n}\n\n// CopilotKit's own browser traffic (Inspector telemetry and announcements) is not app activity.\nconst COPILOTKIT_OWN_URLS = [\n \"https://telemetry.copilotkit.ai/\",\n \"https://cdn.copilotkit.ai/\",\n];\n\n/**\n * Wires `@copilotkit/learning` into Core. Default capture uses Runtime and Phoenix;\n * explicit legacy sinks also use agent events and open-Thread attribution.\n */\nexport class LearningBridge {\n private collector: Collector | null = null;\n private readonly agents = new Map<\n AbstractAgent,\n ReturnType<AbstractAgent[\"subscribe\"]>\n >();\n private readonly openThreads = new Set<OpenThread>();\n private readonly toolCalls = new Map<string, ToolCallOrigin>();\n private readonly executingTools = new Map<string, number>();\n private readonly lastRunIds = new WeakMap<AbstractAgent, string>();\n private lastLinkedThreadId: string | null = null;\n private coreSubscription: ReturnType<CopilotKitCore[\"subscribe\"]> | null =\n null;\n private seq = 0;\n private activeConfig: LegacyLearningConfig | undefined;\n private readonly connection: TrajectoryConnection;\n\n constructor(\n private readonly core: CopilotKitCore,\n private config: LearningConfig | undefined,\n onChange: () => void = () => {},\n ) {\n this.connection = new TrajectoryConnection(core, onChange);\n this.setConfig(config);\n }\n\n setConfig(config: LearningConfig | undefined) {\n this.config = config;\n if (config === undefined) this.stop();\n }\n\n get isConfigured() {\n return this.config !== undefined;\n }\n\n /**\n * Whether events may carry agent message text: not when the capture's config\n * sets `capture.agentText` to false. A running custom-sink capture keeps the\n * choice it started with; otherwise the current config decides.\n */\n get capturesAgentText() {\n const config = this.activeConfig ?? this.config;\n if (config === undefined) return false;\n // Typed for custom sinks only, but honored for authenticated capture too.\n const capture: unknown = config.capture;\n return !(\n typeof capture === \"object\" &&\n capture !== null &&\n (capture as { agentText?: unknown }).agentText === false\n );\n }\n\n private get isLegacyCaptureActive() {\n return this.collector !== null && this.collector.trajectoryId !== null;\n }\n\n private startTracking() {\n if (this.coreSubscription !== null || !this.isLegacyCaptureActive) return;\n this.coreSubscription = this.core.subscribe({\n onAgentsChanged: ({ agents }) => {\n for (const agent of Object.values(agents)) this.track(agent);\n },\n // Per-thread clones are not in `core.agents`; track the running instance too.\n onAgentRunStarted: ({ agent }) => this.track(agent),\n onToolExecutionStart: ({ toolCallId, agentId, toolName }) => {\n if (!this.isLegacyCaptureActive) return;\n this.executingTools.set(toolCallId, Date.now());\n this.emitToolCall(\"executing\", toolCallId, agentId, toolName, {});\n },\n onToolExecutionEnd: ({ toolCallId, agentId, toolName, error }) => {\n if (!this.isLegacyCaptureActive) return;\n const startedAt = this.executingTools.get(toolCallId);\n this.executingTools.delete(toolCallId);\n this.emitToolCall(\"completed\", toolCallId, agentId, toolName, {\n durationMs:\n startedAt === undefined ? undefined : Date.now() - startedAt,\n outcome: error === undefined ? \"ok\" : \"error\",\n });\n this.toolCalls.delete(toolCallId);\n },\n });\n for (const agent of Object.values(this.core.agents)) this.track(agent);\n }\n\n get trajectoryId(): string | null {\n return this.connection.trajectoryId ?? this.collector?.trajectoryId ?? null;\n }\n\n start(options: TrajectoryStartOptions = {}): Promise<StartResult> {\n const config = this.config;\n if (config === undefined) {\n console.warn(\n \"[CopilotKit] startTrajectory() needs the `learning` option on CopilotKitCore (or the CopilotKitProvider `learning` prop).\",\n );\n return Promise.resolve({ status: \"error\", code: \"LEARNING_DISABLED\" });\n }\n if (config.sink === undefined) {\n if (options.learningContainerIds !== undefined) {\n console.warn(\n \"[CopilotKit] learningContainerIds is supported only with a custom sink. Authenticated Trajectory capture ignores it; assign Learning Spaces on the server with getTrajectoryLearningContainerIds on CopilotKitIntelligence, and remove learningContainerIds from the capture options.\",\n );\n }\n this.stopLegacy();\n return this.connection.start(options.trajectoryId, config);\n }\n this.connection.stop();\n const trajectoryId =\n options.trajectoryId ??\n this.collector?.trajectoryId ??\n crypto.randomUUID();\n if (this.collector === null) {\n this.activeConfig = config;\n const runtimeUrl = this.core.runtimeUrl;\n this.collector = createCollector({\n ...config,\n beforeSend: (event) => {\n const sequenced = {\n ...event,\n value: { ...event.value, seq: ++this.seq },\n };\n return config.beforeSend === undefined\n ? sequenced\n : config.beforeSend(sequenced);\n },\n ignoreUrls: [\n ...(config.ignoreUrls ?? []),\n ...COPILOTKIT_OWN_URLS,\n ...(runtimeUrl === undefined ? [] : [runtimeUrl]),\n ],\n enrich: (target) => this.enrich(target),\n });\n }\n const wasActive = this.collector.trajectoryId !== null;\n this.collector.start({ ...options, trajectoryId });\n if (wasActive)\n return Promise.resolve(\n this.collector.trajectoryId === trajectoryId\n ? { status: \"started\", trajectoryId }\n : { status: \"error\", code: \"TRAJECTORY_ACTIVE\" },\n );\n this.startTracking();\n this.lastLinkedThreadId = null;\n for (const threadId of this.distinctOpenThreadIds())\n this.emitThreadLinked(threadId, \"start\");\n return Promise.resolve({ status: \"started\", trajectoryId });\n }\n\n stop() {\n this.connection.stop();\n this.stopLegacy();\n }\n\n private stopLegacy() {\n this.collector?.stop();\n this.collector = null;\n this.activeConfig = undefined;\n this.coreSubscription?.unsubscribe();\n this.coreSubscription = null;\n for (const subscription of this.agents.values()) subscription.unsubscribe();\n this.agents.clear();\n this.toolCalls.clear();\n this.executingTools.clear();\n }\n\n /**\n * A developer event. Only an explicit legacy sink adds open-Thread context;\n * an event that names its own Thread gets no ambiguity next to it.\n */\n emit(name: string, value: JsonValue) {\n this.connection.emit(name, value);\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n const context =\n typeof value[\"threadId\"] === \"string\" ? {} : this.openThreadContext();\n this.collector?.emit(name, { ...context, ...value });\n }\n }\n\n registerOpenThread(params: OpenThread) {\n const entry: OpenThread = { ...params };\n const isNew = !this.distinctOpenThreadIds().includes(entry.threadId);\n this.openThreads.add(entry);\n if (isNew) this.emitThreadLinked(entry.threadId, \"open\");\n const registration: OpenThreadRegistration = {\n update: (threadId) => {\n if (threadId === entry.threadId) return;\n entry.threadId = threadId;\n const others = [...this.openThreads].filter((other) => other !== entry);\n const isOpenElsewhere = others.some(\n (other) => other.threadId === threadId,\n );\n if (!isOpenElsewhere) this.emitThreadLinked(threadId, \"switch\");\n },\n unregister: () => {\n this.openThreads.delete(entry);\n },\n };\n return registration;\n }\n\n private distinctOpenThreadIds() {\n return [...new Set([...this.openThreads].map((open) => open.threadId))];\n }\n\n private emitThreadLinked(\n threadId: string,\n reason: \"start\" | \"open\" | \"switch\",\n ) {\n const isActive =\n this.collector !== null && this.collector.trajectoryId !== null;\n // React StrictMode unregisters and registers again in dev; one link per change is enough.\n if (!isActive || threadId === this.lastLinkedThreadId) return;\n this.lastLinkedThreadId = threadId;\n const owner = [...this.openThreads].find(\n (open) => open.threadId === threadId,\n );\n const agent = this.findAgentForThread(threadId);\n this.collector?.ɵemit(\"thread.linked\", {\n threadId,\n agentId: owner?.agentId ?? agent?.agentId ?? null,\n hasMessages: (agent?.messages.length ?? 0) > 0,\n reason,\n });\n }\n\n private findAgentForThread(threadId: string) {\n return [...this.agents.keys()].find((agent) => agent.threadId === threadId);\n }\n\n private track(agent: AbstractAgent) {\n const agentId = agent.agentId;\n if (\n !this.isLegacyCaptureActive ||\n this.agents.has(agent) ||\n agentId === undefined\n )\n return;\n this.agents.set(\n agent,\n agent.subscribe(this.agentSubscriber(agent, agentId)),\n );\n }\n\n private agentSubscriber(agent: AbstractAgent, agentId: string) {\n const runIdFor = () => this.lastRunIds.get(agent);\n const subscriber: AgentSubscriber = {\n onRunStartedEvent: ({ event }) => {\n this.lastRunIds.set(agent, event.runId);\n this.emitRun(\"started\", agent, event.threadId, event.runId);\n },\n onRunFinishedEvent: ({ event }) => {\n this.emitRun(\"finished\", agent, event.threadId, event.runId);\n },\n onRunErrorEvent: () => {\n this.emitRun(\"error\", agent, agent.threadId, runIdFor() ?? null);\n },\n onToolCallStartEvent: ({ event }) => {\n if (!this.isLegacyCaptureActive) return;\n const origin: ToolCallOrigin = {\n agentId,\n threadId: agent.threadId,\n messageId: event.parentMessageId,\n runId: runIdFor(),\n };\n this.toolCalls.set(event.toolCallId, origin);\n this.emitToolCall(\n \"started\",\n event.toolCallId,\n origin.agentId,\n event.toolCallName,\n {},\n );\n },\n onToolCallResultEvent: ({ event }) => {\n if (!this.executingTools.has(event.toolCallId)) {\n this.toolCalls.delete(event.toolCallId);\n }\n },\n onNewMessage: ({ message }) => this.emitMessage(agent, message),\n };\n return subscriber;\n }\n\n private emitRun(\n phase: \"started\" | \"finished\" | \"error\",\n agent: AbstractAgent,\n threadId: string,\n runId: string | null,\n ) {\n this.collector?.ɵemit(\"agent.run\", {\n phase,\n runId,\n threadId,\n agentId: agent.agentId,\n });\n }\n\n private emitMessage(agent: AbstractAgent, message: Message) {\n // No tool names here: this fires when the text ends, before tool calls stream in.\n // `tool.call` events carry the tool name and this `messageId`.\n const content = typeof message.content === \"string\" ? message.content : \"\";\n const includeText =\n this.capturesAgentText && typeof message.content === \"string\";\n this.collector?.ɵemit(\"agent.message\", {\n messageId: message.id,\n runId: this.runIdForMessage(agent, message.id),\n threadId: agent.threadId,\n agentId: agent.agentId,\n role: message.role,\n textLength: content.length,\n ...(includeText ? { text: content } : {}),\n });\n }\n\n private emitToolCall(\n phase: \"started\" | \"executing\" | \"completed\",\n toolCallId: string,\n agentId: string,\n toolName: string,\n extra: { durationMs?: number; outcome?: \"ok\" | \"error\" },\n ) {\n const origin = this.toolCalls.get(toolCallId);\n this.collector?.ɵemit(\"tool.call\", {\n phase,\n toolCallId,\n toolName,\n agentId,\n threadId: origin?.threadId ?? null,\n messageId: origin?.messageId,\n runId: origin?.runId,\n ...extra,\n });\n }\n\n private runIdForMessage(agent: AbstractAgent, messageId: string) {\n const agentId = agent.agentId;\n if (agentId === undefined) return null;\n return (\n this.core.getRunIdForMessage(agentId, agent.threadId, messageId) ??\n this.lastRunIds.get(agent) ??\n null\n );\n }\n\n private findMessage(messageId: string) {\n for (const agent of this.agents.keys()) {\n const message = agent.messages.find(\n (candidate) => candidate.id === messageId,\n );\n if (message !== undefined) return { agent, message };\n }\n return null;\n }\n\n private toolStatus(agent: AbstractAgent, toolCallId: string) {\n if (this.executingTools.has(toolCallId)) return \"executing\";\n const hasResult = agent.messages.some(\n (message) => message.role === \"tool\" && message.toolCallId === toolCallId,\n );\n return hasResult ? \"complete\" : \"inProgress\";\n }\n\n /** Adds agent context to a click: exact message first, then the single open Thread. */\n enrich(target: ClosestTarget) {\n const messageId =\n target.closest(\"[data-message-id]\")?.getAttribute(\"data-message-id\") ??\n null;\n const toolCallId =\n target\n .closest(\"[data-tool-call-id]\")\n ?.getAttribute(\"data-tool-call-id\") ?? null;\n const found = messageId === null ? null : this.findMessage(messageId);\n if (found !== null) {\n const { agent, message } = found;\n const toolCall =\n toolCallId !== null && message.role === \"assistant\"\n ? message.toolCalls?.find((call) => call.id === toolCallId)\n : undefined;\n return {\n threadId: agent.threadId,\n agentId: agent.agentId,\n messageId: message.id,\n runId: this.runIdForMessage(agent, message.id),\n ...(toolCall === undefined\n ? {}\n : {\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n toolStatus: this.toolStatus(agent, toolCall.id),\n }),\n };\n }\n return this.openThreadContext();\n }\n\n /** The single open Thread, or `null` with the candidates when several are open. */\n private openThreadContext() {\n const openIds = this.distinctOpenThreadIds();\n if (openIds.length > 1) {\n return {\n threadId: null,\n threadAmbiguity: { reason: \"multiple-open\", candidates: openIds },\n };\n }\n return { threadId: openIds[0] ?? null };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n BehaviorSubject,\n Observable,\n OperatorFunction,\n Subject,\n Subscription,\n asapScheduler,\n} from \"rxjs\";\nimport { distinctUntilChanged, filter, map, observeOn } from \"rxjs/operators\";\n\n/**\n * The minimal action shape used by this micro-redux implementation.\n */\nexport interface AnyAction {\n type: string;\n}\n\n/**\n * A typed action creator function with a `type` literal and runtime matcher.\n */\nexport type ActionCreator<\n Type extends string,\n Args extends unknown[] = unknown[],\n Action extends AnyAction & { type: Type } = { type: Type },\n> = ((...args: Args) => Action) & {\n type: Type;\n match(action: AnyAction): action is Action;\n};\n\n/**\n * Extracts the action type produced by an action creator.\n */\nexport type ActionFromCreator<T> = T extends (...args: any[]) => infer A\n ? A\n : never;\n\n/**\n * Extracts a union of actions produced by a tuple/array of action creators.\n */\nexport type ActionFromCreators<\n Creators extends readonly ActionCreator<string, any[], any>[],\n> = ActionFromCreator<Creators[number]>;\n\n/**\n * A reducer transforms state in response to actions.\n */\nexport type Reducer<State, Action extends AnyAction = AnyAction> = (\n state: State | undefined,\n action: Action,\n) => State;\n\n/**\n * A selector derives a value from state.\n */\nexport type Selector<State, Result> = (state: State) => Result;\n\n/**\n * Marker config for action creators that accept no payload.\n */\nexport interface EmptyActionConfig {\n readonly kind: \"empty\";\n}\n\nconst PROPS_MARKER: unique symbol = Symbol(\"props_marker\");\n\n/**\n * Marker config for action creators that require payload props.\n */\nexport interface PropsActionConfig<Props extends Record<string, unknown>> {\n readonly kind: \"props\";\n readonly [PROPS_MARKER]?: Props;\n}\n\n/**\n * Supported action creator config node in an action group.\n */\nexport type ActionConfig =\n | EmptyActionConfig\n | PropsActionConfig<Record<string, unknown>>;\n\n/**\n * Shape of an action group declaration object.\n */\nexport type ActionGroupConfig = Record<string, ActionConfig>;\n\n/**\n * Maps an action group declaration to a strongly typed action-creator object.\n */\nexport type ActionGroupResult<\n Source extends string,\n Config extends ActionGroupConfig,\n> = {\n [K in keyof Config & string]: Config[K] extends PropsActionConfig<infer P>\n ? ActionCreator<`[${Source}] ${K}`, [P], { type: `[${Source}] ${K}` } & P>\n : ActionCreator<`[${Source}] ${K}`, [], { type: `[${Source}] ${K}` }>;\n};\n\ninterface OnReducerEntry<\n State,\n Action extends AnyAction = AnyAction,\n Creators extends readonly ActionCreator<string, any[], any>[] =\n readonly ActionCreator<string, any[], any>[],\n> {\n creators: Creators;\n reducer: (state: State, action: Action) => State;\n}\n\ntype ActionFromOnReducerEntry<TEntry> =\n TEntry extends OnReducerEntry<any, infer TAction, any> ? TAction : never;\n\n/**\n * Effect contract for streams that emit actions to dispatch.\n */\nexport interface DispatchingEffect<\n State,\n InputAction extends AnyAction = AnyAction,\n OutputAction extends AnyAction = AnyAction,\n> {\n run: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<OutputAction>;\n dispatch: true;\n}\n\n/**\n * Effect contract for side-effect-only streams whose emissions are ignored.\n */\nexport interface NonDispatchingEffect<\n State,\n InputAction extends AnyAction = AnyAction,\n> {\n run: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<unknown>;\n dispatch: false;\n}\n\n/**\n * Union of supported effect shapes.\n */\nexport type Effect<\n State,\n InputAction extends AnyAction = AnyAction,\n OutputAction extends AnyAction = AnyAction,\n> =\n | DispatchingEffect<State, InputAction, OutputAction>\n | NonDispatchingEffect<State, InputAction>;\n\n/**\n * Lifecycle actions dispatched by the store.\n */\nexport type StoreLifecycleAction =\n | { type: \"@@micro-redux/init\" }\n | { type: \"@@micro-redux/stop\" };\n\n/**\n * Options for a dispatching effect.\n */\nexport interface DispatchingEffectOptions {\n dispatch?: true;\n}\n\n/**\n * Options for a non-dispatching effect.\n */\nexport interface NonDispatchingEffectOptions {\n dispatch: false;\n}\n\nconst INTERNAL_ACTION_TYPES = {\n boot: \"@@micro-redux/boot\",\n init: \"@@micro-redux/init\",\n stop: \"@@micro-redux/stop\",\n} as const;\n\nconst INTERNAL_BOOT_ACTION: AnyAction = { type: INTERNAL_ACTION_TYPES.boot };\n\n/**\n * Builds a typed action creator from a type string and payload factory.\n */\nfunction createTypedActionCreator<\n Type extends string,\n Args extends unknown[],\n Payload extends Record<string, unknown>,\n>(\n type: Type,\n factory: (...args: Args) => Payload,\n): ActionCreator<Type, Args, { type: Type } & Payload> {\n const creator = ((...args: Args) => ({\n ...factory(...args),\n type,\n })) as ActionCreator<Type, Args, { type: Type } & Payload>;\n\n creator.type = type;\n creator.match = (action: AnyAction): action is { type: Type } & Payload =>\n action.type === type;\n\n return creator;\n}\n\n/**\n * Declares a payload-based action config for `createActionGroup`.\n *\n * @example\n * ```ts\n * const actions = createActionGroup(\"User\", {\n * loaded: props<{ id: string }>(),\n * });\n * ```\n */\nexport function props<\n Props extends Record<string, unknown>,\n>(): PropsActionConfig<Props> {\n return { kind: \"props\" };\n}\n\n/**\n * Declares a no-payload action config for `createActionGroup`.\n *\n * @example\n * ```ts\n * const actions = createActionGroup(\"User\", {\n * reset: empty(),\n * });\n * ```\n */\nexport function empty(): EmptyActionConfig {\n return { kind: \"empty\" };\n}\n\n/**\n * Creates a namespaced group of typed action creators.\n *\n * Action types are formatted as: `[Source] actionName`.\n */\nexport function createActionGroup<\n const Source extends string,\n const Config extends ActionGroupConfig,\n>(source: Source, config: Config): ActionGroupResult<Source, Config> {\n const group = {} as ActionGroupResult<Source, Config>;\n\n for (const eventName of Object.keys(config) as Array<keyof Config & string>) {\n const eventConfig = config[eventName];\n if (!eventConfig) {\n continue;\n }\n\n const actionType = `[${source}] ${eventName}` as const;\n\n if (eventConfig.kind === \"props\") {\n group[eventName] = createTypedActionCreator(\n actionType,\n (payload: Record<string, unknown>) => ({ ...payload }),\n ) as ActionGroupResult<Source, Config>[typeof eventName];\n continue;\n }\n\n group[eventName] = createTypedActionCreator(\n actionType,\n () => ({}),\n ) as ActionGroupResult<Source, Config>[typeof eventName];\n }\n\n return group;\n}\n\n/**\n * Registers one reducer handler for one or more action creators.\n *\n * @throws Error when called without at least one action creator and reducer.\n */\nexport function on<\n State,\n const Creators extends readonly ActionCreator<string, any[], any>[],\n Action extends ActionFromCreators<Creators>,\n>(\n ...args: [\n ...creators: Creators,\n reducer: (state: State, action: Action) => State,\n ]\n): OnReducerEntry<State, Action, Creators> {\n if (args.length < 2) {\n throw new Error(\"on requires at least one action creator and one reducer\");\n }\n\n const reducer = args[args.length - 1] as (\n state: State,\n action: Action,\n ) => State;\n const creators = args.slice(0, -1) as unknown as Creators;\n\n return {\n creators,\n reducer,\n };\n}\n\n/**\n * Creates a reducer from an initial state and `on(...)` handler entries.\n *\n * Unknown action types return the current state unchanged.\n */\nexport function createReducer<\n State,\n const Entries extends readonly OnReducerEntry<any, any, any>[],\n>(\n initialState: State,\n ...entries: Entries\n): Reducer<State, ActionFromOnReducerEntry<Entries[number]>> {\n type ReducerAction = ActionFromOnReducerEntry<Entries[number]>;\n\n const reducerMap = new Map<\n string,\n Array<(state: State, action: ReducerAction) => State>\n >();\n\n for (const entry of entries) {\n for (const creator of entry.creators) {\n const handlers = reducerMap.get(creator.type) ?? [];\n handlers.push(\n entry.reducer as unknown as (\n state: State,\n action: ReducerAction,\n ) => State,\n );\n reducerMap.set(creator.type, handlers);\n }\n }\n\n return (state: State | undefined, action: ReducerAction): State => {\n const currentState = state ?? initialState;\n const handlers = reducerMap.get(action.type);\n\n if (!handlers || handlers.length === 0) {\n return currentState;\n }\n\n let nextState = currentState;\n for (const handler of handlers) {\n nextState = handler(nextState, action);\n }\n return nextState;\n };\n}\n\n/**\n * Creates a memoized selector from a single projector.\n */\nexport function createSelector<State, Result>(\n projector: (state: State) => Result,\n): Selector<State, Result>;\n\n/**\n * Creates a memoized selector from input selectors and a projector.\n *\n * Memoization uses one-entry caching over the latest input selector values.\n */\nexport function createSelector<\n State,\n const Selectors extends readonly Selector<State, unknown>[],\n Result,\n>(\n ...args: [\n ...selectors: Selectors,\n projector: (\n ...inputs: { [K in keyof Selectors]: ReturnType<Selectors[K]> }\n ) => Result,\n ]\n): Selector<State, Result>;\n\n/**\n * Creates a selector that caches and reuses the last computed result\n * when all input references are unchanged.\n */\nexport function createSelector<State, Result>(\n ...args:\n | [(state: State) => Result]\n | [\n ...selectors: Array<Selector<State, unknown>>,\n projector: (...inputs: unknown[]) => Result,\n ]\n): Selector<State, Result> {\n if (args.length === 1) {\n const projector = args[0] as (state: State) => Result;\n let hasCached = false;\n let lastState: State | undefined;\n let lastResult: Result;\n\n return (state: State): Result => {\n if (hasCached && state === lastState) {\n return lastResult;\n }\n\n lastState = state;\n lastResult = projector(state);\n hasCached = true;\n return lastResult;\n };\n }\n\n const projector = args[args.length - 1] as (...inputs: unknown[]) => Result;\n const selectors = args.slice(0, -1) as Array<Selector<State, unknown>>;\n\n let hasCached = false;\n let lastInputs: unknown[] = [];\n let lastResult: Result;\n\n return (state: State): Result => {\n const inputs = selectors.map((selector) => selector(state));\n\n if (\n hasCached &&\n inputs.length === lastInputs.length &&\n inputs.every((value, index) => value === lastInputs[index])\n ) {\n return lastResult;\n }\n\n lastInputs = inputs;\n lastResult = projector(...inputs);\n hasCached = true;\n return lastResult;\n };\n}\n\n/**\n * RxJS operator that maps state emissions through a selector and suppresses\n * unchanged projected values via reference equality.\n */\nexport function select<State, Result>(\n selector: Selector<State, Result>,\n): OperatorFunction<State, Result> {\n return (source$) => source$.pipe(map(selector), distinctUntilChanged());\n}\n\n/**\n * RxJS operator that filters an action stream by action creators and narrows\n * the output action type to the matched creator union.\n *\n * @throws Error when called without at least one action creator.\n */\nexport function ofType<\n const Creators extends readonly ActionCreator<string, any[], AnyAction>[],\n>(\n ...creators: Creators\n): OperatorFunction<AnyAction, ActionFromCreators<Creators>> {\n if (creators.length === 0) {\n throw new Error(\"ofType requires at least one action creator\");\n }\n\n const actionTypes = new Set(creators.map((creator) => creator.type));\n return (source$) => {\n return source$.pipe(\n filter((action: AnyAction): action is ActionFromCreators<Creators> => {\n return actionTypes.has(action.type);\n }),\n );\n };\n}\n\n/**\n * Creates a dispatching effect. Emitted actions are automatically dispatched.\n */\nexport function createEffect<\n State,\n InputAction extends AnyAction,\n OutputAction extends AnyAction,\n>(\n factory: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<OutputAction>,\n options?: DispatchingEffectOptions,\n): DispatchingEffect<State, InputAction, OutputAction>;\n\n/**\n * Creates a non-dispatching effect. Emitted values are ignored.\n */\nexport function createEffect<State, InputAction extends AnyAction>(\n factory: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<unknown>,\n options: NonDispatchingEffectOptions,\n): NonDispatchingEffect<State, InputAction>;\n\n/**\n * Creates an effect descriptor consumed by `createStore`.\n */\nexport function createEffect<\n State,\n InputAction extends AnyAction,\n OutputAction extends AnyAction,\n>(\n factory: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<OutputAction>,\n options: DispatchingEffectOptions | NonDispatchingEffectOptions = {},\n): Effect<State, InputAction, OutputAction> {\n if (options.dispatch === false) {\n return {\n run: factory,\n dispatch: false,\n };\n }\n\n return {\n run: factory,\n dispatch: true,\n };\n}\n\n/**\n * Store interface returned by `createStore`.\n */\nexport interface Store<State, Action extends AnyAction = AnyAction> {\n dispatch(action: Action): void;\n getState(): State;\n readonly state$: Observable<State>;\n readonly actions$: Observable<Action | StoreLifecycleAction>;\n select<Result>(selector: Selector<State, Result>): Observable<Result>;\n init(): void;\n stop(): void;\n}\n\n/**\n * Creates a small observable store with reducer + effects.\n *\n * Behavior:\n * - `init()` starts effects and dispatches `@@micro-redux/init`.\n * - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.\n * - Effect action observation is scheduled on `asapScheduler` to avoid\n * synchronous re-entrancy in the effect loop.\n * - Any effect error triggers fail-fast teardown and errors both `actions$`\n * and `state$`.\n */\nexport function createStore<\n State,\n Action extends AnyAction = AnyAction,\n>(options: {\n reducer: Reducer<State, Action | StoreLifecycleAction>;\n effects?: Array<Effect<State, Action | StoreLifecycleAction, Action>>;\n}): Store<State, Action> {\n const reducer = options.reducer;\n const effects = options.effects ?? [];\n\n let hasFatalError = false;\n let isRunning = false;\n let effectSubscriptions = new Subscription();\n\n let currentState = reducer(\n undefined,\n INTERNAL_BOOT_ACTION as Action | StoreLifecycleAction,\n );\n const stateSubject = new BehaviorSubject<State>(currentState);\n const actionsSubject = new Subject<Action | StoreLifecycleAction>();\n\n const dispatchInternal = (action: Action | StoreLifecycleAction): void => {\n if (hasFatalError) {\n throw new Error(\"Store is in a failed state due to an effect error\");\n }\n\n currentState = reducer(currentState, action);\n stateSubject.next(currentState);\n actionsSubject.next(action);\n };\n\n const failFast = (error: unknown): void => {\n if (hasFatalError) {\n return;\n }\n\n hasFatalError = true;\n isRunning = false;\n effectSubscriptions.unsubscribe();\n effectSubscriptions = new Subscription();\n\n actionsSubject.error(error);\n stateSubject.error(error);\n };\n\n const startEffects = (): void => {\n for (const effect of effects) {\n const scheduledActions$ = actionsSubject\n .asObservable()\n .pipe(observeOn(asapScheduler));\n const state$ = stateSubject.asObservable();\n\n if (effect.dispatch) {\n const subscription = effect.run(scheduledActions$, state$).subscribe({\n next: (effectAction) => {\n if (hasFatalError) {\n return;\n }\n dispatchInternal(effectAction);\n },\n error: (error) => {\n failFast(error);\n },\n });\n\n effectSubscriptions.add(subscription);\n continue;\n }\n\n const subscription = effect.run(scheduledActions$, state$).subscribe({\n error: (error) => {\n failFast(error);\n },\n });\n\n effectSubscriptions.add(subscription);\n }\n };\n\n return {\n dispatch(action: Action): void {\n dispatchInternal(action);\n },\n getState(): State {\n return currentState;\n },\n get state$(): Observable<State> {\n return stateSubject.asObservable();\n },\n get actions$(): Observable<Action | StoreLifecycleAction> {\n return actionsSubject.asObservable();\n },\n select<Result>(selector: Selector<State, Result>): Observable<Result> {\n return stateSubject.asObservable().pipe(select(selector));\n },\n init(): void {\n if (hasFatalError || isRunning) {\n return;\n }\n\n isRunning = true;\n startEffects();\n\n if (hasFatalError) {\n return;\n }\n\n dispatchInternal({ type: INTERNAL_ACTION_TYPES.init });\n },\n stop(): void {\n if (hasFatalError || !isRunning) {\n return;\n }\n\n dispatchInternal({ type: INTERNAL_ACTION_TYPES.stop });\n effectSubscriptions.unsubscribe();\n effectSubscriptions = new Subscription();\n isRunning = false;\n },\n };\n}\n","/**\n * Memory error registry — stable codes for the errors the memory store throws.\n *\n * The memory store (`memory.ts`) used to throw bare `new Error(\"Failed to fetch\n * memories: 500\")` / `\"Request timed out\"` / `\"Request failed: <status>\"`. Those\n * reach the `error` selector (and the consumer UI via `useMemories` /\n * `injectMemories`) verbatim, with no machine-readable `code`/`category`/\n * `retryable`, so they cannot be grouped in observability or branched on by\n * consumers.\n *\n * Per the repo's error-handling architecture standard (AGENTS.md: \"Each project\n * must maintain an explicit error registry\"), this file is the explicit registry\n * for the memory feature. It is deliberately scoped to memory — not a repo-wide\n * registry refactor — because `packages/core` has no pre-existing\n * code/category/retryable registry convention to plug into (the runtime's\n * `lib/error-messages.ts` is a message-templating table, not a typed\n * code/category/retryable registry). It mirrors the existing\n * `AgentThreadLockedError extends Error` precedent in\n * `intelligence-agent.ts`: a real `Error` subclass so `instanceof Error` holds\n * and the public `MemoryState.error: Error | null` contract is preserved.\n *\n * `docsPath` is recorded per entry per the standard; there is no\n * `docs/errors/<project>.md` in this repo, so this docblock plus the registry\n * are the source of truth.\n *\n * Each registry entry carries:\n * - `code`: stable identifier (e.g. `MEMORY_LIST_FAILED`).\n * - `category`: one of the standard categories\n * (`validation`|`auth`|`permission`|`not_found`|`conflict`|`rate_limit`|`internal`|`dependency`).\n * - `retryable`: whether a retry could plausibly succeed (timeouts + transient\n * dependency failures are retryable; client-caused 4xx are not).\n * - `message`: the default human-readable message (callers may override with a\n * status-bearing string to preserve the prior wording).\n * - `docsPath`: documentation pointer for the code.\n */\n\n/** Standard error categories from the repo error-handling architecture. */\nexport type MemoryErrorCategory =\n | \"validation\"\n | \"auth\"\n | \"permission\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limit\"\n | \"internal\"\n | \"dependency\";\n\n/** Stable codes for the memory store's surfaced errors. */\nexport type MemoryErrorCode =\n | \"MEMORY_LIST_FAILED\"\n | \"MEMORY_RECALL_FAILED\"\n | \"MEMORY_CREDENTIALS_FAILED\"\n | \"MEMORY_MUTATION_FAILED\"\n | \"MEMORY_REQUEST_TIMEOUT\";\n\n/** A single registry entry describing one memory error code. */\nexport interface MemoryErrorRegistryEntry {\n readonly code: MemoryErrorCode;\n readonly category: MemoryErrorCategory;\n readonly retryable: boolean;\n readonly message: string;\n readonly docsPath: string;\n}\n\n/**\n * The memory error registry: the single source of truth for memory error\n * metadata. Keyed by `code` so a code maps to exactly one category/retryable\n * default.\n *\n * Categories/retryable rationale:\n * - List/credentials/mutation failures are `dependency` (the runtime/platform\n * the store calls failed). A 5xx is transient (`retryable: true`); a 4xx is\n * caller-caused, so the helpers below downgrade those to non-retryable.\n * - Timeouts are `dependency` and `retryable: true` (the request may simply be\n * slow).\n */\nexport const MEMORY_ERROR_REGISTRY: Readonly<\n Record<MemoryErrorCode, MemoryErrorRegistryEntry>\n> = Object.freeze({\n MEMORY_LIST_FAILED: {\n code: \"MEMORY_LIST_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Failed to fetch memories\",\n docsPath: \"docs/errors/memory.md#memory_list_failed\",\n },\n MEMORY_RECALL_FAILED: {\n code: \"MEMORY_RECALL_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Failed to recall memories\",\n docsPath: \"docs/errors/memory.md#memory_recall_failed\",\n },\n MEMORY_CREDENTIALS_FAILED: {\n code: \"MEMORY_CREDENTIALS_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Failed to fetch memory subscribe credentials\",\n docsPath: \"docs/errors/memory.md#memory_credentials_failed\",\n },\n MEMORY_MUTATION_FAILED: {\n code: \"MEMORY_MUTATION_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Memory mutation request failed\",\n docsPath: \"docs/errors/memory.md#memory_mutation_failed\",\n },\n MEMORY_REQUEST_TIMEOUT: {\n code: \"MEMORY_REQUEST_TIMEOUT\",\n category: \"dependency\",\n retryable: true,\n message: \"Request timed out\",\n docsPath: \"docs/errors/memory.md#memory_request_timeout\",\n },\n});\n\n/**\n * An `Error` carrying a stable memory error `code`, `category`, and `retryable`\n * flag so consumers and observability can branch on it without string-matching\n * the message.\n *\n * It is a real `Error` subclass: `instanceof Error` is true, so the public\n * `MemoryState.error: Error | null` contract (and the `error: Error | null`\n * surfaced by `useMemories` / `injectMemories`) holds unchanged. Existing\n * consumers that only read `.message` keep working; the richer fields are\n * additive.\n */\nexport class MemoryError extends Error {\n /** Stable, machine-readable error identifier. */\n readonly code: MemoryErrorCode;\n /** Coarse error category for grouping/observability. */\n readonly category: MemoryErrorCategory;\n /** Whether retrying the operation could plausibly succeed. */\n readonly retryable: boolean;\n\n /**\n * @param code - Registry code identifying this error.\n * @param options - Optional overrides:\n * - `message`: human-readable message (defaults to the registry message;\n * callers pass a status-bearing string to preserve prior wording).\n * - `retryable`: overrides the registry default (e.g. a 4xx list failure is\n * not retryable even though the code's default is).\n * - `cause`: the underlying error, preserved for debugging.\n */\n constructor(\n code: MemoryErrorCode,\n options?: { message?: string; retryable?: boolean; cause?: unknown },\n ) {\n const entry = MEMORY_ERROR_REGISTRY[code];\n super(options?.message ?? entry.message, { cause: options?.cause });\n this.name = \"MemoryError\";\n this.code = code;\n this.category = entry.category;\n this.retryable = options?.retryable ?? entry.retryable;\n // Restore the prototype chain for environments that downlevel `extends`\n // (matches the pattern the SDK relies on for cross-target `instanceof`).\n Object.setPrototypeOf(this, MemoryError.prototype);\n }\n}\n\n/**\n * Narrows an HTTP status to whether the failure is worth retrying: a 5xx (or a\n * missing/0 status) is a transient dependency failure and retryable; a 4xx is\n * caller-caused and not. Used so a `MEMORY_LIST_FAILED`/`MEMORY_MUTATION_FAILED`\n * carries an accurate `retryable` flag derived from the response status.\n */\nexport function isRetryableStatus(status: number): boolean {\n return !(Number.isInteger(status) && status >= 400 && status <= 499);\n}\n","import { phoenixExponentialBackoff } from \"@copilotkit/shared\";\nimport {\n EMPTY,\n asapScheduler,\n defer,\n firstValueFrom,\n from,\n merge,\n Observable,\n observeOn,\n of,\n} from \"rxjs\";\nimport {\n catchError,\n concatWith,\n filter,\n finalize,\n map,\n mergeMap,\n share,\n shareReplay,\n switchMap,\n take,\n takeUntil,\n timeout,\n withLatestFrom,\n} from \"rxjs/operators\";\nimport {\n createActionGroup,\n createEffect,\n createReducer,\n createSelector,\n createStore,\n empty,\n ofType,\n on,\n props,\n} from \"./utils/micro-redux\";\nimport type { Reducer, Store } from \"./utils/micro-redux\";\nimport { MemoryError, isRetryableStatus } from \"./memory-errors\";\nimport {\n ɵphoenixChannel$,\n ɵphoenixSocket$,\n ɵjoinPhoenixChannel$,\n ɵobservePhoenixEvent$,\n ɵobservePhoenixSocketHealth$,\n ɵobservePhoenixSocketSignals$,\n} from \"./utils/phoenix-observable\";\nimport type { ɵPhoenixChannelSession } from \"./utils/phoenix-observable\";\n\n// Runtime-relative path, mirroring the thread store's `/threads` (NOT\n// `/api/threads`): `runtimeUrl` is the CopilotKit runtime mount (e.g.\n// `/api/copilotkit`), and the runtime maps `/memories` to the app-api's\n// `/api/memories` the same way it maps `/threads` -> `/api/threads`.\nconst MEMORIES_PATH = \"/memories\";\nconst MEMORIES_SUBSCRIBE_PATH = \"/memories/subscribe\";\nconst MEMORIES_RECALL_PATH = \"/memories/recall\";\nconst REQUEST_TIMEOUT_MS = 15_000;\n/** Consecutive socket errors tolerated before the realtime stream gives up. */\nconst MAX_SOCKET_RETRIES = 5;\n/**\n * HTTP status codes that indicate memory routes are not configured (non-fatal).\n * 404/501 mean the route is absent/unimplemented; 422 is the runtime's\n * MISSING_INTELLIGENCE signal (intelligence not configured on the deployment —\n * see packages/runtime/.../handlers/intelligence/memories.ts). All three map to\n * the graceful \"not available\" locked-teaser path, not a hard error.\n */\nconst ROUTE_UNAVAILABLE_STATUSES = new Set([404, 422, 501]);\n/**\n * Thrown when a memory route returns a 404/422/501 — treated as \"not\n * configured\" (422 is the runtime's MISSING_INTELLIGENCE signal).\n */\nclass MemoryRouteUnavailableError extends Error {}\n\n/** Public, customer-facing memory kind vocabulary (single taxonomy, no mapping). */\nexport type MemoryKind = \"topical\" | \"episodic\" | \"operational\";\n\n/** Visibility scope of a memory. */\nexport type MemoryScope = \"user\" | \"project\";\n\n/**\n * Health of the realtime (`user_meta:memories:<code>`) connection that streams\n * live `memory_metadata` deltas. Distinct from `available`/`error`, which\n * describe the REST list route: `realtimeStatus` reports ONLY whether the\n * realtime socket/channel is live so the UI can stop showing a \"live\" indicator\n * over a frozen snapshot once the socket permanently gives up.\n *\n * - `\"connecting\"` — fetching join credentials / opening the socket / joining\n * the channel (the default, and the state every `contextChanged`/`stopped`\n * resets to).\n * - `\"connected\"` — the channel join succeeded; live deltas are flowing.\n * - `\"unavailable\"` — the socket exhausted its retries or the join failed\n * permanently; the snapshot is frozen and no deltas will arrive. This is a\n * silent degrade for `available`/`error` (those stay untouched) — only this\n * signal flips.\n */\nexport type MemoryRealtimeStatus = \"connecting\" | \"connected\" | \"unavailable\";\n\n/**\n * A memory as projected across the public REST/realtime boundary — the minimal\n * shape the SDK surfaces. Mirrors the server's `PublicMemory` projection.\n */\nexport interface Memory {\n id: string;\n kind: MemoryKind;\n scope: MemoryScope;\n content: string;\n sourceThreadIds: readonly string[];\n invalidatedAt: string | null;\n /** Relevance score from a `recall()` (hybrid RAG) query; `undefined` for list/realtime/mutation memories. */\n score?: number;\n}\n\n/** Input for creating a memory; `scope` defaults to `\"user\"` (v1 is user-scoped). */\nexport interface NewMemory {\n content: string;\n kind: MemoryKind;\n scope?: MemoryScope;\n sourceThreadIds?: readonly string[];\n}\n\n/**\n * New values for superseding (updating) a memory — same shape as create.\n *\n * Supersede is a FULL replacement, not a partial patch: this is the complete\n * definition of the new memory that replaces the old one. `content` and `kind`\n * are required and must be re-supplied, and an omitted `sourceThreadIds` resets\n * the new memory's source threads to `[]` — it does NOT preserve the prior\n * memory's value.\n */\nexport type MemoryChanges = NewMemory;\n\n/** Outcome of a mutation, tracked so the caller's promise resolves/rejects. */\ntype MemoryMutationOutcome =\n | { requestId: string; sessionId: number; ok: true; memory: Memory | null }\n | { requestId: string; sessionId: number; ok: false; error: Error };\n\n/**\n * Runtime wiring for the memory store: where to reach the REST surface and the\n * headers (auth + `X-Cpki-User-Id`) to send. Scoped to the current user; v1\n * surfaces user-scoped memories only.\n */\ninterface MemoryRuntimeContext {\n runtimeUrl: string;\n /** WebSocket URL for the realtime gateway (e.g. `wss://gw.example.com/client`). */\n wsUrl: string;\n /**\n * Optional: `environment.fetch` is expected to be `ɵruntimeFetch`, which\n * already resolves and overlays the current core headers at send time\n * (#1937). Set explicitly only when the store's `fetch` does NOT already\n * carry headers.\n */\n headers?: Record<string, string>;\n includeInvalidated?: boolean;\n}\n\n/**\n * In-memory state for the memory store. Session-guarded like the thread store:\n * `sessionId` is bumped whenever the runtime context changes so that responses\n * and realtime deltas from a previous context are ignored.\n */\ninterface MemoryState {\n memories: Memory[];\n isLoading: boolean;\n inFlightMutationCount: number;\n error: Error | null;\n context: MemoryRuntimeContext | null;\n sessionId: number;\n available: boolean;\n realtimeStatus: MemoryRealtimeStatus;\n}\n\n// Deep-frozen so `getServerState()` (which returns this exact reference) cannot\n// be mutated by any caller; a single in-place write would otherwise corrupt\n// every SSR snapshot process-wide. The freeze covers the nested `memories`\n// array too — a shallow `Object.freeze` would leave `getServerState().memories`\n// mutable (`.push(...)` would silently succeed), so the empty array is frozen\n// before being sealed into the state. The reducers always build NEW state\n// objects/arrays (they spread, never mutate in place), so they are unaffected\n// and runtime behavior is unchanged.\nconst initialMemoryState: MemoryState = Object.freeze({\n memories: Object.freeze([]) as unknown as Memory[],\n isLoading: false,\n inFlightMutationCount: 0,\n error: null,\n context: null,\n sessionId: 0,\n available: true,\n realtimeStatus: \"connecting\",\n});\n\nconst memoryAdapterEvents = createActionGroup(\"Memory Adapter\", {\n started: empty(),\n stopped: empty(),\n contextChanged: props<{ context: MemoryRuntimeContext | null }>(),\n addRequested: props<{ requestId: string; input: NewMemory }>(),\n updateRequested: props<{\n requestId: string;\n id: string;\n changes: MemoryChanges;\n }>(),\n removeRequested: props<{ requestId: string; id: string }>(),\n});\n\nconst memoryRestEvents = createActionGroup(\"Memory REST\", {\n listRequested: props<{ sessionId: number }>(),\n listSucceeded: props<{ sessionId: number; memories: Memory[] }>(),\n listFailed: props<{ sessionId: number; error: Error }>(),\n listUnavailable: props<{ sessionId: number }>(),\n mutationFinished: props<{ outcome: MemoryMutationOutcome }>(),\n credentialsRequested: props<{ sessionId: number }>(),\n credentialsSucceeded: props<{\n sessionId: number;\n joinToken?: string;\n joinCode?: string;\n // Optional project-scoped realtime credentials. Present only when the\n // caller's API key resolves a project scope (B1b `/memories/subscribe`\n // returns them alongside the user credentials); omitted otherwise. When\n // present, the socket effect opens a SECOND `project_meta:memories:<code>`\n // channel so project rows stay live. Absent -> user-only (silent degrade).\n projectJoinToken?: string;\n projectJoinCode?: string;\n }>(),\n // Credentials outcomes are a SILENT degrade: they feed only the realtime\n // socket effect and deliberately do NOT touch the reducer's `available`/\n // `error`, which describe the REST list route. See the reducer note near the\n // list handlers.\n credentialsFailed: props<{ sessionId: number; error: Error }>(),\n credentialsUnavailable: props<{ sessionId: number }>(),\n});\n\nconst memoryDomainEvents = createActionGroup(\"Memory Domain\", {\n memoryUpserted: props<{ sessionId: number; memory: Memory }>(),\n memoryInvalidated: props<{ sessionId: number; memoryId: string }>(),\n // Realtime-connection health transitions, session-stamped like every other\n // realtime delta so the reducer's session guard drops transitions left over\n // from a superseded context. These flip ONLY `realtimeStatus`; they never\n // touch `available`/`error` (the realtime path is a silent degrade for those).\n realtimeConnecting: props<{ sessionId: number }>(),\n realtimeConnected: props<{ sessionId: number }>(),\n realtimeUnavailable: props<{ sessionId: number }>(),\n});\n\n/** Wire shape of a memory inside a `memory_metadata` payload (carries tenant ids). */\ninterface MemoryMetadataPayloadMemory extends Memory {\n organizationId: string;\n projectId: string;\n}\n\n/**\n * The realtime `memory_metadata` event broadcast on a memory channel:\n * `created`/`updated` carry the full memory, `invalidated` carries only its id.\n * The same wire shape is delivered on both the user channel\n * (`user_meta:memories:<code>`, current user's memories) and the optional\n * project channel (`project_meta:memories:<code>`, memories shared across the\n * project); the store reduces both into one id-keyed list.\n */\ntype MemoryMetadataEvent =\n | {\n operation: \"created\" | \"updated\";\n memoryId: string;\n organizationId: string;\n projectId: string;\n occurredAt: string;\n memory: MemoryMetadataPayloadMemory;\n }\n | {\n operation: \"invalidated\";\n memoryId: string;\n organizationId: string;\n projectId: string;\n occurredAt: string;\n invalidated: { id: string };\n };\n\n/** Projects a wire memory to the public {@link Memory} shape (drops tenant ids). */\nfunction toMemory(memory: MemoryMetadataPayloadMemory): Memory {\n return {\n id: memory.id,\n kind: memory.kind,\n scope: memory.scope,\n content: memory.content,\n sourceThreadIds: memory.sourceThreadIds,\n invalidatedAt: memory.invalidatedAt,\n };\n}\n\n/**\n * Maps a realtime `memory_metadata` event to the domain action that applies it:\n * `created`/`updated` upsert the projected memory, `invalidated` removes it by\n * id. Carries the current `sessionId` so the reducer's session guard can drop\n * deltas left over from a previous context.\n */\nfunction mapMemoryMetadataEvent(\n event: MemoryMetadataEvent,\n sessionId: number,\n):\n | ReturnType<typeof memoryDomainEvents.memoryUpserted>\n | ReturnType<typeof memoryDomainEvents.memoryInvalidated> {\n if (event.operation === \"invalidated\") {\n return memoryDomainEvents.memoryInvalidated({\n sessionId,\n memoryId: event.invalidated.id,\n });\n }\n\n return memoryDomainEvents.memoryUpserted({\n sessionId,\n memory: toMemory(event.memory),\n });\n}\n\n/**\n * Inserts or replaces a memory by id. A new memory is prepended (newest first,\n * matching the REST list's `created_at DESC` ordering without needing a date\n * field on the public projection); an existing memory is replaced in place.\n */\nfunction upsertMemory(memories: Memory[], memory: Memory): Memory[] {\n const existingIndex = memories.findIndex((item) => item.id === memory.id);\n if (existingIndex === -1) {\n return [memory, ...memories];\n }\n\n const next = [...memories];\n next[existingIndex] = memory;\n return next;\n}\n\nconst memoryReducer = createReducer(\n initialMemoryState,\n on(memoryAdapterEvents.contextChanged, (state: MemoryState, { context }) => ({\n ...state,\n context,\n sessionId: state.sessionId + 1,\n memories: [],\n isLoading: Boolean(context),\n inFlightMutationCount: 0,\n error: null,\n available: true,\n // A new context re-opens the realtime socket from scratch, so the connection\n // is \"connecting\" again until the new channel joins.\n realtimeStatus: \"connecting\" as MemoryRealtimeStatus,\n })),\n on(memoryAdapterEvents.stopped, (state: MemoryState) => ({\n ...state,\n memories: [],\n isLoading: false,\n inFlightMutationCount: 0,\n error: null,\n // Reset to the default (`true`), matching `contextChanged`. Otherwise a\n // `stop()` then `start()` WITHOUT a new `setContext` would retain a stale\n // `available: false` from a prior unconfigured session.\n available: true,\n // Reset to the default (\"connecting\"), matching `contextChanged`. A later\n // `start()` re-opens the socket; a stale \"unavailable\"/\"connected\" from the\n // prior session must not leak into the next.\n realtimeStatus: \"connecting\" as MemoryRealtimeStatus,\n })),\n on(memoryRestEvents.listRequested, (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId || !state.context) {\n return state;\n }\n\n return {\n ...state,\n isLoading: true,\n error: null,\n available: true,\n };\n }),\n on(\n memoryRestEvents.listFailed,\n (state: MemoryState, { sessionId, error }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n isLoading: false,\n error,\n };\n },\n ),\n on(memoryRestEvents.listUnavailable, (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories: [],\n isLoading: false,\n error: null,\n available: false,\n };\n }),\n on(\n memoryAdapterEvents.addRequested,\n memoryAdapterEvents.updateRequested,\n memoryAdapterEvents.removeRequested,\n (state: MemoryState) => ({\n ...state,\n inFlightMutationCount: state.inFlightMutationCount + 1,\n }),\n ),\n on(memoryRestEvents.mutationFinished, (state: MemoryState, { outcome }) => {\n // Drop results from a superseded session. `contextChanged`/`stopped` already\n // reset `inFlightMutationCount`, so a mutation that resolves after the\n // context switched must not write a stale error into the new session.\n // Mirrors every other session-scoped handler (and threads.ts).\n if (outcome.sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n inFlightMutationCount: Math.max(0, state.inFlightMutationCount - 1),\n // On success clear any previously surfaced mutation error so a later\n // successful mutation does not leave a phantom sticky error banner.\n error: outcome.ok ? null : outcome.error,\n };\n }),\n on(\n memoryRestEvents.listSucceeded,\n (state: MemoryState, { sessionId, memories }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories,\n isLoading: false,\n error: null,\n // A successful list proves the memory route is available.\n available: true,\n };\n },\n ),\n // NOTE: `credentialsFailed` and `credentialsUnavailable` intentionally have NO\n // reducer cases. `available`/`error` describe the REST list route only and are\n // driven exclusively by the list events above. The credentials/realtime path\n // is a silent degrade by design: a missing/unconfigured `/memories/subscribe`\n // route (404/501/422) or a credentials error must not flip `available` or\n // surface an `error`, because the list route can still be perfectly healthy.\n // Otherwise `available` would be order-dependent on whichever of the two\n // concurrent `contextChanged` bootstraps responds last. Realtime failures are\n // handled where they occur (the socket effect retries and gives up via\n // console.warn); they do not belong in the REST availability state.\n on(\n memoryDomainEvents.memoryUpserted,\n (state: MemoryState, { sessionId, memory }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories: upsertMemory(state.memories, memory),\n };\n },\n ),\n on(\n memoryDomainEvents.memoryInvalidated,\n (state: MemoryState, { sessionId, memoryId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories: state.memories.filter((memory) => memory.id !== memoryId),\n };\n },\n ),\n // Realtime-connection health. Session-guarded so a transition from a\n // superseded context is ignored. These flip ONLY `realtimeStatus`; `available`\n // and `error` describe the REST list route and are intentionally untouched.\n on(\n memoryDomainEvents.realtimeConnecting,\n (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n realtimeStatus: \"connecting\" as MemoryRealtimeStatus,\n };\n },\n ),\n on(\n memoryDomainEvents.realtimeConnected,\n (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n realtimeStatus: \"connected\" as MemoryRealtimeStatus,\n };\n },\n ),\n on(\n memoryDomainEvents.realtimeUnavailable,\n (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n realtimeStatus: \"unavailable\" as MemoryRealtimeStatus,\n };\n },\n ),\n) as Reducer<MemoryState>;\n\nconst selectMemories = createSelector((state: MemoryState) => state.memories);\nconst selectMemoriesIsLoading = createSelector(\n (state: MemoryState) => state.isLoading,\n);\nconst selectMemoriesError = createSelector((state: MemoryState) => state.error);\n/**\n * Reports whether at least one mutation is in flight. Derived from\n * `inFlightMutationCount` so concurrent mutations stay correct: the boolean\n * only clears once every in-flight mutation has settled.\n */\nconst selectMemoriesIsMutating = createSelector(\n (state: MemoryState) => state.inFlightMutationCount > 0,\n);\n/**\n * Reports whether the memory routes are available. Becomes `false` after a\n * 404, 422 (the runtime's MISSING_INTELLIGENCE signal), or 501 response during\n * an auto-activation read; defaults to `true`.\n */\nconst selectMemoriesAvailable = createSelector(\n (state: MemoryState) => state.available,\n);\n/**\n * Reports the realtime-connection health (see {@link MemoryRealtimeStatus}).\n * Distinct from `available`/`error`: it reflects ONLY the live socket/channel,\n * so the UI can suppress a \"live\" indicator once realtime permanently dies even\n * while the REST list route stays healthy. Defaults to `\"connecting\"`.\n */\nconst selectMemoriesRealtimeStatus = createSelector(\n (state: MemoryState) => state.realtimeStatus,\n);\n\n/**\n * Dependencies injected into the memory store. The store opens its own\n * `user_meta:memories:<joinCode>` socket/channel and does not share the\n * thread store's socket, so only a `fetch` implementation is required.\n */\ninterface MemoryEnvironment {\n fetch: typeof fetch;\n}\n\ninterface MemoryStore {\n start(): void;\n stop(): void;\n setContext(context: MemoryRuntimeContext | null): void;\n /**\n * Re-fetches the REST snapshot without clearing the current list. Resolves\n * once the re-pull settles (success or failure) for the current context, so\n * callers (e.g. a `useMemories` `refresh()`) can await it. Resolves\n * immediately when no context is set.\n */\n refresh(): Promise<void>;\n /**\n * Semantically recalls memories via `POST {runtimeUrl}/memories/recall`\n * (hybrid RAG). Returns memories ordered by relevance, each carrying a\n * `score`. Does NOT mutate the snapshot — a one-shot query. Rejects when no\n * context is set or the request fails.\n */\n recall(\n query: string,\n opts?: { limit?: number; scope?: MemoryScope },\n ): Promise<Memory[]>;\n /** Creates a memory; resolves to the stored memory (server-authoritative). */\n addMemory(input: NewMemory): Promise<Memory>;\n /** Supersedes a memory; resolves to the new memory (its id changes). */\n updateMemory(id: string, changes: MemoryChanges): Promise<Memory>;\n /** Retires a memory (non-lossy delete). */\n removeMemory(id: string): Promise<void>;\n getState(): MemoryState;\n /**\n * Stable, render-safe state for SSR/prerender. React's\n * `useSyncExternalStore` requires a `getServerSnapshot` during SSR/prerender\n * (e.g. Next.js); without one React throws \"Missing getServerSnapshot\". The\n * returned reference is stable across calls so React does not loop. There is\n * no client-side memory data during prerender, so this is the empty initial\n * state (no memories, not loading, no error).\n */\n getServerState(): MemoryState;\n select: Store<MemoryState>[\"select\"];\n}\n\nconst MEMORY_METADATA_EVENT = \"memory_metadata\";\n\n/** Runs a memory request through the injected fetch and aborts on unsubscribe. */\nfunction memoryFromFetch<T>(\n input: string,\n init: RequestInit & {\n selector: (response: Response) => Promise<T>;\n fetch: typeof fetch;\n },\n): Observable<T> {\n const {\n selector,\n fetch: fetchImplementation,\n signal: outerSignal,\n ...requestInit\n } = init;\n\n return new Observable<T>((subscriber) => {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (outerSignal?.aborted) {\n controller.abort();\n } else {\n outerSignal?.addEventListener(\"abort\", abort);\n }\n\n const subscription = from(\n fetchImplementation(input, {\n ...requestInit,\n signal: controller.signal,\n }),\n )\n .pipe(mergeMap((response) => from(selector(response))))\n .subscribe(subscriber);\n\n return () => {\n outerSignal?.removeEventListener(\"abort\", abort);\n controller.abort();\n subscription.unsubscribe();\n };\n });\n}\n\n/**\n * Fetches the memory snapshot and maps it to a success/failure action. Both\n * user- and project-scoped rows are kept: the store now opens a second\n * `project_meta:memories:<code>` realtime channel (when project credentials are\n * available) that keeps project rows in sync, so surfacing them in the snapshot\n * no longer risks a stale list. Rows are keyed by id across both channels, so\n * realtime deltas reconcile either scope idempotently.\n */\nfunction createMemoryFetchObservable(\n environment: MemoryEnvironment,\n context: MemoryRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof memoryRestEvents.listSucceeded>\n | ReturnType<typeof memoryRestEvents.listFailed>\n | ReturnType<typeof memoryRestEvents.listUnavailable>\n> {\n return defer(() => {\n const qs = context.includeInvalidated ? \"?includeInvalidated=true\" : \"\";\n return memoryFromFetch(`${context.runtimeUrl}${MEMORIES_PATH}${qs}`, {\n selector: (response) => {\n if (!response.ok) {\n if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) {\n throw new MemoryRouteUnavailableError(String(response.status));\n }\n throw new MemoryError(\"MEMORY_LIST_FAILED\", {\n message: `Failed to fetch memories: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n\n return response.json() as Promise<{ memories: Memory[] }>;\n },\n fetch: environment.fetch,\n method: \"GET\",\n headers: { ...context.headers },\n }).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n map((data) =>\n memoryRestEvents.listSucceeded({\n sessionId,\n memories: data.memories,\n }),\n ),\n catchError((error) => {\n if (error instanceof MemoryRouteUnavailableError) {\n return of(memoryRestEvents.listUnavailable({ sessionId }));\n }\n return of(\n memoryRestEvents.listFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n );\n });\n}\n\n/**\n * Fetches join credentials from the `/memories/subscribe` endpoint and maps\n * the response to a success/failure action. Requires both `joinToken` and\n * `joinCode` to be non-empty strings; throws otherwise so the `catchError`\n * path emits `credentialsFailed`.\n */\nfunction createMemoryCredentialsFetchObservable(\n environment: MemoryEnvironment,\n context: MemoryRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof memoryRestEvents.credentialsSucceeded>\n | ReturnType<typeof memoryRestEvents.credentialsFailed>\n | ReturnType<typeof memoryRestEvents.credentialsUnavailable>\n> {\n return defer(() =>\n memoryFromFetch(`${context.runtimeUrl}${MEMORIES_SUBSCRIBE_PATH}`, {\n selector: async (response) => {\n if (!response.ok) {\n if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) {\n throw new MemoryRouteUnavailableError(String(response.status));\n }\n throw new MemoryError(\"MEMORY_CREDENTIALS_FAILED\", {\n message: `Failed to fetch memory subscribe credentials: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n\n return response.json() as Promise<{\n joinToken?: string;\n joinCode?: string;\n projectJoinToken?: string;\n projectJoinCode?: string;\n }>;\n },\n fetch: environment.fetch,\n method: \"POST\",\n headers: { ...context.headers, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({}),\n }).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n map((data) => {\n const hasUserCreds =\n typeof data.joinToken === \"string\" &&\n data.joinToken.length > 0 &&\n typeof data.joinCode === \"string\" &&\n data.joinCode.length > 0;\n\n // Project credentials are optional and only forwarded when BOTH are\n // non-empty strings (the silent-degrade contract): a partial/malformed\n // pair is treated as \"no project scope\", so the store falls back to the\n // user channel only rather than erroring. A missing project scope must\n // never fail credentials — the user channel is the baseline.\n const hasProjectCreds =\n typeof data.projectJoinToken === \"string\" &&\n data.projectJoinToken.length > 0 &&\n typeof data.projectJoinCode === \"string\" &&\n data.projectJoinCode.length > 0;\n if (!hasUserCreds && !hasProjectCreds) {\n throw new Error(\"missing memory realtime credentials\");\n }\n\n return memoryRestEvents.credentialsSucceeded({\n sessionId,\n ...(hasUserCreds\n ? { joinToken: data.joinToken, joinCode: data.joinCode }\n : {}),\n ...(hasProjectCreds\n ? {\n projectJoinToken: data.projectJoinToken,\n projectJoinCode: data.projectJoinCode,\n }\n : {}),\n });\n }),\n catchError((error) => {\n if (error instanceof MemoryRouteUnavailableError) {\n return of(memoryRestEvents.credentialsUnavailable({ sessionId }));\n }\n return of(\n memoryRestEvents.credentialsFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n ),\n );\n}\n\ntype MemoryMutationAction =\n | ReturnType<typeof memoryDomainEvents.memoryUpserted>\n | ReturnType<typeof memoryDomainEvents.memoryInvalidated>\n | ReturnType<typeof memoryRestEvents.mutationFinished>;\n\ntype MemoryMutationRequest =\n | {\n requestId: string;\n sessionId: number;\n kind: \"add\";\n body: Record<string, unknown>;\n }\n | {\n requestId: string;\n sessionId: number;\n kind: \"update\";\n id: string;\n body: Record<string, unknown>;\n }\n | { requestId: string; sessionId: number; kind: \"remove\"; id: string };\n\n/** Projects a REST mutation response to the public {@link Memory} shape. */\nfunction responseToMemory(data: {\n id: string;\n kind: MemoryKind;\n scope: MemoryScope;\n content: string;\n sourceThreadIds: readonly string[];\n invalidatedAt: string | null;\n}): Memory {\n return {\n id: data.id,\n kind: data.kind,\n scope: data.scope,\n content: data.content,\n sourceThreadIds: data.sourceThreadIds,\n invalidatedAt: data.invalidatedAt,\n };\n}\n\n/**\n * Projects a recall REST response memory (which carries a relevance `score`)\n * to the public {@link Memory} shape. `score` is copied through when supplied.\n */\nfunction recallResponseToMemory(data: {\n id: string;\n kind: MemoryKind;\n scope: MemoryScope;\n content: string;\n sourceThreadIds: readonly string[];\n invalidatedAt: string | null;\n score?: number;\n}): Memory {\n return {\n id: data.id,\n kind: data.kind,\n scope: data.scope,\n content: data.content,\n sourceThreadIds: data.sourceThreadIds,\n invalidatedAt: data.invalidatedAt,\n ...(typeof data.score === \"number\" ? { score: data.score } : {}),\n };\n}\n\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Validates the required fields of a create/supersede REST response before it is\n * projected to a {@link Memory}. Returns an `Error` describing the first\n * missing/invalid field, or `null` when the body is well-formed. Without this a\n * malformed 200 body yields a Memory with undefined fields that gets upserted.\n */\nfunction validateMutationResponse(\n data: Record<string, unknown> | null,\n): Error | null {\n if (!data || typeof data !== \"object\") {\n return new Error(\"memory mutation response missing/invalid body\");\n }\n if (typeof data.id !== \"string\" || data.id.length === 0) {\n return new Error(\"memory mutation response missing/invalid id\");\n }\n if (typeof data.kind !== \"string\" || !MEMORY_KINDS.has(data.kind)) {\n return new Error(\"memory mutation response missing/invalid kind\");\n }\n if (typeof data.scope !== \"string\" || !MEMORY_SCOPES.has(data.scope)) {\n return new Error(\"memory mutation response missing/invalid scope\");\n }\n if (typeof data.content !== \"string\") {\n return new Error(\"memory mutation response missing/invalid content\");\n }\n // `sourceThreadIds` is `readonly string[]` on the public Memory; a malformed\n // 200 that omits it (or sends a non-array) would otherwise yield a Memory\n // whose `sourceThreadIds` is `undefined`, violating the type for every\n // consumer that maps over it.\n if (\n !Array.isArray(data.sourceThreadIds) ||\n !data.sourceThreadIds.every((id) => typeof id === \"string\")\n ) {\n return new Error(\n \"memory mutation response missing/invalid sourceThreadIds\",\n );\n }\n // `invalidatedAt` is `string | null`; reject any other type so it is not\n // copied through as `undefined`.\n if (data.invalidatedAt !== null && typeof data.invalidatedAt !== \"string\") {\n return new Error(\"memory mutation response missing/invalid invalidatedAt\");\n }\n return null;\n}\n\n/**\n * Request body for create/supersede. `scope` is forwarded only when the caller\n * supplies it: the platform owns the default (`scope` defaults to `\"user\"` in\n * the `/api/memories` schema), so the store does not second-guess it here —\n * one default, at the contract owner. `sourceThreadIds` defaults to `[]`.\n */\nfunction toMutationBody(input: NewMemory): Record<string, unknown> {\n return {\n content: input.content,\n kind: input.kind,\n ...(input.scope !== undefined ? { scope: input.scope } : {}),\n sourceThreadIds: input.sourceThreadIds ?? [],\n };\n}\n\n/**\n * Builds the actions a successful mutation dispatches (server-authoritative):\n * the REST response is applied to local state immediately, and the realtime\n * event reconciles idempotently (upsert-by-id). `mutationFinished` resolves the\n * caller's promise.\n */\nfunction buildMutationSuccessActions(\n request: MemoryMutationRequest,\n data: Record<string, unknown> | null,\n): MemoryMutationAction[] {\n const { requestId, sessionId } = request;\n\n if (request.kind === \"remove\") {\n // The platform's DELETE returns a bare 204 with NO body (the runtime\n // handler responds `new Response(null, { status: 204 })` and the client's\n // `removeMemory` is `Promise<void>`), so there is no confirmation field to\n // validate here — removal is status-code-confirmed. We optimistically remove\n // the row locally on any 2xx; the realtime `memory_metadata` `invalidated`\n // event (and the next REST refresh) reconcile idempotently.\n return [\n memoryDomainEvents.memoryInvalidated({ sessionId, memoryId: request.id }),\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: true, memory: null },\n }),\n ];\n }\n\n // Validate the required fields before projecting. A malformed 200 body would\n // otherwise yield a Memory with undefined fields that gets upserted into\n // state. Fail the mutation instead, mirroring the `retiredId` validation\n // below and the credentials path's joinToken/joinCode validation.\n const validationError = validateMutationResponse(data);\n if (validationError) {\n return [\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: false, error: validationError },\n }),\n ];\n }\n\n const memory = responseToMemory(\n data as Parameters<typeof responseToMemory>[0],\n );\n\n if (request.kind === \"update\") {\n // `retiredId` is optional on the server type. Without it the\n // `memoryInvalidated` would be a no-op (no id to remove), leaving the old\n // memory as a duplicate next to the new one. Validate it like the\n // credentials path validates joinToken/joinCode, and fail the mutation\n // rather than apply a half-baked supersede.\n const retiredId = (data as { retiredId?: string }).retiredId;\n if (typeof retiredId !== \"string\" || retiredId.length === 0) {\n return [\n memoryRestEvents.mutationFinished({\n outcome: {\n requestId,\n sessionId,\n ok: false,\n error: new Error(\"supersede response missing retiredId\"),\n },\n }),\n ];\n }\n\n return [\n memoryDomainEvents.memoryInvalidated({ sessionId, memoryId: retiredId }),\n memoryDomainEvents.memoryUpserted({ sessionId, memory }),\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: true, memory },\n }),\n ];\n }\n\n return [\n memoryDomainEvents.memoryUpserted({ sessionId, memory }),\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: true, memory },\n }),\n ];\n}\n\n/** Performs a create/supersede/retire HTTP call and emits its resulting actions. */\nfunction createMemoryMutationObservable(\n environment: MemoryEnvironment,\n context: MemoryRuntimeContext,\n request: MemoryMutationRequest,\n): Observable<MemoryMutationAction> {\n const method =\n request.kind === \"add\"\n ? \"POST\"\n : request.kind === \"update\"\n ? \"PATCH\"\n : \"DELETE\";\n const path =\n request.kind === \"add\"\n ? MEMORIES_PATH\n : `${MEMORIES_PATH}/${encodeURIComponent(request.id)}`;\n\n return defer(() =>\n memoryFromFetch(`${context.runtimeUrl}${path}`, {\n selector: async (response) => {\n if (!response.ok) {\n throw new MemoryError(\"MEMORY_MUTATION_FAILED\", {\n message: `Request failed: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n\n return request.kind === \"remove\"\n ? null\n : ((await response.json()) as Record<string, unknown>);\n },\n fetch: environment.fetch,\n method,\n headers: { ...context.headers, \"Content-Type\": \"application/json\" },\n body:\n request.kind === \"remove\" ? undefined : JSON.stringify(request.body),\n }).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n mergeMap((data) => of(...buildMutationSuccessActions(request, data))),\n catchError((error) =>\n of(\n memoryRestEvents.mutationFinished({\n outcome: {\n requestId: request.requestId,\n sessionId: request.sessionId,\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n }),\n ),\n ),\n ),\n );\n}\n\n/**\n * Creates the framework-agnostic memory store: a REST snapshot on `setContext`,\n * server-authoritative add/update/remove mutations, and realtime\n * `memory_metadata` deltas off the injected `user_meta` event source — all\n * reduced into observable state.\n */\nfunction createMemoryStore(environment: MemoryEnvironment): MemoryStore {\n // Per-store request-id counter. Kept as a closure variable (not a\n // module-level global) so each store instance has its own monotonic sequence:\n // sharing one global across instances is a latent cross-instance/SSR hazard\n // and makes request ids non-reproducible in tests that reset a single store.\n let memoryRequestId = 0;\n const createMemoryRequestId = (): string => {\n memoryRequestId += 1;\n return `memory-request-${memoryRequestId}`;\n };\n\n const bootstrapEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryAdapterEvents.contextChanged),\n withLatestFrom(state$),\n filter(([, state]) => Boolean(state.context)),\n map(([, state]) =>\n memoryRestEvents.listRequested({ sessionId: state.sessionId }),\n ),\n ),\n );\n\n const credentialsBootstrapEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryAdapterEvents.contextChanged),\n withLatestFrom(state$),\n filter(([, state]) => Boolean(state.context)),\n map(([, state]) =>\n memoryRestEvents.credentialsRequested({ sessionId: state.sessionId }),\n ),\n ),\n );\n\n const credentialsFetchEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryRestEvents.credentialsRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is MemoryRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n memoryAdapterEvents.contextChanged,\n memoryAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createMemoryCredentialsFetchObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const fetchEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryRestEvents.listRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is MemoryRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n memoryAdapterEvents.contextChanged,\n memoryAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createMemoryFetchObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const mutationEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(\n memoryAdapterEvents.addRequested,\n memoryAdapterEvents.updateRequested,\n memoryAdapterEvents.removeRequested,\n ),\n withLatestFrom(state$),\n mergeMap(([action, state]) => {\n const context = state.context;\n const sessionId = state.sessionId;\n if (!context?.runtimeUrl) {\n return of(\n memoryRestEvents.mutationFinished({\n outcome: {\n requestId: action.requestId,\n sessionId,\n ok: false,\n error: new Error(\"Runtime URL is not configured\"),\n },\n }),\n );\n }\n\n if (memoryAdapterEvents.addRequested.match(action)) {\n return createMemoryMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n kind: \"add\",\n body: toMutationBody(action.input),\n });\n }\n if (memoryAdapterEvents.updateRequested.match(action)) {\n return createMemoryMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n kind: \"update\",\n id: action.id,\n body: toMutationBody(action.changes),\n });\n }\n return createMemoryMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n kind: \"remove\",\n id: action.id,\n });\n }),\n ),\n );\n\n const socketEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryRestEvents.credentialsSucceeded),\n withLatestFrom(state$),\n filter(([action, state]) => {\n return (\n action.sessionId === state.sessionId &&\n Boolean(state.context?.wsUrl)\n );\n }),\n switchMap(([action, state]) => {\n const context = state.context as MemoryRuntimeContext;\n const { joinToken, joinCode, projectJoinToken, projectJoinCode } =\n action;\n const primaryJoinToken = joinToken ?? projectJoinToken!;\n const primaryTopic =\n joinToken && joinCode\n ? `user_meta:memories:${joinCode}`\n : `project_meta:memories:${projectJoinCode!}`;\n const sessionId = action.sessionId;\n const shutdown$ = actions$.pipe(\n ofType(\n memoryAdapterEvents.contextChanged,\n memoryAdapterEvents.stopped,\n ),\n );\n\n // Builds the live `memory_metadata` delta stream for one realtime\n // channel (its own socket, keyed by that channel's join token). Both\n // the user channel and the optional project channel feed the SAME\n // reducer through this, and — critically — both stamp their deltas\n // with the SAME `sessionId` (the D4 landmine): the reducer's\n // superseded-context guard therefore drops stale deltas from BOTH\n // channels identically the moment the context changes. The reducer's\n // upsert/invalidate already key by memory id, so interleaving user\n // and project rows is safe (no per-channel bookkeeping needed).\n const channelMetadata$ = (\n channelJoinToken: string,\n topic: string,\n ): Observable<\n | ReturnType<typeof memoryDomainEvents.memoryUpserted>\n | ReturnType<typeof memoryDomainEvents.memoryInvalidated>\n > => {\n const socket$ = ɵphoenixSocket$({\n url: context.wsUrl,\n options: {\n params: { join_token: channelJoinToken },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const channel$ = ɵphoenixChannel$({ socket$, topic }).pipe(\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n const metadata$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<MemoryMetadataEvent>(\n channel,\n MEMORY_METADATA_EVENT,\n ),\n ),\n map((event) => mapMemoryMetadataEvent(event, sessionId)),\n );\n // Drive the join (see the user-channel note below) but swallow its\n // outcome: the project channel deliberately does NOT emit realtime\n // status deltas — `realtimeStatus` is owned by the user channel so\n // a project-channel join failure never regresses the user-facing\n // \"live\" indicator (silent degrade). On failure the metadata stream\n // stays alive for Phoenix's automatic rejoin on reconnect.\n const join$ = ɵjoinPhoenixChannel$(channel$).pipe(\n catchError((error) => {\n console.warn(`[memory] failed to join ${topic}`, error);\n return EMPTY;\n }),\n );\n return merge(metadata$, join$);\n };\n\n return defer(() => {\n const socket$ = ɵphoenixSocket$({\n url: context.wsUrl,\n options: {\n params: { join_token: primaryJoinToken },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const channel$ = ɵphoenixChannel$({\n socket$,\n topic: primaryTopic,\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const socketSignals$ =\n ɵobservePhoenixSocketSignals$(socket$).pipe(share());\n // The socket give-up signal: completes the realtime stream after the\n // health check throws. ALSO surfaces the give-up as a status delta\n // (`realtimeUnavailable`) so the UI can drop its \"live\" indicator —\n // this is the permanent-death signal that was previously only a\n // `console.warn`. `available`/`error` stay untouched by design (the\n // realtime path is a silent degrade for the REST list route).\n const fatalSocketShutdown$ = ɵobservePhoenixSocketHealth$(\n socketSignals$,\n MAX_SOCKET_RETRIES,\n ).pipe(\n catchError(() => {\n console.warn(\n `[memory] WebSocket failed after ${MAX_SOCKET_RETRIES} attempts, giving up`,\n );\n return of(undefined);\n }),\n share(),\n );\n // The give-up mapped to a status delta. Emitted from the merged stream\n // (not the `takeUntil` notifier) so the `realtimeUnavailable` action is\n // dispatched BEFORE teardown: the merged stream is `takeUntil`'d by a\n // microtask-deferred copy of the give-up signal, so this synchronous\n // emission always wins the race and the action reaches the reducer.\n const fatalStatus$ = fatalSocketShutdown$.pipe(\n map(() => memoryDomainEvents.realtimeUnavailable({ sessionId })),\n );\n const metadata$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<MemoryMetadataEvent>(\n channel,\n MEMORY_METADATA_EVENT,\n ),\n ),\n map((event) => mapMemoryMetadataEvent(event, action.sessionId)),\n );\n\n // Drives the actual `channel.join()` AND maps the join outcome to a\n // realtime-status delta. `ɵphoenixChannel$` only creates the channel +\n // a lazy join-outcome stream; the join is sent when that stream is\n // subscribed. Observing channel events (`metadata$`) alone does NOT\n // subscribe it, so without this the socket connects but never joins\n // `user_meta:memories:<code>` and no realtime deltas arrive. The thread\n // store joins for the same reason (its merged `joinOutcome$`).\n //\n // On a successful join -> `realtimeConnected` (the \"live\" signal). On a\n // failed/timed-out join we KEEP the `console.warn` and emit\n // `realtimeUnavailable`, then swallow the error so a transient\n // rejection doesn't tear down the metadata stream (Phoenix re-attempts\n // the join on socket reconnect); the next successful join re-emits\n // `realtimeConnected`.\n const join$ = ɵjoinPhoenixChannel$(channel$).pipe(\n // `ɵjoinPhoenixChannel$` emits `never` (it completes on success), so\n // this concat surfaces the connected status once the join resolves.\n concatWith(\n of(memoryDomainEvents.realtimeConnected({ sessionId })),\n ),\n catchError((error) => {\n console.warn(`[memory] failed to join ${primaryTopic}`, error);\n return of(\n memoryDomainEvents.realtimeUnavailable({ sessionId }),\n );\n }),\n );\n\n // Open the project channel alongside the user channel when project\n // credentials are present. It feeds the SAME reducer with the SAME\n // session stamp (see `channelMetadata$`), so project rows stay live\n // without going stale. Absent project creds -> `EMPTY`: user-only,\n // no second socket, no status regression (silent degrade).\n const projectMetadata$ =\n joinToken && joinCode && projectJoinToken && projectJoinCode\n ? channelMetadata$(\n projectJoinToken,\n `project_meta:memories:${projectJoinCode}`,\n )\n : EMPTY;\n\n return merge(\n // Surface \"connecting\" immediately when the realtime stream starts\n // (credentials succeeded -> socket subscribing/joining). Reset to\n // this on every (re)subscribe so a prior session's terminal status\n // can't bleed through before the new join resolves.\n of(memoryDomainEvents.realtimeConnecting({ sessionId })),\n metadata$,\n join$,\n projectMetadata$,\n fatalStatus$,\n ).pipe(\n takeUntil(\n merge(\n shutdown$,\n // Defer the give-up teardown by a microtask so `fatalStatus$`'s\n // synchronous `realtimeUnavailable` emission is dispatched before\n // the stream is torn down. `observeOn(asapScheduler)` schedules\n // the teardown after the current microtask drains.\n fatalSocketShutdown$.pipe(observeOn(asapScheduler)),\n ),\n ),\n finalize(() => {\n // Socket/channel teardown is handled by the `finalize` operators\n // inside `ɵphoenixSocket$`/`ɵphoenixChannel$`; this hook exists to\n // mirror the thread store's socket-effect lifecycle shape.\n }),\n );\n });\n }),\n ),\n );\n\n const store = createStore<MemoryState>({\n reducer: memoryReducer,\n effects: [\n bootstrapEffect,\n credentialsBootstrapEffect,\n fetchEffect,\n credentialsFetchEffect,\n mutationEffect,\n socketEffect,\n ],\n });\n\n function trackMutation<T>(\n dispatchAction:\n | ReturnType<typeof memoryAdapterEvents.addRequested>\n | ReturnType<typeof memoryAdapterEvents.updateRequested>\n | ReturnType<typeof memoryAdapterEvents.removeRequested>,\n extract: (outcome: Extract<MemoryMutationOutcome, { ok: true }>) => T,\n ): Promise<T> {\n const { requestId } = dispatchAction;\n const completion$ = merge(\n store.actions$.pipe(\n ofType(memoryRestEvents.mutationFinished),\n filter((action) => action.outcome.requestId === requestId),\n map((action) => action.outcome),\n ),\n store.actions$.pipe(\n ofType(memoryAdapterEvents.stopped),\n map(\n () =>\n ({\n requestId,\n sessionId: store.getState().sessionId,\n ok: false,\n error: new Error(\n \"Memory store stopped before mutation completed\",\n ),\n }) satisfies MemoryMutationOutcome,\n ),\n ),\n ).pipe(take(1));\n\n const resultPromise = firstValueFrom(completion$).then((outcome) => {\n if (!outcome.ok) {\n throw outcome.error;\n }\n return extract(outcome);\n });\n\n store.dispatch(dispatchAction);\n return resultPromise;\n }\n\n return {\n start(): void {\n store.init();\n store.dispatch(memoryAdapterEvents.started());\n },\n stop(): void {\n store.dispatch(memoryAdapterEvents.stopped());\n store.stop();\n },\n setContext(context: MemoryRuntimeContext | null): void {\n store.dispatch(memoryAdapterEvents.contextChanged({ context }));\n },\n refresh(): Promise<void> {\n const { sessionId, context } = store.getState();\n if (!context) return Promise.resolve();\n\n // Settle when the re-pulled snapshot completes for this session (success\n // or failure), or if the store is stopped first. Subscribe before\n // dispatching so the resulting list action can't slip past, mirroring\n // trackMutation.\n const completion$ = merge(\n store.actions$.pipe(\n ofType(\n memoryRestEvents.listSucceeded,\n memoryRestEvents.listFailed,\n // `listUnavailable` (404/501/422) is the third terminal outcome of\n // the list fetch. Without it `await refresh()` would hang forever\n // against an unconfigured route.\n memoryRestEvents.listUnavailable,\n ),\n filter((action) => action.sessionId === sessionId),\n ),\n store.actions$.pipe(ofType(memoryAdapterEvents.stopped)),\n // The list `fetchEffect` has `takeUntil(contextChanged, stopped)`, so a\n // `contextChanged` fired after this `listRequested` but before the fetch\n // settles tears down the fetch with NO terminal list action for our\n // session — `await refresh()` would hang forever. Settle on it too.\n store.actions$.pipe(ofType(memoryAdapterEvents.contextChanged)),\n ).pipe(take(1));\n\n // `await refresh()` resolving must mean the snapshot actually refreshed,\n // so reject on anything that isn't a successful re-pull — a failed list\n // (its error also lands in the `error` selector) or the store being\n // stopped mid-flight. This keeps `refresh` fully symmetric with the\n // mutation methods, which reject on both failure and stop via\n // `trackMutation`.\n const done = firstValueFrom(completion$).then((action) => {\n if (memoryRestEvents.listFailed.match(action)) {\n throw action.error;\n }\n if (memoryAdapterEvents.stopped.match(action)) {\n throw new Error(\"Memory store stopped before refresh completed\");\n }\n // A `contextChanged` superseded this refresh: a new context is loading\n // its own snapshot, so this refresh is moot. RESOLVE (do not reject) —\n // resolving is the least-surprising outcome for a superseded refresh.\n if (memoryAdapterEvents.contextChanged.match(action)) {\n return;\n }\n // `listSucceeded` and `listUnavailable` both RESOLVE: an unavailable\n // (not-configured) route is a non-fatal terminal state, consistent with\n // the auto-load path which leaves `available: false` without erroring.\n });\n store.dispatch(memoryRestEvents.listRequested({ sessionId }));\n return done;\n },\n recall(\n query: string,\n opts?: { limit?: number; scope?: MemoryScope },\n ): Promise<Memory[]> {\n const { context } = store.getState();\n if (!context?.runtimeUrl) {\n return Promise.reject(new Error(\"Runtime URL is not configured\"));\n }\n const body: Record<string, unknown> = { query };\n if (opts?.limit !== undefined) body.limit = opts.limit;\n if (opts?.scope !== undefined) body.scope = opts.scope;\n\n const recall$ = memoryFromFetch(\n `${context.runtimeUrl}${MEMORIES_RECALL_PATH}`,\n {\n selector: async (response) => {\n if (!response.ok) {\n throw new MemoryError(\"MEMORY_RECALL_FAILED\", {\n message: `Failed to recall memories: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n return (await response.json()) as { memories: unknown[] };\n },\n fetch: environment.fetch,\n method: \"POST\",\n headers: { ...context.headers, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n ).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n map((data) =>\n (data.memories ?? []).map((m) =>\n recallResponseToMemory(\n m as Parameters<typeof recallResponseToMemory>[0],\n ),\n ),\n ),\n );\n return firstValueFrom(recall$);\n },\n addMemory(input: NewMemory): Promise<Memory> {\n return trackMutation(\n memoryAdapterEvents.addRequested({\n requestId: createMemoryRequestId(),\n input,\n }),\n (outcome) => {\n if (outcome.memory == null) {\n throw new Error(\"add resolved without a memory\");\n }\n return outcome.memory;\n },\n );\n },\n updateMemory(id: string, changes: MemoryChanges): Promise<Memory> {\n return trackMutation(\n memoryAdapterEvents.updateRequested({\n requestId: createMemoryRequestId(),\n id,\n changes,\n }),\n (outcome) => {\n if (outcome.memory == null) {\n throw new Error(\"update resolved without a memory\");\n }\n return outcome.memory;\n },\n );\n },\n removeMemory(id: string): Promise<void> {\n return trackMutation(\n memoryAdapterEvents.removeRequested({\n requestId: createMemoryRequestId(),\n id,\n }),\n () => undefined,\n );\n },\n getState(): MemoryState {\n return store.getState();\n },\n getServerState(): MemoryState {\n return initialMemoryState;\n },\n select: store.select.bind(store),\n };\n}\n\n// `Memory`, `MemoryKind`, `MemoryScope`, `NewMemory`, and `MemoryChanges` are\n// the consumer-facing memory types surfaced by the framework hooks\n// (`useMemories` / `injectMemories`); they are exported unprefixed from their\n// declarations above. The remaining memory internals keep the `ɵ` prefix.\n// The memory error registry surface is consumer-facing: `MemoryError` is what\n// `MemoryState.error` (and the `error: Error | null` from `useMemories` /\n// `injectMemories`) carries on a failure, and consumers branch on its\n// `code`/`category`/`retryable`. Re-exported unprefixed here so it ships through\n// `index.ts` (`export * from \"./memory\"`) alongside the memory types.\nexport {\n MemoryError,\n MEMORY_ERROR_REGISTRY,\n isRetryableStatus as ɵisRetryableMemoryStatus,\n} from \"./memory-errors\";\nexport type {\n MemoryErrorCode,\n MemoryErrorCategory,\n MemoryErrorRegistryEntry,\n} from \"./memory-errors\";\n\nexport type ɵMemoryState = MemoryState;\nexport type ɵMemoryRuntimeContext = MemoryRuntimeContext;\nexport type ɵMemoryMetadataEvent = MemoryMetadataEvent;\nexport type ɵMemoryEnvironment = MemoryEnvironment;\nexport type ɵMemoryStore = MemoryStore;\nexport const ɵmemoryAdapterEvents = memoryAdapterEvents;\nexport const ɵmemoryRestEvents = memoryRestEvents;\nexport const ɵmemoryDomainEvents = memoryDomainEvents;\nexport const ɵmemoryReducer = memoryReducer;\nexport const ɵmapMemoryMetadataEvent = mapMemoryMetadataEvent;\nexport const ɵselectMemories = selectMemories;\nexport const ɵselectMemoriesIsLoading = selectMemoriesIsLoading;\nexport const ɵselectMemoriesError = selectMemoriesError;\nexport const ɵselectMemoriesIsMutating = selectMemoriesIsMutating;\nexport const ɵselectMemoriesAvailable = selectMemoriesAvailable;\nexport const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;\nexport { createMemoryStore as ɵcreateMemoryStore };\n","import type {\n AbstractAgent,\n Context,\n State,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { Throttler } from \"@tanstack/pacer\";\nimport type {\n FrontendTool,\n SuggestionsConfig,\n Suggestion,\n CopilotRuntimeTransport,\n RuntimeMode,\n RuntimeLicenseStatus,\n IntelligenceRuntimeInfo,\n InspectorMetadataV1,\n ThreadEndpointRuntimeInfo,\n} from \"../types\";\nimport type {\n CopilotKitCoreAddAgentParams,\n CopilotKitCoreRegisterProxiedAgentParams,\n CopilotKitCoreRegisterProxiedAgentResult,\n} from \"./agent-registry\";\nimport type { CopilotKitMessageFilter } from \"./message-filter\";\nimport { AgentRegistry } from \"./agent-registry\";\nimport type { ScopedContext } from \"./context-store\";\nimport { ContextStore } from \"./context-store\";\nimport { isForAgent } from \"./agent-scope\";\nimport { SuggestionEngine } from \"./suggestion-engine\";\nimport type {\n CopilotKitCoreRunAgentParams,\n CopilotKitCoreConnectAgentParams,\n CopilotKitCoreGetToolParams,\n CopilotKitCoreRunToolParams,\n CopilotKitCoreRunToolResult,\n CopilotKitCoreCatalogComponent,\n} from \"./run-handler\";\nimport { RunHandler } from \"./run-handler\";\nimport type {\n DebugConfig,\n RuntimeEntitlementResponse,\n} from \"@copilotkit/shared\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { StateManager } from \"./state-manager\";\nimport type { CopilotKitCoreContinuationHandoff } from \"./state-manager\";\nimport { ThreadStoreRegistry } from \"./thread-store-registry\";\nimport { LearningBridge } from \"./learning-bridge\";\nimport type { LearningConfig, TrajectoryStartOptions } from \"./learning-bridge\";\nimport type { JsonValue, StartResult } from \"@copilotkit/learning\";\nimport type { ɵThreadStore } from \"../threads\";\nimport { ɵcreateMemoryStore } from \"../memory\";\nimport type { ɵGenerativeUIDebugSource } from \"./generative-ui-debug\";\nimport type { ɵMemoryStore } from \"../memory\";\nimport { HeaderSourceResolver, isHeaderResolutionError } from \"./header-source\";\nimport type { CopilotKitHeadersSource } from \"./header-source\";\n\n/**\n * Run properties that go only to the runs of some agents.\n * See `CopilotKitCore.addScopedProperties`.\n */\nexport interface ScopedProperties {\n /** The properties to merge on top of the base run properties. */\n properties: Record<string, unknown>;\n /** The agents that get these properties. When omitted, every agent gets them. */\n agentIds?: string[];\n}\n\n/** True for an object literal. Arrays, `null`, and class instances are not plain objects. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** Configuration options for `CopilotKitCore`. */\nexport interface CopilotKitCoreConfig {\n /** The endpoint of the CopilotRuntime. */\n runtimeUrl?: string;\n /** Transport style for CopilotRuntime endpoints. Defaults to REST. */\n runtimeTransport?: CopilotRuntimeTransport;\n /**\n * When true, the constructor sets the runtime config but does NOT start the\n * `/info` connection. Call {@link CopilotKitCore.connect} to start it —\n * typically from a host's commit-phase effect. This prevents a burst of\n * duplicate `/info` requests when a host constructs (and discards) the core\n * during render, e.g. React concurrent rendering / Suspense / StrictMode.\n * See https://github.com/CopilotKit/CopilotKit/issues/5801.\n */\n deferInitialConnection?: boolean;\n /** Mapping from agent name to its `AbstractAgent` instance. For development only - production requires CopilotRuntime. */\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n /**\n * Headers sent with every runtime request: a record, or a sync or async\n * builder that runs when each request is sent. Merged on top of each\n * `HttpAgent`'s own headers (core wins on a key conflict). See `setHeaders`.\n */\n headers?: CopilotKitHeadersSource;\n /** Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies). */\n credentials?: RequestCredentials;\n /**\n * Rewrites the message list sent to runtime agents on every run. Use it when\n * the backend already stores the conversation and re-sending it is waste or\n * duplication. See `setMessageFilter` and {@link CopilotKitMessageFilter}.\n */\n messageFilter?: CopilotKitMessageFilter;\n /** Properties sent as `forwardedProps` to the AG-UI agent. */\n properties?: Record<string, unknown>;\n /** Ordered collection of frontend tools available to the core. */\n tools?: FrontendTool<any>[];\n /** Suggestions config for the core. */\n suggestionsConfig?: SuggestionsConfig[];\n /** Enable debug logging for the client-side event pipeline. */\n debug?: DebugConfig;\n /**\n * Turns on interaction capture (`@copilotkit/learning`). Capture starts only\n * when {@link CopilotKitCore.startTrajectory} authenticates and joins the\n * capture channel. The default path captures outside-chat activity. An explicit\n * legacy sink also receives Thread, message, tool call, and run context.\n * Update future captures with\n * {@link CopilotKitCore.setLearningConfig}.\n */\n learning?: LearningConfig;\n}\n\nexport type { CopilotKitMessageFilter } from \"./message-filter\";\nexport type {\n LearningConfig,\n LegacyLearningConfig,\n TrajectoryStartOptions,\n OpenThreadRegistration,\n} from \"./learning-bridge\";\nexport type { JsonValue, StartResult } from \"@copilotkit/learning\";\n\nexport type {\n CopilotKitCoreAddAgentParams,\n CopilotKitCoreRegisterProxiedAgentParams,\n CopilotKitCoreRegisterProxiedAgentResult,\n};\nexport type {\n CopilotKitCoreRunAgentParams,\n CopilotKitCoreConnectAgentParams,\n CopilotKitCoreGetToolParams,\n CopilotKitCoreRunToolParams,\n CopilotKitCoreRunToolResult,\n CopilotKitCoreCatalogComponent,\n};\n\nexport interface CopilotKitCoreStopAgentParams {\n agent: AbstractAgent;\n}\n\nexport type CopilotKitCoreGetSuggestionsResult = {\n suggestions: Suggestion[];\n isLoading: boolean;\n};\n\nexport enum CopilotKitCoreErrorCode {\n RUNTIME_INFO_FETCH_FAILED = \"runtime_info_fetch_failed\",\n AGENT_CONNECT_FAILED = \"agent_connect_failed\",\n AGENT_RUN_FAILED = \"agent_run_failed\",\n AGENT_RUN_FAILED_EVENT = \"agent_run_failed_event\",\n AGENT_RUN_ERROR_EVENT = \"agent_run_error_event\",\n TOOL_ARGUMENT_PARSE_FAILED = \"tool_argument_parse_failed\",\n TOOL_HANDLER_FAILED = \"tool_handler_failed\",\n TOOL_NOT_FOUND = \"tool_not_found\",\n AGENT_NOT_FOUND = \"agent_not_found\",\n /**\n * Emitted when an agent run fails because the thread is already locked\n * by another active run.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider\n * onError={({ code, error, context }) => {\n * if (code === \"agent_thread_locked\") {\n * // Show \"Agent is busy, retry?\" UI\n * }\n * }}\n * />\n * ```\n */\n AGENT_THREAD_LOCKED = \"agent_thread_locked\",\n // Transcription errors\n TRANSCRIPTION_FAILED = \"transcription_failed\",\n TRANSCRIPTION_SERVICE_NOT_CONFIGURED = \"transcription_service_not_configured\",\n TRANSCRIPTION_INVALID_AUDIO = \"transcription_invalid_audio\",\n TRANSCRIPTION_RATE_LIMITED = \"transcription_rate_limited\",\n TRANSCRIPTION_AUTH_FAILED = \"transcription_auth_failed\",\n TRANSCRIPTION_NETWORK_ERROR = \"transcription_network_error\",\n SUBSCRIBER_CALLBACK_FAILED = \"subscriber_callback_failed\",\n /**\n * The `headers` builder threw, rejected, or returned something other than\n * an object. The request was not sent. `error.cause` is the builder's error.\n */\n HEADER_RESOLUTION_FAILED = \"header_resolution_failed\",\n}\n\nexport interface CopilotKitCoreSubscriber {\n onTrajectoryChanged?: (event: {\n copilotkit: CopilotKitCore;\n trajectoryId: string | null;\n }) => void | Promise<void>;\n onRuntimeConnectionStatusChanged?: (event: {\n copilotkit: CopilotKitCore;\n status: CopilotKitCoreRuntimeConnectionStatus;\n }) => void | Promise<void>;\n onToolExecutionStart?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n args: unknown;\n }) => void | Promise<void>;\n onToolExecutionEnd?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n result: string;\n error?: string;\n }) => void | Promise<void>;\n onAgentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agents: Readonly<Record<string, AbstractAgent>>;\n }) => void | Promise<void>;\n /**\n * Fired when an agent run or connect begins. The `agent` may be a per-thread\n * clone that is not present in `core.agents`, so `onAgentsChanged` never fires\n * for it. Subscribers (e.g. the inspector) can use this to subscribe to the\n * running instance's AG-UI events.\n */\n onAgentRunStarted?: (event: {\n copilotkit: CopilotKitCore;\n agent: AbstractAgent;\n }) => void | Promise<void>;\n onContextChanged?: (event: {\n copilotkit: CopilotKitCore;\n context: Readonly<Record<string, Context>>;\n }) => void | Promise<void>;\n /**\n * Fired when the A2UI catalog component list changes (registration) or when\n * a component is enabled/disabled. Consumers (the provider, the inspector)\n * re-derive the filtered catalog from this event.\n */\n onCatalogComponentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n catalogComponents: ReadonlyArray<CopilotKitCoreCatalogComponent>;\n }) => void | Promise<void>;\n onSuggestionsConfigChanged?: (event: {\n copilotkit: CopilotKitCore;\n suggestionsConfig: Readonly<Record<string, SuggestionsConfig>>;\n }) => void | Promise<void>;\n onSuggestionsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n suggestions: Suggestion[];\n }) => void | Promise<void>;\n onSuggestionsStartedLoading?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n }) => void | Promise<void>;\n onSuggestionsFinishedLoading?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n }) => void | Promise<void>;\n onPropertiesChanged?: (event: {\n copilotkit: CopilotKitCore;\n properties: Readonly<Record<string, unknown>>;\n }) => void | Promise<void>;\n onHeadersChanged?: (event: {\n copilotkit: CopilotKitCore;\n headers: Readonly<Record<string, string>>;\n }) => void | Promise<void>;\n onInspectorMetadataChanged?: (event: {\n copilotkit: CopilotKitCore;\n inspectorMetadata: InspectorMetadataV1 | undefined;\n }) => void | Promise<void>;\n onError?: (event: {\n copilotkit: CopilotKitCore;\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n onThreadStoreRegistered?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n store: ɵThreadStore;\n }) => void | Promise<void>;\n /**\n * Fired when a thread store is removed from the registry, either by an\n * explicit `unregister()` call or by a `register()` call that replaces an\n * existing store for the same `agentId`.\n *\n * The previous store is delivered via `prevStore` so subscribers can tear\n * down state that depends on the concrete instance (e.g. cancel an active\n * subscription) without consulting the registry. By the time async\n * subscribers resume after an `await`, a replacement `register()` may have\n * already installed the new store under the same key, so calling\n * `registry.get(agentId)` inside this callback is unsafe and may return\n * the new store instead of the unregistered one.\n */\n onThreadStoreUnregistered?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n prevStore: ɵThreadStore;\n }) => void | Promise<void>;\n}\n\n// Subscription object returned by subscribe() and subscribeToAgentWithOptions()\nexport interface CopilotKitCoreSubscription {\n unsubscribe: () => void;\n}\n\n/**\n * The callback keys accepted by {@link CopilotKitCore.subscribeToAgentWithOptions}.\n * This tuple is the single source of truth — both the\n * `SubscribeToAgentSubscriber` type and the runtime `ALLOWED_KEYS` set\n * are derived from it, so they cannot desynchronise.\n */\nconst SUBSCRIBE_TO_AGENT_KEYS = [\n \"onMessagesChanged\",\n \"onStateChanged\",\n \"onRunInitialized\",\n \"onRunStartedEvent\",\n \"onRunFinalized\",\n \"onRunFailed\",\n \"onRunErrorEvent\",\n] as const satisfies readonly (keyof AgentSubscriber)[];\n\n/**\n * Runtime allowlist derived from {@link SUBSCRIBE_TO_AGENT_KEYS}. Hoisted\n * to module scope so the Set is allocated once, not per-subscription.\n */\nconst ALLOWED_KEYS: ReadonlySet<(typeof SUBSCRIBE_TO_AGENT_KEYS)[number]> =\n new Set(SUBSCRIBE_TO_AGENT_KEYS);\n\n/**\n * The subset of `AgentSubscriber` callbacks accepted by\n * {@link CopilotKitCore.subscribeToAgentWithOptions}. Only the callbacks\n * listed in {@link SUBSCRIBE_TO_AGENT_KEYS} are supported:\n * `onMessagesChanged`, `onStateChanged`, and the run lifecycle\n * callbacks (`onRunInitialized`, `onRunStartedEvent`, `onRunFinalized`, `onRunFailed`,\n * `onRunErrorEvent`).\n *\n * Two categories of `AgentSubscriber` members are excluded:\n *\n * - **AG-UI event handlers** (`onEvent`, `onToolCallStartEvent`, etc.)\n * return `AgentStateMutation` with `stopPropagation` — semantics that\n * the throttle and error-protection wrappers cannot safely mediate.\n *\n * - **Per-item notification callbacks** (`onNewMessage`, `onNewToolCall`)\n * return `void` and have no mutation concerns, but are excluded to keep\n * the surface area minimal — `onMessagesChanged` already covers the\n * same data at a coarser granularity, and throttling per-item callbacks\n * would have different semantic expectations.\n *\n * `onRunErrorEvent` and `onRunStartedEvent` are AG-UI event handlers whose\n * return types include `stopPropagation`. They are included so framework\n * consumers can reflect running-state changes while a connection stays open:\n * a live error clears busy and a successor run marks it busy again. Consumers\n * use these callbacks for notification and return `void`.\n *\n * Note: the included lifecycle callbacks return\n * `Omit<AgentStateMutation, \"stopPropagation\">` (or full\n * `AgentStateMutation` for the included AG-UI event handlers). On the error\n * path, `safeCall` discards those return values (see its inline\n * documentation).\n *\n * Use `agent.subscribe()` directly when event mutation or per-item\n * notification semantics are needed.\n */\nexport type SubscribeToAgentSubscriber = Pick<\n AgentSubscriber,\n (typeof SUBSCRIBE_TO_AGENT_KEYS)[number]\n>;\n\n/** Options for {@link CopilotKitCore.subscribeToAgentWithOptions}. */\nexport interface SubscribeToAgentOptions {\n /**\n * Throttle interval (ms) for `onMessagesChanged` / `onStateChanged`.\n * Non-negative finite number; `0` explicitly disables throttling.\n * Falls back to `defaultThrottleMs` when `undefined`.\n */\n throttleMs?: number;\n}\n\nexport enum CopilotKitCoreRuntimeConnectionStatus {\n Disconnected = \"disconnected\",\n Connected = \"connected\",\n Connecting = \"connecting\",\n Error = \"error\",\n}\n\n/**\n * Internal interface for delegate classes to access CopilotKitCore methods.\n * This provides type safety while allowing controlled access to private functionality.\n */\nexport interface CopilotKitCoreFriendsAccess {\n // Notification methods\n notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string,\n ): Promise<void>;\n\n emitError(params: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }): Promise<void>;\n\n // Getters for internal state\n readonly headers: Readonly<Record<string, string>>;\n resolveHeaders():\n | Readonly<Record<string, string>>\n | Promise<Readonly<Record<string, string>>>;\n readonly credentials: RequestCredentials | undefined;\n readonly messageFilter: CopilotKitMessageFilter | undefined;\n readonly properties: Readonly<Record<string, unknown>>;\n readonly context: Readonly<Record<string, Context>>;\n readonly debug?: DebugConfig;\n\n // Internal methods\n buildFrontendTools(agentId?: string): import(\"@ag-ui/client\").Tool[];\n getContextForAgent(agentId?: string): Context[];\n getPropertiesForAgent(agentId?: string): Record<string, unknown>;\n getAgent(id: string): AbstractAgent | undefined;\n /**\n * Re-apply the last resolved header snapshot to a single agent, merged on\n * top of the headers the agent was constructed with (see #5635). Never\n * invokes the headers builder — safe to call from anywhere without risking\n * a synchronous throw or an unhandled async rejection from a user-supplied\n * builder.\n */\n applyHeadersToAgent(agent: AbstractAgent): void;\n\n /**\n * Resolve headers fresh (including invoking a sync/async builder) and\n * apply them to `agent` right before a run or connect actually sends\n * (#1937). Friends-only — only the run handler should call this, since\n * unlike `applyHeadersToAgent` it can throw synchronously or return a\n * rejecting promise. Returns a promise only when an async builder must be\n * awaited first; callers that need the write to have landed before\n * continuing must await a returned promise.\n */\n prepareAgentHeadersForRun(agent: AbstractAgent): void | Promise<void>;\n\n // References to delegate subsystems\n readonly suggestionEngine: {\n clearSuggestions(agentId: string): void;\n reloadSuggestions(agentId: string): void;\n };\n\n /**\n * Called before each follow-up agent run (after tool execution).\n * See CopilotKitCore.waitForPendingFrameworkUpdates for details.\n */\n waitForPendingFrameworkUpdates(): Promise<void>;\n\n readonly stateManager: {\n getContinuationRunId(\n agent: AbstractAgent,\n input: Pick<RunAgentInput, \"threadId\" | \"resume\" | \"forwardedProps\">,\n ): string | undefined;\n markNextRunAsContinuation(\n agent: AbstractAgent,\n expectedRunId?: string,\n ): CopilotKitCoreContinuationHandoff;\n };\n}\n\nexport class CopilotKitCore {\n private headerSource: HeaderSourceResolver;\n private _credentials?: RequestCredentials;\n private _messageFilter?: CopilotKitMessageFilter;\n private _properties: Record<string, unknown>;\n private _scopedProperties: Map<string, ScopedProperties> = new Map();\n private _defaultThrottleMs?: number;\n private _debug?: DebugConfig;\n\n private subscribers: Set<CopilotKitCoreSubscriber> = new Set();\n\n // Delegate classes\n private agentRegistry: AgentRegistry;\n private contextStore: ContextStore;\n private suggestionEngine: SuggestionEngine;\n private runHandler: RunHandler;\n private stateManager: StateManager;\n private threadStoreRegistry: ThreadStoreRegistry;\n private learningBridge: LearningBridge;\n private notifiedTrajectoryId: string | null = null;\n private readonly learningConfiguredListeners = new Set<() => void>();\n private _generativeUIDebugSource: ɵGenerativeUIDebugSource | undefined;\n private readonly generativeUIDebugListeners = new Set<() => void>();\n /**\n * The single core-owned memory store, created lazily on first\n * `getMemoryStore()` and kept user-scoped for the lifetime of the core.\n * Its runtime context is wired by the core itself (see `syncMemoryContext`),\n * so callers never register or look it up by `agentId`.\n */\n private _memoryStore?: ɵMemoryStore;\n /**\n * Tracks the agent IDs from the most recent `onAgentsChanged` notification.\n * Used to gate thread-store auto-unregister so the FIRST empty-agents\n * notification (before published agents are merged in) does not rip out a\n * store that was registered prior to that initial notification.\n */\n private previousAgentIds: Set<string> = new Set();\n\n constructor({\n runtimeUrl,\n runtimeTransport = \"auto\",\n deferInitialConnection = false,\n headers = {},\n credentials,\n messageFilter,\n properties = {},\n agents__unsafe_dev_only = {},\n tools = [],\n suggestionsConfig = [],\n debug,\n learning,\n }: CopilotKitCoreConfig) {\n this.headerSource = new HeaderSourceResolver((error) => {\n void this.emitError({\n error,\n code: CopilotKitCoreErrorCode.HEADER_RESOLUTION_FAILED,\n context: { source: \"headers\" },\n });\n });\n this.headerSource.setSource(headers);\n this._credentials = credentials;\n this._messageFilter = messageFilter;\n this._properties = properties;\n this._debug = debug;\n\n // Initialize delegate classes\n this.agentRegistry = new AgentRegistry(this);\n this.contextStore = new ContextStore(this);\n this.suggestionEngine = new SuggestionEngine(this);\n this.runHandler = new RunHandler(this);\n this.stateManager = new StateManager(this);\n this.threadStoreRegistry = new ThreadStoreRegistry(this);\n\n // Initialize each subsystem\n this.agentRegistry.initialize(agents__unsafe_dev_only);\n this.runHandler.initialize(tools);\n this.suggestionEngine.initialize(suggestionsConfig);\n this.stateManager.initialize();\n // After agent initialization: the bridge reads the initial agents.\n this.learningBridge = new LearningBridge(this, learning, () =>\n this.notifyTrajectoryChanged(),\n );\n\n this.agentRegistry.setRuntimeTransport(runtimeTransport);\n this.agentRegistry.setRuntimeUrl(runtimeUrl, {\n deferConnection: deferInitialConnection,\n });\n\n // Seed the previous-agents snapshot from the constructor-supplied agents.\n // `agentRegistry.initialize` does not emit `onAgentsChanged`, so the\n // subscriber below would otherwise see its first non-empty notification\n // as an \"addition\" relative to an empty baseline — and a later removal\n // of those same agents would NOT trigger the auto-unregister branch\n // because the guard would think the agentId was never previously\n // present. Seeding the set here keeps the guard honest.\n this.previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only));\n\n // Subscribe to agent changes to track state for new agents\n this.subscribe({\n // Re-sync the memory store's runtime context whenever the runtime\n // connection status changes. The `/info` fetch sets the connection\n // status and `intelligence` together before firing this notification,\n // so this single hook covers both connection and intelligence changes.\n // Guarded so we never instantiate the store just to sync it.\n onRuntimeConnectionStatusChanged: () => {\n if (this._memoryStore) this.syncMemoryContext();\n },\n onAgentsChanged: ({ agents }) => {\n Object.values(agents).forEach((agent) => {\n if (agent.agentId) {\n this.stateManager.subscribeToAgent(agent);\n }\n });\n\n // Unregister thread stores for agents that have been removed.\n //\n // Critically, only unregister an agentId that was present in the\n // PREVIOUS agents snapshot AND is missing from the new one. Without\n // the \"previously had\" guard, the FIRST `onAgentsChanged({ agents: {} })`\n // delivered to a freshly-published core would tear out a thread store\n // that a consumer (e.g. useThreads) just registered — `core.agents`\n // is asynchronously populated and the empty-map notification fires\n // before the published agents are merged in.\n const currentAgentIds = new Set(Object.keys(agents));\n // Each iteration is wrapped so a throw on one id does not stall\n // cleanup for the rest of the set. Both registries' unregister\n // paths are idempotent, so re-attempts on the next\n // onAgentsChanged are safe.\n for (const agentId of Object.keys(this.threadStoreRegistry.getAll())) {\n if (\n this.previousAgentIds.has(agentId) &&\n !currentAgentIds.has(agentId)\n ) {\n try {\n this.threadStoreRegistry.unregister(agentId);\n } catch (err) {\n console.error(\n `CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for \"${agentId}\":`,\n err,\n );\n }\n }\n }\n\n // Symmetric cleanup for state-manager subscriptions: any agentId\n // that disappeared from the registry (e.g. via `unregister()` from\n // a registerProxiedAgent caller) should release its StateManager\n // subscription. Without this, the subscription leaks — events from\n // a still-running observable on the removed agent would continue\n // to populate stateByRun/messageToRun for the dead id.\n for (const agentId of this.previousAgentIds) {\n if (!currentAgentIds.has(agentId)) {\n try {\n this.stateManager.unsubscribeFromAgent(agentId);\n } catch (err) {\n console.error(\n `CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for \"${agentId}\":`,\n err,\n );\n }\n }\n }\n\n this.previousAgentIds = currentAgentIds;\n },\n });\n }\n\n /**\n * Internal method used by delegate classes and subclasses to notify subscribers\n */\n protected async notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string,\n ): Promise<void> {\n await Promise.all(\n Array.from(this.subscribers).map(async (subscriber) => {\n try {\n await handler(subscriber);\n } catch (error) {\n console.error(errorMessage, error);\n }\n }),\n );\n }\n\n /**\n * Internal method used by delegate classes to emit errors\n */\n private async emitError({\n error,\n code,\n context = {},\n }: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }): Promise<void> {\n if (\n code !== CopilotKitCoreErrorCode.HEADER_RESOLUTION_FAILED &&\n isHeaderResolutionError(error)\n ) {\n // Already reported once as HEADER_RESOLUTION_FAILED.\n return;\n }\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onError?.({\n copilotkit: this,\n error,\n code,\n context,\n }),\n \"Subscriber onError error:\",\n );\n }\n\n /**\n * Log a message to the console and emit an error to subscribers.\n * Catches failures from `emitError` itself to prevent unhandled rejections.\n */\n private logAndEmitError(\n message: string,\n params: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n },\n logLevel: \"error\" | \"warn\" = \"error\",\n ): void {\n console[logLevel](message, params.error);\n this.emitError(params).catch((emitErr: unknown) => {\n console.error(message + \" — emitError itself failed:\", emitErr);\n });\n }\n\n /**\n * Snapshot accessors\n */\n get context(): Readonly<Record<string, ScopedContext>> {\n return this.contextStore.context;\n }\n\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this.agentRegistry.agents;\n }\n\n get tools(): Readonly<FrontendTool<any>[]> {\n return this.runHandler.tools;\n }\n\n get catalogComponents(): ReadonlyArray<CopilotKitCoreCatalogComponent> {\n return this.runHandler.catalogComponents;\n }\n\n get runtimeUrl(): string | undefined {\n return this.agentRegistry.runtimeUrl;\n }\n\n setRuntimeUrl(runtimeUrl: string | undefined): void {\n this.agentRegistry.setRuntimeUrl(runtimeUrl);\n }\n\n /**\n * Start the runtime `/info` connection if it has not been started yet.\n *\n * Intended to be driven from a host's commit-phase effect when the core was\n * constructed with {@link CopilotKitCoreConfig.deferInitialConnection}. Safe\n * to call repeatedly — it is a no-op once a connection is in progress or\n * settled, so a double-invoked mount effect (React StrictMode) collapses to a\n * single request. See #5801.\n */\n connect(): void {\n this.agentRegistry.connectRuntime();\n }\n\n get runtimeTransport(): CopilotRuntimeTransport {\n return this.agentRegistry.runtimeTransport;\n }\n\n setRuntimeTransport(runtimeTransport: CopilotRuntimeTransport): void {\n this.agentRegistry.setRuntimeTransport(runtimeTransport);\n }\n\n get runtimeVersion(): string | undefined {\n return this.agentRegistry.runtimeVersion;\n }\n\n /**\n * The last resolved headers. With a builder this is the value from the most\n * recent request, not necessarily current; call `resolveHeaders()` for that.\n */\n get headers(): Readonly<Record<string, string>> {\n return this.headerSource.headers;\n }\n\n /**\n * Resolve the current headers. Synchronous for a record or a sync builder,\n * a promise for an async builder. Concurrent calls share one builder call.\n * The returned object is shared; copy it before modifying.\n */\n resolveHeaders():\n | Readonly<Record<string, string>>\n | Promise<Readonly<Record<string, string>>> {\n return this.headerSource.resolve();\n }\n\n /** Changes only on `setHeaders` or a new source, never on a new token. */\n get ɵheadersGeneration(): number {\n return this.headerSource.generation;\n }\n\n get credentials(): RequestCredentials | undefined {\n return this._credentials;\n }\n\n get messageFilter(): CopilotKitMessageFilter | undefined {\n return this._messageFilter;\n }\n\n get properties(): Readonly<Record<string, unknown>> {\n return this._properties;\n }\n\n /**\n * Default throttle interval (ms) used by `subscribeToAgentWithOptions()`\n * when the caller does not specify an explicit `throttleMs`.\n * `undefined` means no default is configured; `0` means no throttling.\n */\n get defaultThrottleMs(): number | undefined {\n return this._defaultThrottleMs;\n }\n\n /**\n * Set the default throttle interval (ms) for `subscribeToAgentWithOptions()`.\n *\n * Accepts a non-negative finite number or `undefined` (to clear the\n * default). Invalid values (NaN, Infinity, negative) are logged as\n * errors and ignored — the previous valid value is preserved.\n */\n setDefaultThrottleMs(value: number | undefined): void {\n if (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n this.logAndEmitError(\n `CopilotKitCore.setDefaultThrottleMs: value must be a non-negative finite number or undefined, ` +\n `got ${value}. Keeping current value (${this._defaultThrottleMs}).`,\n {\n error: new Error(\n `setDefaultThrottleMs: invalid value (${value}), keeping current value (${this._defaultThrottleMs})`,\n ),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { value, currentValue: this._defaultThrottleMs },\n },\n );\n return;\n }\n this._defaultThrottleMs = value;\n }\n\n get debug(): DebugConfig | undefined {\n return this._debug;\n }\n\n setDebug(debug: DebugConfig | undefined): void {\n this._debug = debug;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this.agentRegistry.runtimeConnectionStatus;\n }\n\n /** @internal The verbatim single-endpoint URL, including any trailing slash. */\n get ɵruntimeEndpointUrl(): string | undefined {\n return this.agentRegistry.runtimeEndpointUrl;\n }\n\n get ɵruntimeFetch(): typeof fetch {\n return this.agentRegistry.createRuntimeFetch();\n }\n\n get audioFileTranscriptionEnabled(): boolean {\n return this.agentRegistry.audioFileTranscriptionEnabled;\n }\n\n get runtimeMode(): RuntimeMode {\n return this.agentRegistry.runtimeMode;\n }\n\n get intelligence(): IntelligenceRuntimeInfo | undefined {\n return this.agentRegistry.intelligence;\n }\n\n get threadEndpoints(): ThreadEndpointRuntimeInfo | undefined {\n return this.agentRegistry.threadEndpoints;\n }\n\n get suggestions(): boolean | undefined {\n return this.agentRegistry.suggestions;\n }\n\n /** Whether the connected Runtime exposes debug-authorized Learning data. */\n get inspectorLearning(): boolean {\n return this.agentRegistry.inspectorLearning;\n }\n\n /** Trusted, optional metadata advertised by the connected runtime. */\n get inspectorMetadata(): InspectorMetadataV1 | undefined {\n return this.agentRegistry.inspectorMetadata;\n }\n\n /** Refresh trusted inspector metadata without reconnecting runtime agents. */\n async refreshInspectorMetadata(): Promise<void> {\n await this.agentRegistry.refreshInspectorMetadata();\n }\n\n get a2uiEnabled(): boolean {\n return this.agentRegistry.a2uiEnabled;\n }\n\n /**\n * Agent ids the runtime applies A2UI to. `undefined` means A2UI applies to\n * every agent (or is disabled — check `a2uiEnabled`).\n */\n get a2uiAgents(): string[] | undefined {\n return this.agentRegistry.a2uiAgents;\n }\n\n get openGenerativeUIEnabled(): boolean {\n return this.agentRegistry.openGenerativeUIEnabled;\n }\n\n get licenseStatus(): RuntimeLicenseStatus | undefined {\n return this.agentRegistry.licenseStatus;\n }\n\n /** Structured Runtime entitlement authority advertised by `/info`. */\n get runtimeEntitlements(): RuntimeEntitlementResponse | undefined {\n return this.agentRegistry.runtimeEntitlements;\n }\n\n /** Whether Core still has a bounded Runtime entitlement retry to settle. */\n get runtimeEntitlementRetryPending(): boolean {\n return this.agentRegistry.runtimeEntitlementRetryPending;\n }\n\n get telemetryDisabled(): boolean {\n return this.agentRegistry.telemetryDisabled;\n }\n\n /**\n * Configuration updates\n */\n /**\n * Replace the headers sent with every runtime request.\n *\n * This is an overwrite, not a merge — the supplied object becomes the\n * complete header set. Entries whose value is `null` or `undefined` are\n * dropped, which is how you clear a header (e.g. removing `Authorization`\n * on logout) without leaving an empty-string value behind:\n *\n * ```ts\n * copilotkit.setHeaders({\n * ...copilotkit.headers,\n * Authorization: token ? `Bearer ${token}` : null,\n * });\n * ```\n *\n * The resulting header set is also re-applied to every agent in the registry\n * and `onHeadersChanged` subscribers are notified. These headers are merged\n * ON TOP of the headers each `HttpAgent` was constructed with, so per-agent\n * headers (e.g. an `Authorization` for a self-hosted backend) are preserved;\n * on a key conflict the core-level value wins.\n *\n * Because the agent's construction-time headers form the merge baseline, this\n * method can override a per-agent header but cannot REMOVE one: clearing a\n * core key here only drops the core-level override, after which the agent's\n * own value (if any) re-surfaces. To change a header an agent was constructed\n * with, set it at the provider/core level instead of on the agent, or update\n * it on the agent directly. The clear-on-logout pattern above is for\n * core-level headers.\n *\n * Pass a function to have headers evaluated when each request is sent\n * (sync or async). Setting the same function again is a no-op. A new token\n * from the builder doesn't notify `onHeadersChanged`. On a user switch,\n * call `setHeaders` with a NEW function (or a record), or remount.\n *\n * Passing a record equal (by value) to the currently applied record is\n * also a no-op — safe to call on every render with a fresh object literal.\n */\n setHeaders(headers: CopilotKitHeadersSource): void {\n if (!this.headerSource.setSource(headers)) return;\n if (this._memoryStore) this.syncMemoryContext();\n this.agentRegistry.applyHeadersToAgents(\n this.agentRegistry.agents as Record<string, AbstractAgent>,\n );\n this.agentRegistry.handleHeadersChanged();\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onHeadersChanged?.({\n copilotkit: this,\n headers: this.headers,\n }),\n \"Subscriber onHeadersChanged error:\",\n );\n }\n\n setCredentials(credentials: RequestCredentials | undefined): void {\n this._credentials = credentials;\n this.agentRegistry.applyCredentialsToAgents(\n this.agentRegistry.agents as Record<string, AbstractAgent>,\n );\n this.agentRegistry.handleCredentialsChanged();\n }\n\n /**\n * Replace the message filter applied to every runtime agent.\n *\n * Applies to agents already discovered as well as ones discovered later, so\n * a filter set before `/info` lands is not lost. Pass `undefined` to go back\n * to sending the full thread.\n */\n setMessageFilter(messageFilter: CopilotKitMessageFilter | undefined): void {\n this._messageFilter = messageFilter;\n this.agentRegistry.applyMessageFilterToAgents(\n this.agentRegistry.agents as Record<string, AbstractAgent>,\n );\n }\n\n /**\n * Add run properties that go only to the runs of `agentIds`. When\n * `agentIds` is omitted, every agent gets them. They merge on top of the\n * base `properties`.\n *\n * When an entry value and the existing value under the same key are both\n * plain objects, their keys merge one level deep. So several entries can\n * add keys under one namespace (for example `copilotkit`).\n *\n * @param entry - The properties and the optional agent ids.\n * @returns The id to pass to `removeScopedProperties`.\n *\n * @example\n * const id = copilotkit.addScopedProperties({\n * properties: { copilotkit: { theme: \"dark\" } },\n * agentIds: [\"research\"],\n * });\n * copilotkit.removeScopedProperties(id);\n */\n addScopedProperties({ properties, agentIds }: ScopedProperties) {\n let id = randomUUID();\n // An id source that repeats itself (a mock, say) must not replace an\n // earlier entry: every call adds one.\n for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;\n this._scopedProperties.set(id, {\n properties,\n ...(agentIds ? { agentIds } : {}),\n });\n return id;\n }\n\n /** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */\n removeScopedProperties(id: string) {\n this._scopedProperties.delete(id);\n }\n\n /**\n * Build the forwarded properties for a run of the given agent: the base\n * properties plus every scoped entry that matches the agent. An entry with\n * `agentIds` does not match when `agentId` is omitted.\n */\n getPropertiesForAgent(agentId?: string) {\n const merged: Record<string, unknown> = { ...this._properties };\n const entries = this._scopedProperties.values();\n for (const entry of entries) {\n if (!isForAgent(entry.agentIds, agentId)) continue;\n\n const properties = Object.entries(entry.properties);\n for (const [key, value] of properties) {\n const base = merged[key];\n merged[key] =\n isPlainObject(base) && isPlainObject(value)\n ? { ...base, ...value }\n : value;\n }\n }\n return merged;\n }\n\n setProperties(properties: Record<string, unknown>): void {\n this._properties = properties;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onPropertiesChanged?.({\n copilotkit: this,\n properties: this.properties,\n }),\n \"Subscriber onPropertiesChanged error:\",\n );\n }\n\n /**\n * Agent management (delegated to AgentRegistry)\n */\n setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void {\n this.agentRegistry.setAgents__unsafe_dev_only(agents);\n }\n\n addAgent__unsafe_dev_only(params: CopilotKitCoreAddAgentParams): void {\n this.agentRegistry.addAgent__unsafe_dev_only(params);\n }\n\n removeAgent__unsafe_dev_only(id: string): void {\n this.agentRegistry.removeAgent__unsafe_dev_only(id);\n }\n\n /**\n * Register a proxied agent against an existing runtime agent. The proxy is\n * exposed under `agentId` (local registry id) and routes outbound runtime\n * requests to `runtimeAgentId`. Throws if `agentId` is already taken.\n *\n * Returns the minted proxy and an `unregister` handle for cleanup.\n *\n * Use this to mount multiple frontend agents against a single runtime\n * agent (e.g. one per chat window) without implicit per-thread cloning.\n *\n * @example\n * const { agent, unregister } = copilotkit.registerProxiedAgent({\n * agentId: \"chat-1\",\n * runtimeAgentId: \"default\",\n * });\n * // ... <CopilotChat agentId=\"chat-1\" />\n * // on cleanup:\n * unregister();\n */\n registerProxiedAgent(\n params: CopilotKitCoreRegisterProxiedAgentParams,\n ): CopilotKitCoreRegisterProxiedAgentResult {\n return this.agentRegistry.registerProxiedAgent(params);\n }\n\n getAgent(id: string): AbstractAgent | undefined {\n return this.agentRegistry.getAgent(id);\n }\n\n /** Updates settings for the next capture. Removing the config stops capture. */\n setLearningConfig(config: LearningConfig | undefined): void {\n const wasConfigured = this.ɵlearningConfigured;\n this.learningBridge.setConfig(config);\n this.notifyTrajectoryChanged();\n if (this.ɵlearningConfigured === wasConfigured) return;\n for (const listener of this.learningConfiguredListeners) {\n try {\n listener();\n } catch (error) {\n console.error(\"Learning configured listener error:\", error);\n }\n }\n }\n\n /**\n * @internal Whether a `learning` config is set. Unlike {@link trajectoryId},\n * it does not change with capture start, connection failures or reconnects.\n */\n get ɵlearningConfigured(): boolean {\n return this.learningBridge.isConfigured;\n }\n\n /**\n * @internal Whether captured events may carry agent message text: false\n * without a `learning` config, or when a custom sink sets\n * `capture.agentText` to false. A running custom-sink capture keeps the\n * choice it started with.\n */\n get ɵlearningCapturesAgentText(): boolean {\n return this.learningBridge.capturesAgentText;\n }\n\n /** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */\n ɵsubscribeToLearningConfigured(listener: () => void): () => void {\n this.learningConfiguredListeners.add(listener);\n return () => {\n this.learningConfiguredListeners.delete(listener);\n };\n }\n\n /**\n * @internal The generative UI of the framework package, for the inspector.\n * `undefined` when no provider has a `generativeUI` config.\n */\n get ɵgenerativeUIDebugSource(): ɵGenerativeUIDebugSource | undefined {\n return this._generativeUIDebugSource;\n }\n\n /** @internal Set by the framework package. `undefined` removes it. */\n ɵsetGenerativeUIDebugSource(source: ɵGenerativeUIDebugSource | undefined) {\n if (source === this._generativeUIDebugSource) return;\n this._generativeUIDebugSource = source;\n for (const listener of [...this.generativeUIDebugListeners]) {\n try {\n listener();\n } catch (error) {\n console.error(\"Generative UI debug listener error:\", error);\n }\n }\n }\n\n /** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */\n ɵsubscribeToGenerativeUIDebugSource(listener: () => void): () => void {\n this.generativeUIDebugListeners.add(listener);\n return () => {\n this.generativeUIDebugListeners.delete(listener);\n };\n }\n\n /** The active capture's Trajectory ID, or null while capture is stopped. */\n get trajectoryId(): string | null {\n return this.learningBridge.trajectoryId;\n }\n\n private notifyTrajectoryChanged(): void {\n const trajectoryId = this.trajectoryId;\n if (trajectoryId === this.notifiedTrajectoryId) return;\n this.notifiedTrajectoryId = trajectoryId;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onTrajectoryChanged?.({ copilotkit: this, trajectoryId }),\n \"Subscriber onTrajectoryChanged error:\",\n );\n }\n\n /**\n * Starts one Trajectory after Runtime authorization and the Gateway join.\n * Omit the ID to create one. Repeated starts await the active connection;\n * a different ID stops the previous capture. Explicit sinks retain the\n * prototype's synchronous capture and require a stop before changing IDs.\n *\n * @example copilotkit.startTrajectory({ trajectoryId: crypto.randomUUID() })\n */\n startTrajectory(options: TrajectoryStartOptions = {}): Promise<StartResult> {\n const result = this.learningBridge.start(options);\n this.notifyTrajectoryChanged();\n return result;\n }\n\n /** Cancels pending work and stops capture, attempting one final batch without waiting for its ACK. */\n stopTrajectory() {\n this.learningBridge.stop();\n this.notifyTrajectoryChanged();\n }\n\n /**\n * Records an outcome that clicks cannot show, such as a saved report or an\n * approved deal. The wire adds `value.seq`; arrays, primitives, and objects\n * already containing `seq` are preserved under `value.data`. Explicit legacy\n * sinks retain object-only events with open-Thread enrichment.\n * No-op while no Trajectory runs. Events emitted during connection recovery\n * count as dropped. Built-in names such as `click` are rejected.\n *\n * @example copilotkit.emitTrajectoryEvent(\"deal.approved\", { dealId: \"deal-1\" })\n */\n emitTrajectoryEvent(name: string, value: JsonValue = {}) {\n this.learningBridge.emit(name, value);\n }\n\n /**\n * Tells Core that a view shows this Thread, so captured interactions can link to it.\n * Framework bindings call this; call it yourself only without a CopilotKit provider.\n */\n registerOpenThread(params: { agentId: string; threadId: string }) {\n return this.learningBridge.registerOpenThread(params);\n }\n\n /**\n * Re-apply the last resolved header snapshot to a single agent (delegated\n * to AgentRegistry). Core headers are merged on top of the agent's own\n * construction-time headers rather than replacing them, so headers\n * configured directly on an `HttpAgent` (e.g. an `Authorization` for a\n * self-hosted backend) survive header updates instead of being silently\n * dropped (see #5635). On a key conflict the core-level value wins.\n *\n * The merge baseline is the agent's headers as captured the first time the\n * agent is applied (at registration), so the way to change headers\n * afterwards is `setHeaders` (which re-applies to every agent), not mutating\n * `agent.headers` directly — a direct mutation is overwritten on the next\n * re-apply.\n *\n * A `ProxiedCopilotRuntimeAgent` keeps only its own construction-time\n * headers here — core headers are added by `ɵruntimeFetch` when each\n * request is sent (see #1937), so `agent.headers` never carries a stale\n * copy of a core header the builder has since stopped returning.\n *\n * Never invokes the headers builder (unlike the run/connect path's\n * internal `prepareAgentHeadersForRun`): safe to call from a dev-only\n * registration helper or a React effect that re-runs on every render\n * without risking a synchronous throw or an unhandled async rejection from\n * a user-supplied builder.\n */\n applyHeadersToAgent(agent: AbstractAgent): void {\n this.agentRegistry.applyHeadersToAgent(agent);\n }\n\n /**\n * Resolve headers fresh and apply them to `agent` right before a run or\n * connect actually sends (#1937). Friends-only (delegated to\n * AgentRegistry) — the run handler is the sole caller, since resolving can\n * invoke a user-supplied builder that throws or rejects.\n */\n private prepareAgentHeadersForRun(\n agent: AbstractAgent,\n ): void | Promise<void> {\n return this.agentRegistry.prepareAgentHeadersForRun(agent);\n }\n\n /**\n * Context management (delegated to ContextStore).\n * Pass `agentIds` to restrict the entry to runs of specific agents;\n * omit it for context every agent should receive.\n */\n addContext(context: ScopedContext): string {\n return this.contextStore.addContext(context);\n }\n\n removeContext(id: string): void {\n this.contextStore.removeContext(id);\n }\n\n /**\n * Build the context array for a run of the given agent, dropping entries\n * scoped to other agents and stripping the scoping metadata.\n */\n getContextForAgent(agentId?: string): Context[] {\n return this.contextStore.getContextForAgent(agentId);\n }\n\n /**\n * Thread store registry (delegated to ThreadStoreRegistry)\n */\n registerThreadStore(agentId: string, store: ɵThreadStore): void {\n this.threadStoreRegistry.register(agentId, store);\n }\n\n unregisterThreadStore(agentId: string): void {\n this.threadStoreRegistry.unregister(agentId);\n }\n\n getThreadStore(agentId: string): ɵThreadStore | undefined {\n return this.threadStoreRegistry.get(agentId);\n }\n\n getThreadStores(): Readonly<Record<string, ɵThreadStore>> {\n return this.threadStoreRegistry.getAll();\n }\n\n /**\n * Returns the single core-owned, user-scoped memory store, creating and\n * starting it on first access. Unlike thread stores, memory is not scoped per\n * agent: there is exactly one store whose runtime context the core wires\n * itself (see `syncMemoryContext`), so consumers (e.g. a `useMemories`\n * binding) just read this store rather than registering one.\n */\n getMemoryStore(): ɵMemoryStore {\n return this.ensureMemoryStore();\n }\n\n /**\n * Lazily creates, starts, and context-syncs the core-owned memory store on\n * first access, then returns it. Subsequent calls return the existing store.\n * The store uses the Core Runtime fetch so REST and single-route transports\n * share the same resource behavior. Its Runtime context is synced at once.\n */\n private ensureMemoryStore(): ɵMemoryStore {\n if (!this._memoryStore) {\n this._memoryStore = ɵcreateMemoryStore({\n fetch: this.ɵruntimeFetch,\n });\n this._memoryStore.start();\n this.syncMemoryContext();\n }\n return this._memoryStore;\n }\n\n /**\n * Pushes the current runtime wiring into the memory store. When the runtime\n * is connected and both the intelligence WebSocket URL and runtime URL are\n * available, the store receives a context (runtime URL, WebSocket URL);\n * otherwise its context is cleared. No-op when the store has not been\n * created yet.\n *\n * Headers are deliberately NOT part of this context: the store's `fetch` is\n * `ɵruntimeFetch` (see `ensureMemoryStore`), which already resolves and\n * overlays the current core headers at send time (#1937) — a header\n * snapshot copied here would go stale between context syncs.\n */\n private syncMemoryContext(): void {\n if (!this._memoryStore) return;\n if (\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected &&\n this.intelligence?.wsUrl &&\n this.runtimeUrl\n ) {\n this._memoryStore.setContext({\n runtimeUrl: this.runtimeUrl,\n wsUrl: this.intelligence.wsUrl,\n });\n } else {\n this._memoryStore.setContext(null);\n }\n }\n\n /**\n * Suggestions management (delegated to SuggestionEngine)\n */\n addSuggestionsConfig(config: SuggestionsConfig): string {\n return this.suggestionEngine.addSuggestionsConfig(config);\n }\n\n removeSuggestionsConfig(id: string): void {\n this.suggestionEngine.removeSuggestionsConfig(id);\n }\n\n reloadSuggestions(agentId: string): void {\n this.suggestionEngine.reloadSuggestions(agentId);\n }\n\n clearSuggestions(agentId: string): void {\n this.suggestionEngine.clearSuggestions(agentId);\n }\n\n getSuggestions(agentId: string): CopilotKitCoreGetSuggestionsResult {\n return this.suggestionEngine.getSuggestions(agentId);\n }\n\n /**\n * Tool management (delegated to RunHandler)\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>,\n ): void {\n this.runHandler.addTool(tool);\n }\n\n removeTool(id: string, agentId?: string): void {\n this.runHandler.removeTool(id, agentId);\n }\n\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n return this.runHandler.getTool(params);\n }\n\n setTools(tools: FrontendTool<any>[]): void {\n this.runHandler.setTools(tools);\n }\n\n /**\n * Enable/disable a registered frontend tool at runtime without unregistering\n * it (Inspector \"Capabilities\" tool). A disabled tool is omitted from the\n * tool list sent to the agent on the next run. The override is keyed by name\n * (+ optional agentId) and survives the tool being re-registered.\n */\n setToolEnabled(name: string, enabled: boolean, agentId?: string): void {\n this.runHandler.setToolEnabled(name, enabled, agentId);\n }\n\n /** Whether a registered tool is currently enabled (defaults true). */\n isToolEnabled(name: string, agentId?: string): boolean {\n return this.runHandler.isToolEnabled(name, agentId);\n }\n\n /**\n * A2UI catalog component management (delegated to RunHandler).\n * Registers the full component list and controls per-component enablement.\n */\n setCatalogComponents(components: CopilotKitCoreCatalogComponent[]): void {\n this.runHandler.setCatalogComponents(components);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onCatalogComponentsChanged?.({\n copilotkit: this,\n catalogComponents: this.runHandler.catalogComponents,\n }),\n \"Subscriber onCatalogComponentsChanged error:\",\n );\n }\n\n setCatalogComponentEnabled(name: string, enabled: boolean): void {\n this.runHandler.setCatalogComponentEnabled(name, enabled);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onCatalogComponentsChanged?.({\n copilotkit: this,\n catalogComponents: this.runHandler.catalogComponents,\n }),\n \"Subscriber onCatalogComponentsChanged error:\",\n );\n }\n\n isCatalogComponentEnabled(name: string): boolean {\n return this.runHandler.isCatalogComponentEnabled(name);\n }\n\n /**\n * Subscription lifecycle\n */\n subscribe(subscriber: CopilotKitCoreSubscriber): CopilotKitCoreSubscription {\n this.subscribers.add(subscriber);\n\n // Return subscription with unsubscribe method\n return {\n unsubscribe: () => {\n this.subscribers.delete(subscriber);\n },\n };\n }\n\n /**\n * Subscribe to an agent's notification and lifecycle events with\n * optional configuration (e.g. throttling).\n *\n * Wraps every callback with error protection (`safeCall`) and applies\n * the options before delegating to `agent.subscribe()`.\n *\n * See {@link SubscribeToAgentSubscriber} for the accepted callback subset\n * and the rationale for excluding AG-UI event handlers.\n */\n subscribeToAgentWithOptions(\n agent: AbstractAgent,\n subscriber: SubscribeToAgentSubscriber,\n options?: SubscribeToAgentOptions,\n ): CopilotKitCoreSubscription {\n const resolved = options?.throttleMs ?? this._defaultThrottleMs ?? 0;\n\n let effectiveMs = 0;\n if (!Number.isFinite(resolved) || resolved < 0) {\n const source =\n options?.throttleMs !== undefined ? \"throttleMs\" : \"defaultThrottleMs\";\n this.logAndEmitError(\n `CopilotKitCore.subscribeToAgentWithOptions: ${source} must be a non-negative finite number, ` +\n `got ${resolved}. Falling back to unthrottled.`,\n {\n error: new Error(\n `subscribeToAgentWithOptions: invalid ${source} (${resolved}), falling back to unthrottled`,\n ),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { agentId: agent.agentId, source, value: resolved },\n },\n );\n } else {\n effectiveMs = resolved;\n }\n\n const agentLabel = agent.agentId || \"(unknown agent)\";\n\n // Wraps a callback so that synchronous throws and async rejections are\n // caught, logged, and emitted — preventing one failing callback from\n // corrupting the agent's notification loop.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const safeCall = <F extends (...args: any[]) => any>(\n label: string,\n fn: F,\n ...args: Parameters<F>\n ): any => {\n const reportError = (err: unknown, verb: string) => {\n this.logAndEmitError(\n `CopilotKitCore.subscribeToAgentWithOptions[${agentLabel}]: ${label} callback ${verb}:`,\n {\n error: err instanceof Error ? err : new Error(String(err)),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { agentId: agent.agentId, callback: label },\n },\n );\n };\n try {\n const result = fn(...args);\n if (result instanceof Promise) {\n return result.catch((err: unknown) => {\n reportError(err, \"rejected\");\n });\n }\n return result;\n } catch (err) {\n reportError(err, \"threw\");\n }\n };\n\n const guardAll = (\n sub: SubscribeToAgentSubscriber,\n ): SubscribeToAgentSubscriber => {\n const guarded: SubscribeToAgentSubscriber = {};\n if (sub.onMessagesChanged) {\n const fn = sub.onMessagesChanged;\n guarded.onMessagesChanged = (params) =>\n safeCall(\"onMessagesChanged\", fn, params);\n }\n if (sub.onStateChanged) {\n const fn = sub.onStateChanged;\n guarded.onStateChanged = (params) =>\n safeCall(\"onStateChanged\", fn, params);\n }\n if (sub.onRunInitialized) {\n const fn = sub.onRunInitialized;\n guarded.onRunInitialized = (params) =>\n safeCall(\"onRunInitialized\", fn, params);\n }\n if (sub.onRunStartedEvent) {\n const fn = sub.onRunStartedEvent;\n guarded.onRunStartedEvent = (params) =>\n safeCall(\"onRunStartedEvent\", fn, params);\n }\n if (sub.onRunFinalized) {\n const fn = sub.onRunFinalized;\n guarded.onRunFinalized = (params) =>\n safeCall(\"onRunFinalized\", fn, params);\n }\n if (sub.onRunFailed) {\n const fn = sub.onRunFailed;\n guarded.onRunFailed = (params) => safeCall(\"onRunFailed\", fn, params);\n }\n if (sub.onRunErrorEvent) {\n const fn = sub.onRunErrorEvent;\n guarded.onRunErrorEvent = (params) =>\n safeCall(\"onRunErrorEvent\", fn, params);\n }\n return guarded;\n };\n\n // Warn about unsupported keys so JS / `as any` consumers get diagnostics.\n for (const key of Object.keys(subscriber)) {\n if (\n typeof (subscriber as Record<string, unknown>)[key] === \"function\" &&\n !(ALLOWED_KEYS as ReadonlySet<string>).has(key)\n ) {\n const message =\n `CopilotKitCore.subscribeToAgentWithOptions[${agentLabel}]: callback \"${key}\" is not supported ` +\n `and was dropped. Supported callbacks: ${Array.from(ALLOWED_KEYS).join(\", \")}. ` +\n `Use agent.subscribe() directly for event handlers and per-item notifications.`;\n this.logAndEmitError(\n message,\n {\n error: new Error(message),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { agentId: agent.agentId, droppedCallback: key },\n },\n \"warn\",\n );\n }\n }\n\n // No throttle — guard callbacks and subscribe directly.\n if (effectiveMs <= 0) {\n const subscription = agent.subscribe(guardAll(subscriber));\n return { unsubscribe: () => subscription.unsubscribe() };\n }\n\n // Throttled path: lifecycle callbacks fire immediately; onMessagesChanged\n // and onStateChanged share a single Throttler that flushes the latest\n // params for both channels.\n let active = true;\n let latestMessagesParams:\n | Parameters<\n NonNullable<SubscribeToAgentSubscriber[\"onMessagesChanged\"]>\n >[0]\n | null = null;\n let latestStateParams:\n | Parameters<NonNullable<SubscribeToAgentSubscriber[\"onStateChanged\"]>>[0]\n | null = null;\n\n const flushPending = () => {\n if (active && subscriber.onMessagesChanged && latestMessagesParams) {\n const params = latestMessagesParams;\n latestMessagesParams = null;\n safeCall(\"onMessagesChanged\", subscriber.onMessagesChanged, params);\n }\n if (active && subscriber.onStateChanged && latestStateParams) {\n const params = latestStateParams;\n latestStateParams = null;\n safeCall(\"onStateChanged\", subscriber.onStateChanged, params);\n }\n };\n\n const throttler = new Throttler(flushPending, {\n wait: effectiveMs,\n leading: true,\n trailing: true,\n });\n\n // Lifecycle callbacks are guarded but never throttled.\n const lifecycleOnly: SubscribeToAgentSubscriber = {};\n if (subscriber.onRunInitialized)\n lifecycleOnly.onRunInitialized = subscriber.onRunInitialized;\n if (subscriber.onRunStartedEvent)\n lifecycleOnly.onRunStartedEvent = subscriber.onRunStartedEvent;\n if (subscriber.onRunFinalized)\n lifecycleOnly.onRunFinalized = subscriber.onRunFinalized;\n if (subscriber.onRunFailed)\n lifecycleOnly.onRunFailed = subscriber.onRunFailed;\n if (subscriber.onRunErrorEvent)\n lifecycleOnly.onRunErrorEvent = subscriber.onRunErrorEvent;\n\n const wrappedSubscriber: SubscribeToAgentSubscriber =\n guardAll(lifecycleOnly);\n\n if (subscriber.onMessagesChanged) {\n wrappedSubscriber.onMessagesChanged = (params) => {\n latestMessagesParams = params;\n throttler.maybeExecute();\n };\n }\n\n if (subscriber.onStateChanged) {\n wrappedSubscriber.onStateChanged = (params) => {\n latestStateParams = params;\n throttler.maybeExecute();\n };\n }\n\n const subscription = agent.subscribe(wrappedSubscriber);\n\n return {\n unsubscribe: () => {\n active = false;\n throttler.cancel();\n subscription.unsubscribe();\n },\n };\n }\n\n /**\n * Agent connectivity (delegated to RunHandler)\n */\n async connectAgent(\n params: CopilotKitCoreConnectAgentParams,\n ): Promise<import(\"@ag-ui/client\").RunAgentResult> {\n return this.runHandler.connectAgent(params);\n }\n\n stopAgent(params: CopilotKitCoreStopAgentParams): void {\n this.runHandler.abortCurrentRun(params.agent);\n params.agent.abortRun();\n }\n\n async runAgent(\n params: CopilotKitCoreRunAgentParams,\n ): Promise<import(\"@ag-ui/client\").RunAgentResult> {\n return this.runHandler.runAgent(params);\n }\n\n /**\n * Programmatically execute a registered frontend tool without going through an LLM turn.\n * The handler runs, render components show up in the UI, and both the tool call and\n * result messages are added to `agent.messages`.\n */\n async runTool(\n params: CopilotKitCoreRunToolParams,\n ): Promise<CopilotKitCoreRunToolResult> {\n return this.runHandler.runTool(params);\n }\n\n /**\n * State management (delegated to StateManager)\n */\n getStateByRun(\n agentId: string,\n threadId: string,\n runId: string,\n ): State | undefined {\n return this.stateManager.getStateByRun(agentId, threadId, runId);\n }\n\n getRunIdForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): string | undefined {\n return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);\n }\n\n getRawEventForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): unknown {\n return this.stateManager.getRawEventForMessage(\n agentId,\n threadId,\n messageId,\n );\n }\n\n getRunIdsForThread(agentId: string, threadId: string): string[] {\n return this.stateManager.getRunIdsForThread(agentId, threadId);\n }\n\n /**\n * Internal method used by RunHandler to build frontend tools\n */\n private buildFrontendTools(agentId?: string): import(\"@ag-ui/client\").Tool[] {\n return this.runHandler.buildFrontendTools(agentId);\n }\n\n /**\n * Called before each follow-up agent run (after tool execution).\n *\n * When a frontend tool handler calls framework state setters (e.g. React's\n * setState), those updates are batched and deferred — they do not take effect\n * until the framework's scheduler runs (React uses MessageChannel).\n * useAgentContext registers context via useLayoutEffect, which runs\n * synchronously after React commits that deferred batch.\n *\n * Without yielding here, the follow-up runAgent reads the context store\n * synchronously while the deferred updates are still pending, producing stale\n * context for the next agent turn.\n *\n * Override in framework-specific subclasses to yield to the framework\n * scheduler before the follow-up run. The base implementation is a no-op\n * because non-React environments have no deferred state to flush.\n */\n async waitForPendingFrameworkUpdates(): Promise<void> {}\n}\n","import type { AbstractAgent, ToolCall } from \"@ag-ui/client\";\nimport type {\n InspectorMetadataV1,\n IntelligenceRuntimeInfo,\n RuntimeMode,\n RuntimeLicenseStatus,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\n\n/**\n * Status of a tool call execution\n */\nexport enum ToolCallStatus {\n InProgress = \"inProgress\",\n Executing = \"executing\",\n Complete = \"complete\",\n}\n\nexport type CopilotRuntimeTransport = \"rest\" | \"single\" | \"auto\";\nexport type {\n InspectorMetadataV1,\n RuntimeMode,\n IntelligenceRuntimeInfo,\n RuntimeLicenseStatus,\n ThreadEndpointRuntimeInfo,\n};\n\n/**\n * Context passed to a frontend tool handler\n */\nexport type FrontendToolHandlerContext = {\n toolCall: ToolCall;\n /**\n * The agent that invoked the tool. Absent when the tool is invoked through\n * the WebMCP browser API (`document.modelContext`), which has no agent.\n */\n agent?: AbstractAgent;\n /** Aborted when `stopAgent()` is called. Handlers can check `signal.aborted`\n * or pass the signal to fetch/setTimeout to cooperatively cancel. */\n signal?: AbortSignal;\n /**\n * True when CopilotKit runs this call while restoring a thread's history on\n * connect, for a call that a previous page or client left without a result.\n * Absent for a call made by a live run. See `reconnectBehavior`.\n */\n isReplay?: boolean;\n};\n\n/**\n * What a frontend tool does with its own calls that are still unanswered when\n * a thread's history is restored (a reload, a remount, or a thread switch).\n * Only calls after the latest user message are eligible; older unanswered\n * calls remain historical and never resume work on reconnect.\n *\n * - `\"passive\"` (default) — show the call, but do not run the handler. Nothing\n * the handler did runs twice.\n * - `\"resume-pending\"` — run the handler for each call that has no result,\n * with `isReplay: true` in its context, then continue the run as usual\n * (follow-up included, unless `followUp` is false).\n *\n * Use `\"resume-pending\"` only for a handler that is safe to run more than\n * once. A call does not start twice at the same time in one CopilotKit\n * instance, but it can run again after a stop or a thread switch if its result\n * never reached the agent, and two tabs or devices that restore the same\n * thread can each run it.\n *\n * If one assistant message also calls a tool that stays passive, the follow-up\n * run sends that call without a result, which some model providers reject.\n * Opt in every tool the agent calls together, or set `followUp: false`.\n */\nexport type FrontendToolReconnectBehavior = \"passive\" | \"resume-pending\";\n\n/**\n * Annotations for a WebMCP tool, passed through to\n * `document.modelContext.registerTool`. Mirrors the WebMCP spec's tool\n * annotations. These are hints for browser agents only — they do not enforce\n * any policy on their own.\n */\nexport type WebMCPToolAnnotations = {\n /**\n * Hint that the tool does not modify state. Defaults to false.\n * Set it for read-only tools (search, status lookup, ...).\n */\n readOnlyHint?: boolean;\n /**\n * Hint that the tool's output may contain untrusted content\n * (e.g. user-generated or external content). Defaults to false.\n */\n untrustedContentHint?: boolean;\n};\n\n/**\n * WebMCP registration options for a frontend tool.\n */\nexport type WebMCPToolConfig = {\n /** Hints that tell browser agents how the tool behaves. */\n annotations?: WebMCPToolAnnotations;\n};\n\nexport type FrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n> = {\n /**\n * @internal Classifies local execution. Omitted means an ordinary frontend\n * tool. Pending calls in the latest user turn are eligible for restoration.\n * Human-in-the-loop handlers are restored from history replay;\n * other handlers only with `reconnectBehavior: \"resume-pending\"`. Tools\n * without a handler restore missing empty completion results automatically.\n * This field is not sent to the agent as part of the tool schema.\n */\n type?: \"frontend\" | \"human-in-the-loop\";\n name: string;\n description?: string;\n parameters?: StandardSchemaV1<any, T>;\n handler?: (args: T, context: FrontendToolHandlerContext) => Promise<unknown>;\n followUp?: boolean;\n /**\n * Whether to run the handler again for a call that is still unanswered when\n * the thread's history is restored. Defaults to `\"passive\"`. See\n * {@link FrontendToolReconnectBehavior}.\n */\n reconnectBehavior?: FrontendToolReconnectBehavior;\n /**\n * Optional agent ID to constrain this tool to a specific agent.\n * If specified, this tool will only be available to the specified agent.\n */\n agentId?: string;\n /**\n * Whether this tool is available to the agent.\n * Set to false to hide the tool from the agent without unregistering it.\n * Defaults to true when not specified.\n */\n available?: boolean;\n /**\n * Also expose this tool to browser agents through the WebMCP API\n * (`document.modelContext`) while keeping the normal agent registration.\n *\n * - `true` — register with default annotations.\n * - `{ annotations }` — register with the given WebMCP annotations.\n * - `false` / `undefined` — do not register.\n *\n * The tool's `handler` runs when a browser agent calls the tool; the handler\n * context then has no `agent`. No-op in environments without WebMCP support\n * (e.g. React Native, or browsers without the API enabled).\n */\n webmcp?: boolean | WebMCPToolConfig;\n};\n\nexport type Suggestion = {\n title: string;\n message: string;\n /** Indicates whether this suggestion is still being generated. */\n isLoading: boolean;\n /** Optional CSS class name applied to the suggestion pill. */\n className?: string;\n};\n\nexport type SuggestionAvailability =\n | \"before-first-message\"\n | \"after-first-message\"\n | \"always\"\n | \"disabled\";\n\nexport type DynamicSuggestionsConfig = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * When the suggestions are available. Defaults to \"after-first-message\".\n */\n available?: SuggestionAvailability;\n\n /**\n * The agent ID of the provider of the suggestions. Defaults to `\"default\"`.\n */\n providerAgentId?: string;\n\n /**\n * The agent ID of the consumer of the suggestions. Defaults to `\"*\"` (all agents).\n */\n consumerAgentId?: string;\n};\n\nexport type StaticSuggestionsConfig = {\n /**\n * The suggestions to display.\n */\n suggestions: Omit<Suggestion, \"isLoading\">[];\n\n /**\n * When the suggestions are available. Defaults to \"before-first-message\".\n */\n available?: SuggestionAvailability;\n\n /**\n * The agent ID of the consumer of the suggestions. Defaults to `\"*\"` (all agents).\n */\n consumerAgentId?: string;\n};\n\nexport type SuggestionsConfig =\n | DynamicSuggestionsConfig\n | StaticSuggestionsConfig;\n","export function completePartialMarkdown(input: string): string {\n let s = input;\n\n // Handle code fences first - use FIRST unmatched fence for proper nesting\n const fenceMatches = Array.from(s.matchAll(/^(\\s*)(`{3,}|~{3,})/gm));\n if (fenceMatches.length % 2 === 1) {\n const [, indent, fence] = fenceMatches[0]!;\n s += `\\n${indent}${fence}`;\n }\n\n // Identify incomplete links at the end and close them\n const incompleteLinkMatch = s.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (incompleteLinkMatch) {\n s += \")\";\n }\n\n // State-based parsing\n interface OpenElement {\n type: string;\n marker: string;\n position: number;\n }\n\n const openElements: OpenElement[] = [];\n const chars = Array.from(s);\n\n // First pass: identify code block boundaries and inline code to avoid processing their content\n const codeBlockRanges: Array<{ start: number; end: number }> = [];\n const inlineCodeRanges: Array<{ start: number; end: number }> = [];\n\n // Find code block ranges\n let tempCodeFenceCount = 0;\n let currentCodeBlockStart = -1;\n\n for (let i = 0; i < chars.length; i++) {\n if (i === 0 || chars[i - 1] === \"\\n\") {\n const lineMatch = s.substring(i).match(/^(\\s*)(`{3,}|~{3,})/);\n if (lineMatch) {\n tempCodeFenceCount++;\n if (tempCodeFenceCount % 2 === 1) {\n currentCodeBlockStart = i;\n } else if (currentCodeBlockStart !== -1) {\n codeBlockRanges.push({\n start: currentCodeBlockStart,\n end: i + lineMatch[0].length,\n });\n currentCodeBlockStart = -1;\n }\n i += lineMatch[0].length - 1;\n }\n }\n }\n\n // Find inline code ranges\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\") {\n // Check if escaped\n let backslashCount = 0;\n for (let j = i - 1; j >= 0 && chars[j] === \"\\\\\"; j--) {\n backslashCount++;\n }\n if (backslashCount % 2 === 0) {\n // Not escaped - find the closing backtick\n for (let j = i + 1; j < chars.length; j++) {\n if (chars[j] === \"`\") {\n let closingBackslashCount = 0;\n for (let k = j - 1; k >= 0 && chars[k] === \"\\\\\"; k--) {\n closingBackslashCount++;\n }\n if (closingBackslashCount % 2 === 0) {\n inlineCodeRanges.push({ start: i, end: j + 1 });\n i = j;\n break;\n }\n }\n }\n }\n }\n }\n\n // Helper function to check if position is in code\n const isInCode = (pos: number): boolean => {\n return (\n codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||\n inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)\n );\n };\n\n // Second pass: process markdown elements, skipping code regions\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n const nextChar = chars[i + 1];\n const prevChar = chars[i - 1];\n\n if (isInCode(i)) {\n continue;\n }\n\n // Handle brackets (but not if they're part of already-complete links)\n if (char === \"[\") {\n // Check if this is part of a complete link [text](url)\n let isCompleteLink = false;\n let bracketDepth = 1;\n let j = i + 1;\n\n // Find the matching ]\n while (j < chars.length && bracketDepth > 0) {\n if (chars[j] === \"[\" && !isInCode(j)) bracketDepth++;\n if (chars[j] === \"]\" && !isInCode(j)) bracketDepth--;\n j++;\n }\n\n // Check if followed by (\n if (bracketDepth === 0 && chars[j] === \"(\") {\n // Find the closing )\n let parenDepth = 1;\n j++;\n while (j < chars.length && parenDepth > 0) {\n if (chars[j] === \"(\" && !isInCode(j)) parenDepth++;\n if (chars[j] === \")\" && !isInCode(j)) parenDepth--;\n j++;\n }\n if (parenDepth === 0) {\n isCompleteLink = true;\n i = j - 1;\n continue;\n }\n }\n\n // This is a standalone bracket, treat as markdown\n if (!isCompleteLink) {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bracket\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bracket\", marker: \"[\", position: i });\n }\n }\n }\n\n // Handle double emphasis first (**, __, ~~) - these take precedence\n else if (char === \"*\" && nextChar === \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_star\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bold_star\", marker: \"**\", position: i });\n }\n i++; // Skip next character\n } else if (char === \"_\" && nextChar === \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_underscore\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"bold_underscore\",\n marker: \"__\",\n position: i,\n });\n }\n i++; // Skip next character\n } else if (char === \"~\" && nextChar === \"~\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"strike\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"strike\", marker: \"~~\", position: i });\n }\n i++; // Skip next character\n }\n\n // Handle single emphasis (*, _) - only if not part of double\n else if (char === \"*\" && prevChar !== \"*\" && nextChar !== \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_star\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"italic_star\", marker: \"*\", position: i });\n }\n } else if (char === \"_\" && prevChar !== \"_\" && nextChar !== \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_underscore\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"italic_underscore\",\n marker: \"_\",\n position: i,\n });\n }\n }\n }\n\n // Handle remaining unmatched backticks (outside of inline code ranges)\n let backtickCount = 0;\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\" && !isInCode(i)) {\n backtickCount++;\n }\n }\n if (backtickCount % 2 === 1) {\n s += \"`\";\n }\n\n // Close remaining open elements in reverse order (LIFO stack semantics)\n openElements.sort((a, b) => b.position - a.position);\n\n const closers = openElements.map((el) => {\n switch (el.type) {\n case \"bracket\":\n return \"]\";\n case \"bold_star\":\n return \"**\";\n case \"bold_underscore\":\n return \"__\";\n case \"strike\":\n return \"~~\";\n case \"italic_star\":\n return \"*\";\n case \"italic_underscore\":\n return \"_\";\n default:\n return \"\";\n }\n });\n\n let result = s + closers.join(\"\");\n\n // Handle parentheses ONLY if not inside code\n const finalFenceMatches = Array.from(\n result.matchAll(/^(\\s*)(`{3,}|~{3,})/gm),\n );\n const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;\n const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;\n\n let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;\n\n if (shouldCloseParens) {\n const lastOpenParen = result.lastIndexOf(\"(\");\n if (lastOpenParen !== -1) {\n // Check if this paren is inside a backtick pair\n const beforeParen = result.substring(0, lastOpenParen);\n const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;\n if (backticksBeforeParen % 2 === 1) {\n shouldCloseParens = false;\n }\n }\n }\n\n if (shouldCloseParens) {\n const openParens = (result.match(/\\(/g) || []).length;\n const closeParens = (result.match(/\\)/g) || []).length;\n if (openParens > closeParens) {\n result += \")\".repeat(openParens - closeParens);\n }\n }\n\n return result;\n}\n","import { phoenixExponentialBackoff } from \"@copilotkit/shared\";\nimport type { Subscription } from \"rxjs\";\nimport { defer, firstValueFrom, merge, Observable, of } from \"rxjs\";\nimport {\n catchError,\n filter,\n map,\n mergeMap,\n share,\n shareReplay,\n switchMap,\n take,\n takeUntil,\n tap,\n withLatestFrom,\n} from \"rxjs/operators\";\nimport {\n createActionGroup,\n createEffect,\n createReducer,\n createSelector,\n createStore,\n empty,\n ofType,\n on,\n props,\n} from \"./utils/micro-redux\";\nimport type { Reducer, Store } from \"./utils/micro-redux\";\nimport type {\n RuntimeRequestInit,\n RuntimeRequestMeta,\n} from \"./utils/runtime-request\";\nimport {\n ɵphoenixChannel$,\n ɵphoenixSocket$,\n ɵobservePhoenixEvent$,\n ɵobservePhoenixJoinOutcome$,\n ɵobservePhoenixSocketHealth$,\n ɵobservePhoenixSocketSignals$,\n} from \"./utils/phoenix-observable\";\nimport type { ɵPhoenixChannelSession } from \"./utils/phoenix-observable\";\n\nconst THREADS_CHANNEL_EVENT = \"thread_metadata\";\nconst THREAD_RUN_ACTIVITY_CHANNEL_EVENT = \"thread_run_activity\";\nconst THREAD_SUBSCRIBE_PATH = \"/threads/subscribe\";\nconst MAX_SOCKET_RETRIES = 5;\nconst REQUEST_TIMEOUT_MS = 15_000;\n\ninterface ThreadRecord {\n id: string;\n organizationId: string;\n agentId: string;\n createdById: string;\n name: string | null;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n lastRunAt?: string;\n}\n\ninterface ThreadRuntimeContext {\n runtimeUrl: string;\n /**\n * Optional: `environment.fetch` is expected to be `ɵruntimeFetch`, which\n * already resolves and overlays the current core headers at send time\n * (#1937). Set explicitly only when the store's `fetch` does NOT already\n * carry headers.\n */\n headers?: Record<string, string>;\n wsUrl?: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n}\n\ntype ThreadMetadataEvent =\n | {\n operation: \"created\" | \"renamed\" | \"archived\" | \"unarchived\" | \"updated\";\n threadId: string;\n userId: string;\n organizationId: string;\n occurredAt: string;\n thread: ThreadRecord;\n }\n | {\n operation: \"deleted\";\n threadId: string;\n userId: string;\n organizationId: string;\n occurredAt: string;\n deleted: {\n id: string;\n };\n };\n\n/**\n * Internal notification emitted when Intelligence observes new run activity\n * for a thread without changing that thread's metadata row.\n */\nexport type ThreadRunActivityNotification = {\n type: \"thread_run_activity\";\n threadId: string;\n agentId?: string;\n runId?: string;\n eventType: string;\n latestEventId?: string;\n};\n\ntype ThreadRunActivityGatewayPayload = {\n threadId?: unknown;\n thread_id?: unknown;\n agentId?: unknown;\n agent_id?: unknown;\n runId?: unknown;\n run_id?: unknown;\n eventType?: unknown;\n event_type?: unknown;\n latestEventId?: unknown;\n latest_event_id?: unknown;\n};\n\ninterface ThreadListResponse {\n threads: ThreadRecord[];\n joinCode?: string | null;\n nextCursor?: string | null;\n}\n\ninterface ThreadMetadataCredentialsResponse {\n joinToken: string;\n}\n\ninterface MutationRequest {\n requestId: string;\n /** Session the mutation was dispatched in; stale results are dropped. */\n sessionId: number;\n path: string;\n method: \"PATCH\" | \"POST\" | \"DELETE\";\n body: Record<string, unknown>;\n}\n\ntype MutationOutcome =\n | { requestId: string; sessionId: number; ok: true }\n | { requestId: string; sessionId: number; ok: false; error: Error };\n\ninterface ThreadEnvironment {\n fetch: typeof fetch;\n /**\n * Optional callback invoked whenever a thread mutation (rename, archive,\n * unarchive, delete) is rejected by the server. Lets framework wrappers\n * surface a transient error toast without subscribing to the error\n * selector. The error is also recorded in `state.error` regardless.\n *\n * Fired after any rollback (delete) has been applied to local state.\n */\n onError?: (error: Error) => void;\n}\n\ninterface ThreadState {\n threads: ThreadRecord[];\n isLoading: boolean;\n isFetchingNextPage: boolean;\n error: Error | null;\n /**\n * Error from the most recent failed next-page (`fetchMore`) load, or `null`.\n * Tracked SEPARATELY from `error` so a paginated-load failure surfaces an\n * inline \"couldn't load more\" affordance without replacing the already-loaded\n * list with a full-panel error. Cleared when a fetch-more is retried or when\n * one succeeds; reset on context change / stop.\n */\n fetchMoreError: Error | null;\n context: ThreadRuntimeContext | null;\n sessionId: number;\n metadataCredentialsRequested: boolean;\n metadataJoinCode: string | null;\n nextCursor: string | null;\n /** Number of thread mutations currently awaiting a server response. */\n inFlightMutationCount: number;\n /**\n * Rows optimistically removed by an in-flight `delete`, keyed by the\n * originating request id. DELETE is the one mutation that rolls back on\n * rejection, so the removed row is parked here and restored if the server\n * rejects. Rename/archive/unarchive are optimistic no-rollback and do not\n * populate this map.\n */\n pendingDeletes: Record<string, ThreadRecord>;\n}\n\nconst initialThreadState: ThreadState = {\n threads: [],\n isLoading: false,\n isFetchingNextPage: false,\n error: null,\n fetchMoreError: null,\n context: null,\n sessionId: 0,\n metadataCredentialsRequested: false,\n metadataJoinCode: null,\n nextCursor: null,\n inFlightMutationCount: 0,\n pendingDeletes: {},\n};\n\nconst threadAdapterEvents = createActionGroup(\"Thread Adapter\", {\n started: empty(),\n stopped: empty(),\n contextChanged: props<{ context: ThreadRuntimeContext | null }>(),\n fetchNextPageRequested: empty(),\n renameRequested: props<{\n requestId: string;\n threadId: string;\n name: string;\n }>(),\n archiveRequested: props<{ requestId: string; threadId: string }>(),\n unarchiveRequested: props<{ requestId: string; threadId: string }>(),\n deleteRequested: props<{ requestId: string; threadId: string }>(),\n newThreadStarted: empty(),\n});\n\nconst threadRestEvents = createActionGroup(\"Thread REST\", {\n listRequested: props<{ sessionId: number }>(),\n listSucceeded: props<{\n sessionId: number;\n threads: ThreadRecord[];\n joinCode: string | null;\n nextCursor: string | null;\n }>(),\n listFailed: props<{ sessionId: number; error: Error }>(),\n nextPageSucceeded: props<{\n sessionId: number;\n threads: ThreadRecord[];\n nextCursor: string | null;\n }>(),\n nextPageFailed: props<{ sessionId: number; error: Error }>(),\n metadataCredentialsRequested: props<{ sessionId: number }>(),\n metadataCredentialsSucceeded: props<{\n sessionId: number;\n joinToken: string;\n }>(),\n metadataCredentialsFailed: props<{ sessionId: number; error: Error }>(),\n mutationFinished: props<{ outcome: MutationOutcome }>(),\n});\n\nconst threadSocketEvents = createActionGroup(\"Thread Socket\", {\n opened: props<{ sessionId: number }>(),\n errored: props<{ sessionId: number }>(),\n joinFailed: props<{ sessionId: number }>(),\n joinTimedOut: props<{ sessionId: number }>(),\n metadataReceived: props<{\n sessionId: number;\n payload: ThreadMetadataEvent;\n }>(),\n runActivityReceived: props<{\n sessionId: number;\n notification: ThreadRunActivityNotification;\n }>(),\n});\n\nconst threadDomainEvents = createActionGroup(\"Thread Domain\", {\n threadUpserted: props<{ sessionId: number; thread: ThreadRecord }>(),\n threadDeleted: props<{ sessionId: number; threadId: string }>(),\n});\n\nfunction sortThreadsByRecency(threads: ThreadRecord[]): ThreadRecord[] {\n // Prefer lastRunAt so the order reflects actual agent activity and stays\n // stable when a user performs metadata-only actions like archive or rename.\n // Fall back to updatedAt (and then createdAt) for threads that have never run.\n return [...threads].sort((left, right) => {\n const leftKey = left.lastRunAt ?? left.updatedAt ?? left.createdAt;\n const rightKey = right.lastRunAt ?? right.updatedAt ?? right.createdAt;\n return rightKey.localeCompare(leftKey);\n });\n}\n\nfunction upsertThread(\n threads: ThreadRecord[],\n thread: ThreadRecord,\n): ThreadRecord[] {\n const existingIndex = threads.findIndex((item) => item.id === thread.id);\n if (existingIndex === -1) {\n return sortThreadsByRecency([...threads, thread]);\n }\n\n const next = [...threads];\n next[existingIndex] = thread;\n return sortThreadsByRecency(next);\n}\n\n/**\n * Returns a non-empty string payload field or undefined for absent fields.\n */\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * REST `/threads` is agent-scoped. The Phoenix `user_meta` channel is not.\n * Drop live upserts that belong to a different agent, or one Inspector\n * `all-agents` flatten shows the same thread twice until a hard refresh.\n */\nfunction threadMetadataTargetsAgent(\n payload: ThreadMetadataEvent,\n agentId: string | undefined,\n): boolean {\n if (!agentId || payload.operation === \"deleted\") {\n return true;\n }\n\n const threadAgentId = optionalString(payload.thread.agentId);\n return !threadAgentId || threadAgentId === agentId;\n}\n\n/**\n * Converts gateway run-activity payloads into the internal TypeScript shape.\n */\nfunction normalizeThreadRunActivityNotification(\n payload: ThreadRunActivityGatewayPayload,\n): ThreadRunActivityNotification | null {\n const threadId = optionalString(payload.threadId ?? payload.thread_id);\n const eventType = optionalString(payload.eventType ?? payload.event_type);\n\n if (!threadId || !eventType) {\n return null;\n }\n\n return {\n type: \"thread_run_activity\",\n threadId,\n agentId: optionalString(payload.agentId ?? payload.agent_id),\n runId: optionalString(payload.runId ?? payload.run_id),\n eventType,\n latestEventId: optionalString(\n payload.latestEventId ?? payload.latest_event_id,\n ),\n };\n}\n\nconst threadReducer = createReducer(\n initialThreadState,\n on(threadAdapterEvents.contextChanged, (state: ThreadState, { context }) => ({\n ...state,\n context,\n sessionId: state.sessionId + 1,\n threads: [],\n isLoading: Boolean(context),\n isFetchingNextPage: false,\n error: null,\n fetchMoreError: null,\n metadataCredentialsRequested: false,\n metadataJoinCode: null,\n nextCursor: null,\n inFlightMutationCount: 0,\n pendingDeletes: {},\n })),\n on(threadAdapterEvents.stopped, (state: ThreadState) => ({\n ...state,\n threads: [],\n isLoading: false,\n isFetchingNextPage: false,\n error: null,\n fetchMoreError: null,\n metadataCredentialsRequested: false,\n metadataJoinCode: null,\n nextCursor: null,\n inFlightMutationCount: 0,\n pendingDeletes: {},\n })),\n on(threadRestEvents.listRequested, (state: ThreadState, { sessionId }) => {\n if (sessionId !== state.sessionId || !state.context) {\n return state;\n }\n\n return {\n ...state,\n isLoading: true,\n error: null,\n // A full-list refetch supersedes any prior fetch-more failure: the whole\n // list is being reloaded, so the stale inline \"couldn't load more\" banner\n // must not survive onto the fresh list.\n fetchMoreError: null,\n };\n }),\n on(\n threadRestEvents.listSucceeded,\n (state: ThreadState, { sessionId, threads, joinCode, nextCursor }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n const joinCodeChanged = joinCode !== state.metadataJoinCode;\n\n return {\n ...state,\n threads: sortThreadsByRecency(threads),\n isLoading: false,\n error: null,\n // The fresh full list also clears any lingering fetch-more error, in\n // case the list arrived without passing through `listRequested`.\n fetchMoreError: null,\n metadataJoinCode: joinCode,\n metadataCredentialsRequested: joinCodeChanged\n ? false\n : state.metadataCredentialsRequested,\n nextCursor,\n };\n },\n ),\n on(\n threadRestEvents.listFailed,\n (state: ThreadState, { sessionId, error }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n isLoading: false,\n error,\n };\n },\n ),\n on(\n threadRestEvents.nextPageSucceeded,\n (state: ThreadState, { sessionId, threads, nextCursor }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n let merged = state.threads;\n for (const thread of threads) {\n merged = upsertThread(merged, thread);\n }\n\n return {\n ...state,\n threads: merged,\n isFetchingNextPage: false,\n // A successful next page clears any prior fetch-more error.\n fetchMoreError: null,\n nextCursor,\n };\n },\n ),\n on(\n threadRestEvents.nextPageFailed,\n (state: ThreadState, { sessionId, error }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n // A failed next-page load records the error on the DEDICATED fetch-more\n // channel — NOT `state.error` — so the already-loaded list is preserved\n // and the drawer renders an inline \"couldn't load more — retry\" panel\n // rather than replacing the whole list with a full-panel error.\n return {\n ...state,\n isFetchingNextPage: false,\n fetchMoreError: error,\n };\n },\n ),\n on(\n threadRestEvents.metadataCredentialsFailed,\n (state: ThreadState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n // Non-fatal: the metadata-credentials (realtime join-token) fetch runs\n // AFTER the thread list has already loaded and only powers the realtime\n // channel. A failure means realtime won't connect, but the fetched list\n // is still valid — so we do NOT write `state.error` (which would replace\n // the whole list with a \"couldn't load\" panel). The failure is surfaced\n // as a diagnostic warning instead (socketDiagnosticsEffect), mirroring the\n // stay-stale handling of a realtime channel join failure. Clear the\n // request latch so a later list refresh can retry realtime setup.\n return {\n ...state,\n metadataCredentialsRequested: false,\n };\n },\n ),\n on(\n threadRestEvents.metadataCredentialsRequested,\n (state: ThreadState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n metadataCredentialsRequested: true,\n };\n },\n ),\n on(threadAdapterEvents.fetchNextPageRequested, (state: ThreadState) => {\n if (!state.nextCursor || state.isFetchingNextPage) {\n return state;\n }\n\n return {\n ...state,\n isFetchingNextPage: true,\n // Clear any prior fetch-more error so a retry dismisses the inline panel\n // immediately while the next-page request is in flight.\n fetchMoreError: null,\n };\n }),\n on(\n threadAdapterEvents.renameRequested,\n (state: ThreadState, { threadId, name }) => {\n // Optimistic, no-rollback: reflect the new name immediately. A failure\n // surfaces via `error`/`onError` but the local row is left as-is; a\n // realtime metadata event or refetch reconciles the true server state.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, { ...existing, name }),\n inFlightMutationCount,\n };\n },\n ),\n on(\n threadAdapterEvents.archiveRequested,\n (state: ThreadState, { threadId }) => {\n // Optimistic, no-rollback. When archived threads are hidden, drop the\n // row; otherwise flip the flag in place. Note: archiving the active\n // thread is non-destructive — the wrapper keeps viewing it.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n if (!state.context?.includeArchived) {\n return {\n ...state,\n threads: state.threads.filter((thread) => thread.id !== threadId),\n inFlightMutationCount,\n };\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, { ...existing, archived: true }),\n inFlightMutationCount,\n };\n },\n ),\n on(\n threadAdapterEvents.unarchiveRequested,\n (state: ThreadState, { threadId }) => {\n // Optimistic, no-rollback.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, { ...existing, archived: false }),\n inFlightMutationCount,\n };\n },\n ),\n on(\n threadAdapterEvents.deleteRequested,\n (state: ThreadState, { requestId, threadId }) => {\n // Optimistic WITH rollback: remove the row now, but park it under the\n // request id so it can be restored if the server rejects the delete.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n return {\n ...state,\n threads: state.threads.filter((thread) => thread.id !== threadId),\n pendingDeletes: { ...state.pendingDeletes, [requestId]: existing },\n inFlightMutationCount,\n };\n },\n ),\n on(threadAdapterEvents.newThreadStarted, (state: ThreadState) => ({\n // Lazy creation: a fresh client-side thread does NOT add a phantom row —\n // it only materializes once its first run persists server-side. The\n // store-side concern is purely to clear any stale error so the welcome\n // screen renders cleanly; the wrapper owns the active/explicit threadId.\n ...state,\n error: null,\n })),\n on(threadRestEvents.mutationFinished, (state: ThreadState, { outcome }) => {\n // Drop results from a superseded session. `contextChanged`/`stopped` already\n // reset `threads`, `pendingDeletes`, and `inFlightMutationCount`, so a\n // mutation that resolves after the context switched must not write an error,\n // fire onError (guarded in subscribeErrors), or roll a stale row back into\n // the new list. Mirrors every other session-scoped handler.\n if (outcome.sessionId !== state.sessionId) {\n return state;\n }\n\n const inFlightMutationCount = Math.max(0, state.inFlightMutationCount - 1);\n\n if (outcome.ok) {\n // Success: drop any parked delete-rollback snapshot for this request.\n if (state.pendingDeletes[outcome.requestId] === undefined) {\n return { ...state, inFlightMutationCount };\n }\n\n const { [outcome.requestId]: _settled, ...rest } = state.pendingDeletes;\n return { ...state, inFlightMutationCount, pendingDeletes: rest };\n }\n\n // Failure: surface the error. For a rejected delete, restore the row that\n // was optimistically removed (rollback). Other mutations are no-rollback.\n const rolledBack = state.pendingDeletes[outcome.requestId];\n if (rolledBack === undefined) {\n return { ...state, inFlightMutationCount, error: outcome.error };\n }\n\n const { [outcome.requestId]: _restored, ...rest } = state.pendingDeletes;\n return {\n ...state,\n threads: upsertThread(state.threads, rolledBack),\n pendingDeletes: rest,\n inFlightMutationCount,\n error: outcome.error,\n };\n }),\n on(\n threadDomainEvents.threadUpserted,\n (state: ThreadState, { sessionId, thread }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, thread),\n };\n },\n ),\n on(\n threadDomainEvents.threadDeleted,\n (state: ThreadState, { sessionId, threadId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n threads: state.threads.filter((thread) => thread.id !== threadId),\n };\n },\n ),\n) as Reducer<ThreadState>;\n\n/**\n * The set of memoized thread selectors bound to a single store instance.\n *\n * @see createThreadSelectors\n */\ninterface ThreadSelectors {\n threads: (state: ThreadState) => ThreadRecord[];\n isLoading: (state: ThreadState) => boolean;\n error: (state: ThreadState) => Error | null;\n fetchMoreError: (state: ThreadState) => Error | null;\n hasNextPage: (state: ThreadState) => boolean;\n isFetchingNextPage: (state: ThreadState) => boolean;\n isMutating: (state: ThreadState) => boolean;\n}\n\n/**\n * Builds a fresh set of memoized thread selectors.\n *\n * Each `createSelector` closure owns a private one-entry cache. Sharing a\n * single module-level selector instance across multiple concurrent stores\n * (e.g. a `<CopilotThreadsDrawer>` plus an independent `useThreads`) makes every\n * cross-store emission a cache miss, defeating memoization and risking\n * emission instability for any future selector that allocates a new\n * object/array. Creating a per-store instance keeps each store's cache\n * isolated so concurrent stores never thrash one another.\n */\nfunction createThreadSelectors(): ThreadSelectors {\n return {\n threads: createSelector((state: ThreadState) => state.threads),\n isLoading: createSelector((state: ThreadState) => state.isLoading),\n error: createSelector((state: ThreadState) => state.error),\n fetchMoreError: createSelector(\n (state: ThreadState) => state.fetchMoreError,\n ),\n hasNextPage: createSelector(\n (state: ThreadState) => state.nextCursor != null,\n ),\n isFetchingNextPage: createSelector(\n (state: ThreadState) => state.isFetchingNextPage,\n ),\n isMutating: createSelector(\n (state: ThreadState) => state.inFlightMutationCount > 0,\n ),\n };\n}\n\n// Standalone selector instances retained for callers that read a one-off\n// snapshot (e.g. `selectThreads(store.getState())`) where cross-store memo\n// isolation is irrelevant. Subscriptions through `store.select(...)` should\n// prefer the per-store `ThreadStore.selectors` bundle below.\nconst standaloneSelectors = createThreadSelectors();\nconst selectThreads = standaloneSelectors.threads;\nconst selectThreadsIsLoading = standaloneSelectors.isLoading;\nconst selectThreadsError = standaloneSelectors.error;\nconst selectFetchMoreError = standaloneSelectors.fetchMoreError;\nconst selectHasNextPage = standaloneSelectors.hasNextPage;\nconst selectIsFetchingNextPage = standaloneSelectors.isFetchingNextPage;\nconst selectIsMutating = standaloneSelectors.isMutating;\n\ninterface ThreadStore {\n start(): void;\n stop(): void;\n setContext(context: ThreadRuntimeContext | null): void;\n /** Re-fetches the thread list without resetting the current list to empty. */\n refresh(): void;\n /**\n * Re-fetches the thread list without resetting the current list to empty.\n *\n * Public, design-named alias of {@link refresh} used by the drawer's\n * error-state Retry affordance and the Active/All filter-change refetch.\n */\n refetchThreads(): void;\n /**\n * Resets to a fresh, client-side thread so the welcome screen can show.\n *\n * Lazy creation: no phantom row is added to the list — the new thread only\n * materializes once its first run persists server-side. This is distinct\n * from selecting an existing thread (which the wrapper marks *explicit*,\n * suppressing the welcome screen): the thread produced here is NOT explicit.\n */\n startNewThread(): void;\n fetchNextPage(): void;\n renameThread(threadId: string, name: string): Promise<void>;\n archiveThread(threadId: string): Promise<void>;\n unarchiveThread(threadId: string): Promise<void>;\n deleteThread(threadId: string): Promise<void>;\n /**\n * Subscribes to synthetic run-activity notifications without changing the\n * thread metadata list.\n */\n subscribeToRunActivity?(\n callback: (notification: ThreadRunActivityNotification) => void,\n ): Subscription;\n getState(): ThreadState;\n /**\n * Returns a stable initial snapshot for server-side rendering.\n *\n * `useSyncExternalStore` requires a `getServerSnapshot` during SSR/prerender\n * (e.g. Next.js); without one React throws \"Missing getServerSnapshot\". The\n * returned reference is stable across calls so React does not loop. There is\n * no client-side thread data during prerender, so this is the empty initial\n * state.\n */\n getServerState(): ThreadState;\n select: Store<ThreadState>[\"select\"];\n /**\n * Memoized selectors bound to THIS store instance.\n *\n * Subscriptions should pass these to {@link select} (e.g.\n * `store.select(store.selectors.threads)`) so each store keeps its own\n * one-entry memo cache. Sharing the module-level singletons across\n * concurrent stores defeats memoization and risks emission instability.\n */\n selectors: ThreadSelectors;\n}\n\nlet threadRequestId = 0;\n\nfunction createThreadRequestId(): string {\n threadRequestId += 1;\n return `thread-request-${threadRequestId}`;\n}\n\nfunction threadFromFetch<T>(\n input: string,\n init: RequestInit & {\n selector: (response: Response) => Promise<T>;\n fetch: typeof fetch;\n timeoutMs?: number;\n nonCritical?: boolean;\n },\n): Observable<T> {\n return new Observable<T>((subscriber) => {\n const {\n fetch: fetchImpl,\n selector,\n signal,\n timeoutMs,\n nonCritical,\n ...requestInit\n } = init;\n const controller = new AbortController();\n const runtimeRequest: RuntimeRequestMeta = {\n ...(nonCritical ? { nonCritical: true } : {}),\n ...(timeoutMs === undefined ? {} : { selfBounded: true }),\n };\n let timedOut = false;\n const abortRequest = () => controller.abort();\n\n if (signal?.aborted) {\n abortRequest();\n } else {\n signal?.addEventListener(\"abort\", abortRequest, { once: true });\n }\n\n const timeoutId =\n timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n timedOut = true;\n runtimeRequest.timedOut = true;\n abortRequest();\n }, timeoutMs);\n\n const requestInitWithMeta: RuntimeRequestInit = {\n ...requestInit,\n signal: controller.signal,\n ɵruntimeRequest: runtimeRequest,\n };\n\n fetchImpl(input, requestInitWithMeta)\n .then((response) => selector(response))\n .then((value) => {\n if (subscriber.closed) return;\n subscriber.next(value);\n subscriber.complete();\n })\n .catch((error: unknown) => {\n if (!subscriber.closed) {\n subscriber.error(\n timedOut ? new Error(\"Request timed out\") : (error as Error),\n );\n }\n });\n\n return () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n signal?.removeEventListener(\"abort\", abortRequest);\n abortRequest();\n };\n });\n}\n\nfunction createThreadFetchObservable(\n environment: ThreadEnvironment,\n context: ThreadRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof threadRestEvents.listSucceeded>\n | ReturnType<typeof threadRestEvents.listFailed>\n> {\n return defer(() => {\n const params: Record<string, string> = {\n agentId: context.agentId,\n };\n if (context.includeArchived) params.includeArchived = \"true\";\n if (context.limit != null) params.limit = String(context.limit);\n\n const qs = new URLSearchParams(params);\n return threadFromFetch(`${context.runtimeUrl}/threads?${qs.toString()}`, {\n selector: (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch threads: ${response.status}`);\n }\n\n return response.json() as Promise<ThreadListResponse>;\n },\n fetch: environment.fetch,\n timeoutMs: REQUEST_TIMEOUT_MS,\n method: \"GET\",\n headers: { ...context.headers },\n }).pipe(\n map((data) =>\n threadRestEvents.listSucceeded({\n sessionId,\n threads: data.threads,\n joinCode:\n typeof data.joinCode === \"string\" && data.joinCode.length > 0\n ? data.joinCode\n : null,\n nextCursor: data.nextCursor ?? null,\n }),\n ),\n catchError((error) => {\n return of(\n threadRestEvents.listFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n );\n });\n}\n\nfunction createThreadMetadataCredentialsObservable(\n environment: ThreadEnvironment,\n context: ThreadRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof threadRestEvents.metadataCredentialsSucceeded>\n | ReturnType<typeof threadRestEvents.metadataCredentialsFailed>\n> {\n return defer(() => {\n return threadFromFetch(`${context.runtimeUrl}${THREAD_SUBSCRIBE_PATH}`, {\n selector: async (response) => {\n if (!response.ok) {\n throw new Error(\n `Failed to fetch thread metadata credentials: ${response.status}`,\n );\n }\n\n return response.json() as Promise<ThreadMetadataCredentialsResponse>;\n },\n fetch: environment.fetch,\n timeoutMs: REQUEST_TIMEOUT_MS,\n nonCritical: true,\n method: \"POST\",\n headers: {\n ...context.headers,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({}),\n }).pipe(\n map((data) => {\n if (typeof data.joinToken !== \"string\" || data.joinToken.length === 0) {\n throw new Error(\"missing joinToken\");\n }\n\n return threadRestEvents.metadataCredentialsSucceeded({\n sessionId,\n joinToken: data.joinToken,\n });\n }),\n catchError((error) => {\n return of(\n threadRestEvents.metadataCredentialsFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n );\n });\n}\n\nfunction createThreadMutationObservable(\n environment: ThreadEnvironment,\n context: ThreadRuntimeContext,\n request: MutationRequest,\n): Observable<ReturnType<typeof threadRestEvents.mutationFinished>> {\n return defer(() => {\n return threadFromFetch(`${context.runtimeUrl}${request.path}`, {\n selector: async (response) => {\n if (!response.ok) {\n throw new Error(`Request failed: ${response.status}`);\n }\n\n return null;\n },\n fetch: environment.fetch,\n method: request.method,\n headers: {\n ...context.headers,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request.body),\n }).pipe(\n map(() =>\n threadRestEvents.mutationFinished({\n outcome: {\n requestId: request.requestId,\n sessionId: request.sessionId,\n ok: true,\n },\n }),\n ),\n catchError((error) => {\n return of(\n threadRestEvents.mutationFinished({\n outcome: {\n requestId: request.requestId,\n sessionId: request.sessionId,\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n }),\n );\n }),\n );\n });\n}\n\nfunction createThreadStore(environment: ThreadEnvironment): ThreadStore {\n // Per-store selector instances keep this store's memo cache isolated from\n // any other concurrent store (see createThreadSelectors).\n const selectors = createThreadSelectors();\n\n const bootstrapEffect = createEffect(\n (\n actions$,\n state$: Observable<ThreadState>,\n ): Observable<ReturnType<typeof threadRestEvents.listRequested>> =>\n actions$.pipe(\n ofType(threadAdapterEvents.contextChanged),\n withLatestFrom(state$),\n filter(([, state]) => Boolean(state.context)),\n map(([, state]) =>\n threadRestEvents.listRequested({ sessionId: state.sessionId }),\n ),\n ),\n );\n\n const fetchEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.listRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is ThreadRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createThreadFetchObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const metadataCredentialsEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.listSucceeded),\n withLatestFrom(state$),\n filter(([action, state]) => {\n return (\n action.sessionId === state.sessionId &&\n !state.metadataCredentialsRequested &&\n Boolean(state.context?.wsUrl) &&\n Boolean(state.metadataJoinCode)\n );\n }),\n map(([action]) =>\n threadRestEvents.metadataCredentialsRequested({\n sessionId: action.sessionId,\n }),\n ),\n ),\n );\n\n const metadataCredentialsFetchEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.metadataCredentialsRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is ThreadRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createThreadMetadataCredentialsObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const socketEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.metadataCredentialsSucceeded),\n withLatestFrom(state$),\n filter(([action, state]) => {\n return (\n action.sessionId === state.sessionId &&\n Boolean(state.context?.wsUrl)\n );\n }),\n switchMap(([action, state]) => {\n const context = state.context as ThreadRuntimeContext;\n const joinToken = action.joinToken as string;\n const joinCode = state.metadataJoinCode as string;\n const shutdown$ = actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n );\n\n return defer(() => {\n const socket$ = ɵphoenixSocket$({\n url: context.wsUrl!,\n options: {\n params: { join_token: joinToken },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const channel$ = ɵphoenixChannel$({\n socket$,\n topic: `user_meta:${joinCode}`,\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const socketSignals$ =\n ɵobservePhoenixSocketSignals$(socket$).pipe(share());\n const fatalSocketShutdown$ = ɵobservePhoenixSocketHealth$(\n socketSignals$,\n MAX_SOCKET_RETRIES,\n ).pipe(\n catchError(() => {\n console.warn(\n `[threads] WebSocket failed after ${MAX_SOCKET_RETRIES} attempts, giving up`,\n );\n return of(undefined);\n }),\n share(),\n );\n const socketLifecycle$ = socketSignals$.pipe(\n map((signal) =>\n signal.type === \"open\"\n ? threadSocketEvents.opened({ sessionId: action.sessionId })\n : threadSocketEvents.errored({ sessionId: action.sessionId }),\n ),\n );\n const metadata$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<ThreadMetadataEvent>(\n channel,\n THREADS_CHANNEL_EVENT,\n ),\n ),\n map((payload) =>\n threadSocketEvents.metadataReceived({\n sessionId: action.sessionId,\n payload,\n }),\n ),\n );\n const runActivity$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<ThreadRunActivityGatewayPayload>(\n channel,\n THREAD_RUN_ACTIVITY_CHANNEL_EVENT,\n ),\n ),\n map((payload) => normalizeThreadRunActivityNotification(payload)),\n filter(\n (notification): notification is ThreadRunActivityNotification =>\n notification !== null,\n ),\n map((notification) =>\n threadSocketEvents.runActivityReceived({\n sessionId: action.sessionId,\n notification,\n }),\n ),\n );\n const joinOutcome$ = ɵobservePhoenixJoinOutcome$(channel$).pipe(\n filter((outcome) => outcome.type !== \"joined\"),\n map((outcome) =>\n outcome.type === \"timeout\"\n ? threadSocketEvents.joinTimedOut({\n sessionId: action.sessionId,\n })\n : threadSocketEvents.joinFailed({\n sessionId: action.sessionId,\n }),\n ),\n );\n\n return merge(\n socketLifecycle$,\n metadata$,\n runActivity$,\n joinOutcome$,\n ).pipe(takeUntil(merge(shutdown$, fatalSocketShutdown$)));\n });\n }),\n ),\n );\n\n const realtimeMappingEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadSocketEvents.metadataReceived),\n withLatestFrom(state$),\n filter(\n ([action, state]) =>\n action.sessionId === state.sessionId &&\n threadMetadataTargetsAgent(action.payload, state.context?.agentId),\n ),\n map(([action, state]) => {\n if (action.payload.operation === \"deleted\") {\n return threadDomainEvents.threadDeleted({\n sessionId: action.sessionId,\n threadId: action.payload.deleted.id,\n });\n }\n\n // When includeArchived is false, an \"archived\" event should remove\n // the thread from the local list rather than upserting it.\n if (\n action.payload.operation === \"archived\" &&\n !state.context?.includeArchived\n ) {\n return threadDomainEvents.threadDeleted({\n sessionId: action.sessionId,\n threadId: action.payload.threadId,\n });\n }\n\n return threadDomainEvents.threadUpserted({\n sessionId: action.sessionId,\n thread: action.payload.thread,\n });\n }),\n ),\n );\n\n // Observability-only effect for realtime-join health. The socket effect\n // dispatches `joinFailed`/`joinTimedOut`/`errored` but the reducer has no\n // handler for them by design: a transient WS drop while the (already\n // fetched) list is present must NOT become a hard list error — the user\n // keeps the stale list. Previously these actions were silently swallowed,\n // leaving a realtime-join failure with zero signal. This effect emits a\n // non-fatal warning (mirroring the MAX_SOCKET_RETRIES warn) so the failure\n // is diagnosable. Session-guarded so a superseded session stays quiet.\n const socketDiagnosticsEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(\n threadSocketEvents.joinFailed,\n threadSocketEvents.joinTimedOut,\n threadSocketEvents.errored,\n threadRestEvents.metadataCredentialsFailed,\n ),\n withLatestFrom(state$),\n filter(([action, state]) => action.sessionId === state.sessionId),\n tap(([action]) => {\n const reason = threadSocketEvents.joinTimedOut.match(action)\n ? \"channel join timed out\"\n : threadSocketEvents.joinFailed.match(action)\n ? \"channel join was rejected\"\n : threadRestEvents.metadataCredentialsFailed.match(action)\n ? \"metadata credentials fetch failed\"\n : \"socket errored\";\n console.warn(\n `[threads] realtime ${reason}; the thread list may be stale until reconnect`,\n );\n }),\n ),\n { dispatch: false },\n );\n\n const fetchNextPageEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadAdapterEvents.fetchNextPageRequested),\n withLatestFrom(state$),\n filter(\n ([, state]) => Boolean(state.context) && Boolean(state.nextCursor),\n ),\n switchMap(([, state]) => {\n const context = state.context as ThreadRuntimeContext;\n const params: Record<string, string> = {\n agentId: context.agentId,\n cursor: state.nextCursor!,\n };\n if (context.includeArchived) params.includeArchived = \"true\";\n if (context.limit != null) params.limit = String(context.limit);\n\n return threadFromFetch(\n `${context.runtimeUrl}/threads?${new URLSearchParams(params).toString()}`,\n {\n selector: (response) => {\n if (!response.ok) {\n throw new Error(\n `Failed to fetch next page: ${response.status}`,\n );\n }\n\n return response.json() as Promise<ThreadListResponse>;\n },\n fetch: environment.fetch,\n timeoutMs: REQUEST_TIMEOUT_MS,\n method: \"GET\",\n headers: { ...context.headers },\n },\n ).pipe(\n map((data) =>\n threadRestEvents.nextPageSucceeded({\n sessionId: state.sessionId,\n threads: data.threads,\n nextCursor: data.nextCursor ?? null,\n }),\n ),\n catchError((error) =>\n of(\n threadRestEvents.nextPageFailed({\n sessionId: state.sessionId,\n error:\n error instanceof Error ? error : new Error(String(error)),\n }),\n ),\n ),\n takeUntil(\n actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n ),\n ),\n );\n }),\n ),\n );\n\n const mutationEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(\n threadAdapterEvents.renameRequested,\n threadAdapterEvents.archiveRequested,\n threadAdapterEvents.unarchiveRequested,\n threadAdapterEvents.deleteRequested,\n ),\n withLatestFrom(state$),\n mergeMap(([action, state]) => {\n // Capture the dispatching session so a result that resolves after a\n // `contextChanged` is dropped by the reducer instead of leaking an\n // error/onError/rollback into the new session. The mergeMap is not\n // cancelled on context change, so the session tag is the guard.\n const sessionId = state.sessionId;\n const context = state.context;\n if (!context?.runtimeUrl) {\n const requestId = action.requestId;\n return of(\n threadRestEvents.mutationFinished({\n outcome: {\n requestId,\n sessionId,\n ok: false,\n error: new Error(\"Runtime URL is not configured\"),\n },\n }),\n );\n }\n\n const commonBody = {\n agentId: context.agentId,\n };\n\n if (threadAdapterEvents.renameRequested.match(action)) {\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"PATCH\",\n path: `/threads/${encodeURIComponent(action.threadId)}`,\n body: {\n ...commonBody,\n name: action.name,\n },\n });\n }\n\n if (threadAdapterEvents.archiveRequested.match(action)) {\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"POST\",\n path: `/threads/${encodeURIComponent(action.threadId)}/archive`,\n body: commonBody,\n });\n }\n\n if (threadAdapterEvents.unarchiveRequested.match(action)) {\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"PATCH\",\n path: `/threads/${encodeURIComponent(action.threadId)}`,\n body: {\n ...commonBody,\n archived: false,\n },\n });\n }\n\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"DELETE\",\n path: `/threads/${encodeURIComponent(action.threadId)}`,\n body: commonBody,\n });\n }),\n ),\n );\n\n const store = createStore<ThreadState>({\n reducer: threadReducer,\n effects: [\n bootstrapEffect,\n fetchEffect,\n metadataCredentialsEffect,\n metadataCredentialsFetchEffect,\n socketEffect,\n realtimeMappingEffect,\n socketDiagnosticsEffect,\n fetchNextPageEffect,\n mutationEffect,\n ],\n });\n\n function trackMutation(\n dispatchAction:\n | ReturnType<typeof threadAdapterEvents.renameRequested>\n | ReturnType<typeof threadAdapterEvents.archiveRequested>\n | ReturnType<typeof threadAdapterEvents.unarchiveRequested>\n | ReturnType<typeof threadAdapterEvents.deleteRequested>,\n ): Promise<void> {\n const completion$ = merge(\n store.actions$.pipe(\n ofType(threadRestEvents.mutationFinished),\n filter(\n (action) => action.outcome.requestId === dispatchAction.requestId,\n ),\n map((action) => action.outcome),\n ),\n store.actions$.pipe(\n ofType(threadAdapterEvents.stopped),\n map(\n () =>\n ({\n requestId: dispatchAction.requestId,\n sessionId: store.getState().sessionId,\n ok: false,\n error: new Error(\n \"Thread store stopped before mutation completed\",\n ),\n }) satisfies MutationOutcome,\n ),\n ),\n ).pipe(take(1));\n\n const resultPromise = firstValueFrom(completion$).then((outcome) => {\n if (outcome.ok) {\n return;\n }\n\n throw outcome.error;\n });\n\n store.dispatch(dispatchAction);\n return resultPromise;\n }\n\n // Surface mutation rejections to the optional environment callback. The\n // reducer has already applied any delete rollback by the time this fires\n // (the store reduces state before re-emitting the action), so consumers see\n // a consistent list when they react to the error.\n let errorSubscription: Subscription | null = null;\n const subscribeErrors = (): void => {\n if (!environment.onError || errorSubscription) {\n return;\n }\n\n errorSubscription = store.actions$\n .pipe(\n ofType(threadRestEvents.mutationFinished),\n // Drop stale-session failures: a mutation that rejects after a\n // `contextChanged` belongs to a context the user already left, so\n // surfacing it would fire onError for the wrong session. The reducer\n // applies the same guard before writing `state.error`.\n filter(\n (action) =>\n !action.outcome.ok &&\n action.outcome.sessionId === store.getState().sessionId,\n ),\n )\n .subscribe((action) => {\n if (!action.outcome.ok) {\n environment.onError?.(action.outcome.error);\n }\n });\n };\n\n return {\n start(): void {\n store.init();\n subscribeErrors();\n store.dispatch(threadAdapterEvents.started());\n },\n stop(): void {\n store.dispatch(threadAdapterEvents.stopped());\n errorSubscription?.unsubscribe();\n errorSubscription = null;\n store.stop();\n },\n setContext(context: ThreadRuntimeContext | null): void {\n store.dispatch(threadAdapterEvents.contextChanged({ context }));\n },\n refresh(): void {\n const { sessionId, context } = store.getState();\n if (!context) return;\n store.dispatch(threadRestEvents.listRequested({ sessionId }));\n },\n refetchThreads(): void {\n const { sessionId, context } = store.getState();\n if (!context) return;\n store.dispatch(threadRestEvents.listRequested({ sessionId }));\n },\n startNewThread(): void {\n store.dispatch(threadAdapterEvents.newThreadStarted());\n },\n fetchNextPage(): void {\n store.dispatch(threadAdapterEvents.fetchNextPageRequested());\n },\n renameThread(threadId: string, name: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.renameRequested({\n requestId: createThreadRequestId(),\n threadId,\n name,\n }),\n );\n },\n archiveThread(threadId: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.archiveRequested({\n requestId: createThreadRequestId(),\n threadId,\n }),\n );\n },\n unarchiveThread(threadId: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.unarchiveRequested({\n requestId: createThreadRequestId(),\n threadId,\n }),\n );\n },\n deleteThread(threadId: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.deleteRequested({\n requestId: createThreadRequestId(),\n threadId,\n }),\n );\n },\n subscribeToRunActivity(\n callback: (notification: ThreadRunActivityNotification) => void,\n ): Subscription {\n return store.actions$\n .pipe(\n ofType(threadSocketEvents.runActivityReceived),\n filter((action) => action.sessionId === store.getState().sessionId),\n map((action) => action.notification),\n )\n .subscribe(callback);\n },\n getState(): ThreadState {\n return store.getState();\n },\n getServerState(): ThreadState {\n return initialThreadState;\n },\n select: store.select.bind(store),\n selectors,\n };\n}\n\nexport type ɵThread = ThreadRecord;\nexport type ɵThreadRuntimeContext = ThreadRuntimeContext;\nexport type ɵThreadMetadataEvent = ThreadMetadataEvent;\nexport type ɵThreadEnvironment = ThreadEnvironment;\nexport type ɵThreadStore = ThreadStore;\nexport type ɵThreadSelectors = ThreadSelectors;\nexport const ɵthreadAdapterEvents = threadAdapterEvents;\nexport const ɵcreateThreadSelectors = createThreadSelectors;\nexport const ɵselectThreads = selectThreads;\nexport const ɵselectThreadsIsLoading = selectThreadsIsLoading;\nexport const ɵselectThreadsError = selectThreadsError;\nexport const ɵselectFetchMoreError = selectFetchMoreError;\nexport const ɵselectHasNextPage = selectHasNextPage;\nexport const ɵselectIsFetchingNextPage = selectIsFetchingNextPage;\nexport const ɵselectIsMutating = selectIsMutating;\nexport { createThreadStore as ɵcreateThreadStore };\n/**\n * Number of consecutive WebSocket connection failures after which the\n * threads channel tears itself down rather than retrying indefinitely.\n * Exposed for tests so they can assert teardown semantics without\n * hardcoding the threshold separately from production.\n */\nexport const ɵMAX_SOCKET_RETRIES = MAX_SOCKET_RETRIES;\n/**\n * How long a thread REST request is given before the store gives up on it.\n * Exposed for tests for the same reason as {@link ɵMAX_SOCKET_RETRIES}: a\n * separately hardcoded copy silently drifts away from this one.\n */\nexport const ɵTHREAD_REQUEST_TIMEOUT_MS = REQUEST_TIMEOUT_MS;\n","/**\n * Central registry of CopilotKit feature names.\n *\n * Feature names are the strings passed to a license context's `checkFeature`\n * (see `@copilotkit/shared`'s `LicenseContextValue`). Historically the only\n * features referenced by literal were the chat surfaces (`chat`, `sidebar`,\n * `popup`); this module makes the set explicit and typed so new surfaces —\n * such as the threads drawer — register a real, discoverable feature name\n * rather than an ad-hoc string scattered across components.\n *\n * `checkFeature` itself still accepts any `string` for backward compatibility;\n * this registry simply documents and types the names CopilotKit recognises.\n */\n\n/**\n * The set of feature names CopilotKit recognises.\n *\n * Frozen so the array cannot be mutated at runtime. Add new surfaces here when\n * they begin gating behaviour on `checkFeature`.\n */\nexport const ɵCOPILOTKIT_FEATURES = Object.freeze([\n \"chat\",\n \"sidebar\",\n \"popup\",\n \"threads\",\n] as const);\n\n/**\n * Union of recognised CopilotKit feature names.\n */\nexport type ɵCopilotKitFeature = (typeof ɵCOPILOTKIT_FEATURES)[number];\n\nconst FEATURE_SET: ReadonlySet<string> = new Set(ɵCOPILOTKIT_FEATURES);\n\n/**\n * Type guard: returns `true` when `name` is a recognised CopilotKit feature.\n *\n * @param name - Candidate feature name.\n * @returns Whether `name` is a registered feature.\n *\n * @example\n * ```ts\n * if (ɵisCopilotKitFeature(\"threads\")) {\n * // narrowed to ɵCopilotKitFeature\n * }\n * ```\n */\nexport function ɵisCopilotKitFeature(name: string): name is ɵCopilotKitFeature {\n return FEATURE_SET.has(name);\n}\n","export const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID =\n \"cpk-inspector-thread\" as const;\n\nconst EVENT_PREFIX = `copilotkit:${INSPECTOR_THREAD_BRIDGE_PLUGIN_ID}`;\n\ntype InspectorBridgeGlobal = typeof globalThis & {\n __COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__?: EventTarget;\n};\n\nexport type InspectorViewThreadPayload = {\n requestId: string;\n threadId: string;\n agentId: string;\n};\n\nexport type InspectorStopViewingPayload = {\n requestId: string;\n agentId: string;\n};\n\nexport type InspectorActiveThreadPayload = {\n requestId: string;\n threadId: string;\n agentId: string;\n source: \"app\" | \"override\";\n};\n\nexport type InspectorViewThreadResultPayload =\n | {\n requestId: string;\n threadId: string;\n agentId: string;\n ok: true;\n }\n | {\n requestId: string;\n threadId: string;\n agentId: string;\n ok: false;\n reason: \"connect-failed\";\n };\n\ntype InspectorThreadBridgeEvents = {\n \"stop-viewing\": InspectorStopViewingPayload;\n \"active-thread\": InspectorActiveThreadPayload;\n \"view-thread-result\": InspectorViewThreadResultPayload;\n};\n\ntype ClaimableViewThreadEvent = {\n payload: InspectorViewThreadPayload;\n claimed: boolean;\n};\n\nfunction eventName(suffix: string): string {\n return `${EVENT_PREFIX}:${suffix}`;\n}\n\nfunction getEventTarget(): EventTarget | null {\n if (\n typeof window !== \"undefined\" &&\n typeof window.addEventListener === \"function\"\n ) {\n return window;\n }\n if (typeof EventTarget === \"undefined\") return null;\n // Shared by duplicate @copilotkit/core copies in non-browser test realms.\n // Browser copies use window itself as the shared event target.\n const sharedGlobal = globalThis as InspectorBridgeGlobal;\n sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__ ??=\n new EventTarget();\n return sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__;\n}\n\nfunction createDetailEvent<T>(name: string, detail: T): Event {\n if (typeof CustomEvent !== \"undefined\") {\n return new CustomEvent(name, { detail });\n }\n const event = new Event(name);\n Object.defineProperty(event, \"detail\", { value: detail });\n return event;\n}\n\nfunction detailFromEvent<T>(event: Event): T {\n return (event as Event & { detail: T }).detail;\n}\n\n/** The Inspector thread bridge is development-only. */\nexport function isInspectorThreadBridgeEnabled(): boolean {\n return process.env.NODE_ENV !== \"production\";\n}\n\nexport function createInspectorThreadRequestId(): string {\n if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) {\n return crypto.randomUUID();\n }\n return `inspector-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\nfunction dispatch<K extends keyof InspectorThreadBridgeEvents>(\n suffix: K,\n payload: InspectorThreadBridgeEvents[K],\n): void {\n if (!isInspectorThreadBridgeEnabled()) return;\n const target = getEventTarget();\n if (!target) return;\n target.dispatchEvent(createDetailEvent(eventName(suffix), payload));\n}\n\nfunction on<K extends keyof InspectorThreadBridgeEvents>(\n suffix: K,\n handler: (payload: InspectorThreadBridgeEvents[K]) => void,\n): () => void {\n if (!isInspectorThreadBridgeEnabled()) return () => undefined;\n const target = getEventTarget();\n if (!target) return () => undefined;\n const listener = (event: Event) => {\n handler(detailFromEvent<InspectorThreadBridgeEvents[K]>(event));\n };\n const name = eventName(suffix);\n target.addEventListener(name, listener);\n return () => target.removeEventListener(name, listener);\n}\n\n/**\n * Ask the first mounted official chat for the matching agent to load a thread.\n * Returns false when no chat claims the request synchronously.\n */\nexport function emitInspectorViewThread(\n payload: InspectorViewThreadPayload,\n): boolean {\n if (!isInspectorThreadBridgeEnabled()) return false;\n const target = getEventTarget();\n if (!target) return false;\n const detail: ClaimableViewThreadEvent = { payload, claimed: false };\n target.dispatchEvent(createDetailEvent(eventName(\"view-thread\"), detail));\n return detail.claimed;\n}\n\nexport function emitInspectorStopViewing(\n payload: InspectorStopViewingPayload,\n): void {\n dispatch(\"stop-viewing\", payload);\n}\n\nexport function emitInspectorActiveThread(\n payload: InspectorActiveThreadPayload,\n): void {\n dispatch(\"active-thread\", payload);\n}\n\nexport function emitInspectorViewThreadResult(\n payload: InspectorViewThreadResultPayload,\n): void {\n dispatch(\"view-thread-result\", payload);\n}\n\nexport function onInspectorViewThread(\n handler: (payload: InspectorViewThreadPayload) => boolean,\n): () => void {\n if (!isInspectorThreadBridgeEnabled()) return () => undefined;\n const target = getEventTarget();\n if (!target) return () => undefined;\n const listener = (event: Event) => {\n const detail = detailFromEvent<ClaimableViewThreadEvent>(event);\n if (detail.claimed) return;\n detail.claimed = handler(detail.payload);\n };\n const name = eventName(\"view-thread\");\n target.addEventListener(name, listener);\n return () => target.removeEventListener(name, listener);\n}\n\nexport function onInspectorStopViewing(\n handler: (payload: InspectorStopViewingPayload) => void,\n): () => void {\n return on(\"stop-viewing\", handler);\n}\n\nexport function onInspectorActiveThread(\n handler: (payload: InspectorActiveThreadPayload) => void,\n): () => void {\n return on(\"active-thread\", handler);\n}\n\nexport function onInspectorViewThreadResult(\n handler: (payload: InspectorViewThreadResultPayload) => void,\n): () => void {\n return on(\"view-thread-result\", handler);\n}\n","/** Language of a fenced code block that carries A2UI operations. */\nexport const A2UI_FENCE_LANGUAGE = \"a2ui\";\n\n/**\n * One part of an assistant message, in source order: prose markdown, or the\n * body of a top-level ```a2ui fence. `target` is the id from a\n * `target=<id>` token in the fence info string. With no target, the surface\n * goes to the chat.\n */\nexport type MarkdownSegment =\n | { type: \"markdown\"; text: string }\n | {\n type: \"a2ui\";\n index: number;\n text: string;\n closed: boolean;\n target?: string;\n };\n\ntype A2UISegment = Extract<MarkdownSegment, { type: \"a2ui\" }>;\n\n/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */\nconst FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;\n\n/** Info-string token that names the placement target of an a2ui fence. */\nconst TARGET_TOKEN = /^target=(.+)$/;\n\ninterface OpenFence {\n /** Fence character (` or ~). */\n char: string;\n /** Length of the opening marker; the closer must be at least this long. */\n length: number;\n /** Offset in the source where the fence body starts. */\n bodyStart: number;\n /** a2ui fence index, or -1 for fences of other languages. */\n index: number;\n /** Target id from the info string of an a2ui fence. */\n target: string | undefined;\n}\n\nfunction isCloser(line: string, fence: OpenFence) {\n const trimmed = line.trim();\n if (trimmed.length < fence.length) return false;\n for (const ch of trimmed) {\n if (ch !== fence.char) return false;\n }\n return true;\n}\n\n/** The id of the first `target=<id>` token. Other tokens are ignored. */\nfunction readTarget(tokens: string[]) {\n for (const token of tokens) {\n const match = TARGET_TOKEN.exec(token);\n if (match) return match[1];\n }\n return undefined;\n}\n\nfunction a2uiSegment(fence: OpenFence, text: string, closed: boolean) {\n const segment: A2UISegment = {\n type: \"a2ui\",\n index: fence.index,\n text,\n closed,\n };\n if (fence.target !== undefined) segment.target = fence.target;\n return segment;\n}\n\n/**\n * Split a (possibly still streaming) markdown string into prose segments and\n * top-level ```a2ui fences. Fences of other languages stay inside prose\n * segments byte-for-byte, and a2ui markers inside them are ignored. Only\n * column-0 fences are recognised, so a fence indented inside a list item is\n * left to the markdown renderer.\n *\n * The first info-string token must be exactly `a2ui`. A later\n * `target=<id>` token sets `target` on the segment (for example\n * ```` ```a2ui target=recommendations ````). Other tokens are ignored.\n *\n * An a2ui segment's `text` is the fence body. For a closed fence it ends with\n * \"\\n\" when non-empty. For an open (still streaming or aborted) fence it is\n * everything after the opener line, minus a half-streamed closing marker.\n *\n * @param markdown - The assistant message text, complete or still streaming.\n * @returns The segments in source order.\n *\n * @example\n * ```ts\n * for (const segment of splitA2UIMarkdown(message.content)) {\n * if (segment.type === \"a2ui\") renderSurface(segment.text, segment.target);\n * else renderMarkdown(segment.text);\n * }\n * ```\n */\nexport function splitA2UIMarkdown(markdown: string) {\n const segments: MarkdownSegment[] = [];\n let proseStart = 0;\n let fence: OpenFence | null = null;\n let a2uiIndex = 0;\n\n const pushProse = (end: number) => {\n if (end > proseStart) {\n segments.push({\n type: \"markdown\",\n text: markdown.slice(proseStart, end),\n });\n }\n };\n\n let lineStart = 0;\n while (lineStart <= markdown.length) {\n const newline = markdown.indexOf(\"\\n\", lineStart);\n const lineEnd = newline < 0 ? markdown.length : newline;\n // A CRLF line keeps its \"\\r\" in the source slices (prose stays\n // byte-identical) but is matched without it, since \".\" does not match \"\\r\".\n const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === \"\\r\";\n const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);\n\n if (fence) {\n if (isCloser(line, fence)) {\n if (fence.index >= 0) {\n const body = markdown.slice(\n fence.bodyStart,\n Math.max(fence.bodyStart, lineStart),\n );\n segments.push(a2uiSegment(fence, body, true));\n proseStart = hasCR ? lineEnd - 1 : lineEnd;\n }\n fence = null;\n }\n } else {\n const open = FENCE_OPEN.exec(line);\n if (open) {\n const marker = open[1] ?? \"\";\n const info = open[2] ?? \"\";\n const char = marker.charAt(0);\n // Backtick fences cannot have backticks in their info string (CommonMark).\n const isValidOpener = !(char === \"`\" && info.includes(\"`\"));\n if (isValidOpener) {\n const [lang = \"\", ...tokens] = info.trim().split(/\\s+/);\n const isA2UI = lang === A2UI_FENCE_LANGUAGE;\n if (isA2UI) pushProse(lineStart);\n fence = {\n char,\n length: marker.length,\n bodyStart: newline < 0 ? markdown.length : lineEnd + 1,\n index: isA2UI ? a2uiIndex++ : -1,\n target: isA2UI ? readTarget(tokens) : undefined,\n };\n }\n }\n }\n\n if (newline < 0) break;\n lineStart = newline + 1;\n }\n\n if (fence && fence.index >= 0) {\n const { char } = fence;\n let body = markdown.slice(fence.bodyStart);\n // Drop a closing marker that is still streaming in (e.g. \"``\").\n const lastNewline = body.lastIndexOf(\"\\n\");\n const lastLine = body.slice(lastNewline + 1).replace(/\\r$/, \"\");\n const isHalfCloser =\n lastLine.length > 0 && [...lastLine].every((ch) => ch === char);\n if (isHalfCloser) {\n body = body.slice(0, lastNewline + 1);\n }\n segments.push(a2uiSegment(fence, body, false));\n } else {\n pushProse(markdown.length);\n }\n\n return segments;\n}\n","import { jsonrepair } from \"jsonrepair\";\nimport { A2UI_VERSION, GENERATIVE_UI_ROOT_ID } from \"@copilotkit/shared\";\n\n/**\n * An A2UI v1.0 message as the model wrote it in an a2ui fence: an object that\n * carries one of createSurface, updateComponents, updateDataModel,\n * deleteSurface or callRendererFunction. The shape is not checked yet.\n * Validate it (for example with `validateOperation` from `@copilotkit/shared`)\n * before it reaches a surface or runs a function.\n *\n * It is named `A2UIMarkdownOperation` because `@copilotkit/shared` already\n * exports the strict `A2UIOperation` type.\n */\nexport type A2UIMarkdownOperation = Record<string, unknown>;\n\n/** The operation keys that change a surface. */\nconst SURFACE_OP_KEYS = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n] as const;\n\n/** The operation key of an agent-called function. It has no surface. */\nconst FUNCTION_CALL_KEY = \"callRendererFunction\";\n\nconst OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isWhitespace(ch: string | undefined) {\n return ch === \" \" || ch === \"\\n\" || ch === \"\\r\" || ch === \"\\t\";\n}\n\nfunction skipWhitespace(s: string, i: number) {\n while (i < s.length && isWhitespace(s[i])) i++;\n return i;\n}\n\n/** Index of the closing quote of the JSON string opening at `start`, or -1. */\nfunction findStringEnd(s: string, start: number) {\n for (let i = start + 1; i < s.length; i++) {\n if (s[i] === \"\\\\\") {\n i++;\n continue;\n }\n if (s[i] === '\"') return i;\n }\n return -1;\n}\n\n/**\n * Find the first `\"key\":` whose value starts with `opener` and return the index\n * of that opener, or -1.\n */\nfunction findKeyValue(s: string, key: string, opener: string) {\n const needle = `\"${key}\"`;\n let from = 0;\n while (true) {\n const k = s.indexOf(needle, from);\n if (k < 0) return -1;\n let i = skipWhitespace(s, k + needle.length);\n if (s[i] === \":\") {\n i = skipWhitespace(s, i + 1);\n if (s[i] === opener) return i;\n }\n from = k + 1;\n }\n}\n\n/**\n * Read `\"key\":\"value\"` from partial JSON. The first match anywhere in the\n * text wins, at any depth.\n *\n * @param partialJson - JSON text that can still be streaming.\n * @param key - The field name.\n * @returns The string value, or null until its closing quote has arrived.\n *\n * @example\n * ```ts\n * extractStringField('{\"createSurface\":{\"surfaceId\":\"plan\",\"cat', \"surfaceId\"); // \"plan\"\n * ```\n */\nexport function extractStringField(partialJson: string, key: string) {\n const start = findKeyValue(partialJson, key, '\"');\n if (start < 0) return null;\n const end = findStringEnd(partialJson, start);\n if (end < 0) return null;\n try {\n const value: unknown = JSON.parse(partialJson.slice(start, end + 1));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n}\n\nfunction pushItem(raw: string, items: unknown[]) {\n const trimmed = raw.trim();\n if (!trimmed) return;\n try {\n items.push(JSON.parse(trimmed));\n } catch {\n // Incomplete primitive; ignore until it completes.\n }\n}\n\n/**\n * Find `\"key\":[` in partial JSON and return every complete item of that array\n * so far, plus whether the array has closed. Items of a `components` array get\n * structural-key depth repair: a component that lost closing braces is fixed\n * when its `id`, `component`, `child` or `children` key shows where it ends.\n *\n * @param partialJson - JSON text that can still be streaming.\n * @param key - The name of the array field.\n * @returns `{ items, closed }`, or null when the key (with an array value)\n * has not appeared yet.\n *\n * @example\n * ```ts\n * const result = extractCompleteArrayItems(streamedText, \"components\");\n * if (result) render(result.items);\n * ```\n */\nexport function extractCompleteArrayItems(partialJson: string, key: string) {\n const open = findKeyValue(partialJson, key, \"[\");\n if (open < 0) return null;\n return completeArrayItemsAt(partialJson, open, {\n repairComponents: key === \"components\",\n });\n}\n\n/** Index of the last non-whitespace character before `i`, or -1. */\nfunction prevNonWhitespace(s: string, i: number) {\n let j = i - 1;\n while (j >= 0 && isWhitespace(s[j])) j--;\n return j;\n}\n\n/**\n * Keys that only ever belong at a component's top level. Seen nested inside\n * the component's objects, they mean the model forgot closing braces.\n */\nconst STRUCTURAL_KEYS = new Set([\"id\", \"component\", \"child\", \"children\"]);\n\n/** Whether a value starting with `ch` has the shape `key` takes on a component. */\nfunction structuralValueFits(key: string, ch: string | undefined) {\n if (key === \"children\") return ch === \"[\" || ch === \"{\";\n return ch === '\"';\n}\n\n/** `{\"id\":` — a new component object starting at `i`. */\nconst COMPONENT_START = /^\\{\\s*\"id\"\\s*:/;\n\n/**\n * Structural-key depth repair for one component item. While scanning, a\n * structural key (`id`, `component`, `child`, `children`) found as an object\n * key below the item's top level, with only objects (no arrays) between it\n * and the item root, a value of the expected shape, and not already present\n * at the top level, means closing braces were dropped: the missing `}` are\n * synthesized right before it so it lands at the top level. Containers still\n * open at the end are closed. Returns null when a string never terminates.\n */\nfunction repairComponentItem(item: string) {\n const stack: string[] = [];\n const topKeys = new Set<string>();\n let out = \"\";\n let copied = 0;\n for (let i = 0; i < item.length; i++) {\n const c = item[i];\n if (c === '\"') {\n const end = findStringEnd(item, i);\n if (end < 0) return null;\n const prev = prevNonWhitespace(item, i);\n const prevCh = item[prev];\n const colon = skipWhitespace(item, end + 1);\n const isKey =\n stack[stack.length - 1] === \"{\" &&\n (prevCh === \",\" || prevCh === \"{\") &&\n item[colon] === \":\";\n if (isKey) {\n let key: unknown;\n try {\n key = JSON.parse(item.slice(i, end + 1));\n } catch {\n return null;\n }\n if (typeof key === \"string\") {\n if (stack.length === 1) {\n topKeys.add(key);\n } else if (\n STRUCTURAL_KEYS.has(key) &&\n !topKeys.has(key) &&\n stack.every((x) => x === \"{\") &&\n structuralValueFits(key, item[skipWhitespace(item, colon + 1)])\n ) {\n const closers = \"}\".repeat(stack.length - 1);\n if (prevCh === \",\") {\n out += item.slice(copied, prev) + closers;\n copied = prev;\n } else {\n // `\"x\":{\"children\":…` — close the empty object, then a comma.\n out += item.slice(copied, i) + closers + \",\";\n copied = i;\n }\n stack.length = 1;\n topKeys.add(key);\n }\n }\n }\n i = end;\n continue;\n }\n if (c === \"{\" || c === \"[\") {\n stack.push(c);\n } else if (c === \"}\" || c === \"]\") {\n stack.pop();\n if (stack.length === 0) return out + item.slice(copied, i + 1);\n }\n }\n // Close the open brackets, innermost first.\n const closers = stack.reduceRight(\n (text, opener) => text + (opener === \"{\" ? \"}\" : \"]\"),\n \"\",\n );\n return out + item.slice(copied) + closers;\n}\n\nfunction parseRecord(text: string | null) {\n if (text === null) return undefined;\n try {\n const value: unknown = JSON.parse(text);\n return isRecord(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Complete items of the (possibly unterminated) array whose \"[\" is at `open`.\n * With `repairComponents`, an item that balanced but does not parse is retried\n * with structural-key repair, and a `,{\"id\":` where an item expects a key\n * ends that (unbalanced) item there, so one malformed component cannot\n * swallow the rest of the array; the cut item is kept only if repair makes\n * it parse.\n */\nfunction completeArrayItemsAt(\n partialJson: string,\n open: number,\n options: { repairComponents: boolean },\n) {\n const { repairComponents } = options;\n const s = partialJson;\n const items: unknown[] = [];\n const stack: string[] = [];\n let inString = false;\n let itemStart = -1;\n\n const finishItem = (end: number, balanced: boolean) => {\n const raw = s.slice(itemStart, end);\n if (!repairComponents) {\n pushItem(raw, items);\n return;\n }\n if (balanced) {\n try {\n items.push(JSON.parse(raw));\n return;\n } catch {\n // Fall through to repair.\n }\n }\n const repaired = parseRecord(repairComponentItem(raw.trim()));\n if (repaired !== undefined) items.push(repaired);\n };\n\n for (let i = open + 1; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n continue;\n }\n if (c === '\"') {\n inString = true;\n if (stack.length === 0 && itemStart < 0) itemStart = i;\n continue;\n }\n if (c === \"{\" || c === \"[\") {\n if (\n repairComponents &&\n c === \"{\" &&\n stack[stack.length - 1] === \"{\" &&\n COMPONENT_START.test(s.slice(i, i + 24))\n ) {\n const prev = prevNonWhitespace(s, i);\n if (s[prev] === \",\") {\n // A new component where a key was expected: the current item\n // is missing closers. End it before the comma and start anew.\n finishItem(prev, false);\n stack.length = 0;\n itemStart = i;\n stack.push(c);\n continue;\n }\n }\n if (stack.length === 0) itemStart = i;\n stack.push(c);\n continue;\n }\n if (c === \"}\" || c === \"]\") {\n if (stack.length === 0) {\n // Closing bracket of the items array itself (or malformed input).\n if (c === \"]\") {\n if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);\n return { items, closed: true };\n }\n return { items, closed: false };\n }\n stack.pop();\n if (stack.length === 0) {\n finishItem(i + 1, true);\n itemStart = -1;\n }\n continue;\n }\n if (stack.length === 0) {\n if (c === \",\") {\n if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);\n itemStart = -1;\n } else if (itemStart < 0 && !isWhitespace(c)) {\n itemStart = i; // start of a primitive item\n }\n }\n }\n return { items, closed: false };\n}\n\n/** The first operation key whose value is an object, with that value. */\nfunction getOperationEntry(op: A2UIMarkdownOperation) {\n for (const key of OP_KEYS) {\n const inner = op[key];\n if (isRecord(inner)) return { key, inner };\n }\n return null;\n}\n\n/**\n * The surfaceId an operation targets: the one nested under its operation key,\n * else a top-level `surfaceId`. A `callRendererFunction` operation targets no\n * surface, so it gets undefined.\n *\n * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`\n * already exports a strict `getOperationSurfaceId`. This one also reads a\n * top-level `surfaceId`, which models sometimes write.\n *\n * @param op - An operation from an a2ui fence.\n * @returns The surfaceId, or undefined when the operation names none or is a\n * function call.\n *\n * @example\n * ```ts\n * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: \"plan\" } }); // \"plan\"\n * ```\n */\nexport function getMarkdownOperationSurfaceId(op: A2UIMarkdownOperation) {\n if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return undefined;\n for (const key of SURFACE_OP_KEYS) {\n const inner = op[key];\n if (isRecord(inner) && typeof inner.surfaceId === \"string\") {\n return inner.surfaceId;\n }\n }\n return typeof op.surfaceId === \"string\" ? op.surfaceId : undefined;\n}\n\n/**\n * Index just past the JSON value starting at `start`, or -1 when the value is\n * still incomplete. A primitive at the very end of the input counts as\n * incomplete, since more digits or letters may still stream in.\n */\nfunction findValueEnd(s: string, start: number) {\n const c = s[start];\n if (c === '\"') {\n const end = findStringEnd(s, start);\n return end < 0 ? -1 : end + 1;\n }\n if (c === \"{\" || c === \"[\") {\n let depth = 0;\n for (let i = start; i < s.length; i++) {\n const ch = s[i];\n if (ch === '\"') {\n const end = findStringEnd(s, i);\n if (end < 0) return -1;\n i = end;\n } else if (ch === \"{\" || ch === \"[\") {\n depth++;\n } else if (ch === \"}\" || ch === \"]\") {\n depth--;\n if (depth === 0) return i + 1;\n }\n }\n return -1;\n }\n let i = start;\n while (i < s.length && !isWhitespace(s[i]) && !\",}]\".includes(s[i]!)) i++;\n return i >= s.length ? -1 : i;\n}\n\n/**\n * Walk the direct entries of the (possibly unterminated) JSON object whose \"{\"\n * is at `objStart`, calling `visit` with each key and the index where its value\n * starts. Nested objects and arrays are skipped whole, so keys inside them are\n * never visited. Stops when `visit` returns true, at the object's end, or where\n * the input runs out.\n */\nfunction visitDirectEntries(\n s: string,\n objStart: number,\n visit: (key: string, valueStart: number) => boolean,\n) {\n let i = objStart + 1;\n while (i < s.length) {\n i = skipWhitespace(s, i);\n const c = s[i];\n if (c === \",\") {\n i++;\n continue;\n }\n if (c !== '\"') return; // \"}\" (object closed), end of input, or malformed\n const keyEnd = findStringEnd(s, i);\n if (keyEnd < 0) return;\n let key: unknown;\n try {\n key = JSON.parse(s.slice(i, keyEnd + 1));\n } catch {\n return;\n }\n i = skipWhitespace(s, keyEnd + 1);\n if (s[i] !== \":\") return;\n i = skipWhitespace(s, i + 1);\n if (i >= s.length) return;\n if (typeof key === \"string\" && visit(key, i)) return;\n const valueEnd = findValueEnd(s, i);\n if (valueEnd < 0) return;\n i = valueEnd;\n }\n}\n\n/**\n * Value start of a direct `key` of the object at `objStart` whose value begins\n * with `opener` (any value when omitted), or -1.\n */\nfunction findDirectKeyValue(\n s: string,\n objStart: number,\n key: string,\n opener?: string,\n) {\n let found = -1;\n visitDirectEntries(s, objStart, (k, valueStart) => {\n if (k !== key) return false;\n if (opener === undefined || s[valueStart] === opener) found = valueStart;\n return true;\n });\n return found;\n}\n\n/** A direct string field of the object at `objStart`, once its closing quote has arrived. */\nfunction readDirectString(s: string, objStart: number, key: string) {\n if (objStart < 0) return null;\n const start = findDirectKeyValue(s, objStart, key, '\"');\n if (start < 0) return null;\n const end = findValueEnd(s, start);\n if (end < 0) return null;\n try {\n const value: unknown = JSON.parse(s.slice(start, end));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n}\n\n/** A direct object field of the object at `objStart`, once the whole object has arrived. */\nfunction readDirectRecord(s: string, objStart: number, key: string) {\n const start = findDirectKeyValue(s, objStart, key, \"{\");\n if (start < 0) return undefined;\n const end = findValueEnd(s, start);\n if (end < 0) return undefined;\n return parseRecord(s.slice(start, end));\n}\n\n/**\n * The complete part of a (possibly unterminated) JSON value: the parsed value\n * when it is complete; for an open object, its complete entries plus the\n * complete items of any streaming array entry; otherwise undefined.\n */\nfunction completePartOfValue(s: string, start: number) {\n const end = findValueEnd(s, start);\n if (end >= 0) {\n try {\n const value: unknown = JSON.parse(s.slice(start, end));\n return value;\n } catch {\n return undefined;\n }\n }\n if (s[start] !== \"{\") return undefined;\n const out: Record<string, unknown> = {};\n visitDirectEntries(s, start, (key, valueStart) => {\n const valueEnd = findValueEnd(s, valueStart);\n if (valueEnd >= 0) {\n try {\n out[key] = JSON.parse(s.slice(valueStart, valueEnd));\n } catch {\n // Malformed entry; leave it out.\n }\n } else if (s[valueStart] === \"[\") {\n const { items } = completeArrayItemsAt(s, valueStart, {\n repairComponents: false,\n });\n if (items.length > 0) out[key] = items;\n }\n return false;\n });\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Best-effort operation from an unfinished or malformed top-level object.\n * Fields are read only from the operation's own keys (`version` at the top\n * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside\n * the operation object), never from component props or data-model values that\n * happen to share a name.\n *\n * A `createSurface` keeps its complete components and a `dataModel` that has\n * fully arrived, so a surface created in one line renders while it streams.\n * A `callRendererFunction` gives nothing: a function must not run with half\n * of its args.\n */\nfunction partialOperation(line: string) {\n const root = skipWhitespace(line, 0);\n if (line[root] !== \"{\") return null;\n const version = readDirectString(line, root, \"version\") ?? A2UI_VERSION;\n\n const components = findDirectKeyValue(line, root, \"updateComponents\", \"{\");\n if (components >= 0) {\n const arrayStart = findDirectKeyValue(line, components, \"components\", \"[\");\n if (arrayStart < 0) return null;\n const { items } = completeArrayItemsAt(line, arrayStart, {\n repairComponents: true,\n });\n if (items.length === 0) return null;\n const surfaceId = readDirectString(line, components, \"surfaceId\");\n return {\n version,\n updateComponents: {\n ...(surfaceId ? { surfaceId } : {}),\n components: items,\n },\n };\n }\n\n const data = findDirectKeyValue(line, root, \"updateDataModel\", \"{\");\n if (data >= 0) {\n const valueStart = findDirectKeyValue(line, data, \"value\");\n if (valueStart < 0) return null;\n const value = completePartOfValue(line, valueStart);\n if (value === undefined) return null;\n const surfaceId = readDirectString(line, data, \"surfaceId\");\n const path = readDirectString(line, data, \"path\");\n return {\n version,\n updateDataModel: {\n ...(surfaceId ? { surfaceId } : {}),\n ...(path ? { path } : {}),\n value,\n },\n };\n }\n\n const create = findDirectKeyValue(line, root, \"createSurface\", \"{\");\n if (create >= 0) {\n const surfaceId = readDirectString(line, create, \"surfaceId\");\n if (!surfaceId) return null;\n const catalogId = readDirectString(line, create, \"catalogId\");\n const dataModel = readDirectRecord(line, create, \"dataModel\");\n const componentsStart = findDirectKeyValue(line, create, \"components\", \"[\");\n const components =\n componentsStart < 0\n ? []\n : completeArrayItemsAt(line, componentsStart, {\n repairComponents: true,\n }).items;\n return {\n version,\n createSurface: {\n surfaceId,\n ...(catalogId ? { catalogId } : {}),\n ...(dataModel ? { dataModel } : {}),\n ...(components.length > 0 ? { components } : {}),\n },\n };\n }\n return null;\n}\n\n/**\n * A line that opens a new top-level operation: `{\"version\":\"1…` or\n * `{\"<operation>\":{`. Seen at the start of a line while an earlier object is\n * still unbalanced, it means that object is malformed and has ended.\n */\nconst OPERATION_START = new RegExp(\n `^\\\\{\\\\s*\"(?:version\"\\\\s*:\\\\s*\"\\\\d|(?:${OP_KEYS.join(\"|\")})\"\\\\s*:\\\\s*\\\\{)`,\n);\n\n/**\n * Scan the top-level object whose \"{\" is at `start`. Returns the index just\n * past it and whether it balanced. An unbalanced object ends early (at the\n * start of the line) when a line opens a new operation; otherwise it runs to\n * the end of the input. JSON strings cannot contain raw newlines, so a newline\n * inside a string ends it: a stray quote then breaks one line, not the rest of\n * the fence.\n */\nfunction scanTopLevelObject(s: string, start: number) {\n let depth = 0;\n let inString = false;\n for (let i = start; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (c === \"\\\\\" && s[i + 1] !== \"\\n\") i++;\n else if (c === '\"' || c === \"\\n\") inString = false;\n if (c !== \"\\n\") continue;\n }\n if (c === \"\\n\") {\n const next = skipWhitespace(s, i + 1);\n if (OPERATION_START.test(s.slice(next, next + 40))) {\n return { end: i + 1, balanced: false };\n }\n continue;\n }\n if (c === '\"') inString = true;\n else if (c === \"{\" || c === \"[\") depth++;\n else if (c === \"}\" || c === \"]\") {\n depth--;\n if (depth === 0) return { end: i + 1, balanced: true };\n }\n }\n return { end: s.length, balanced: false };\n}\n\nconst OPERATION_NAMES = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n \"callRendererFunction\",\n];\n\n/** Whether a value is shaped like one A2UI operation, with named components. */\nfunction isOperationShape(value: unknown): boolean {\n if (!isRecord(value) || value.version !== A2UI_VERSION) return false;\n const names = OPERATION_NAMES.filter((name) => name in value);\n if (names.length !== 1 || Object.keys(value).length !== 2) return false;\n const body = value[names[0]!];\n if (!isRecord(body)) return false;\n if (names[0] === \"callRendererFunction\") return true;\n if (typeof body.surfaceId !== \"string\") return false;\n const components = body.components;\n return (\n components === undefined ||\n (Array.isArray(components) &&\n components.every(\n (c) =>\n isRecord(c) &&\n typeof c.id === \"string\" &&\n typeof c.component === \"string\",\n ))\n );\n}\n\n/** Openers minus closers ({ and [ against } and ]) outside strings. */\nfunction closerImbalance(line: string) {\n let depth = 0;\n let inString = false;\n for (let i = 0; i < line.length; i++) {\n const c = line[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n } else if (c === '\"') inString = true;\n else if (c === \"{\" || c === \"[\") depth++;\n else if (c === \"}\" || c === \"]\") depth--;\n }\n return depth;\n}\n\n/** The text with closers and whitespace removed, to compare a repair. */\nfunction withoutClosers(text: string) {\n return text.replace(/[\\]}\\s]/g, \"\");\n}\n\n/**\n * Whether a component of the operation holds a structural key (`id`,\n * `component`, `child`, `children`) in a nested object: a closer added at\n * the end instead of where it was dropped. The scan below repairs those.\n */\nfunction nestsStructuralKey(value: unknown) {\n const nests = (v: unknown): boolean =>\n isRecord(v) &&\n Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));\n const body = isRecord(value)\n ? Object.values(value).find(isRecord)\n : undefined;\n const components = body?.components;\n return (\n Array.isArray(components) &&\n components.some(\n (c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)),\n )\n );\n}\n\n/**\n * Repairs the complete lines of a fence that are not valid JSON (a missing\n * or extra brace) with jsonrepair, when the repair only adds or removes\n * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.\n */\nfunction repairFenceLines(fenceText: string) {\n const repaired: string[] = [];\n const lines = fenceText.split(\"\\n\");\n // A top-level array spreads its closers over lines: nothing to repair.\n if (fenceText.trimStart().startsWith(\"[\"))\n return { text: fenceText, repaired };\n for (let n = 0; n < lines.length - 1; n++) {\n const line = lines[n]!;\n if (!line.trim().startsWith(\"{\")) continue;\n try {\n JSON.parse(line);\n continue;\n } catch {\n // Not valid JSON: try a repair.\n }\n // Only a slip of one closer: the first line of a pretty-printed\n // operation is off by more and must stay for the scan below.\n const imbalance = closerImbalance(line);\n if (Math.abs(imbalance) !== 1) continue;\n // A line that misses a closer and is followed by more than a new\n // operation is the start of an object over several lines.\n const next = lines.slice(n + 1).find((l) => l.trim() !== \"\");\n if (imbalance > 0 && next !== undefined && !next.trim().startsWith(\"{\")) {\n continue;\n }\n try {\n const fixed = jsonrepair(line);\n const value: unknown = JSON.parse(fixed);\n if (\n withoutClosers(fixed) === withoutClosers(line) &&\n isOperationShape(value) &&\n !nestsStructuralKey(value) &&\n // A call must not run with args that a closer moved.\n !(isRecord(value) && \"callRendererFunction\" in value)\n ) {\n repaired.push(line.trim());\n lines[n] = JSON.stringify(value);\n }\n } catch {\n // Leave it: the scan below drops or salvages it as before.\n }\n }\n return { text: lines.join(\"\\n\"), repaired };\n}\n\n/**\n * Parse the body of an a2ui fence as a stream of top-level JSON values, so\n * operations may be one per line (the documented format), several per line,\n * pretty-printed over many lines, or wrapped in a top-level array (which is\n * flattened). Whitespace and commas between objects are ignored.\n *\n * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),\n * its raw text goes to `invalidLines` and whatever `partialOperation` can\n * salvage (complete components, data-model entries, createSurface fields)\n * is kept.\n * - An unbalanced object followed by a line that opens a new operation is\n * treated the same way.\n * - The trailing unbalanced object (still streaming, or never closed) is\n * `partialObject` and yields a partial operation when it has usable data.\n * - Other text between objects is skipped and reported in `recovered` (and in\n * `invalidLines`, which predates it).\n *\n * `partialLine` is a deprecated alias of `partialObject`.\n *\n * @param fenceText - The body of an a2ui fence (`text` of an a2ui\n * `MarkdownSegment`), complete or still streaming.\n * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.\n *\n * @example\n * ```ts\n * const { operations } = extractFenceOperations(segment.text);\n * ```\n */\nexport function extractFenceOperations(fenceText: string) {\n const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);\n const operations: A2UIMarkdownOperation[] = [];\n const invalidLines: string[] = [];\n const recovered: string[] = [];\n let partialObject: string | null = null;\n\n const salvage = (raw: string) => {\n invalidLines.push(raw.trim());\n const partial = partialOperation(raw);\n if (partial) operations.push(partial);\n };\n\n let junkStart = -1;\n const flushJunk = (end: number) => {\n if (junkStart < 0) return;\n const junk = s.slice(junkStart, end).trim();\n junkStart = -1;\n if (!junk) return;\n recovered.push(junk);\n invalidLines.push(junk);\n };\n\n let i = 0;\n while (i < s.length) {\n const c = s[i]!;\n if (c === \"{\") {\n flushJunk(i);\n const { end, balanced } = scanTopLevelObject(s, i);\n const raw = s.slice(i, end);\n if (balanced) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n parsed = undefined;\n }\n if (isRecord(parsed)) operations.push(parsed);\n else salvage(raw);\n } else if (end < s.length) {\n salvage(raw);\n } else {\n partialObject = raw;\n const partial = partialOperation(raw);\n if (partial) operations.push(partial);\n }\n i = end;\n continue;\n }\n if (c === \"\\n\" || c === \"[\" || c === \"]\") {\n // A top-level array of operations is flattened by skipping its brackets.\n flushJunk(i);\n } else if (junkStart < 0 && !isWhitespace(c) && c !== \",\") {\n junkStart = i;\n }\n i++;\n }\n flushJunk(s.length);\n\n return {\n operations,\n partialObject,\n partialLine: partialObject,\n invalidLines,\n recovered,\n /** Complete lines that were off by one closing brace and were repaired. */\n repairedLines,\n };\n}\n\n/**\n * Normalise a fence's operations for the renderer: drop unknown messages, fill\n * in `version` and missing `surfaceId`s, keep only the first `createSurface`,\n * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize\n * `createSurface` when the model omitted it, and report the\n * surfaceId (the first one found, else `fallbackSurfaceId`).\n *\n * `callRendererFunction` operations target no surface. They get no surfaceId,\n * do not cause a synthesized `createSurface`, and come back in\n * `functionCalls` (in fence order), never in `operations`.\n *\n * @param input.operations - Operations from `extractFenceOperations`.\n * @param input.fallbackSurfaceId - The surfaceId to use when no operation\n * names one.\n * @param input.catalogId - The client catalog. It replaces a catalogId of the\n * model that `catalogIds` does not list.\n * @param input.catalogIds - The catalogs that the model can name. Left out,\n * only `catalogId`.\n * @returns `{ surfaceId, operations, functionCalls }`.\n *\n * @example\n * ```ts\n * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({\n * operations: extractFenceOperations(segment.text).operations,\n * fallbackSurfaceId: `${messageId}-${segment.index}`,\n * catalogId,\n * });\n * ```\n */\nexport function prepareSurfaceOperations(input: {\n operations: A2UIMarkdownOperation[];\n fallbackSurfaceId: string;\n catalogId: string;\n catalogIds?: readonly string[];\n}) {\n const { operations, fallbackSurfaceId, catalogId } = input;\n const catalogIds = input.catalogIds ?? [catalogId];\n const surfaceId =\n operations\n .map(getMarkdownOperationSurfaceId)\n .find((id): id is string => !!id) ?? fallbackSurfaceId;\n\n const out: A2UIMarkdownOperation[] = [];\n const functionCalls: A2UIMarkdownOperation[] = [];\n let hasCreate = false;\n for (const op of operations) {\n const entry = getOperationEntry(op);\n if (!entry) continue;\n const { key } = entry;\n const inner = { ...entry.inner };\n const version = typeof op.version === \"string\" ? op.version : A2UI_VERSION;\n if (key === FUNCTION_CALL_KEY) {\n functionCalls.push({ version, [key]: inner });\n continue;\n }\n if (typeof inner.surfaceId !== \"string\") inner.surfaceId = surfaceId;\n if (key === \"createSurface\") {\n // A surface is created once; a repeated createSurface (e.g. a later\n // reply that rebuilds a page target) would throw \"Surface already\n // exists\". Its data model and components become updates instead, so\n // the new UI is not lost.\n if (hasCreate) {\n const { surfaceId: id, dataModel, components } = inner;\n if (dataModel !== undefined) {\n out.push({\n version,\n updateDataModel: { surfaceId: id, path: \"/\", value: dataModel },\n });\n }\n if (Array.isArray(components) && components.length > 0) {\n out.push({\n version,\n updateComponents: { surfaceId: id, components },\n });\n }\n continue;\n }\n hasCreate = true;\n // The catalog is client-owned: a catalog that the client does not\n // list is replaced.\n if (!catalogIds.includes(inner.catalogId as string)) {\n inner.catalogId = catalogId;\n }\n }\n out.push({ version, [key]: inner });\n }\n\n if (!hasCreate && out.length > 0) {\n out.unshift({\n version: A2UI_VERSION,\n createSurface: { surfaceId, catalogId },\n });\n }\n return { surfaceId, operations: out, functionCalls };\n}\n\n/**\n * Components a user operates. A Card containing one of these is an\n * interactive panel and keeps its box; every other Card is informational.\n */\nconst INTERACTIVE_COMPONENTS = new Set([\n \"Button\",\n \"Pressable\",\n \"Form\",\n \"TextField\",\n \"TextArea\",\n \"Select\",\n \"CheckBox\",\n \"Radio\",\n \"RadioGroup\",\n \"Slider\",\n \"SegmentedControl\",\n \"ChoicePicker\",\n \"DateTimeInput\",\n]);\n\n/** A component id referenced by a `child`/`children` entry or a table cell. */\nfunction referencedId(value: unknown) {\n if (typeof value === \"string\") return value;\n if (isRecord(value)) {\n if (typeof value.componentId === \"string\") return value.componentId;\n if (typeof value.id === \"string\") return value.id;\n }\n return undefined;\n}\n\n/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */\nfunction cellComponentId(value: unknown) {\n return isRecord(value) ? referencedId(value) : undefined;\n}\n\n/**\n * More ids a component renders, beyond `child`, `children` and the table\n * cells: the typed child references of its catalog, which can sit at any\n * depth of its props (the `child` of each entry of `tabs`). The catalog\n * knows them; the operations alone do not.\n */\nexport type ChildIdsOf = (\n component: Record<string, unknown>,\n) => string[] | \"unknown\";\n\n/** The options of the walks that follow child ids. */\nexport interface ChildWalkOptions {\n childIds?: ChildIdsOf;\n}\n\n/**\n * Ids a component renders directly: `child`, `children` (string ids, an\n * array, or a `{componentId}` template), component cells of a Table's\n * `rows`/`columns`, and the ids that `extra` finds in its typed references.\n */\nfunction directChildIds(\n component: Record<string, unknown>,\n extra?: ChildIdsOf,\n) {\n const ids: string[] = [];\n const add = (id: string | undefined) => {\n if (id) ids.push(id);\n };\n const extraIds = extra?.(component);\n if (Array.isArray(extraIds)) extraIds.forEach(add);\n add(referencedId(component.child));\n const children = component.children;\n if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));\n else add(referencedId(children));\n if (Array.isArray(component.columns)) {\n component.columns.forEach((c) => add(cellComponentId(c)));\n }\n if (Array.isArray(component.rows)) {\n for (const row of component.rows) {\n if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));\n }\n }\n return ids;\n}\n\n/** Components of every updateComponents operation, by id (last definition wins). */\nfunction componentsById(operations: A2UIMarkdownOperation[]) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const op of operations) {\n const update = op.updateComponents;\n const list = isRecord(update) ? update.components : undefined;\n if (!Array.isArray(list)) continue;\n for (const c of list) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n }\n return byId;\n}\n\nfunction descendantIds(\n rootId: string,\n byId: Map<string, Record<string, unknown>>,\n extra?: ChildIdsOf,\n) {\n const seen = new Set<string>();\n const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];\n while (stack.length > 0) {\n const id = stack.pop()!;\n if (seen.has(id) || id === rootId) continue;\n seen.add(id);\n const c = byId.get(id);\n if (c) stack.push(...directChildIds(c, extra));\n }\n return seen;\n}\n\n/**\n * Ids of the `Card` components that are interactive panels: at least one\n * descendant (via `child`, `children` or table component cells) is a control\n * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,\n * RadioGroup, Slider, SegmentedControl, DateTimeInput).\n *\n * @param components - The components of one surface.\n * @returns The ids of the interactive cards.\n *\n * @example\n * ```ts\n * const interactive = classifySurfaceCards(components);\n * const keepsBox = interactive.has(\"quote-form\");\n * ```\n */\nexport function classifySurfaceCards(\n components: Record<string, unknown>[],\n options: ChildWalkOptions = {},\n) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const c of components) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n const interactive = new Set<string>();\n for (const [id, c] of byId) {\n if (c.component !== \"Card\") continue;\n for (const d of descendantIds(id, byId, options.childIds)) {\n const type = byId.get(d)?.component;\n if (typeof type === \"string\" && INTERACTIVE_COMPONENTS.has(type)) {\n interactive.add(id);\n break;\n }\n }\n }\n return interactive;\n}\n\n/**\n * Markdown mode: only interactive panels keep a box. Every `Card` that is not\n * an interactive panel (see `classifySurfaceCards`), sets no `variant` or\n * `border` of its own and is not nested inside an interactive panel becomes\n * `variant: \"section\"` (a heading plus content without a box). Operations\n * other than updateComponents pass through unchanged.\n *\n * @param operations - The operations of one surface.\n * @returns The operations with informational cards set to `variant: \"section\"`.\n * When no card changes, it returns the same array.\n *\n * @example\n * ```ts\n * const operations = flattenInformationalCards(prepared.operations);\n * ```\n */\nexport function flattenInformationalCards(\n operations: A2UIMarkdownOperation[],\n options: ChildWalkOptions = {},\n) {\n const byId = componentsById(operations);\n if (![...byId.values()].some((c) => c.component === \"Card\")) {\n return operations;\n }\n const interactive = classifySurfaceCards([...byId.values()], options);\n const insideInteractive = new Set<string>();\n for (const id of interactive) {\n for (const d of descendantIds(id, byId, options.childIds)) {\n insideInteractive.add(d);\n }\n }\n const flatten = (c: Record<string, unknown>) =>\n c.component === \"Card\" &&\n typeof c.id === \"string\" &&\n !interactive.has(c.id) &&\n !insideInteractive.has(c.id) &&\n c.variant == null &&\n c.border == null;\n\n const flattened: A2UIMarkdownOperation[] = operations.map((op) => {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) return op;\n if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;\n return {\n ...op,\n updateComponents: {\n ...update,\n components: update.components.map((c) =>\n isRecord(c) && flatten(c) ? { ...c, variant: \"section\" } : c,\n ),\n },\n };\n });\n return flattened;\n}\n\n/** Text-bearing components that belong in the chat's markdown, not a surface. */\nconst PROSE_TEXT_COMPONENTS = new Set([\"Title\", \"Text\", \"Caption\", \"Markdown\"]);\n\n/** A component that converts to markdown: text-bearing prose, or a separator next to it. */\ntype ProseItem =\n | { kind: \"text\"; markdown: string }\n | { kind: \"divider\" | \"spacer\" };\n\n/** One line of text: list items and headings cannot span lines in markdown. */\nfunction oneLine(text: string) {\n return text.trim().replace(/\\s*\\n\\s*/g, \" \");\n}\n\n/**\n * A literal List entry as list-item markdown: a non-empty string, or\n * `{ label, description? }` with literal strings only. Anything carrying\n * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.\n */\nfunction listEntryMarkdown(entry: unknown) {\n if (typeof entry === \"string\") return entry.trim() ? oneLine(entry) : null;\n if (!isRecord(entry)) return null;\n for (const key of Object.keys(entry)) {\n if (key !== \"label\" && key !== \"description\") return null;\n }\n if (typeof entry.label !== \"string\" || !entry.label.trim()) return null;\n const label = oneLine(entry.label);\n if (entry.description === undefined) return label;\n if (typeof entry.description !== \"string\") return null;\n return entry.description.trim()\n ? `**${label}** — ${oneLine(entry.description)}`\n : label;\n}\n\n/**\n * A List of literal text items as a markdown list (`marker: \"number\"` →\n * `1. …`, otherwise `- …`), or null when it binds its items, renders\n * `children`, or any item is not plain text.\n */\nfunction listToMarkdown(c: Record<string, unknown>) {\n const children = c.children;\n if (children != null && !(Array.isArray(children) && children.length === 0)) {\n return null;\n }\n if (!Array.isArray(c.items) || c.items.length === 0) return null;\n const lines: string[] = [];\n for (const entry of c.items) {\n const line = listEntryMarkdown(entry);\n if (line === null) return null;\n lines.push(line);\n }\n if (c.marker === \"number\") {\n const start =\n typeof c.start === \"number\" && Number.isInteger(c.start) ? c.start : 1;\n return lines.map((line, i) => `${start + i}. ${line}`).join(\"\\n\");\n }\n return lines.map((line) => `- ${line}`).join(\"\\n\");\n}\n\n/** The prose item a component converts to, or null when it is not prose. */\nfunction toProseItem(c: Record<string, unknown> | undefined) {\n if (!c) return null;\n // A component with an accessibility envelope stays a component: markdown\n // has no place for its label, its live region or its hidden state.\n if (c.accessibility !== undefined) return null;\n if (c.component === \"Divider\") return { kind: \"divider\" as const };\n if (c.component === \"Spacer\") return { kind: \"spacer\" as const };\n if (c.component === \"List\") {\n // A horizontal list is a layout, not a text list; a bound direction\n // may be horizontal at render time.\n if (c.direction !== undefined && c.direction !== \"vertical\") return null;\n const markdown = listToMarkdown(c);\n return markdown === null ? null : { kind: \"text\" as const, markdown };\n }\n if (typeof c.component !== \"string\") return null;\n if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;\n // Only literal strings are prose; `{path}`-bound text is data.\n if (typeof c.text !== \"string\" || c.text.trim() === \"\") return null;\n const text = c.text.trim();\n switch (c.component) {\n case \"Title\": {\n const size = typeof c.size === \"string\" ? c.size : \"md\";\n const level =\n size === \"sm\" ? \"####\" : size === \"md\" || size === \"lg\" ? \"###\" : \"##\";\n return { kind: \"text\" as const, markdown: `${level} ${text}` };\n }\n case \"Text\":\n // Inline children (e.g. a Badge) have no markdown form.\n if (directChildIds(c).length > 0) return null;\n return {\n kind: \"text\" as const,\n markdown: c.strong === true ? `**${text}**` : text,\n };\n default:\n return { kind: \"text\" as const, markdown: text };\n }\n}\n\n/** Prose items as markdown: separators only survive between two text items. */\nfunction proseItemsToMarkdown(items: (ProseItem | null)[]) {\n const blocks: string[] = [];\n let pendingDivider = false;\n for (const item of items) {\n if (item?.kind === \"text\") {\n if (pendingDivider && blocks.length > 0) blocks.push(\"---\");\n pendingDivider = false;\n blocks.push(item.markdown);\n } else if (item?.kind === \"divider\") {\n pendingDivider = true;\n }\n }\n return blocks.join(\"\\n\\n\");\n}\n\n/** Column, column-direction Box, or an informational Card (section/unset variant). */\nfunction isVerticalStack(\n c: Record<string, unknown>,\n interactiveCards: Set<string>,\n) {\n // A container with an accessibility envelope keeps its children: lifted\n // text would lose its hidden state or its live region.\n if (c.accessibility !== undefined) return false;\n if (c.component === \"Column\") return true;\n if (c.component === \"Box\") {\n return c.direction == null || c.direction === \"col\";\n }\n if (c.component === \"Card\") {\n return (\n (c.variant == null || c.variant === \"section\") &&\n typeof c.id === \"string\" &&\n !interactiveCards.has(c.id)\n );\n }\n return false;\n}\n\n/** The child-id list of a stack (`children`, or a lone `child`), else null. */\n/**\n * The children of a stack in render order: `child` first (a Card renders\n * its `child` before its `children`), then `children`.\n */\nfunction stackChildren(c: Record<string, unknown>) {\n const first = typeof c.child === \"string\" ? [c.child] : [];\n if (Array.isArray(c.children)) return [...first, ...c.children];\n if (first.length > 0 && c.children === undefined) return first;\n return null;\n}\n\n/** A contiguous slice `[start, end)` of the stack's children. */\ntype ChildRun = { prose: boolean; start: number; end: number };\n\n/**\n * Partitions the stack's children into alternating prose and surface runs.\n * A run of consecutive prose items is prose only when it holds text: a run of\n * separators alone (Divider/Spacer between two UI components, or at the very\n * start/end of the stack) stays with the surface it sits in.\n */\nfunction partitionChildren(items: (ProseItem | null)[]) {\n const runs: ChildRun[] = [];\n let i = 0;\n while (i < items.length) {\n const candidate = items[i] !== null;\n let hasText = false;\n let j = i;\n while (j < items.length && (items[j] !== null) === candidate) {\n if (items[j]?.kind === \"text\") hasText = true;\n j++;\n }\n const prose = candidate && hasText;\n const last = runs[runs.length - 1];\n if (!prose && last && !last.prose) last.end = j;\n else runs.push({ prose, start: i, end: j });\n i = j;\n }\n return runs;\n}\n\n/** One block of a segmented surface, in render order. */\nexport type SurfaceSegment =\n | { kind: \"markdown\"; markdown: string }\n | { kind: \"surface\"; components: Record<string, unknown>[] };\n\n/**\n * Markdown mode: split a surface into markdown and surface segments so that\n * only real UI renders as A2UI and everything else is the chat's markdown.\n *\n * From `root`, descend through single-child vertical containers (Column,\n * column Box, informational Card) to the first one with several children:\n * the stack. Its children are partitioned, in order, into runs of prose and\n * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal\n * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:\n * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →\n * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →\n * `- …` (or `1. …` for `marker: \"number\"`, `**label** — description` for\n * described items), and a `Divider` between two prose blocks → `---`.\n *\n * Not prose: `{path}`-bound text or items, a Text with inline children, a\n * List with `children`/icons/actions, a template entry, a component with an\n * `accessibility` envelope, and a child whose component has not streamed\n * yet. Separators with no text beside them stay in\n * the surface. An interactive Card (see `classifySurfaceCards`) is never\n * entered.\n *\n * Each prose run becomes a markdown segment; each UI run becomes a surface\n * segment whose `root` is a copy of the stack (its other props kept, `child`\n * dropped) with only that run's `children`, followed by every component\n * reachable from them. When nothing is prose the input comes back as the one\n * surface segment (same array); when everything is (or `root` itself is),\n * there are only markdown segments.\n *\n * Pure and linear in the number of components, so it runs on every stream\n * update.\n *\n * @param components - The components of one surface, root included.\n * @returns The segments in render order.\n *\n * @example\n * ```ts\n * for (const segment of segmentSurfaceProse(components)) {\n * if (segment.kind === \"markdown\") renderMarkdown(segment.markdown);\n * else renderSurface(segment.components);\n * }\n * ```\n */\nexport function segmentSurfaceProse(\n components: Record<string, unknown>[],\n options: ChildWalkOptions = {},\n) {\n const unchanged: SurfaceSegment[] = [{ kind: \"surface\", components }];\n const byId = new Map<string, Record<string, unknown>>();\n for (const c of components) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n const root = byId.get(GENERATIVE_UI_ROOT_ID);\n if (!root) return unchanged;\n // A component whose children are known only at render time (a bound\n // list of tabs) could reference any component. The lift cannot tell\n // which ones to keep, so it keeps the surface whole.\n const hasUnknownChildren = components.some(\n (c) => isRecord(c) && options.childIds?.(c) === \"unknown\",\n );\n if (hasUnknownChildren) return unchanged;\n\n const rootItem = toProseItem(root);\n if (rootItem?.kind === \"text\") {\n const whole: SurfaceSegment[] = [\n { kind: \"markdown\", markdown: rootItem.markdown },\n ];\n return whole;\n }\n\n const interactiveCards = classifySurfaceCards(components, options);\n let stack = root;\n let stackId: string = GENERATIVE_UI_ROOT_ID;\n let children: unknown[];\n const visited = new Set<string>();\n while (true) {\n if (!isVerticalStack(stack, interactiveCards)) return unchanged;\n visited.add(stackId);\n const list = stackChildren(stack);\n if (!list) return unchanged;\n children = list;\n const nextId = list.length === 1 ? list[0] : undefined;\n if (typeof nextId !== \"string\") break;\n const next = byId.get(nextId);\n if (!next || visited.has(nextId) || toProseItem(next)) break;\n stack = next;\n stackId = nextId;\n }\n\n const stackChildIds = children;\n const items = stackChildIds.map((id) =>\n typeof id === \"string\" ? toProseItem(byId.get(id)) : null,\n );\n const runs = partitionChildren(items);\n if (!runs.some((run) => run.prose)) return unchanged;\n\n // Which surface segments each component belongs to (shared ones go to all).\n const surfaceRuns = runs.filter((run) => !run.prose);\n const owners = new Map<string, number[]>();\n surfaceRuns.forEach((run, index) => {\n const pending = stackChildIds\n .slice(run.start, run.end)\n .map(referencedId)\n .filter((id): id is string => id !== undefined);\n const seen = new Set<string>();\n while (pending.length > 0) {\n const id = pending.pop()!;\n // `root` is replaced by the stack copy; the stack never nests in itself.\n const isSkipped = id === GENERATIVE_UI_ROOT_ID || id === stackId;\n if (isSkipped || seen.has(id)) continue;\n seen.add(id);\n const list = owners.get(id);\n if (list) list.push(index);\n else owners.set(id, [index]);\n const c = byId.get(id);\n if (c) pending.push(...directChildIds(c, options.childIds));\n }\n });\n const surfaceComponents = surfaceRuns.map((run) => {\n // `child` is folded into `children` by stackChildren, so the copy must\n // not render it a second time.\n const { child: _child, ...stackRest } = stack;\n const nextRoot: Record<string, unknown> = {\n ...stackRest,\n id: GENERATIVE_UI_ROOT_ID,\n children: stackChildIds.slice(run.start, run.end),\n };\n delete nextRoot.child;\n return [nextRoot];\n });\n for (const c of components) {\n if (!isRecord(c) || typeof c.id !== \"string\" || byId.get(c.id) !== c) {\n continue;\n }\n const ownerIndexes = owners.get(c.id) ?? [];\n for (const index of ownerIndexes) {\n surfaceComponents[index]!.push(c);\n }\n }\n\n let surfaceIndex = 0;\n const segments: SurfaceSegment[] = runs.map((run) => {\n if (run.prose) {\n return {\n kind: \"markdown\",\n markdown: proseItemsToMarkdown(items.slice(run.start, run.end)),\n };\n }\n return { kind: \"surface\", components: surfaceComponents[surfaceIndex++]! };\n });\n return segments;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAUA,SAAgB,aAAa,OAAoC;AAC/D,KAAI,iBAAiB,UAAW,QAAO;AACvC,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAY;AAClB,QACE,OAAO,UAAU,QAAQ,YACzB,OAAO,UAAU,YAAY,YAC7B,UAAU,YAAY,QACtB,UAAU,2BAA2B,mBACrC,OAAO,UAAU,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACiDlC,eAAsB,iCACpB,OACA,YACA,YACA,SAIyB;CAOzB,MAAM,OAAO;CACb,IAAI,oBAAoB;AACtB,QAAM,YAAY;;AAGpB,KAAI;AACF,QAAM,YAAY;AAClB,QAAM,UAAU,MAAM,WAAW,YAAY;EAE7C,MAAM,QAAQ,KAAK,qBAAqB,WAAW;EACnD,IAAI;EACJ,MAAM,qBAAqB,IAAI,IAAI,MAAM,SAAS,KAAK,MAAM,EAAE,GAAG,CAAC;EAGnE,IAAI,cAAc;EAClB,MAAM,6BAAa,IAAI,SAAoB;EAC3C,MAAM,cAAiC;GACrC;IACE,yBAAyB;AACvB,WAAM,YAAY;;IAEpB,kBAAkB,EAAE,YAAY;AAC9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AAO,IAAI,IAAI,CAAC,MAAM,CAAC;GAC5B,MAAM,IAAI,KAAK,IAAI,GAAG;AACtB,OAAI,EAAG,SAAQ,KAAK,GAAG,eAAe,GAAG,QAAQ,SAAS,CAAC;;GAE7D;CACF,MAAM,oBAAoB,YAAY,KAAK,QAAQ;EAGjD,MAAM,EAAE,OAAO,QAAQ,GAAG,cAAc;EACxC,MAAM,WAAoC;GACxC,GAAG;GACH,IAAI;GACJ,UAAU,cAAc,MAAM,IAAI,OAAO,IAAI,IAAI;GAClD;AACD,SAAO,SAAS;AAChB,SAAO,CAAC,SAAS;GACjB;AACF,MAAK,MAAM,KAAK,YAAY;AAC1B,MAAI,CAAC,SAAS,EAAE,IAAI,OAAO,EAAE,OAAO,YAAY,KAAK,IAAI,EAAE,GAAG,KAAK,EACjE;EAEF,MAAM,eAAe,OAAO,IAAI,EAAE,GAAG,IAAI,EAAE;AAC3C,OAAK,MAAM,SAAS,aAClB,mBAAkB,OAAQ,KAAK,EAAE;;CAIrC,IAAI,eAAe;AAUnB,QATmC,KAAK,KAAK,QAAQ;AACnD,MAAI,IAAI,MACN,QAAO;GACL,MAAM;GACN,UAAU,qBAAqB,MAAM,MAAM,IAAI,OAAO,IAAI,IAAI,CAAC;GAChE;AAEH,SAAO;GAAE,MAAM;GAAW,YAAY,kBAAkB;GAAkB;GAC1E"}
1
+ {"version":3,"file":"index.mjs","names":["switchMap","switchMapOperator","isAbortError","#applyMessageFilter","switchMap","#connectViaDelegate","#connectViaHttp","#runViaDelegate","#runViaHttp","#prepareOutboundMessages","isAbortError","isAbortError","randomUUID","randomUUID","#responses","#pending","#replace","#sealed","#adoptedContent","#respond","#decide","randomUUID","isAbortError","randomUUID","observeOn","REQUEST_TIMEOUT_MS","MAX_SOCKET_RETRIES","switchMap","randomUUID","ɵcreateMemoryStore","switchMap","on"],"sources":["../src/utils/http-agent.ts","../src/utils/connect-replay.ts","../src/utils/phoenix-observable.ts","../src/intelligence-agent.ts","../src/utils/runtime-info-error.ts","../src/core/message-filter.ts","../src/agent.ts","../src/utils/abort-error.ts","../src/utils/runtime-request.ts","../src/utils/single-route-resource-request.ts","../src/core/header-source.ts","../src/core/agent-registry.ts","../src/core/agent-scope.ts","../src/core/context-store.ts","../src/core/suggestion-engine.ts","../src/core/tool-result-content.ts","../src/core/tool-schema.ts","../src/interrupt-state.ts","../src/core/webmcp.ts","../src/core/run-handler.ts","../src/core/state-manager.ts","../src/core/thread-store-registry.ts","../src/core/trajectory-connection.ts","../src/core/learning-bridge.ts","../src/utils/micro-redux.ts","../src/memory-errors.ts","../src/memory.ts","../src/core/core.ts","../src/types.ts","../src/utils/markdown.ts","../src/threads.ts","../src/features.ts","../src/inspector-thread-bridge.ts","../src/a2ui-markdown/fence-parser.ts","../src/a2ui-markdown/operations.ts"],"sourcesContent":["import { HttpAgent } from \"@ag-ui/client\";\n\n/**\n * Whether an agent is an `HttpAgent`, including one built from another copy of\n * `@ag-ui/client` (an app that pins its own 0.x version next to CopilotKit's\n * 1.0, for example). `instanceof` is false across package copies, which made\n * CopilotKit silently skip headers and abort wiring for those agents. The\n * fallback checks the public fields CopilotKit uses, which every published\n * `HttpAgent` has.\n */\nexport function ɵisHttpAgent(agent: unknown): agent is HttpAgent {\n if (agent instanceof HttpAgent) return true;\n if (typeof agent !== \"object\" || agent === null) return false;\n const candidate = agent as Record<string, unknown>;\n return (\n typeof candidate.url === \"string\" &&\n typeof candidate.headers === \"object\" &&\n candidate.headers !== null &&\n candidate.abortController instanceof AbortController &&\n typeof candidate.runAgent === \"function\"\n );\n}\n","import type {\n AbstractAgent,\n AgentSubscriber,\n BaseEvent,\n RunAgentInput,\n RunAgentParameters,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport {\n AGUIConnectNotImplementedError,\n CompatibilityBoundary,\n EventType,\n randomUUID,\n structuredClone_,\n transformChunks,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { EMPTY, Subject, defer, lastValueFrom } from \"rxjs\";\nimport { catchError, finalize, takeUntil, tap } from \"rxjs/operators\";\n\n/** Internal connection callbacks; HTTP connections keep their EOF behavior. */\nexport interface ConnectionReplayLifecycle {\n onReplayStarted?: () => void;\n onReplayFinished?: () => void;\n}\n\n/**\n * Whether a RUN_ERROR received while connecting is stored history (`replay`)\n * or a failure of a run that is happening now (`live`). `unknown` when the\n * transport reports no replay boundaries, as with HTTP `/connect`.\n */\nexport type RunErrorPhase = \"replay\" | \"live\" | \"unknown\";\n\nconst connectRunErrorPhases = new WeakMap<BaseEvent, \"replay\" | \"live\">();\n\n/**\n * The phase in which a connection received `event`, as recorded when it\n * arrived. Events that did not come through a connection with replay\n * boundaries report `unknown`.\n */\nexport function ɵgetConnectRunErrorPhase(event: BaseEvent): RunErrorPhase {\n return connectRunErrorPhases.get(event) ?? \"unknown\";\n}\n\n/**\n * Runs an agent's `connect()` stream through the AbstractAgent apply pipeline\n * with the `verifyEvents` step omitted.\n *\n * `verifyEvents` enforces AG-UI's *single run* lifecycle rules: exactly one\n * RUN_STARTED opening the stream, no events after a terminal RUN_FINISHED /\n * RUN_ERROR. Those rules are correct for `/run`, but a `/connect` response is a\n * replay of a thread's history and can legitimately carry several past runs\n * back to back — including a run that ended in RUN_ERROR followed by a later\n * RUN_STARTED. Verifying a replay against single-run rules makes hydration of\n * an existing thread fail outright:\n *\n * Cannot send event type 'RUN_STARTED': The run has already errored with\n * 'RUN_ERROR'. No further events can be sent.\n *\n * The AG-UI 1.0 compatibility boundary still runs first, so stored 0.x history\n * is translated (THINKING_* events, `binary` parts, legacy nulls) exactly as in\n * the base pipeline. `enforceEvents` is omitted too: a replay is stored\n * history, and one event that the 1.0 schema rejects (the Intelligence gateway\n * replays RUN_STARTED without `runId`, for example) must not stop the whole\n * thread from hydrating. That keeps the leniency this path had before 1.0.\n *\n * Connection-local replay hooks track the phase before applying events. An\n * explicitly live RUN_ERROR clears busy without closing the connection;\n * historical errors remain data. Connections without hooks retain the existing\n * completion behavior.\n *\n * Apart from the above, this mirrors the base `AbstractAgent.connectAgent`\n * implementation, so callers keep the same subscriber notifications, detach\n * semantics, and `{ result, newMessages }` return shape.\n *\n * TODO: Remove this in favour of the base implementation once AG-UI's\n * AbstractAgent supports opting out of `verifyEvents` for transports whose\n * connection life-cycle isn't a single run AND preserves the connection-local\n * replay lifecycle and running-state behavior below. Skipping verification alone\n * is insufficient. As of `@ag-ui/client@1.0.1`\n * `connectAgent(parameters?, subscriber?)` takes no such option.\n *\n * @param agent - The agent whose `connect()` stream should be consumed.\n * @param parameters - Run parameters, forwarded to `prepareRunAgentInput`.\n * @param subscriber - Optional one-shot subscriber for this connect call.\n */\nexport async function ɵconnectWithoutEventVerification(\n agent: AbstractAgent,\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n connect?: (\n input: RunAgentInput,\n lifecycle: ConnectionReplayLifecycle,\n ) => Observable<BaseEvent>,\n): Promise<RunAgentResult> {\n // Access protected/private members through a type escape hatch — they are\n // set and read by the base class and must be managed identically to the\n // original implementation. `any` is required because these fields are\n // private in AbstractAgent, and intersecting private+public members of the\n // same name produces `never`.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const self = agent as any;\n let finalizeRun = () => {\n agent.isRunning = false;\n };\n\n try {\n agent.isRunning = true;\n agent.agentId = agent.agentId ?? randomUUID();\n\n const input = self.prepareRunAgentInput(parameters);\n let result: RunAgentResult[\"result\"];\n const previousMessageIds = new Set(agent.messages.map((m) => m.id));\n // Record the phase when an error arrives: subscriber callbacks may run\n // asynchronously after replay_complete has already changed the phase.\n let isReplaying = true;\n // Only a transport that reports replay boundaries can say which phase an\n // error arrived in; without them the phase stays unknown.\n let reportsReplayPhase = false;\n const liveErrors = new WeakSet<BaseEvent>();\n const subscribers: AgentSubscriber[] = [\n {\n onRunStartedEvent: () => {\n agent.isRunning = true;\n },\n onRunErrorEvent: ({ event }) => {\n if (liveErrors.has(event)) agent.isRunning = false;\n },\n onRunFinishedEvent: (event) => {\n if (event.outcome === \"success\") {\n result = event.result;\n }\n },\n },\n ...agent.subscribers,\n subscriber ?? {},\n ];\n\n const activeRunDetach$ = new Subject<void>();\n self.activeRunDetach$ = activeRunDetach$;\n let resolveCompletion: (() => void) | undefined;\n self.activeRunCompletionPromise = new Promise<void>((resolve) => {\n resolveCompletion = resolve;\n });\n let detached = false;\n let finalized = false;\n const detachSubscription = activeRunDetach$.subscribe(() => {\n detached = true;\n });\n finalizeRun = () => {\n if (finalized) return;\n finalized = true;\n detachSubscription.unsubscribe();\n if (self.activeRunDetach$ === activeRunDetach$) {\n agent.isRunning = false;\n self.activeRunCompletionPromise = undefined;\n self.activeRunDetach$ = undefined;\n // Keep AG-UI's callback timing. A finalizer can await the next run.\n void self.onFinalize(input, subscribers);\n }\n resolveCompletion?.();\n resolveCompletion = undefined;\n };\n\n // Initialization can await subscribers that return state mutations.\n // Publish teardown first, then wait for those mutations before releasing it.\n await self.onInitialize(input, subscribers);\n if (detached) return { result: undefined, newMessages: [] };\n\n // Only an explicitly live error changes busy state. Connection lifetime\n // remains owned by the transport (Intelligence idle or HTTP EOF).\n const lifecycle: ConnectionReplayLifecycle = {\n onReplayStarted: () => {\n reportsReplayPhase = true;\n isReplaying = true;\n agent.isRunning = true;\n },\n onReplayFinished: () => {\n reportsReplayPhase = true;\n isReplaying = false;\n },\n };\n const source$ = defer(() =>\n // The boundary is a middleware; hand it a stand-in agent whose run() is\n // this connect stream, as AG-UI's own connect operator does internally.\n new CompatibilityBoundary().run(input, {\n run: () =>\n connect\n ? connect(input, lifecycle)\n : (self.connect(input) as Observable<BaseEvent>),\n } as unknown as AbstractAgent),\n ).pipe(\n // NOTE: enforceEvents is intentionally omitted here. See JSDoc above.\n tap((event) => {\n if (event.type !== EventType.RUN_ERROR) return;\n if (!isReplaying) liveErrors.add(event);\n if (reportsReplayPhase) {\n connectRunErrorPhases.set(event, isReplaying ? \"replay\" : \"live\");\n }\n }),\n // transformChunks reassembles partial/streamed messages — still needed.\n transformChunks(self.debugLogger),\n // NOTE: verifyEvents is intentionally omitted here. See JSDoc above.\n takeUntil(activeRunDetach$),\n );\n\n const applied$ = self.apply(input, source$, subscribers);\n const processed$ = self.processApplyEvents(input, applied$, subscribers);\n\n await lastValueFrom(\n processed$.pipe(\n catchError((error: unknown) => {\n if (self.activeRunDetach$ !== activeRunDetach$) return EMPTY;\n agent.isRunning = false;\n // An agent that doesn't implement connect() is not an error worth\n // surfacing: the base pipeline swallows it, and callers rely on that.\n // `CopilotKitCore` awaits `detachActiveRun()` before every run, which\n // only resolves because this path still reaches the finalize block\n // below (see the historical note in run-handler.ts). Routing it\n // through onError would also fire run-failure callbacks on every\n // subscriber for a benign condition.\n if (error instanceof AGUIConnectNotImplementedError) {\n return EMPTY;\n }\n return self.onError(input, error, subscribers);\n }),\n finalize(() => finalizeRun()),\n ),\n { defaultValue: undefined },\n );\n\n const newMessages = structuredClone_(agent.messages).filter(\n (m) => !previousMessageIds.has(m.id),\n );\n return { result, newMessages };\n } finally {\n finalizeRun();\n }\n}\n","import { Socket } from \"phoenix\";\nimport { EMPTY, NEVER, Observable, concat, defer, of, throwError } from \"rxjs\";\nimport {\n filter,\n finalize,\n mergeMap,\n scan,\n shareReplay,\n switchMap,\n take,\n} from \"rxjs/operators\";\n\n/**\n * Minimal Phoenix push contract used by the observable adapters.\n */\nexport interface ɵPhoenixPushLike {\n receive(\n status: string,\n callback: (payload?: unknown) => unknown,\n ): ɵPhoenixPushLike;\n}\n\n/**\n * Minimal Phoenix channel contract used by the observable adapters.\n */\nexport interface ɵPhoenixChannelLike {\n on(event: string, callback: (payload: unknown) => void): number;\n off(event: string, ref?: number): void;\n onError?(callback: (reason?: unknown) => void): unknown;\n join(params?: Record<string, unknown>): ɵPhoenixPushLike;\n push?(event: string, payload: unknown): ɵPhoenixPushLike;\n leave(): void;\n}\n\n/**\n * Minimal Phoenix socket contract used by the observable adapters.\n */\nexport interface ɵPhoenixSocketLike {\n connect(): void;\n disconnect(): void;\n channel(topic: string, params?: Record<string, unknown>): ɵPhoenixChannelLike;\n onError(callback: (error?: unknown) => void): unknown;\n onOpen(callback: () => void): unknown;\n}\n\n/**\n * Socket lifecycle notifications exposed by {@link ɵphoenixSocket$}.\n */\nexport type ɵPhoenixSocketSignal =\n | { type: \"open\" }\n | { type: \"error\"; error?: unknown };\n\n/**\n * Terminal outcomes of a Phoenix channel join attempt.\n */\nexport type ɵPhoenixJoinOutcome =\n | { type: \"joined\" }\n | { type: \"error\"; response?: unknown }\n | { type: \"timeout\" };\n\n/**\n * Active Phoenix socket session plus its derived lifecycle stream.\n */\nexport interface ɵPhoenixSocketSession {\n socket: ɵPhoenixSocketLike;\n signals$: Observable<ɵPhoenixSocketSignal>;\n}\n\n/**\n * Active Phoenix channel session plus its derived join-outcome stream.\n */\nexport interface ɵPhoenixChannelSession {\n channel: ɵPhoenixChannelLike;\n joinOutcome$: Observable<ɵPhoenixJoinOutcome>;\n}\n\n/**\n * Options for creating a cold Phoenix socket session stream.\n */\nexport interface ɵPhoenixSocketOptions {\n url: string;\n options?: Record<string, unknown>;\n}\n\n/**\n * Options for creating a cold Phoenix channel session stream from a socket stream.\n */\nexport interface ɵPhoenixChannelOptions {\n socket$: Observable<ɵPhoenixSocketSession>;\n topic: string;\n params?: Record<string, unknown>;\n leaveOnUnsubscribe?: boolean;\n}\n\n/**\n * Adapt Phoenix socket open/error callbacks into an observable signal stream.\n *\n * The returned observable is shared and replayable by the caller when needed,\n * but this helper itself does not own socket connection teardown.\n */\nfunction ɵcreatePhoenixSocketSignals$(\n socket: ɵPhoenixSocketLike,\n): Observable<ɵPhoenixSocketSignal> {\n return new Observable<ɵPhoenixSocketSignal>((observer) => {\n socket.onOpen(() => observer.next({ type: \"open\" }));\n socket.onError((error) => observer.next({ type: \"error\", error }));\n });\n}\n\n/**\n * Adapt a Phoenix channel join attempt into a single-outcome observable.\n */\nfunction ɵcreatePhoenixJoinOutcome$(\n channel: ɵPhoenixChannelLike,\n): Observable<ɵPhoenixJoinOutcome> {\n return new Observable<ɵPhoenixJoinOutcome>((observer) => {\n channel\n .join()\n .receive(\"ok\", () => {\n observer.next({ type: \"joined\" });\n observer.complete();\n })\n .receive(\"error\", (response?: unknown) => {\n observer.next({ type: \"error\", response });\n observer.complete();\n })\n .receive(\"timeout\", () => {\n observer.next({ type: \"timeout\" });\n observer.complete();\n });\n });\n}\n\n/**\n * Create a cold Phoenix socket session.\n *\n * The socket is constructed and connected on subscription, and disconnected on\n * teardown. Each subscription creates an isolated socket instance.\n *\n * Heartbeats default to every 15s: Phoenix's own 30s default matches common\n * reverse-proxy WebSocket idle timeouts (e.g. Azure Application Gateway), which\n * would drop the socket during a quiet run. Callers may override it.\n */\nexport function ɵphoenixSocket$(\n options: ɵPhoenixSocketOptions,\n): Observable<ɵPhoenixSocketSession> {\n return defer(() => {\n const socket = new Socket(options.url, {\n heartbeatIntervalMs: 15_000,\n ...options.options,\n } as ConstructorParameters<typeof Socket>[1]) as ɵPhoenixSocketLike;\n const signals$ = ɵcreatePhoenixSocketSignals$(socket).pipe(\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n\n socket.connect();\n\n return concat(\n of({\n socket,\n signals$,\n }),\n NEVER,\n ).pipe(finalize(() => socket.disconnect()));\n });\n}\n\n/**\n * Create a cold Phoenix channel session from a socket session stream.\n *\n * A channel is created and joined for each active socket session. If the\n * upstream socket session changes, the previous channel is left before the\n * next one becomes active.\n */\nexport function ɵphoenixChannel$(\n options: ɵPhoenixChannelOptions,\n): Observable<ɵPhoenixChannelSession> {\n return options.socket$.pipe(\n switchMap(({ socket }) =>\n defer(() => {\n const channel = socket.channel(options.topic, options.params);\n const joinOutcome$ = ɵcreatePhoenixJoinOutcome$(channel).pipe(\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n\n return concat(\n of({\n channel,\n joinOutcome$,\n }),\n NEVER,\n ).pipe(\n finalize(() => {\n if (options.leaveOnUnsubscribe !== false) {\n channel.leave();\n }\n }),\n );\n }),\n ),\n );\n}\n\n/**\n * Observe a named Phoenix channel event as an observable payload stream.\n */\nexport function ɵobservePhoenixEvent$<T>(\n channel: ɵPhoenixChannelLike,\n eventName: string,\n): Observable<T> {\n return new Observable<T>((observer) => {\n const ref = channel.on(eventName, (payload) => observer.next(payload as T));\n\n return () => {\n channel.off(eventName, ref);\n };\n });\n}\n\n/**\n * Flatten channel sessions into their join-outcome stream.\n */\nexport function ɵobservePhoenixJoinOutcome$(\n channel$: Observable<ɵPhoenixChannelSession>,\n): Observable<ɵPhoenixJoinOutcome> {\n return channel$.pipe(switchMap((session) => session.joinOutcome$));\n}\n\n/**\n * Complete when a channel joins successfully, or error if the join fails.\n */\nexport function ɵjoinPhoenixChannel$(\n channel$: Observable<ɵPhoenixChannelSession>,\n): Observable<never> {\n return ɵobservePhoenixJoinOutcome$(channel$).pipe(\n take(1),\n mergeMap((outcome) => {\n if (outcome.type === \"joined\") {\n return EMPTY;\n }\n\n throw outcome.type === \"timeout\"\n ? new Error(\"Timed out joining channel\")\n : new Error(\n `Failed to join channel: ${JSON.stringify(outcome.response)}`,\n );\n }),\n );\n}\n\n/**\n * Flatten socket sessions into their lifecycle signal stream.\n */\nexport function ɵobservePhoenixSocketSignals$(\n socket$: Observable<ɵPhoenixSocketSession>,\n): Observable<ɵPhoenixSocketSignal> {\n return socket$.pipe(switchMap((session) => session.signals$));\n}\n\n/**\n * Error after a socket emits the configured number of consecutive error\n * signals, resetting the counter after each successful open signal.\n */\nexport function ɵobservePhoenixSocketHealth$(\n socketSignals$: Observable<ɵPhoenixSocketSignal>,\n maxConsecutiveErrors: number,\n): Observable<never> {\n return socketSignals$.pipe(\n scan(\n (consecutiveErrors, signal) =>\n signal.type === \"open\" ? 0 : consecutiveErrors + 1,\n 0,\n ),\n filter((consecutiveErrors) => consecutiveErrors >= maxConsecutiveErrors),\n take(1),\n mergeMap((consecutiveErrors) =>\n throwError(\n () =>\n new Error(\n `WebSocket connection failed after ${consecutiveErrors} consecutive errors`,\n ),\n ),\n ),\n );\n}\n","import type { ConnectionReplayLifecycle } from \"./utils/connect-replay\";\nimport type {\n RunAgentInput,\n RunAgentParameters,\n RunAgentResult,\n AgentSubscriber,\n BaseEvent,\n} from \"@ag-ui/client\";\nimport { AbstractAgent, EventType } from \"@ag-ui/client\";\n\nimport {\n EMPTY,\n Notification,\n combineLatest,\n defer,\n dematerialize,\n merge,\n of,\n switchMap,\n throwError,\n} from \"rxjs\";\nimport type { ObservableNotification, Observable } from \"rxjs\";\nimport {\n catchError,\n delay,\n endWith,\n filter,\n finalize,\n ignoreElements,\n map,\n mergeMap,\n startWith,\n share,\n shareReplay,\n switchMap as switchMapOperator,\n take,\n takeUntil,\n tap,\n} from \"rxjs/operators\";\nimport {\n phoenixExponentialBackoff,\n stripIntelligenceRoutingFields,\n} from \"@copilotkit/shared\";\nimport { ɵconnectWithoutEventVerification } from \"./utils/connect-replay\";\nimport {\n ɵphoenixChannel$,\n ɵphoenixSocket$,\n ɵjoinPhoenixChannel$,\n ɵobservePhoenixSocketSignals$,\n ɵobservePhoenixSocketHealth$,\n ɵobservePhoenixEvent$,\n} from \"./utils/phoenix-observable\";\nimport type {\n ɵPhoenixChannelLike,\n ɵPhoenixChannelSession,\n ɵPhoenixPushLike,\n ɵPhoenixSocketLike,\n ɵPhoenixSocketSession,\n} from \"./utils/phoenix-observable\";\n\n/**\n * Structural Phoenix socket/channel contracts used by this agent, derived from\n * the minimal `*Like` interfaces in {@link ./utils/phoenix-observable}.\n */\ntype Socket = ɵPhoenixSocketLike;\n\ninterface Channel extends ɵPhoenixChannelLike {\n push(event: string, payload: unknown): ɵPhoenixPushLike;\n}\n\nconst globalFetch: typeof fetch = (...args) => fetch(...args);\n\nconst CLIENT_AG_UI_EVENT = \"ag_ui_event\";\nconst REPLAY_COMPLETE_EVENT = \"replay_complete\";\nconst REPLAY_FAILED_EVENT = \"replay_failed\";\nconst STREAM_IDLE_EVENT = \"stream_idle\";\nconst STOP_RUN_EVENT = \"stop_run\";\nconst CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS = 100;\nconst CONNECT_IDLE_WARNING_MS = 30_000;\n// Credential refreshes allowed in a row for sockets that never opened. Past this,\n// the run fails instead of waiting on a realtime endpoint that is not answering.\nconst MAX_UNOPENED_CREDENTIAL_REFRESHES = 2;\n\ninterface IntelligenceAgentSharedState {\n lastSeenEventIds: Map<string, string>;\n}\n\n/** Control-frame cursor state for one channel join. */\ninterface ControlCursorState {\n /** The last `latestEventId` that this join saved as the reconnect cursor. */\n applied: string | null;\n /** True after `replay_failed`. The gateway then repeats the prior cursor on purpose. */\n replayFailed: boolean;\n}\n\ninterface RealtimeConnectionInfo {\n clientUrl: string;\n topic: string;\n}\n\ninterface ThreadJoinCredentials {\n threadId: string;\n runId: string | null;\n joinToken: string;\n realtime: RealtimeConnectionInfo;\n}\n\ninterface McpResourceReadResponse {\n kind: \"mcp-resource-read\";\n threadId: string;\n runId: string;\n result: unknown;\n}\n\nfunction isMcpResourceRead(input: RunAgentInput): boolean {\n const forwardedProps = input.forwardedProps as\n | Record<string, unknown>\n | undefined;\n const request = forwardedProps?.__proxiedMCPRequest;\n return (\n forwardedProps?.__copilotkitMcpResourceReadOnly === true &&\n typeof request === \"object\" &&\n request !== null &&\n (request as { method?: unknown }).method === \"resources/read\"\n );\n}\n\nexport class AgentThreadLockedError extends Error {\n constructor(threadId?: string) {\n super(threadId ? `Thread ${threadId} is locked` : \"Thread is locked\");\n this.name = \"AgentThreadLockedError\";\n }\n}\n\n/**\n * The gateway could not replay a live run's events, so the client cannot\n * verify the run it is following. The run itself may still be going on the\n * server; reconnecting to the thread shows its real state.\n */\nexport class IntelligenceReplayFailedError extends Error {\n readonly code = \"INTELLIGENCE_REPLAY_FAILED\";\n\n constructor(\n readonly threadId: string,\n readonly runId: string | null,\n ) {\n super(\n \"The run's events could not be replayed. Reconnect to the thread to check the run's status.\",\n );\n this.name = \"IntelligenceReplayFailedError\";\n }\n}\n\n/**\n * Typed contract for agents that expose the completion promise of their\n * currently in-flight run.\n *\n * `IntelligenceAgent` resolves this promise once a run's observable pipeline\n * finalizes (see {@link IntelligenceAgent.connectAgent}). Consumers (e.g. the\n * v2 `CopilotChat` send-serialization path) await it to let an in-flight run —\n * notably an interrupt RESUME — finish before dispatching a new run, instead\n * of pre-empting it.\n *\n * The base `AbstractAgent` from `@ag-ui/client` only declares this property\n * privately, so it is reachable only through this contract plus the\n * {@link isRunCompletionAware} type guard. This keeps callers off `as unknown`\n * casts while still degrading safely for agents that don't implement it.\n */\nexport interface RunCompletionAware {\n /**\n * Resolves when the active run's pipeline finalizes (completes, errors, or is\n * detached). `undefined` when no run is in flight.\n */\n readonly activeRunCompletionPromise?: Promise<void>;\n}\n\n/**\n * Type guard for {@link RunCompletionAware}. Returns true when `agent` exposes\n * an `activeRunCompletionPromise` property, so callers can await an in-flight\n * run without an `as unknown as` cast. Returns false for agents that don't\n * implement the contract, letting the caller skip the await and degrade safely.\n */\nexport function isRunCompletionAware(\n agent: unknown,\n): agent is RunCompletionAware {\n return (\n typeof agent === \"object\" &&\n agent !== null &&\n \"activeRunCompletionPromise\" in agent\n );\n}\n\nexport interface IntelligenceAgentConfig {\n /** Phoenix websocket URL, e.g. \"ws://localhost:4000/socket\" */\n url: string;\n /** Runtime base URL, e.g. \"http://localhost:4000\" */\n runtimeUrl: string;\n /** HTTP transport for run/connect requests. Defaults to REST. */\n transport?: \"rest\" | \"single\";\n /** Agent identifier for REST endpoints */\n agentId: string;\n /** Optional params sent on socket connect (e.g. auth token) */\n socketParams?: Record<string, string>;\n /** Optional headers sent with REST requests */\n headers?: Record<string, string>;\n /** Optional credentials mode for fetch requests */\n credentials?: RequestCredentials;\n fetch?: typeof fetch;\n}\n\nexport class IntelligenceAgent extends AbstractAgent {\n private config: IntelligenceAgentConfig;\n private socket: Socket | null = null;\n private activeChannel: Channel | null = null;\n private canonicalRunId: string | null = null;\n private sharedState: IntelligenceAgentSharedState;\n\n constructor(\n config: IntelligenceAgentConfig,\n sharedState: IntelligenceAgentSharedState = {\n lastSeenEventIds: new Map<string, string>(),\n },\n ) {\n super();\n this.config = config;\n this.sharedState = sharedState;\n }\n\n /**\n * Headers sent with the REST join requests (`/connect`, `/run`).\n *\n * Deliberately a public accessor pair rather than a plain read of `config`.\n * `ProxiedCopilotRuntimeAgent` builds its delegate once and caches it for the\n * proxy's lifetime, so a header that changes later (a tenant switch, a\n * rotated bearer) would otherwise never reach the gateway. The accessor is\n * what closes that gap: `syncDelegate` refreshes the delegate before every\n * join, and its `hasHeaders` probe is an `\"headers\" in agent` check — which a\n * prototype accessor satisfies but a `private config` does not.\n *\n * The setter replaces the config object instead of mutating it because\n * `clone()` hands the same config reference to the copy. An in-place write\n * would therefore have a per-thread clone's headers land on the original's\n * config too. The join path itself would survive that (`syncDelegate`\n * rewrites the headers just before every join), but the re-acquisition inside\n * an already-running pipeline does not go through `syncDelegate` — so a\n * clone's tenant could ride out on the original's socket-error refresh. That\n * is the same cross-tenant leak this accessor exists to prevent.\n */\n get headers(): Record<string, string> | undefined {\n return this.config.headers;\n }\n\n set headers(headers: Record<string, string> | undefined) {\n this.config = { ...this.config, headers };\n }\n\n /** Credentials mode for the REST join requests. Live for the same reason as {@link headers}. */\n get credentials(): RequestCredentials | undefined {\n return this.config.credentials;\n }\n\n set credentials(credentials: RequestCredentials | undefined) {\n this.config = { ...this.config, credentials };\n }\n\n clone(): IntelligenceAgent {\n return new IntelligenceAgent(this.config, this.sharedState);\n }\n\n /**\n * Override of AbstractAgent.connectAgent that removes the `verifyEvents` step.\n *\n * IntelligenceAgent uses long-lived WebSocket connections rather than\n * request-scoped SSE streams. When connecting to replay historical messages\n * for an existing thread, the connection semantics don't map to a single\n * agent run start/stop cycle: the replayed events may omit the\n * RUN_STARTED/RUN_FINISHED bookends, or carry events from several past runs,\n * either of which makes `verifyEvents` stall or error out.\n *\n * See {@link ɵconnectWithoutEventVerification} for the pipeline itself, which\n * the self-hosted `/connect` path shares for the same reason.\n */\n override async connectAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n // A run already in flight owns the canonical run id; reuse it so the\n // replay is attributed to that run rather than minting a new one.\n const effectiveParameters =\n parameters?.runId || !this.canonicalRunId\n ? parameters\n : {\n ...parameters,\n runId: this.canonicalRunId,\n };\n\n return ɵconnectWithoutEventVerification(\n this,\n effectiveParameters,\n subscriber,\n (input, lifecycle) => this.connect(input, lifecycle),\n );\n }\n\n abortRun(): void {\n if (this.activeChannel && this.canonicalRunId) {\n // Defer cleanup until the push is acknowledged so socket.disconnect()\n // doesn't clear the push buffer before the stop signal is sent.\n // The 5-second fallback handles the case where the socket is down and\n // Phoenix never flushes the buffered push (its .receive(\"timeout\") only\n // fires for pushes that were actually sent but not replied to).\n // detachActiveRun() gracefully tears down the connectAgent() pipeline;\n // cleanup() follows as a safety net for the run() path.\n const fallback = setTimeout(() => clear(), 5_000);\n const clear = () => {\n clearTimeout(fallback);\n void this.detachActiveRun();\n this.cleanup();\n };\n\n this.activeChannel\n .push(STOP_RUN_EVENT, { run_id: this.canonicalRunId })\n .receive(\"ok\", clear)\n .receive(\"error\", clear)\n .receive(\"timeout\", clear);\n } else {\n void this.detachActiveRun();\n this.cleanup();\n }\n }\n\n /**\n * Trigger the run via REST, then join the realtime thread channel and relay\n * server-pushed AG-UI events to the Observable subscriber.\n */\n run(input: RunAgentInput): Observable<BaseEvent> {\n if (!isMcpResourceRead(input)) {\n this.threadId = input.threadId;\n this.canonicalRunId = input.runId;\n }\n\n return defer(() => this.requestJoinCredentials$(\"run\", input)).pipe(\n switchMap((credentials) => {\n if (credentials === null) {\n return throwError(\n () => new Error(\"REST run request returned no credentials\"),\n );\n }\n\n if (\"kind\" in credentials) {\n return of(\n {\n type: EventType.RUN_STARTED,\n threadId: credentials.threadId,\n runId: credentials.runId,\n } as BaseEvent,\n {\n type: EventType.RUN_FINISHED,\n threadId: credentials.threadId,\n runId: credentials.runId,\n result: credentials.result,\n } as BaseEvent,\n );\n }\n\n const canonicalInput = this.applyCanonicalRunIdentity(\n input,\n credentials,\n { fallbackToInputRunId: true },\n );\n\n return this.observeThread$(canonicalInput, credentials, {\n completeOnRunError: false,\n streamMode: \"run\",\n });\n }),\n );\n }\n\n /**\n * Reconnect to an existing thread by fetching websocket credentials and\n * joining the realtime thread channel.\n */\n /**\n * Reconnect to an existing thread by fetching websocket credentials\n * and joining the realtime thread channel.\n *\n * Note: this method does NOT clear the replay cursor. Whether to\n * request a full historical replay vs. resume from\n * `lastSeenEventId` is a decision the caller (typically\n * `RunHandler.connectAgent`) makes by calling\n * {@link clearReconnectCursor} ahead of time on a fresh thread\n * restore. Same-thread churn re-connects preserve the cursor so the\n * gateway only streams events past it instead of replaying the\n * entire history every time the chat re-opens a socket.\n */\n protected connect(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent> {\n this.threadId = input.threadId;\n this.canonicalRunId = null;\n const replayCursor = this.getReconnectCursor(input);\n\n return defer(() =>\n this.requestJoinCredentials$(\"connect\", input, replayCursor),\n ).pipe(\n switchMap((credentials) => {\n if (credentials === null) {\n lifecycle?.onReplayStarted?.();\n lifecycle?.onReplayFinished?.();\n return EMPTY;\n }\n\n const canonicalInput = this.applyCanonicalRunIdentity(\n input,\n credentials,\n { fallbackToInputRunId: false },\n );\n\n return this.observeThread$(canonicalInput, credentials, {\n completeOnRunError: false,\n streamMode: \"connect\",\n replayCursor,\n lifecycle,\n });\n }),\n );\n }\n\n /**\n * Tear down a specific channel + socket pair that belongs to one pipeline.\n * Only nulls instance references when they still point to the owned resource,\n * so a concurrent pipeline's resources are never clobbered.\n */\n private cleanupOwned(\n ownChannel: Channel | null,\n ownSocket: Socket | null,\n ): void {\n if (ownChannel) {\n ownChannel.leave();\n if (this.activeChannel === ownChannel) {\n this.activeChannel = null;\n }\n }\n if (ownSocket) {\n ownSocket.disconnect();\n if (this.socket === ownSocket) {\n this.socket = null;\n }\n }\n this.canonicalRunId = null;\n }\n\n private cleanup(): void {\n this.cleanupOwned(this.activeChannel, this.socket);\n }\n\n private requestJoinCredentials$(\n mode: \"run\",\n input: RunAgentInput,\n ): Observable<ThreadJoinCredentials | McpResourceReadResponse>;\n private requestJoinCredentials$(\n mode: \"connect\",\n input: RunAgentInput,\n replayCursor?: string | null,\n ): Observable<ThreadJoinCredentials | null>;\n private requestJoinCredentials$(\n mode: \"run\" | \"connect\",\n input: RunAgentInput,\n replayCursor?: string | null,\n ): Observable<ThreadJoinCredentials | McpResourceReadResponse | null> {\n return defer(async () => {\n try {\n const requestFetch = this.config.fetch ?? globalFetch;\n const body = {\n ...input,\n ...(mode === \"connect\"\n ? {\n lastSeenEventId:\n replayCursor === undefined\n ? this.getReconnectCursor(input)\n : replayCursor,\n }\n : {}),\n };\n const single = this.config.transport === \"single\";\n const response = await requestFetch(\n single ? this.config.runtimeUrl : this.buildRuntimeUrl(mode),\n {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n // Post the whole RunAgentInput rather than naming each field, so a\n // protocol field such as `resume` cannot be dropped here again.\n body: JSON.stringify(\n single\n ? {\n method: `agent/${mode}`,\n params: { agentId: this.config.agentId },\n body,\n }\n : body,\n ),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n },\n );\n\n if (response.status === 204 && mode === \"connect\") {\n return null;\n }\n\n if (response.status === 409 && mode === \"run\") {\n throw new AgentThreadLockedError(input.threadId);\n }\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new Error(\n text || response.statusText || String(response.status),\n );\n }\n\n const payload: unknown = await response.json();\n if (\n mode === \"run\" &&\n isMcpResourceRead(input) &&\n typeof payload === \"object\" &&\n payload !== null &&\n (payload as { kind?: unknown }).kind === \"mcp-resource-read\"\n ) {\n const resource = payload as Partial<McpResourceReadResponse>;\n if (\n typeof resource.threadId !== \"string\" ||\n !resource.threadId ||\n typeof resource.runId !== \"string\" ||\n !resource.runId\n ) {\n throw new Error(\"invalid MCP resource response identity\");\n }\n return {\n kind: \"mcp-resource-read\" as const,\n threadId: resource.threadId,\n runId: resource.runId,\n result: resource.result,\n };\n }\n return this.normalizeJoinCredentials(payload, input);\n } catch (error) {\n if (error instanceof AgentThreadLockedError) {\n throw error;\n }\n throw new Error(\n `REST ${mode} request failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n });\n }\n\n private normalizeJoinCredentials(\n payload: unknown,\n input: RunAgentInput,\n ): ThreadJoinCredentials {\n const envelope =\n payload && typeof payload === \"object\"\n ? (payload as Record<string, unknown>)\n : null;\n const realtime =\n envelope?.realtime && typeof envelope.realtime === \"object\"\n ? (envelope.realtime as Record<string, unknown>)\n : null;\n\n if (typeof envelope?.joinToken !== \"string\" || !envelope.joinToken) {\n throw new Error(\"missing joinToken\");\n }\n\n if (typeof realtime?.clientUrl !== \"string\" || !realtime.clientUrl) {\n throw new Error(\"missing realtime.clientUrl\");\n }\n\n if (typeof realtime.topic !== \"string\" || !realtime.topic) {\n throw new Error(\"missing realtime.topic\");\n }\n\n return {\n threadId:\n typeof envelope.threadId === \"string\" && envelope.threadId\n ? envelope.threadId\n : input.threadId,\n runId:\n typeof envelope.runId === \"string\" && envelope.runId\n ? envelope.runId\n : null,\n joinToken: envelope.joinToken,\n realtime: {\n clientUrl: realtime.clientUrl,\n topic: realtime.topic,\n },\n };\n }\n\n private observeThread$(\n input: RunAgentInput,\n credentials: ThreadJoinCredentials,\n options: {\n completeOnRunError: boolean;\n streamMode: \"run\" | \"connect\";\n lifecycle?: ConnectionReplayLifecycle;\n channelMode?: \"run\" | \"connect\";\n replayCursor?: string | null;\n unopenedRefreshes?: number;\n },\n ): Observable<BaseEvent> {\n const { unopenedRefreshes: previousUnopened = 0, ...sessionOptions } =\n options;\n return defer(() => {\n let socketOpened = false;\n return this.observeThreadSession$(input, credentials, {\n ...sessionOptions,\n onSocketOpen: () => {\n socketOpened = true;\n },\n }).pipe(\n catchError((error) => {\n if (!this.isSocketReconnectExhaustedError(error)) {\n return throwError(() => error);\n }\n\n // A session whose socket opened was a real connection that dropped, so\n // it restarts the count. Sessions that never open mean the realtime\n // endpoint is unavailable, and fresh credentials will not fix that.\n // Only a run is capped: a developer is waiting on its turn. A connect\n // restores history in the background, and nothing retries it after it\n // fails, so it keeps reconnecting until the endpoint recovers.\n const unopenedRefreshes = socketOpened ? 0 : previousUnopened + 1;\n if (\n options.streamMode === \"run\" &&\n unopenedRefreshes > MAX_UNOPENED_CREDENTIAL_REFRESHES\n ) {\n return throwError(\n () =>\n new Error(\n `Realtime connection to ${credentials.realtime.clientUrl} never opened ` +\n `in ${unopenedRefreshes} connection attempts. ` +\n `The realtime endpoint is unavailable.`,\n ),\n );\n }\n\n const replayCursor = this.getReconnectCursor(input);\n return this.requestJoinCredentials$(\n \"connect\",\n input,\n replayCursor,\n ).pipe(\n switchMap((refreshedCredentials) =>\n refreshedCredentials === null\n ? EMPTY\n : this.observeThread$(\n this.applyCanonicalRunIdentity(\n input,\n refreshedCredentials,\n {\n fallbackToInputRunId: options.streamMode === \"run\",\n },\n ),\n refreshedCredentials,\n {\n ...sessionOptions,\n channelMode: \"connect\",\n replayCursor,\n unopenedRefreshes,\n },\n ),\n ),\n );\n }),\n );\n });\n }\n\n private observeThreadSession$(\n input: RunAgentInput,\n credentials: ThreadJoinCredentials,\n options: {\n completeOnRunError: boolean;\n streamMode: \"run\" | \"connect\";\n lifecycle?: ConnectionReplayLifecycle;\n channelMode?: \"run\" | \"connect\";\n replayCursor?: string | null;\n onSocketOpen?: () => void;\n },\n ): Observable<BaseEvent> {\n return defer(() => {\n options.lifecycle?.onReplayStarted?.();\n // Capture references to the socket and channel created by THIS pipeline\n // so the finalize closure only tears down its own resources. Without\n // this, a fire-and-forget detachActiveRun() from run-handler can race:\n // the old pipeline's deferred cleanup reads from `this.socket` /\n // `this.activeChannel`, which by then may already point to the NEW\n // pipeline's resources — destroying the live connection and preventing\n // the stop signal from ever reaching the backend.\n let ownSocket: Socket | null = null;\n let ownChannel: Channel | null = null;\n\n // Silence after replay may mean a long-running agent or an unavailable\n // thread-lock lookup. Diagnose it without declaring an active run idle.\n let replayFinished = false;\n let warnedAboutIdle = false;\n let idleWarning: ReturnType<typeof setTimeout> | undefined;\n const clearIdleWarning = () => {\n clearTimeout(idleWarning);\n idleWarning = undefined;\n };\n const scheduleIdleWarning = () => {\n clearIdleWarning();\n if (\n options.streamMode !== \"connect\" ||\n !replayFinished ||\n warnedAboutIdle\n )\n return;\n idleWarning = setTimeout(() => {\n warnedAboutIdle = true;\n this.debugLogger?.lifecycle(\n \"INTELLIGENCE\",\n \"No progress or stream_idle for 30 seconds after replay_complete; the run may still be active or its status unavailable.\",\n { threadId: input.threadId },\n );\n }, CONNECT_IDLE_WARNING_MS);\n };\n\n const socket$ = ɵphoenixSocket$({\n url: credentials.realtime.clientUrl,\n options: {\n params: {\n ...this.config.socketParams,\n join_token: credentials.joinToken,\n },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(\n tap(({ socket }) => {\n ownSocket = socket as Socket;\n this.socket = ownSocket;\n }),\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n const params = this.createThreadChannelParams(\n input,\n options.channelMode ?? options.streamMode,\n options.replayCursor,\n );\n const channel$ = ɵphoenixChannel$({\n socket$,\n topic: credentials.realtime.topic,\n params,\n }).pipe(\n tap(({ channel }) => {\n ownChannel = channel as Channel;\n this.activeChannel = ownChannel;\n }),\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n const reconnectCursor = this.readDurableEventId(\n options.replayCursor ?? this.getReconnectCursor(input),\n );\n let latestObservedReplayCursor: string | null = null;\n const threadEvents$ = this.observeThreadEvents$(\n input.threadId,\n channel$,\n options,\n ).pipe(\n tap((payload) => {\n latestObservedReplayCursor =\n this.readEventId(payload) ?? latestObservedReplayCursor;\n scheduleIdleWarning();\n }),\n share(),\n );\n const controlCursor: ControlCursorState = {\n applied: null,\n replayFailed: false,\n };\n const replayFailed$ = channel$.pipe(\n switchMapOperator(({ channel }) =>\n this.observeChannelEvent$<unknown>(channel, REPLAY_FAILED_EVENT),\n ),\n tap(() => {\n controlCursor.replayFailed = true;\n // A live run cannot continue from an incomplete replay: the events\n // after it would be verified against a lifecycle missing its start.\n // Settle the client run without stopping the one on the server.\n // Keyed on streamMode, because refreshed run credentials join with\n // the connect channel mode while still following a live run.\n if (options.streamMode === \"run\") {\n // Ending the stream here skips the replay_complete that would\n // restore the join's checkpoint, so restore it now. Otherwise a\n // replayed event that advanced the cursor makes the next connect\n // skip the history this replay failed to deliver.\n if (reconnectCursor === null) {\n this.clearReconnectCursor(input.threadId);\n } else {\n this.advanceLastSeenEventId(input.threadId, reconnectCursor);\n }\n // `input` carries the canonical identity: a run stream keeps its\n // own run ID when refreshed credentials omit one.\n throw new IntelligenceReplayFailedError(\n input.threadId,\n input.runId ?? null,\n );\n }\n }),\n );\n // Controls are scoped to each replay epoch, not cached across rejoin.\n const replayComplete$ = this.observeControlEvent$(\n input.threadId,\n channel$,\n REPLAY_COMPLETE_EVENT,\n controlCursor,\n ).pipe(\n // Notify before idle completion can unsubscribe other observers.\n tap(() => {\n replayFinished = true;\n scheduleIdleWarning();\n options.lifecycle?.onReplayFinished?.();\n }),\n share(),\n );\n const streamIdle$ = this.observeControlEvent$(\n input.threadId,\n channel$,\n STREAM_IDLE_EVENT,\n controlCursor,\n ).pipe(share());\n const replayRestart$ = merge(\n this.observeControlEvent$(\n input.threadId,\n channel$,\n \"phx_error\",\n controlCursor,\n ),\n ɵobservePhoenixSocketSignals$(socket$).pipe(\n filter((signal) => signal.type === \"error\"),\n ),\n ).pipe(\n tap(() => {\n replayFinished = false;\n warnedAboutIdle = false;\n clearIdleWarning();\n options.lifecycle?.onReplayStarted?.();\n }),\n share(),\n );\n const streamIdleCompletion$ =\n options.streamMode === \"connect\"\n ? replayRestart$.pipe(\n startWith(null),\n switchMap(() =>\n merge(\n combineLatest([\n replayComplete$.pipe(take(1)),\n streamIdle$.pipe(take(1)),\n ]),\n streamIdle$.pipe(\n take(1),\n filter((payload) =>\n this.canFallbackCompleteConnect(\n payload,\n reconnectCursor,\n latestObservedReplayCursor,\n ),\n ),\n delay(CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS),\n tap(() => {\n this.debugLogger?.lifecycle(\n \"INTELLIGENCE\",\n \"Completing connection on stream_idle fallback without replay_complete.\",\n {\n threadId: input.threadId,\n fallbackMs: CONNECT_STREAM_IDLE_REPLAY_FALLBACK_MS,\n },\n );\n }),\n ),\n ),\n ),\n take(1),\n shareReplay({ bufferSize: 1, refCount: true }),\n )\n : EMPTY;\n const threadCompleted$ = threadEvents$.pipe(\n ignoreElements(),\n endWith(null),\n take(1),\n );\n const terminal$ = merge(threadCompleted$, streamIdleCompletion$);\n\n return merge(\n // Install replay/idle observers before joining the channel.\n replayFailed$.pipe(ignoreElements(), takeUntil(terminal$)),\n replayComplete$.pipe(ignoreElements(), takeUntil(terminal$)),\n this.joinThreadChannel$(channel$),\n this.observeSocketHealth$(socket$, options.onSocketOpen).pipe(\n takeUntil(terminal$),\n ),\n threadEvents$.pipe(takeUntil(streamIdleCompletion$)),\n streamIdleCompletion$.pipe(\n ignoreElements(),\n takeUntil(threadCompleted$),\n ),\n ).pipe(\n finalize(() => {\n clearIdleWarning();\n this.cleanupOwned(ownChannel, ownSocket);\n }),\n );\n });\n }\n\n private joinThreadChannel$(\n channel$: Observable<ɵPhoenixChannelSession>,\n ): Observable<never> {\n return ɵjoinPhoenixChannel$(channel$);\n }\n\n private observeSocketHealth$(\n socket$: Observable<ɵPhoenixSocketSession>,\n onSocketOpen?: () => void,\n ): Observable<never> {\n return ɵobservePhoenixSocketHealth$(\n ɵobservePhoenixSocketSignals$(socket$).pipe(\n tap((signal) => {\n if (signal.type === \"open\") onSocketOpen?.();\n }),\n ),\n 5,\n );\n }\n\n private observeThreadEvents$(\n threadId: string,\n channel$: Observable<ɵPhoenixChannelSession>,\n options: { completeOnRunError: boolean; streamMode: \"run\" | \"connect\" },\n ): Observable<BaseEvent> {\n return channel$.pipe(\n switchMapOperator(({ channel }) =>\n this.observeChannelEvent$<BaseEvent>(channel, CLIENT_AG_UI_EVENT),\n ),\n tap((payload) => {\n this.updateLastSeenEventId(threadId, payload);\n }),\n // Only the run stream goes through AG-UI 1.0 enforcement, which would\n // strip these fields with a warning each. Replays stay as sent.\n map((payload) =>\n options.streamMode === \"run\"\n ? stripIntelligenceRoutingFields(payload)\n : payload,\n ),\n mergeMap(\n (payload) =>\n this.createThreadNotifications(payload, {\n completeOnRunError: options.completeOnRunError,\n completeOnRunFinished: options.streamMode === \"run\",\n errorOnRunError: options.streamMode === \"run\",\n }) as ObservableNotification<BaseEvent>[],\n ),\n dematerialize(),\n );\n }\n\n private observeControlEvent$(\n threadId: string,\n channel$: Observable<ɵPhoenixChannelSession>,\n eventName: string,\n controlCursor: ControlCursorState,\n ): Observable<unknown> {\n return channel$.pipe(\n switchMapOperator(({ channel }) =>\n this.observeChannelEvent$<unknown>(channel, eventName),\n ),\n tap((payload) =>\n this.updateLastSeenEventIdFromControl(threadId, payload, controlCursor),\n ),\n );\n }\n\n private observeChannelEvent$<T>(\n channel: ɵPhoenixChannelLike,\n eventName: string,\n ): Observable<T> {\n return ɵobservePhoenixEvent$<T>(channel, eventName);\n }\n\n private createThreadNotifications(\n payload: BaseEvent,\n options: {\n completeOnRunError: boolean;\n completeOnRunFinished: boolean;\n errorOnRunError: boolean;\n },\n ): Array<Notification<BaseEvent>> {\n if (payload.type === EventType.RUN_FINISHED) {\n return options.completeOnRunFinished\n ? [Notification.createNext(payload), Notification.createComplete()]\n : [Notification.createNext(payload)];\n }\n\n if (payload.type === EventType.RUN_ERROR) {\n const errorMessage =\n (payload as BaseEvent & { message?: string }).message ?? \"Run error\";\n\n return options.completeOnRunError\n ? [Notification.createNext(payload), Notification.createComplete()]\n : options.errorOnRunError\n ? [\n Notification.createNext(payload),\n Notification.createError(new Error(errorMessage)),\n ]\n : [Notification.createNext(payload)];\n }\n\n return [Notification.createNext(payload)];\n }\n\n private buildRuntimeUrl(mode: \"run\" | \"connect\"): string {\n const path = `${this.config.runtimeUrl}/agent/${encodeURIComponent(this.config.agentId)}/${mode}`;\n const origin =\n typeof window !== \"undefined\" && window.location\n ? window.location.origin\n : \"http://localhost\";\n\n return new URL(path, new URL(this.config.runtimeUrl, origin)).toString();\n }\n\n private createThreadChannelParams(\n input: RunAgentInput,\n streamMode: \"run\" | \"connect\",\n replayCursor?: string | null,\n ): Record<string, unknown> {\n return streamMode === \"run\"\n ? {\n stream_mode: \"run\",\n run_id: input.runId,\n }\n : {\n stream_mode: \"connect\",\n last_seen_event_id:\n replayCursor === undefined\n ? this.getReconnectCursor(input)\n : replayCursor,\n };\n }\n\n private getLastSeenEventId(threadId: string): string | null {\n return this.sharedState.lastSeenEventIds.get(threadId) ?? null;\n }\n\n private getReconnectCursor(input: RunAgentInput): string | null {\n return this.getLastSeenEventId(input.threadId);\n }\n\n /**\n * Drop the cached `lastSeenEventId` cursor for `threadId` so the\n * next connect to that topic asks the gateway for a full historical\n * replay (rather than resuming). Public because\n * `RunHandler.connectAgent` calls it on a detected thread switch\n * to rebuild local state from scratch, and skips it on same-thread\n * churn so the gateway can resume.\n */\n public clearReconnectCursor(threadId: string): void {\n this.sharedState.lastSeenEventIds.delete(threadId);\n }\n\n private updateLastSeenEventId(threadId: string, payload: BaseEvent): void {\n const eventId = this.readEventId(payload);\n if (!eventId) {\n return;\n }\n\n this.advanceLastSeenEventId(threadId, eventId);\n }\n\n private updateLastSeenEventIdFromControl(\n threadId: string,\n payload: unknown,\n controlCursor: ControlCursorState,\n ): void {\n const eventId = this.readControlEventId(payload);\n if (!eventId) {\n return;\n }\n\n // An older gateway repeats the join's history checkpoint on every control\n // frame, also on stream_idle after live events moved past it. A repeat is\n // stale and must not replace the newer event cursor, or the next join\n // replays those live events again. After replay_failed the gateway repeats\n // the prior cursor on purpose, so the next join retries the failed history.\n if (eventId === controlCursor.applied && !controlCursor.replayFailed) {\n return;\n }\n\n controlCursor.applied = eventId;\n this.advanceLastSeenEventId(threadId, eventId);\n }\n\n private advanceLastSeenEventId(threadId: string, eventId: string): void {\n this.sharedState.lastSeenEventIds.set(threadId, eventId);\n }\n\n private readEventId(payload: BaseEvent): string | null {\n const metadata = (payload as BaseEvent & { metadata?: unknown }).metadata;\n if (!metadata || typeof metadata !== \"object\") {\n return null;\n }\n\n const eventMetadata = metadata as { cpki_event_id?: unknown };\n return this.readDurableEventId(eventMetadata.cpki_event_id);\n }\n\n private readControlEventId(payload: unknown): string | null {\n if (!payload || typeof payload !== \"object\") {\n return null;\n }\n\n const controlPayload = payload as {\n latestEventId?: unknown;\n latest_event_id?: unknown;\n };\n const latestEventId =\n controlPayload.latestEventId ?? controlPayload.latest_event_id;\n return this.readDurableEventId(latestEventId);\n }\n\n private readDurableEventId(eventId: unknown): string | null {\n if (typeof eventId !== \"string\" || eventId.trim() === \"\") {\n return null;\n }\n\n return eventId.startsWith(\"cpki_ingested\") ? null : eventId;\n }\n\n private canFallbackCompleteConnect(\n streamIdlePayload: unknown,\n reconnectCursor: string | null,\n latestObservedReplayCursor: string | null,\n ): boolean {\n const idleCursor = this.readControlEventId(streamIdlePayload);\n if (!idleCursor) {\n return true;\n }\n\n return (\n idleCursor === reconnectCursor ||\n idleCursor === latestObservedReplayCursor\n );\n }\n\n private applyCanonicalRunIdentity(\n input: RunAgentInput,\n credentials: ThreadJoinCredentials,\n options: { fallbackToInputRunId: boolean },\n ): RunAgentInput {\n this.threadId = credentials.threadId;\n const runId =\n credentials.runId ?? (options.fallbackToInputRunId ? input.runId : null);\n this.canonicalRunId = runId;\n\n return {\n ...input,\n threadId: credentials.threadId,\n ...(runId === null ? {} : { runId }),\n };\n }\n\n private isSocketReconnectExhaustedError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"WebSocket connection failed after\")\n );\n }\n}\n","/**\n * Build the error for a failed runtime `/info` response, folding in whatever\n * explanation the runtime sent back.\n *\n * The status alone cannot distinguish a wrong `runtimeUrl` from a transport\n * mismatch, so the runtime answers the latter with a body naming the cause\n * (see the handler's `single_route_envelope_against_multi_route_runtime`\n * diagnostic). Discarding that body — as every `/info` caller used to — left\n * the developer with a bare 404 and nothing to act on (OSS-882).\n *\n * A body that isn't JSON, or carries no string `message`, contributes nothing:\n * the status is then the whole error.\n */\nexport async function runtimeInfoError(\n response: Response,\n): Promise<RuntimeInfoRequestError> {\n const base = `Runtime info request failed with status ${response.status}`;\n\n let detail: string | undefined;\n try {\n const body: unknown = await response.clone().json();\n const message = (body as { message?: unknown } | null)?.message;\n if (typeof message === \"string\" && message.trim().length > 0) {\n detail = message.trim();\n }\n } catch {\n // Unparseable or already-consumed body — fall back to the status.\n }\n\n const error = new Error(\n detail ? `${base}: ${detail}` : base,\n ) as RuntimeInfoRequestError;\n error.runtimeInfoStatus = response.status;\n return error;\n}\n\nexport interface RuntimeInfoRequestError extends Error {\n runtimeInfoStatus: number;\n}\n\nexport function isRuntimeInfoRequestError(\n error: unknown,\n): error is RuntimeInfoRequestError {\n return (\n typeof error === \"object\" &&\n error !== null &&\n typeof (error as { runtimeInfoStatus?: unknown }).runtimeInfoStatus ===\n \"number\"\n );\n}\n","import type { Message } from \"@ag-ui/client\";\n\n/**\n * Rewrites the message list a runtime agent sends on each run.\n *\n * CopilotKit sends the whole thread on every request. When the backend already\n * stores the conversation (a LangGraph checkpointer, a Mastra memory store, a\n * Strands `SessionManager`, an Agent Framework chat history provider), that\n * history is dead weight: the payload grows without bound, and an agent that\n * merges the inbound list with its own store can show the model every turn\n * twice. See https://github.com/CopilotKit/CopilotKit/issues/1482.\n *\n * The filter runs on the outbound payload only. It never touches the messages\n * the UI renders, so trimming here does not shorten the visible transcript.\n *\n * Return the messages to send. Returning an empty array is valid and means\n * \"send nothing but the run metadata\".\n *\n * @param messages - The thread as the client holds it, in order, with\n * `activity`-role messages already removed.\n * @param context - Which agent is about to run.\n */\nexport type CopilotKitMessageFilter = (\n messages: Message[],\n context: { agentId: string },\n) => Message[];\n\n/**\n * The string ids of a message's tool calls.\n *\n * Malformed entries are ignored rather than thrown on, matching\n * {@link ɵkeepToolResultsWithCalls}: a null or primitive entry, or an entry\n * without a string `id`, opens no pair instead of failing the repair.\n */\nfunction toolCallIdsOf(message: Message): string[] {\n const calls = (message as { toolCalls?: unknown }).toolCalls;\n if (!Array.isArray(calls)) return [];\n const ids: string[] = [];\n for (const call of calls) {\n if (typeof call !== \"object\" || call === null) continue;\n const id = (call as { id?: unknown }).id;\n if (typeof id === \"string\" && id) ids.push(id);\n }\n return ids;\n}\n\nfunction resultCallIdOf(message: Message): string | undefined {\n if (message.role !== \"tool\") return undefined;\n return (message as { toolCallId?: string }).toolCallId;\n}\n\n/**\n * Repair the tool-call pairs a filter broke.\n *\n * Every provider rejects a half pair. A tool result whose call is gone reads as\n * a reply to nothing, and an assistant tool call whose result is gone leaves\n * the turn unanswered — the failure reporters hit on #1482 when a trimmed\n * history landed mid-HITL and Anthropic answered \"a tool result is expected\".\n * A filter written as `messages.slice(-1)` cannot know this, so the repair runs\n * for every filter rather than being something each caller opts into.\n *\n * Both repairs restore, never discard, and both are anchored on the untrimmed\n * thread:\n *\n * - A kept tool result whose assistant call was trimmed away gets that call put\n * back in front of it. Dropping the result instead would be protocol-safe and\n * semantically wrong: on a human-in-the-loop turn the result IS the new\n * information, and a backend that already holds the call would be asked to\n * resume with nothing.\n * - A kept assistant call whose result was trimmed gets that result restored,\n * placed directly after the call.\n *\n * Restoring a call pulls in every result for that call, not only the one the\n * filter kept. Providers reject an assistant turn with a parallel tool call\n * left unanswered, so a half-answered set is as invalid as a missing one.\n *\n * A call with no result anywhere in `full` is left alone. That is an open call\n * (a pending frontend tool, an unanswered interrupt), not a broken pair. A\n * result whose call is nowhere in `full` is left alone too: it was already\n * unpaired before the filter ran, so it is not this function's to fix.\n *\n * The filter's own ordering is preserved. Restorations are the only insertions,\n * and messages the filter synthesized (absent from `full`) pass through\n * untouched.\n */\nexport function ɵrepairToolCallPairs(\n kept: Message[],\n full: Message[],\n): Message[] {\n // Pair each result with the nearest unmatched call before it. Providers\n // often reuse call ids across turns, so an id alone cannot identify a pair.\n // The untrimmed thread supplies the order the filter may have removed.\n const pendingIssuersByCallId = new Map<string, Message[]>();\n const issuerIdToResultsByCallId = new Map<string, Map<string, Message[]>>();\n const resultIdToIssuer = new Map<string, Message>();\n for (const message of full) {\n for (const callId of toolCallIdsOf(message)) {\n push(pendingIssuersByCallId, callId, message);\n }\n const resultCallId = resultCallIdOf(message);\n if (resultCallId !== undefined) {\n const pendingIssuers = pendingIssuersByCallId.get(resultCallId);\n const issuer = pendingIssuers?.pop();\n if (issuer) {\n resultIdToIssuer.set(message.id, issuer);\n let resultsByCallId = issuerIdToResultsByCallId.get(issuer.id);\n if (!resultsByCallId) {\n resultsByCallId = new Map();\n issuerIdToResultsByCallId.set(issuer.id, resultsByCallId);\n }\n push(resultsByCallId, resultCallId, message);\n }\n }\n }\n\n const repaired: Message[] = [];\n const emitted = new Set<string>();\n const expandedMessages = new Set<Message>();\n\n const emit = (message: Message) => {\n if (emitted.has(message.id)) return;\n emitted.add(message.id);\n repaired.push(message);\n };\n\n /** Emit an assistant turn together with every result it is owed. */\n const emitWithResults = (message: Message) => {\n emit(message);\n if (expandedMessages.has(message)) return;\n expandedMessages.add(message);\n const resultsByCallId = issuerIdToResultsByCallId.get(message.id);\n for (const callId of toolCallIdsOf(message)) {\n for (const result of resultsByCallId?.get(callId) ?? []) emit(result);\n }\n };\n\n for (const message of kept) {\n const resultCallId = resultCallIdOf(message);\n if (resultCallId === undefined) {\n emitWithResults(message);\n continue;\n }\n\n const issuer = resultIdToIssuer.get(message.id);\n if (issuer) {\n // Emits the issuer first, then this result along with its siblings.\n emitWithResults(issuer);\n continue;\n }\n emit(message);\n }\n\n return repaired;\n}\n\n/**\n * Move each detached tool result to sit behind the assistant call that issued\n * it — usually back to an earlier call, and forward only when no earlier call\n * has its id and exactly one call in the list does — and change nothing else.\n * Used for unfiltered sends, and on a configured filter's output only when\n * {@link ɵrepairToolCallPairs}, which filtered sends go through otherwise,\n * throws.\n *\n * The client store can detach a tool result from its call on its own: when a\n * backend's `MESSAGES_SNAPSHOT` carries a tool message under a different id\n * than the streamed `TOOL_CALL_RESULT`, the `@ag-ui/client` merge drops the\n * copy placed after its call and appends the snapshot's copy at the end,\n * leaving `assistant(tool_call), assistant(text), tool(result)`. A backend that\n * rebuilds its state from that payload discards every result it cannot pair.\n *\n * The pairing rule mirrors the `@ag-ui/client` snapshot pass\n * (ag-ui-protocol/ag-ui#3114):\n *\n * - Everything is by list position. The same object or id appearing twice is\n * two independent slots, including an assistant call the merge duplicated,\n * so a duplicated call can be left unanswered. Nothing is dropped,\n * deduplicated, or added, and only tool-role messages ever change position.\n * - Transparent entries are `activity` and `reasoning` messages and anything\n * that is not a plain object (`null`, arrays, primitives). They are never\n * the anchor, never separate a call from its result, and stay in place.\n * Reasoning stored between a call and its result is the next step's: in a\n * multi-step turn whose calls share one assistant message, Mastra leaves\n * `assistant(c1, c2), tool(c1), reasoning, tool(c2)`. Moving the result in\n * front of it leaves the reasoning trailing, and Mastra drops it.\n * - The anchor is the last non-transparent message so far that is not `tool`.\n * Each tool call an assistant issues opens a slot for its call id, and a\n * result pairs with slots for its `toolCallId` alone. `subagentRunId` is\n * ignored: results CopilotKit creates itself (frontend tool results,\n * interrupt responses) do not carry one, and on a result it names the run\n * that executed the tool, which may differ from the run that issued the\n * call. Known limitation: a parent call and a subagent call that reuse one\n * id are indistinguishable, so their drifted results can be swapped.\n * - Pass 1, left to right: a result with an open slot issued at the anchor is\n * in place; it takes that slot and stays put. A result with an open slot\n * issued earlier is detached. A result with no slot for its id issued\n * earlier at all is early. Any other result — every earlier slot for its id\n * already answered — stays put. Detached results take no slot in this\n * pass: they could only ever take a slot issued before the current anchor,\n * which no later in-place result can want.\n * - Pass 2, backward, per id: the detached results, from the newest back,\n * each take the newest still-open slot issued before them; one that finds\n * none stays put. So when several results for a reused id (providers reuse\n * `call_0` every turn) are all detached, they keep their stored order\n * across the calls, and a later turn's lone result goes to the later call\n * rather than to an earlier one that was abandoned.\n * - Pass 3, forward, per id: an early result moves forward only when its id\n * is unambiguous — exactly one call slot in the whole list has it, that\n * slot is issued after the result, and it is still open after passes 1-2.\n * The first early result for the id, left to right, takes it; any other\n * early result for that id stays put. This repairs a result whose call\n * was re-issued after it (a snapshot that re-ids the assistant message but\n * keeps the result's id). With a reused id (providers reuse `call_0` every\n * turn) nothing moves forward: in `[t0, t1, a1(c), user, a2(c)]` nothing\n * says t1 answers a2, and a2 may be a pending call (a frontend tool, an\n * interrupt, a human-in-the-loop call waiting on the user). Only early\n * results move forward: an extra result for a call that is already\n * answered never does.\n * - A moved result goes behind its issuer, after the tool and transparent\n * entries already following it, but in front of any reasoning among those\n * transparent entries: reasoning belongs to the message after it, so a\n * moved result never lands between a reasoning message and its owner.\n * Results moved behind one issuer keep their stored order. Any other\n * message between a call and its result separates them, so a\n * backward-moved result moves before it and a forward-moved result moves\n * past it.\n * - The rule cannot tell a duplicate result from a detached one. A second\n * result for an already-answered call moves back to an older still-open\n * slot for its id if there is one, even across user turns; it never moves\n * forward.\n * - Malformed entries are ignored rather than thrown on. Non-array\n * `toolCalls`, call entries without a string `id`, and results without a\n * string `toolCallId` open or take no slot.\n *\n * Returns `messages` itself when nothing moved.\n */\nexport function ɵkeepToolResultsWithCalls(messages: Message[]): Message[] {\n type Slot = { issuer: number; open: boolean };\n // Per call id, the slots its calls opened, in stored order.\n const slots = new Map<string, Slot[]>();\n // Per call id, how many of its slots are still open.\n const openCount = new Map<string, number>();\n const close = (callId: string, slot: Slot) => {\n slot.open = false;\n openCount.set(callId, openCount.get(callId)! - 1);\n };\n // Per call id, the detached results, in stored order.\n const detached = new Map<string, number[]>();\n // Per call id, the results with no slot for their id issued before them at\n // all, in stored order: the only results that may move forward.\n const early = new Map<string, number[]>();\n let anchor = -1;\n\n for (let index = 0; index < messages.length; index++) {\n const message: unknown = messages[index];\n if (isTransparent(message)) continue;\n const role = roleOf(message);\n\n if (role !== \"tool\") {\n anchor = index;\n const calls =\n role === \"assistant\"\n ? (message as { toolCalls?: unknown }).toolCalls\n : undefined;\n if (!Array.isArray(calls)) continue;\n for (const call of calls) {\n if (typeof call !== \"object\" || call === null) continue;\n const callId = (call as { id?: unknown }).id;\n if (typeof callId !== \"string\") continue;\n push(slots, callId, { issuer: index, open: true });\n openCount.set(callId, (openCount.get(callId) ?? 0) + 1);\n }\n continue;\n }\n\n const callId = (message as { toolCallId?: unknown }).toolCallId;\n if (typeof callId !== \"string\") continue;\n const forId = slots.get(callId);\n if (!forId) {\n push(early, callId, index);\n continue;\n }\n\n // Slots open in stored order and the anchor is the newest issuer, so the\n // anchor's slots sit at the tail: scan only those.\n let atAnchor: Slot | undefined;\n for (let s = forId.length - 1; s >= 0; s--) {\n const slot = forId[s]!;\n if (slot.issuer !== anchor) break;\n if (slot.open) atAnchor = slot;\n }\n if (atAnchor) {\n close(callId, atAnchor);\n continue;\n }\n // Every earlier slot for this id already answered: an extra or stale\n // result. It stays, so it cannot answer a later pending call.\n if (openCount.get(callId)! > 0) push(detached, callId, index);\n }\n\n const movedBehind = new Map<number, number[]>();\n const moved = new Set<number>();\n const take = (callId: string, slot: Slot, index: number) => {\n close(callId, slot);\n moved.add(index);\n push(movedBehind, slot.issuer, index);\n };\n\n for (const [callId, results] of detached) {\n const forId = slots.get(callId)!;\n // Results go newest first and each needs a slot issued before it, so the\n // newest usable slot only ever moves left: one cursor per id keeps the\n // pass linear even when every turn reuses the same id.\n let s = forId.length - 1;\n for (let r = results.length - 1; r >= 0; r--) {\n const index = results[r]!;\n while (s >= 0 && (!forId[s]!.open || forId[s]!.issuer >= index)) s--;\n // One that finds none had an earlier call for its id, so it stays.\n if (s < 0) break;\n take(callId, forId[s]!, index);\n }\n }\n\n for (const [callId, results] of early) {\n // Only an unambiguous id moves forward: exactly one call slot for it in\n // the whole list. With a reused id (providers reuse `call_0` every turn)\n // nothing says which later call an early result answers, and guessing\n // can answer a pending human-in-the-loop call with another turn's\n // result. Every slot is issued after an early result (none came before\n // it), so the one slot only has to be still open; the first early\n // result takes it and the rest stay put.\n const forId = slots.get(callId);\n if (forId?.length !== 1 || !forId[0]!.open) continue;\n take(callId, forId[0]!, results[0]!);\n }\n\n if (moved.size === 0) return messages;\n\n const result: Message[] = [];\n let openIssuer = -1;\n const flush = () => {\n const behind = movedBehind.get(openIssuer);\n if (!behind) return;\n // Converters give a reasoning message to the message after it, so the\n // moved results go in front of any reasoning among the transparent\n // entries at the tail, never between a reasoning message and its owner.\n // Activity is stripped before sending, so it is looked past too.\n let at = result.length;\n for (let tail = result.length - 1; tail >= 0; tail--) {\n if (!isTransparent(result[tail])) break;\n if (roleOf(result[tail]) === \"reasoning\") at = tail;\n }\n // Collected id by id, and within an id in pass order; emit them in\n // stored order.\n result.splice(\n at,\n 0,\n ...[...behind]\n .sort((a, b) => a - b)\n .map((index) => messages[index] as Message),\n );\n };\n for (let index = 0; index < messages.length; index++) {\n if (moved.has(index)) continue;\n const message: unknown = messages[index];\n if (!isTransparent(message) && roleOf(message) !== \"tool\") {\n flush();\n openIssuer = index;\n }\n result.push(message as Message);\n }\n flush();\n return result;\n}\n\nfunction push<K, T>(map: Map<K, T[]>, key: K, value: T): void {\n const list = map.get(key);\n if (list) list.push(value);\n else map.set(key, [value]);\n}\n\n/**\n * Activity and reasoning messages and anything that is not a plain object\n * (`null`, arrays, primitives) never anchor or separate.\n */\nfunction isTransparent(message: unknown): boolean {\n return (\n typeof message !== \"object\" ||\n message === null ||\n Array.isArray(message) ||\n (message as { role?: unknown }).role === \"activity\" ||\n (message as { role?: unknown }).role === \"reasoning\"\n );\n}\n\nfunction roleOf(message: unknown): unknown {\n if (typeof message !== \"object\" || message === null) return undefined;\n return (message as { role?: unknown }).role;\n}\n","import type {\n AbstractAgent,\n AgentCapabilities,\n AgentSubscriber,\n BaseEvent,\n HttpAgentConfig,\n Message,\n RunAgentInput,\n RunAgentParameters,\n RunAgentResult,\n} from \"@ag-ui/client\";\nimport {\n EventType,\n HttpAgent,\n runHttpRequest,\n structuredClone_,\n transformHttpEventStream,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { EMPTY, defer, from, of } from \"rxjs\";\nimport {\n catchError,\n concatMap,\n concatWith,\n finalize,\n switchMap,\n} from \"rxjs/operators\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport type {\n IntelligenceRuntimeInfo,\n RuntimeInfo,\n RuntimeMode,\n ResolvedDebugConfig,\n} from \"@copilotkit/shared\";\nimport { IntelligenceAgent } from \"./intelligence-agent\";\nimport type { CopilotRuntimeTransport } from \"./types\";\nimport { runtimeInfoError } from \"./utils/runtime-info-error\";\nimport type { RuntimeRequestInit } from \"./utils/runtime-request\";\nimport type { ConnectionReplayLifecycle } from \"./utils/connect-replay\";\nimport { ɵconnectWithoutEventVerification } from \"./utils/connect-replay\";\nimport type { CopilotKitMessageFilter } from \"./core/message-filter\";\nimport {\n ɵkeepToolResultsWithCalls,\n ɵrepairToolCallPairs,\n} from \"./core/message-filter\";\n\ntype ResolvedRuntimeMode = RuntimeMode | \"pending\";\n\ninterface RunnableAgent {\n connect(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent>;\n run(input: RunAgentInput): Observable<BaseEvent>;\n}\n\nfunction hasHeaders(\n agent: AbstractAgent,\n): agent is AbstractAgent & { headers?: Record<string, string> } {\n return \"headers\" in agent;\n}\n\nfunction hasCredentials(\n agent: AbstractAgent,\n): agent is AbstractAgent & { credentials?: RequestCredentials } {\n return \"credentials\" in agent;\n}\n\nfunction isZodError(error: unknown): boolean {\n return (\n error !== null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n (error as { name: string }).name === \"ZodError\"\n );\n}\n\nfunction isAbortError(error: unknown): boolean {\n return (\n (error instanceof DOMException || error instanceof Error) &&\n (error as Error).name === \"AbortError\"\n );\n}\n\nfunction withAbortErrorHandling(\n observable: Observable<BaseEvent>,\n): Observable<BaseEvent> {\n return observable.pipe(\n catchError((error) => {\n if (isZodError(error) || isAbortError(error)) {\n return EMPTY;\n }\n throw error;\n }),\n );\n}\n\nexport interface ProxiedCopilotRuntimeAgentConfig extends Omit<\n HttpAgentConfig,\n \"url\"\n> {\n runtimeUrl?: string;\n transport?: CopilotRuntimeTransport;\n credentials?: RequestCredentials;\n runtimeMode?: ResolvedRuntimeMode;\n intelligence?: IntelligenceRuntimeInfo;\n capabilities?: AgentCapabilities;\n debug?: ResolvedDebugConfig;\n /**\n * When set, runtime requests (HTTP path, single-route envelope, intelligence\n * delegate) are routed to this agent on the runtime instead of `agentId`.\n * The local `agentId` remains the registry key used for subscriber\n * bookkeeping; only outbound routing is overridden.\n */\n runtimeAgentId?: string;\n /**\n * Rewrites the outbound message list on every run. See\n * {@link CopilotKitMessageFilter}. Not applied in Intelligence mode.\n */\n messageFilter?: CopilotKitMessageFilter;\n}\n\nexport class ProxiedCopilotRuntimeAgent extends HttpAgent {\n runtimeUrl?: string;\n credentials?: RequestCredentials;\n // `readonly` because `super.url` is baked at construction; mutating\n // `runtimeAgentId` post-construction would desync the REST `run` URL\n // (already captured) from `routedAgentId()` (consulted per-call by\n // stop/connect/single-route paths).\n readonly runtimeAgentId?: string;\n private transport: CopilotRuntimeTransport;\n /**\n * The runtime URL exactly as the caller supplied it. `runtimeUrl` is the\n * slash-stripped form used for path joins; the single-route endpoint (run,\n * connect, stop, info envelopes) is this verbatim value, because a trailing\n * slash can select a different proxy location.\n */\n private readonly runtimeEndpointUrl?: string;\n private singleEndpointUrl?: string;\n private runtimeMode: ResolvedRuntimeMode;\n private intelligence?: IntelligenceRuntimeInfo;\n private _capabilities?: AgentCapabilities;\n private delegate?: AbstractAgent;\n private runtimeInfoPromise?: Promise<void>;\n private connectionAttempt?: object;\n private _messageFilter?: CopilotKitMessageFilter;\n /**\n * The HTTP `run` this agent started and has not yet seen finish, as the\n * exact `{ threadId, runId }` it POSTed. `abortRun` narrows `/stop` to this\n * run only while `threadId` still matches: `threadId` is a public field the\n * host may reassign under a live run, and a runId from another thread must\n * not be sent as if it were this thread's. Released when the run stream\n * finalizes, cleared on `connect` (a reconnected thread may run under a\n * runId this client never saw) and never copied by `clone`. Without a\n * provable active run the stop stays thread-wide.\n */\n private activeRun?: { threadId: string; runId: string };\n\n constructor(config: ProxiedCopilotRuntimeAgentConfig) {\n const normalizedRuntimeUrl = config.runtimeUrl\n ? config.runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n const transport = config.transport ?? \"auto\";\n const routedId = config.runtimeAgentId ?? config.agentId ?? \"\";\n // The single endpoint is the caller's URL exactly as given: a trailing\n // slash can select a different proxy location, so it must survive. Only\n // the path joins (`/agent/…`, `/info`) use the slash-stripped form.\n const runUrl =\n transport === \"single\"\n ? (config.runtimeUrl ?? \"\")\n : `${normalizedRuntimeUrl ?? config.runtimeUrl}/agent/${encodeURIComponent(routedId)}/run`;\n\n if (!runUrl) {\n throw new Error(\n \"ProxiedCopilotRuntimeAgent requires a runtimeUrl when transport is set to 'single'.\",\n );\n }\n\n super({\n ...config,\n url: runUrl,\n });\n this.runtimeUrl = normalizedRuntimeUrl ?? config.runtimeUrl;\n this.runtimeEndpointUrl = config.runtimeUrl;\n this.credentials = config.credentials;\n this.runtimeAgentId = config.runtimeAgentId;\n this.transport = transport;\n this.runtimeMode = config.runtimeMode ?? RUNTIME_MODE_SSE;\n this.intelligence = config.intelligence;\n this._capabilities = config.capabilities;\n this._messageFilter = config.messageFilter;\n if (config.debug) {\n this.debug = config.debug;\n }\n if (this.transport === \"single\") {\n this.singleEndpointUrl = this.runtimeEndpointUrl;\n }\n }\n\n /**\n * Adopt the runtime mode a fresh `/info` just reported.\n *\n * A live proxy outlives the runtime configuration that minted it: a\n * redeploy, an env-var change or a rollback can flip `intelligence` → `sse`\n * under a page that is already open. The registry preserves the proxy across\n * that re-sync on purpose — it is backing an open conversation — so the new\n * mode is pushed onto the instance here instead of replacing it.\n *\n * Without this the mode was decided once, at construction, and `run()` kept\n * taking the delegate path against a runtime serving plain SSE, where\n * `response.json()` on a `text/event-stream` body throws for the rest of the\n * page's life. See #7130.\n *\n * A delegate built for the old mode is torn down: it speaks a protocol the\n * runtime no longer serves, and it may be holding a websocket open. The\n * memoized `/info` promise goes with it — it answered for the old\n * configuration, so a later `ensureRuntimeConfiguration()` must re-ask\n * rather than treat that answer as current.\n *\n * Only `wsUrl` is compared on the Intelligence metadata, because that is the\n * one field the delegate bakes in at construction.\n */\n adoptRuntimeMode(\n runtimeMode: ResolvedRuntimeMode,\n intelligence: IntelligenceRuntimeInfo | undefined,\n ): void {\n const unchanged =\n this.runtimeMode === runtimeMode &&\n this.intelligence?.wsUrl === intelligence?.wsUrl;\n\n this.runtimeMode = runtimeMode;\n this.intelligence = intelligence;\n\n if (unchanged) {\n return;\n }\n this.connectionAttempt = undefined;\n this.runtimeInfoPromise = undefined;\n const staleDelegate = this.delegate;\n this.delegate = undefined;\n if (staleDelegate) {\n staleDelegate.abortRun();\n }\n // SSE also owns a pipeline, even though it has no delegate.\n void this.detachActiveRun();\n }\n\n /**\n * The agent id used for outbound runtime requests — `runtimeAgentId` when\n * set (manually-registered proxy), otherwise `agentId` (registry id\n * matches runtime id). Subscriber bookkeeping keeps using `agentId`\n * directly.\n *\n * Throws when both are unset: a proxy reaching an HTTP path with no\n * routable id is a bug, and a missing id would otherwise produce a\n * malformed `/agent//run` or `/agent/undefined/connect` URL silently.\n */\n private routedAgentId(): string {\n const id = this.runtimeAgentId ?? this.agentId;\n if (!id) {\n throw new Error(\n \"ProxiedCopilotRuntimeAgent: cannot make a runtime request without an agentId or runtimeAgentId.\",\n );\n }\n return id;\n }\n\n get capabilities(): AgentCapabilities | undefined {\n return this._capabilities;\n }\n\n /**\n * The filter applied to the outbound message list on every run.\n *\n * Registry-owned. `AgentRegistry` writes it whenever the core-level filter\n * changes, so an agent discovered before the app configured one still picks\n * it up — and so a value written here by hand is replaced on the registry's\n * next sweep. Configure it through `CopilotKitCore` instead.\n */\n get messageFilter(): CopilotKitMessageFilter | undefined {\n return this._messageFilter;\n }\n\n set messageFilter(filter: CopilotKitMessageFilter | undefined) {\n this._messageFilter = filter;\n }\n\n /**\n * Build the outbound payload, keeping every tool result with the call that\n * issued it.\n *\n * - **No filter** (or a filter whose output is unusable, which falls back to\n * the full thread): `ɵkeepToolResultsWithCalls` re-places tool results\n * that drifted from their call and changes nothing else. The client store\n * can detach them on its own when a `MESSAGES_SNAPSHOT` re-ids a tool\n * message, and a backend that rebuilds state from such a payload drops\n * every result it cannot pair.\n * - **Filter**: `ɵrepairToolCallPairs(kept, full)` restores the call or the\n * results a filter trimmed. Its known limitations are tracked in\n * https://github.com/CopilotKit/CopilotKit/issues/7891.\n * - **Filter repair throws**: the filter's output goes through\n * `ɵkeepToolResultsWithCalls` instead, keeping its trimming and\n * redaction; if that throws too, the output is sent as is.\n *\n * **Called from the HTTP paths only, and that placement is the Intelligence\n * exemption.** An earlier revision applied the filter in\n * `prepareRunAgentInput`, which runs before the runtime mode is resolved:\n * with the default `\"auto\"` transport, or on a proxy still `\"pending\"` its\n * first `/info`, `run()` prepared the input, *then* resolved the mode, then\n * handed that already-filtered input to `#runViaDelegate` — so a managed\n * runtime received a truncated thread despite the exemption. Filtering here\n * makes that unreachable by construction: `#runViaHttp` and\n * `#connectViaHttp` are only entered once the mode is known not to be\n * Intelligence. Do not move this back up the call chain.\n *\n * The managed runtime is the store of record for the thread — the threads\n * drawer and the Slack transcript read from it — so a client-side truncation\n * there has a blast radius nobody asked for. Every reporter on #1482 is\n * self-hosted.\n *\n * `prepareRunAgentInput` has already deep-cloned the thread and stripped\n * `activity` messages by the time the input reaches here, so the filter\n * cannot reach the messages the UI renders no matter what it does with the\n * array it is handed. The filter gets a *second* deep clone on top of that,\n * because `input.messages` is also the repair baseline and the untrimmed\n * fallback: sharing the message objects let a filter that rewrote the tool\n * call id of an assistant message it dropped hide that issuer from the\n * repair, and the kept tool result then went out orphaned — a payload the\n * provider rejects, which is exactly the failure this whole mechanism\n * exists to prevent.\n */\n #prepareOutboundMessages(input: RunAgentInput): RunAgentInput {\n const full = input.messages;\n const kept = this.#applyMessageFilter(full);\n\n // The pairing step is a best-effort fix-up, so it is guarded on its own\n // and kept apart from the filter call: a bug here is reported as the\n // repair failing, never as the app's filter failing. A successful filter\n // repair changes more than pairing: it can add stored calls and results,\n // reorder messages, drop messages that share an id or results under a\n // reused call id, and replace a filter's edited copies with the stored\n // originals (see above). If the repair throws, the payload goes out as\n // it would have without it — the input unchanged when nothing was\n // filtered, the filter's output with only drifted results moved when a\n // filter ran.\n const agentId = this.agentId ?? \"\";\n try {\n const messages =\n kept === undefined\n ? ɵkeepToolResultsWithCalls(full)\n : ɵrepairToolCallPairs(kept, full);\n return { ...input, messages };\n } catch (error) {\n if (kept === undefined) {\n console.warn(\n `ProxiedCopilotRuntimeAgent: tool-call repair failed for agent \"${agentId}\"; sending the message history unrepaired instead.`,\n error,\n );\n return input;\n }\n try {\n const messages = ɵkeepToolResultsWithCalls(kept);\n console.warn(\n `ProxiedCopilotRuntimeAgent: tool-call repair failed for agent \"${agentId}\"; sending the filtered message history with only drifted tool results moved instead.`,\n error,\n );\n return { ...input, messages };\n } catch (moveError) {\n console.warn(\n `ProxiedCopilotRuntimeAgent: tool-call repair failed for agent \"${agentId}\"; sending the filtered message history unrepaired instead.`,\n error,\n moveError,\n );\n return { ...input, messages: kept };\n }\n }\n }\n\n /**\n * Run the configured filter. Returns `undefined` when there is no filter,\n * copying the thread for it fails, or the filter's output cannot be used,\n * meaning \"send the full thread\".\n *\n * A filter that throws, returns a non-array, or returns an array with an\n * entry that is not a message object (a hole or a nested array included)\n * falls back to the untrimmed thread rather than failing the run. Trimming\n * is an optimization, and taking the user's message down with it would be\n * the worse outcome; the warning is what surfaces the bug.\n */\n #applyMessageFilter(full: Message[]): Message[] | undefined {\n const filter = this._messageFilter;\n if (!filter) return undefined;\n\n // Copied outside the filter's guard, so a thread that cannot be cloned is\n // reported as that, not as the app's filter failing.\n let copy: Message[];\n try {\n copy = structuredClone_(full);\n } catch (error) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: could not copy the message history for messageFilter; sending the full message history instead.\",\n error,\n );\n return undefined;\n }\n\n let kept: unknown;\n try {\n kept = filter(copy, { agentId: this.agentId ?? \"\" });\n } catch (error) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: messageFilter failed; sending the full message history instead.\",\n error,\n );\n return undefined;\n }\n if (!Array.isArray(kept)) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: messageFilter returned a non-array value; sending the full message history instead.\",\n );\n return undefined;\n }\n // An index loop, not `every`: `every` skips the holes of a sparse array.\n for (let index = 0; index < kept.length; index++) {\n const entry: unknown = kept[index];\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: messageFilter returned an entry that is not a message; sending the full message history instead.\",\n );\n return undefined;\n }\n }\n return kept as Message[];\n }\n\n override requestInit(input: RunAgentInput): RequestInit {\n const baseInit = super.requestInit(input);\n return {\n ...baseInit,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n };\n }\n\n async getCapabilities(): Promise<AgentCapabilities> {\n return this._capabilities ?? {};\n }\n\n override async detachActiveRun(): Promise<void> {\n this.connectionAttempt = undefined;\n this.isRunning = false;\n const delegateDetach = this.delegate?.detachActiveRun();\n const proxyDetach = super.detachActiveRun();\n await Promise.all([delegateDetach, proxyDetach]);\n }\n\n abortRun(): void {\n if (this.delegate) {\n this.syncDelegate(this.delegate);\n this.delegate.abortRun();\n // Also detach the proxy's own runAgent pipeline so the proxy's\n // isRunning resets and onRunFinalized fires even if the delegate's\n // observable doesn't propagate a clean completion.\n void this.detachActiveRun();\n return;\n }\n\n if (!this.agentId || !this.threadId) {\n return;\n }\n\n if (typeof fetch === \"undefined\") {\n return;\n }\n\n const routedId = this.routedAgentId();\n const runId =\n this.activeRun?.threadId === this.threadId\n ? this.activeRun.runId\n : undefined;\n\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n return;\n }\n\n const headers = new Headers({\n ...this.headers,\n \"Content-Type\": \"application/json\",\n });\n void this.fetch(this.singleEndpointUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n method: \"agent/stop\",\n params: {\n agentId: routedId,\n threadId: this.threadId,\n },\n ...(runId === undefined ? {} : { body: { runId } }),\n }),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n // A stop is fire-and-forget: its failure shouldn't arm the runtime\n // reachability watchdog or trigger a reachability probe.\n ɵruntimeRequest: { nonCritical: true },\n } as RuntimeRequestInit).catch((error) => {\n console.error(\"ProxiedCopilotRuntimeAgent: stop request failed\", error);\n });\n return;\n }\n\n if (!this.runtimeUrl) {\n return;\n }\n\n const stopPath = `${this.runtimeUrl}/agent/${encodeURIComponent(routedId)}/stop/${encodeURIComponent(this.threadId)}`;\n const origin =\n typeof window !== \"undefined\" && window.location\n ? window.location.origin\n : \"http://localhost\";\n const base = new URL(this.runtimeUrl, origin);\n const stopUrl = new URL(stopPath, base);\n\n void this.fetch(stopUrl.toString(), {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n ...(runId === undefined ? {} : { body: JSON.stringify({ runId }) }),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n // A stop is fire-and-forget: its failure shouldn't arm the runtime\n // reachability watchdog or trigger a reachability probe.\n ɵruntimeRequest: { nonCritical: true },\n } as RuntimeRequestInit).catch((error) => {\n console.error(\"ProxiedCopilotRuntimeAgent: stop request failed\", error);\n });\n }\n\n override async connectAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n const detached = this.detachActiveRun();\n const connection = {};\n const threadId = this.threadId;\n this.connectionAttempt = connection;\n const isCurrentConnection = () =>\n this.connectionAttempt === connection && this.threadId === threadId;\n await detached;\n if (!isCurrentConnection()) return { result: undefined, newMessages: [] };\n await this.ensureRuntimeConfiguration();\n if (!isCurrentConnection()) return { result: undefined, newMessages: [] };\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) {\n // A self-hosted `/connect` response replays the thread's history, so it\n // can carry several past runs — including one that ended in RUN_ERROR\n // followed by a later RUN_STARTED. The base pipeline's `verifyEvents`\n // step enforces single-run lifecycle rules and rejects that stream\n // outright, so an existing thread never hydrates (#4943).\n return ɵconnectWithoutEventVerification(\n this,\n parameters,\n subscriber,\n (input, lifecycle) => this.connect(input, lifecycle),\n );\n }\n\n // Ensure the delegate exists and is synced with the proxy's current state.\n await this.resolveDelegate();\n if (!isCurrentConnection()) return { result: undefined, newMessages: [] };\n const delegate = this.delegate!;\n\n // Subscribe a bridging observer FIRST so it fires before the forwarded\n // UI subscribers. This keeps proxy.messages in sync with the delegate\n // in real-time — otherwise the UI re-renders (triggered by the\n // forwarded onMessagesChanged) but reads stale proxy.messages because\n // the final sync only happens after connectAgent resolves.\n const bridgeSub = delegate.subscribe({\n onMessagesChanged: () => {\n if (!isCurrentConnection()) return;\n this.setMessages([...delegate.messages]);\n },\n onStateChanged: () => {\n if (!isCurrentConnection()) return;\n this.setState({ ...delegate.state });\n },\n // Mirror isRunning so the proxy reflects the delegate's run lifecycle.\n // Without this, UI components read proxy.isRunning (always false) even\n // though the delegate is actively running, causing the stop button to\n // never appear.\n onRunInitialized: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = true;\n },\n onRunFinalized: () => {\n if (!isCurrentConnection()) return;\n this.pendingInterrupts = structuredClone_(delegate.pendingInterrupts);\n this.isRunning = false;\n },\n // Local exception (network error, deserialization failure, etc.)\n onRunFailed: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = false;\n },\n // The connect pipeline updates the delegate before forwarding events:\n // live errors clear busy, historical errors keep replay busy, and a\n // successor run can start while the same connection keeps listening.\n onRunErrorEvent: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = delegate.isRunning;\n },\n onRunStartedEvent: () => {\n if (!isCurrentConnection()) return;\n this.isRunning = delegate.isRunning;\n },\n });\n\n // Forward the proxy's subscribers to the delegate so that UI hooks\n // (e.g. useAgent's onMessagesChanged) receive real-time updates as\n // the delegate processes events during connectAgent.\n const forwardedSubs = [\n ...this.subscribers,\n ...(subscriber ? [subscriber] : []),\n ].map((subscriber) =>\n delegate.subscribe(\n new Proxy(subscriber, {\n get(target, property, receiver) {\n const callback = Reflect.get(target, property, receiver);\n if (typeof callback !== \"function\") return callback;\n return (...args: unknown[]) =>\n isCurrentConnection()\n ? Reflect.apply(callback, target, args)\n : undefined;\n },\n }),\n ),\n );\n\n try {\n const result = await delegate.connectAgent(parameters);\n\n // Final sync to guarantee the proxy reflects the delegate's end state.\n if (isCurrentConnection()) {\n this.setMessages([...delegate.messages]);\n this.setState({ ...delegate.state });\n this.pendingInterrupts = structuredClone_(delegate.pendingInterrupts);\n }\n\n return result;\n } finally {\n // Ensure the proxy's isRunning is reset — the bridging subscription\n // may have already handled this, but if the delegate threw before\n // firing onRunFinalized the proxy would be stuck in isRunning=true.\n if (isCurrentConnection()) this.isRunning = false;\n // Remove forwarded subscribers to avoid duplicate notifications on\n // subsequent calls (they'll be re-forwarded next time).\n bridgeSub.unsubscribe();\n for (const sub of forwardedSubs) {\n sub.unsubscribe();\n }\n }\n }\n\n connect(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent> {\n if (\n this.runtimeMode === \"pending\" ||\n (this.transport === \"auto\" &&\n this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE)\n ) {\n return defer(() => from(this.ensureRuntimeConfiguration())).pipe(\n switchMap(() => this.connect(input, lifecycle)),\n );\n }\n if (this.runtimeMode === RUNTIME_MODE_INTELLIGENCE) {\n return this.#connectViaDelegate(input, lifecycle);\n }\n return this.#connectViaHttp(input);\n }\n\n public run(input: RunAgentInput): Observable<BaseEvent> {\n if (\n this.runtimeMode === \"pending\" ||\n (this.transport === \"auto\" &&\n this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE)\n ) {\n return defer(() => from(this.ensureRuntimeConfiguration())).pipe(\n switchMap(() => this.run(input)),\n );\n }\n if (this.runtimeMode === RUNTIME_MODE_INTELLIGENCE) {\n return this.#runViaDelegate(input);\n }\n return this.#runViaHttp(input);\n }\n\n #connectViaDelegate(\n input: RunAgentInput,\n lifecycle?: ConnectionReplayLifecycle,\n ): Observable<BaseEvent> {\n return defer(() => from(this.resolveDelegate())).pipe(\n switchMap((delegate) =>\n withAbortErrorHandling(delegate.connect(input, lifecycle)),\n ),\n );\n }\n\n #connectViaHttp(unfiltered: RunAgentInput): Observable<BaseEvent> {\n const input = this.#prepareOutboundMessages(unfiltered);\n this.activeRun = undefined;\n const routedId = this.routedAgentId();\n let httpEvents: ReturnType<typeof runHttpRequest>;\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n throw new Error(\"Single endpoint transport requires a runtimeUrl\");\n }\n\n const requestInit = this.createSingleRouteRequestInit(\n input,\n \"agent/connect\",\n {\n agentId: routedId,\n },\n );\n httpEvents = runHttpRequest(() =>\n this.fetch(this.singleEndpointUrl!, requestInit),\n );\n } else {\n const connectUrl = `${this.runtimeUrl}/agent/${routedId}/connect`;\n const connectRequestInit = this.requestInit(input);\n httpEvents = runHttpRequest(() =>\n this.fetch(connectUrl, connectRequestInit),\n );\n }\n\n const replay = defer(() => {\n let replayStarted = false;\n const emptyHistory = [\n { type: EventType.MESSAGES_SNAPSHOT, messages: [] },\n { type: EventType.STATE_SNAPSHOT, snapshot: {} },\n ];\n return transformHttpEventStream(httpEvents).pipe(\n concatMap((event) => {\n if (replayStarted) return of(event);\n replayStarted = true;\n // Reset through the event pipeline because it captures the old view.\n // Keep that view until the first replay event arrives.\n return from([...emptyHistory, event]);\n }),\n concatWith(defer(() => (replayStarted ? EMPTY : from(emptyHistory)))),\n );\n });\n // A failed or aborted request must not become a successful empty replay.\n return withAbortErrorHandling(replay);\n }\n\n #runViaDelegate(input: RunAgentInput): Observable<BaseEvent> {\n return defer(() => from(this.resolveDelegate())).pipe(\n switchMap((delegate) => withAbortErrorHandling(delegate.run(input))),\n );\n }\n\n #runViaHttp(unfiltered: RunAgentInput): Observable<BaseEvent> {\n const input = this.#prepareOutboundMessages(unfiltered);\n const activeRun = { threadId: input.threadId, runId: input.runId };\n // Hold this run's identity for as long as its stream lives. The identity\n // check keeps a late-finalizing stream from releasing a newer run.\n const trackActiveRun = (source: Observable<BaseEvent>) => {\n this.activeRun = activeRun;\n return source.pipe(\n finalize(() => {\n if (this.activeRun === activeRun) this.activeRun = undefined;\n }),\n );\n };\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n throw new Error(\"Single endpoint transport requires a runtimeUrl\");\n }\n\n const requestInit = this.createSingleRouteRequestInit(\n input,\n \"agent/run\",\n {\n agentId: this.routedAgentId(),\n },\n );\n const httpEvents = runHttpRequest(() =>\n this.fetch(this.singleEndpointUrl!, requestInit),\n );\n return trackActiveRun(\n withAbortErrorHandling(transformHttpEventStream(httpEvents)),\n );\n }\n\n return trackActiveRun(withAbortErrorHandling(super.run(input)));\n }\n\n public override clone(): ProxiedCopilotRuntimeAgent {\n const cloned = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this.runtimeEndpointUrl ?? this.runtimeUrl,\n agentId: this.agentId,\n runtimeAgentId: this.runtimeAgentId,\n description: this.description,\n headers: { ...this.headers },\n credentials: this.credentials,\n transport: this.transport,\n runtimeMode: this.runtimeMode,\n intelligence: this.intelligence,\n capabilities: this._capabilities,\n debug: this.debug,\n fetch: this.fetch,\n messageFilter: this._messageFilter,\n });\n cloned.threadId = this.threadId;\n cloned.setState(this.state);\n cloned.setMessages(this.messages);\n cloned.pendingInterrupts = structuredClone_(this.pendingInterrupts);\n if (this.delegate) {\n const clonedDelegate: AbstractAgent = this.delegate.clone();\n cloned.delegate = clonedDelegate;\n cloned.syncDelegate(clonedDelegate);\n }\n return cloned;\n }\n\n /** Run presentation-only MCP reads on a separate client agent so their\n * lifecycle cannot replace an in-flight approval's detach/completion state. */\n public async ɵrunMcpResourceRead(\n parameters: RunAgentParameters,\n ): Promise<RunAgentResult> {\n const request = (\n parameters.forwardedProps as Record<string, unknown> | undefined\n )?.__proxiedMCPRequest;\n if (\n typeof request !== \"object\" ||\n request === null ||\n (request as { method?: unknown }).method !== \"resources/read\"\n ) {\n throw new Error(\"Only MCP resources/read can use the read-only path\");\n }\n await this.ensureRuntimeConfiguration();\n // Only the renderer's dedicated read path opts into the direct response.\n // Other MCP callers still receive the normal realtime run protocol.\n const resourceParameters = {\n ...parameters,\n forwardedProps: {\n ...parameters.forwardedProps,\n __copilotkitMcpResourceReadOnly: true,\n },\n };\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) {\n return this.runAgent(resourceParameters);\n }\n const resourceAgent = this.clone();\n // A resource read does not resume the conversation. Only its disposable\n // client skips the pending-interrupt gate; the original agent and ordinary\n // clones must retain every approval for the next conversation run.\n resourceAgent.pendingInterrupts = [];\n return resourceAgent.runAgent(resourceParameters);\n }\n\n /**\n * Drop the delegate's cached `lastSeenEventId` for this thread so\n * the next connect requests a full historical replay from the\n * gateway. Used by `RunHandler.connectAgent` on a detected thread\n * switch (the chat moved between threads, so its local\n * messages/state are about to be cleared and need rebuilding from\n * the gateway). Skipped on same-thread churn re-connects so the\n * gateway can resume from the cursor instead.\n *\n * No-op for non-Intelligence runtime modes — the HTTP transport\n * doesn't replay.\n */\n public clearReplayCursor(threadId: string): void {\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) return;\n const delegate = this.delegate as\n | { clearReconnectCursor?: (id: string) => void }\n | null\n | undefined;\n delegate?.clearReconnectCursor?.(threadId);\n }\n\n private async resolveDelegate(): Promise<RunnableAgent> {\n await this.ensureRuntimeConfiguration();\n\n if (!this.delegate) {\n if (this.runtimeMode !== RUNTIME_MODE_INTELLIGENCE) {\n throw new Error(\"A delegate is only created for Intelligence mode\");\n }\n this.delegate = this.createIntelligenceDelegate();\n }\n\n this.syncDelegate(this.delegate);\n\n // AbstractAgent declares connect() as protected, but concrete delegates\n // (IntelligenceAgent, HttpAgent) expose both connect() and run() publicly.\n return this.delegate as unknown as RunnableAgent;\n }\n\n /** Resolve transport and runtime mode before the first outbound request. */\n private async ensureRuntimeConfiguration(): Promise<void> {\n if (\n this.runtimeMode === RUNTIME_MODE_INTELLIGENCE ||\n (this.runtimeMode !== \"pending\" && this.transport !== \"auto\")\n ) {\n return;\n }\n\n if (!this.runtimeUrl) {\n throw new Error(\"Runtime URL is not set\");\n }\n\n const runtimeInfoPromise =\n this.runtimeInfoPromise ??\n this.fetchRuntimeInfo().then((runtimeInfo) => {\n if (this.runtimeInfoPromise !== runtimeInfoPromise) return;\n this.runtimeMode = runtimeInfo.mode ?? RUNTIME_MODE_SSE;\n this.intelligence = runtimeInfo.intelligence;\n });\n this.runtimeInfoPromise = runtimeInfoPromise;\n\n try {\n await runtimeInfoPromise;\n } catch (error) {\n if (this.runtimeInfoPromise === runtimeInfoPromise) {\n this.runtimeInfoPromise = undefined;\n }\n throw error;\n }\n }\n\n private async fetchRuntimeInfo(): Promise<RuntimeInfo> {\n const headers: Record<string, string> = {\n ...this.headers,\n };\n\n if (this.transport === \"auto\") {\n return this.fetchRuntimeInfoAutoDetect(headers);\n }\n\n let init: RequestInit;\n let url: string;\n\n if (this.transport === \"single\") {\n if (!this.singleEndpointUrl) {\n throw new Error(\"Single endpoint transport requires a runtimeUrl\");\n }\n if (!headers[\"Content-Type\"]) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n url = this.singleEndpointUrl;\n init = { method: \"POST\", body: JSON.stringify({ method: \"info\" }) };\n } else {\n url = `${this.runtimeUrl}/info`;\n init = {};\n }\n\n const response = await this.fetch(url, {\n ...init,\n headers,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n return (await response.json()) as RuntimeInfo;\n }\n\n private async fetchRuntimeInfoAutoDetect(\n headers: Record<string, string>,\n ): Promise<RuntimeInfo> {\n // Try REST first (GET /info)\n try {\n const response = await this.fetch(`${this.runtimeUrl}/info`, {\n headers: { ...headers },\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n // Only treat a successful (2xx) response as a valid REST runtime.\n // 404/405 means the endpoint doesn't exist; other non-2xx errors\n // (500, 403, etc.) should also fall through to single-endpoint.\n if (response.status >= 200 && response.status < 300) {\n this.transport = \"rest\";\n return (await response.json()) as RuntimeInfo;\n }\n } catch {\n // REST failed — fall through to single-endpoint attempt\n }\n\n // Try single-endpoint (POST with { method: \"info\" })\n const singleHeaders = { ...headers };\n if (!singleHeaders[\"Content-Type\"]) {\n singleHeaders[\"Content-Type\"] = \"application/json\";\n }\n const endpointUrl = this.runtimeEndpointUrl ?? this.runtimeUrl!;\n const response = await this.fetch(endpointUrl, {\n method: \"POST\",\n headers: singleHeaders,\n body: JSON.stringify({ method: \"info\" }),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n this.transport = \"single\";\n this.singleEndpointUrl = endpointUrl;\n return (await response.json()) as RuntimeInfo;\n }\n\n private createSingleRouteRequestInit(\n input: RunAgentInput,\n method: string,\n params?: Record<string, string>,\n ): RequestInit {\n if (!this.agentId) {\n throw new Error(\n \"ProxiedCopilotRuntimeAgent requires agentId to make runtime requests\",\n );\n }\n\n const baseInit = super.requestInit(input);\n const headers = new Headers(baseInit.headers ?? {});\n headers.set(\"Content-Type\", \"application/json\");\n headers.set(\"Accept\", headers.get(\"Accept\") ?? \"text/event-stream\");\n\n let originalBody: unknown = undefined;\n if (typeof baseInit.body === \"string\") {\n try {\n originalBody = JSON.parse(baseInit.body);\n } catch (error) {\n console.warn(\n \"ProxiedCopilotRuntimeAgent: failed to parse request body for single route transport\",\n error,\n );\n }\n }\n\n const envelope: Record<string, unknown> = { method };\n\n if (params && Object.keys(params).length > 0) {\n envelope.params = params;\n }\n\n if (originalBody !== undefined) {\n envelope.body = originalBody;\n }\n\n return {\n ...baseInit,\n headers,\n body: JSON.stringify(envelope),\n ...(this.credentials ? { credentials: this.credentials } : {}),\n };\n }\n\n private createIntelligenceDelegate(): AbstractAgent {\n const routedId = this.routedAgentId();\n if (!this.runtimeUrl || !routedId || !this.intelligence?.wsUrl) {\n throw new Error(\n \"Intelligence mode requires runtimeUrl, agentId, and intelligence websocket metadata\",\n );\n }\n\n const single = this.transport === \"single\";\n\n return new IntelligenceAgent({\n url: this.intelligence.wsUrl,\n // Single-route posts to the endpoint itself, so it needs the caller's URL\n // verbatim: a trailing slash can select a different proxy location\n // (issue #7028). REST needs the slash-stripped form, because it joins\n // `/agent/:id/:mode` onto it.\n runtimeUrl: single\n ? (this.runtimeEndpointUrl ?? this.runtimeUrl)\n : this.runtimeUrl,\n transport: single ? \"single\" : \"rest\",\n agentId: routedId,\n headers: { ...this.headers },\n credentials: this.credentials,\n fetch: this.fetch as typeof fetch,\n });\n }\n\n private syncDelegate(delegate: AbstractAgent): void {\n // Delegate is the IntelligenceAgent that talks to the runtime — it must\n // use the routed id so that requests reach the right runtime agent.\n delegate.agentId = this.routedAgentId();\n delegate.description = this.description;\n delegate.threadId = this.threadId;\n delegate.debugLogger = this.debugLogger;\n delegate.setMessages(this.messages);\n delegate.setState(this.state);\n delegate.pendingInterrupts = structuredClone_(this.pendingInterrupts);\n\n if (hasHeaders(delegate)) {\n delegate.headers = { ...this.headers };\n }\n\n if (hasCredentials(delegate)) {\n delegate.credentials = this.credentials;\n }\n }\n}\n","const ABORT_MESSAGES: ReadonlySet<string> = new Set([\n \"Fetch is aborted\",\n \"signal is aborted without reason\",\n \"component unmounted\",\n]);\n\nexport function isAbortError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n const { name, message } = error as { name?: unknown; message?: unknown };\n if (name === \"AbortError\") {\n return true;\n }\n return typeof message === \"string\" && ABORT_MESSAGES.has(message);\n}\n","export const RUNTIME_REQUEST_WATCHDOG_MS = 10_000;\n\nexport interface RuntimeRequestMeta {\n nonCritical?: boolean;\n selfBounded?: boolean;\n timedOut?: boolean;\n}\n\nexport interface RuntimeRequestInit extends RequestInit {\n ɵruntimeRequest?: RuntimeRequestMeta;\n}\n\nexport function runtimeRequestMeta(\n init?: RequestInit,\n): RuntimeRequestMeta | undefined {\n return (init as RuntimeRequestInit | undefined)?.ɵruntimeRequest;\n}\n","interface SingleRouteResourceRequest {\n input: RequestInfo | URL;\n init: RequestInit;\n}\n\n/** Returns true when a path belongs to an Intelligence resource API. */\nfunction isIntelligenceResourcePath(path: string): boolean {\n return (\n path === \"/threads\" ||\n path.startsWith(\"/threads/\") ||\n path === \"/memories\" ||\n path.startsWith(\"/memories/\") ||\n path === \"/annotate\"\n );\n}\n\n/** Reads a JSON resource body without changing invalid JSON error behavior. */\nasync function readResourceBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n headers: Headers,\n method: string,\n): Promise<unknown | undefined> {\n if (method === \"GET\" || method === \"HEAD\") return undefined;\n\n let text: string | undefined;\n if (init?.body != null) {\n text = await new Response(init.body).text();\n } else if (input instanceof Request) {\n text = await input.clone().text();\n }\n if (!text) return undefined;\n\n if (headers.get(\"content-type\")?.toLowerCase().includes(\"application/json\")) {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n }\n return text;\n}\n\n/**\n * Converts one Runtime resource fetch into a single-route JSON envelope.\n * Requests outside the mounted Runtime or outside its resource APIs pass\n * through unchanged.\n */\nexport async function createSingleRouteResourceRequest(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n runtimeUrl: string,\n): Promise<SingleRouteResourceRequest | null> {\n const baseUrl =\n typeof window !== \"undefined\" && window.location?.href\n ? window.location.href\n : \"http://localhost\";\n const runtime = new URL(runtimeUrl, baseUrl);\n const inputUrl =\n input instanceof Request\n ? input.url\n : input instanceof URL\n ? input.href\n : input;\n const target = new URL(inputUrl, baseUrl);\n const runtimePath = runtime.pathname.replace(/\\/$/, \"\");\n if (target.origin !== runtime.origin) return null;\n if (!target.pathname.startsWith(`${runtimePath}/`)) return null;\n\n const resourcePath = target.pathname.slice(runtimePath.length);\n if (!isIntelligenceResourcePath(resourcePath)) return null;\n\n const method = (\n init?.method ?? (input instanceof Request ? input.method : \"GET\")\n ).toUpperCase();\n const headers = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n );\n const body = await readResourceBody(input, init, headers, method);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const requestDefaults: RequestInit =\n input instanceof Request\n ? {\n cache: input.cache,\n credentials: input.credentials,\n integrity: input.integrity,\n keepalive: input.keepalive,\n mode: input.mode,\n redirect: input.redirect,\n referrer: input.referrer,\n referrerPolicy: input.referrerPolicy,\n signal: input.signal,\n }\n : {};\n\n return {\n input: runtimeUrl,\n init: {\n ...requestDefaults,\n ...init,\n method: \"POST\",\n headers,\n body: JSON.stringify({\n method: \"resource/request\",\n params: {\n path: `${resourcePath}${target.search}`,\n httpMethod: method,\n },\n ...(body === undefined ? {} : { body }),\n }),\n },\n };\n}\n","export type HeaderRecordInput = Record<string, string | null | undefined>;\n\n/**\n * What `headers` accepts: a record, a sync builder, or an async builder. A\n * builder runs once per request, when the request is sent. See #1937.\n */\nexport type CopilotKitHeadersSource =\n | HeaderRecordInput\n | (() => HeaderRecordInput)\n | (() => Promise<HeaderRecordInput>);\n\nexport class CopilotKitHeaderResolutionError extends Error {\n override readonly name = \"CopilotKitHeaderResolutionError\";\n constructor(cause: unknown) {\n // Fixed message on purpose: never echo header values.\n super(\"[CopilotKit] Failed to resolve request headers\", { cause });\n }\n}\n\nexport function isHeaderResolutionError(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 5 && current; depth++) {\n if (current instanceof CopilotKitHeaderResolutionError) return true;\n current = (current as { cause?: unknown }).cause;\n }\n return false;\n}\n\nexport function isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Normalize a header map to a `Record<string, string>` with no `null` or\n * `undefined` values. Dropping an entry is how a header is cleared.\n */\nexport function normalizeHeaders(\n headers: HeaderRecordInput,\n): Record<string, string> {\n return Object.fromEntries(\n Object.entries(headers).filter(\n (entry): entry is [string, string] => entry[1] != null,\n ),\n );\n}\n\n/** Same keys, same values (order-independent). */\nfunction shallowEqualRecord(\n a: Record<string, string>,\n b: Record<string, string>,\n): boolean {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((key) => a[key] === b[key]);\n}\n\nfunction isHeaderRecordInput(value: unknown): value is HeaderRecordInput {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Owns the headers source for one core. Resolution is synchronous for a\n * record or a sync builder, so those callers never pay an extra await.\n */\nexport class HeaderSourceResolver {\n private source: CopilotKitHeadersSource = {};\n private sourceGeneration = 0;\n private snapshot: Record<string, string> = {};\n private inFlight?: {\n generation: number;\n promise: Promise<Record<string, string>>;\n };\n\n constructor(\n private readonly onFailure: (\n error: CopilotKitHeaderResolutionError,\n ) => void,\n ) {}\n\n /** The last resolved headers. Not necessarily current for a builder. */\n get headers(): Record<string, string> {\n return this.snapshot;\n }\n\n /** Bumped on every accepted `setSource`, never by a new token. */\n get generation(): number {\n return this.sourceGeneration;\n }\n\n /**\n * Returns false when a builder with the same identity is set again, or\n * when a record replaces another record with equal normalized values (a\n * caller re-passing an equivalent literal on every re-render must not\n * bump the generation). A record replacing a builder, a builder replacing\n * a record, and a new builder function all still count as a change.\n */\n setSource(source: CopilotKitHeadersSource): boolean {\n if (typeof source === \"function\" && source === this.source) return false;\n const nextSnapshot =\n typeof source === \"function\" ? {} : normalizeHeaders(source);\n if (\n typeof source !== \"function\" &&\n typeof this.source !== \"function\" &&\n shallowEqualRecord(nextSnapshot, this.snapshot)\n ) {\n return false;\n }\n this.source = source;\n this.sourceGeneration += 1;\n this.inFlight = undefined;\n // A builder hasn't run yet, so the previous source's snapshot must not\n // survive the switch — otherwise a stale value (e.g. the old user's\n // Authorization) would be re-applied to agents and broadcast as current.\n this.snapshot = nextSnapshot;\n return true;\n }\n\n resolve(): Record<string, string> | Promise<Record<string, string>> {\n const source = this.source;\n if (typeof source !== \"function\") return this.snapshot;\n const generation = this.sourceGeneration;\n if (this.inFlight?.generation === generation) return this.inFlight.promise;\n\n let value: HeaderRecordInput | Promise<HeaderRecordInput>;\n try {\n value = source();\n } catch (error) {\n throw this.fail(error);\n }\n if (!isPromiseLike(value)) return this.accept(value, generation);\n\n const promise: Promise<Record<string, string>> = Promise.resolve(value)\n .then(\n (resolved) => this.accept(resolved, generation),\n (error: unknown) => {\n throw this.fail(error);\n },\n )\n .finally(() => {\n if (this.inFlight?.promise === promise) this.inFlight = undefined;\n });\n this.inFlight = { generation, promise };\n return promise;\n }\n\n private accept(value: unknown, generation: number): Record<string, string> {\n if (!isHeaderRecordInput(value)) {\n throw this.fail(\n new TypeError(\"headers builder must return an object of header values\"),\n );\n }\n const normalized = normalizeHeaders(value);\n if (generation === this.sourceGeneration) {\n // Keep the previous snapshot's identity when nothing actually changed,\n // so `core.headers` (and anything keyed on it, e.g. a React dep array)\n // only sees a new reference when a header value really changed.\n if (!shallowEqualRecord(normalized, this.snapshot)) {\n this.snapshot = normalized;\n }\n return this.snapshot;\n }\n return normalized;\n }\n\n private fail(cause: unknown): CopilotKitHeaderResolutionError {\n if (cause instanceof CopilotKitHeaderResolutionError) return cause;\n const error = new CopilotKitHeaderResolutionError(cause);\n this.onFailure(error);\n return error;\n }\n}\n\nconst PROTOCOL_HEADERS = new Set([\"content-type\", \"accept\"]);\n\n/**\n * Put fresh core headers on top of a request's headers, keeping the input's\n * shape. Core beats an agent's own headers (#5635). A site's Content-Type and\n * Accept are never overridden, matching every site's existing spread order.\n */\nexport function ɵoverlayCoreHeaders(\n existing: HeadersInit | undefined,\n core: Record<string, string>,\n): HeadersInit {\n if (existing instanceof Headers) {\n const headers = new Headers(existing);\n for (const [key, value] of Object.entries(core)) {\n if (PROTOCOL_HEADERS.has(key.toLowerCase()) && headers.has(key)) continue;\n headers.set(key, value);\n }\n return headers;\n }\n const base: Record<string, string> = Array.isArray(existing)\n ? Object.fromEntries(existing)\n : { ...existing };\n const keyByLower = new Map(\n Object.keys(base).map((k) => [k.toLowerCase(), k]),\n );\n for (const [key, value] of Object.entries(core)) {\n const existingKey = keyByLower.get(key.toLowerCase());\n if (existingKey !== undefined) {\n if (PROTOCOL_HEADERS.has(key.toLowerCase())) continue;\n delete base[existingKey];\n }\n base[key] = value;\n }\n return base;\n}\n\n/** Reject with the signal's AbortError if it aborts before `value` settles. */\nexport async function abortable<T>(\n value: T | Promise<T>,\n signal: AbortSignal | null | undefined,\n): Promise<T> {\n if (!signal || !isPromiseLike(value)) return value;\n if (signal.aborted) throw abortError(signal);\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n Promise.resolve(value).then(\n (v) => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve(v);\n },\n (e) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(e);\n },\n );\n });\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\n/**\n * Add default headers (e.g. the public API key) to a source, only where the\n * source left the key unset or empty. The single shared replacement for the\n * React, Vue and Angular providers' own merges.\n */\nexport function ɵwithHeaderDefaults(\n source: CopilotKitHeadersSource,\n defaults: Record<string, string>,\n): CopilotKitHeadersSource {\n if (Object.keys(defaults).length === 0) return source;\n const fill = (headers: HeaderRecordInput): HeaderRecordInput => {\n const out: HeaderRecordInput = { ...headers };\n for (const [key, value] of Object.entries(defaults)) {\n if (!out[key]) out[key] = value;\n }\n return out;\n };\n if (typeof source !== \"function\") return fill(source);\n // The wrapper's return type tracks its argument (sync stays sync, async\n // stays async), but that dependency isn't expressible in\n // `CopilotKitHeadersSource`'s shape, so the cast below stands in for it.\n return (() => {\n const value = source();\n return isPromiseLike(value)\n ? Promise.resolve(value).then((resolved) =>\n isHeaderRecordInput(resolved) ? fill(resolved) : resolved,\n )\n : isHeaderRecordInput(value)\n ? fill(value)\n : value;\n }) as CopilotKitHeadersSource;\n}\n","import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { HttpAgent } from \"@ag-ui/client\";\nimport { ɵisHttpAgent } from \"../utils/http-agent\";\nimport type {\n RuntimeInfo,\n RuntimeMode,\n RuntimeLicenseStatus,\n RuntimeEntitlementResponse,\n IntelligenceRuntimeInfo,\n InspectorMetadataV1,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport {\n logger,\n parseInspectorMetadataV1,\n RUNTIME_MODE_SSE,\n resolveDebugConfig,\n} from \"@copilotkit/shared\";\nimport { ProxiedCopilotRuntimeAgent } from \"../agent\";\nimport type { CopilotKitCore, CopilotKitCoreFriendsAccess } from \"./core\";\nimport {\n CopilotKitCoreErrorCode,\n CopilotKitCoreRuntimeConnectionStatus,\n} from \"./core\";\nimport type { CopilotRuntimeTransport } from \"../types\";\nimport {\n isRuntimeInfoRequestError,\n runtimeInfoError,\n} from \"../utils/runtime-info-error\";\nimport { isAbortError } from \"../utils/abort-error\";\nimport type { RuntimeRequestMeta } from \"../utils/runtime-request\";\nimport {\n RUNTIME_REQUEST_WATCHDOG_MS,\n runtimeRequestMeta,\n} from \"../utils/runtime-request\";\nimport { createSingleRouteResourceRequest } from \"../utils/single-route-resource-request\";\nimport {\n abortable,\n isHeaderResolutionError,\n isPromiseLike,\n ɵoverlayCoreHeaders,\n} from \"./header-source\";\n\ntype ResolvedCopilotRuntimeTransport = Exclude<CopilotRuntimeTransport, \"auto\">;\n\ntype RuntimeInfoFetchResult = {\n runtimeInfo: RuntimeInfo;\n resolvedTransport: ResolvedCopilotRuntimeTransport;\n};\n\n/** Maximum wait for optional Inspector metadata before degrading to absence. */\nconst INSPECTOR_METADATA_REQUEST_TIMEOUT_MS = 5_000;\n\nexport const ɵRUNTIME_PROBE_TIMEOUT_MS = 5_000;\n\ntype RuntimeRequestOutcome = \"ok\" | \"failed\" | \"aborted\" | \"ignored\";\n\nfunction classifyRuntimeRequestFailure(\n error: unknown,\n meta: RuntimeRequestMeta | undefined,\n): RuntimeRequestOutcome {\n if (meta?.nonCritical) {\n return \"ignored\";\n }\n if (isAbortError(error) && !meta?.timedOut) {\n return \"aborted\";\n }\n return \"failed\";\n}\n\ninterface RuntimeConnectionOptions {\n preserveOnFailure?: boolean;\n recovery?: boolean;\n}\n\n/** Build case-insensitive JSON headers without mutating the Core snapshot. */\nfunction withJsonContentType(headers: Record<string, string>): Headers {\n const requestHeaders = new Headers(headers);\n if (!requestHeaders.has(\"content-type\")) {\n requestHeaders.set(\"content-type\", \"application/json\");\n }\n return requestHeaders;\n}\n\nconst RUNTIME_ENTITLEMENT_RETRY_DELAY_MS = 5_000;\n\ninterface RuntimeConnectionAttempt {\n key: string;\n generation: number;\n}\n\ninterface RuntimeAgentConnection {\n runtimeUrl: string;\n /** The caller-supplied URL the proxy was built with (trailing slash intact). */\n endpointUrl?: string;\n transport: CopilotRuntimeTransport;\n}\n\nexport interface CopilotKitCoreAddAgentParams {\n id: string;\n agent: AbstractAgent;\n}\n\n/**\n * Parameters for registering a proxied agent against an existing runtime agent.\n */\nexport interface CopilotKitCoreRegisterProxiedAgentParams {\n /**\n * The local registry id under which the proxy is registered. Used by\n * `useAgent`, state-manager subscriptions, and all subscriber bookkeeping.\n * Must not collide with any existing local or runtime-discovered agent id.\n */\n agentId: string;\n /**\n * The id of the runtime agent that this proxy routes outbound HTTP requests\n * to. Invisible to subscribers — only affects URL paths and single-route\n * envelopes.\n */\n runtimeAgentId: string;\n}\n\nexport interface CopilotKitCoreRegisterProxiedAgentResult {\n agent: ProxiedCopilotRuntimeAgent;\n unregister: () => void;\n}\n\n/**\n * Manages agent registration, lifecycle, and runtime connectivity for CopilotKitCore.\n * Handles both local development agents and remote runtime agents.\n */\nexport class AgentRegistry {\n private _agents: Record<string, AbstractAgent> = {};\n private localAgents: Record<string, AbstractAgent> = {};\n private remoteAgents: Record<string, AbstractAgent> = {};\n\n private readonly mintedThreadIds = new WeakMap<AbstractAgent, string>();\n\n private _runtimeUrl?: string;\n /** The runtime URL as the caller supplied it; the single-route endpoint uses it verbatim. */\n private _runtimeEndpointUrl?: string;\n // Tracks an in-flight `/info` connection so concurrent calls targeting the\n // same runtime (url + requested transport) collapse to a single request\n // instead of each firing their own. See #5801.\n private _connectionInFlight?: {\n attempt: RuntimeConnectionAttempt;\n promise: Promise<void>;\n };\n private _runtimeConnectionGeneration = 0;\n private _activeRuntimeConnectionAttempt?: RuntimeConnectionAttempt;\n private _runtimeEntitlementRetryTimer?: ReturnType<typeof setTimeout>;\n private _runtimeEntitlementRetryAttemptedKey?: string;\n private _runtimeEntitlementRetryPendingKey?: string;\n private _runtimeVersion?: string;\n private _runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus =\n CopilotKitCoreRuntimeConnectionStatus.Disconnected;\n private _runtimeTransport: CopilotRuntimeTransport = \"auto\";\n // The transport MODE last requested via `setRuntimeTransport` (e.g. \"auto\").\n // Distinct from `_runtimeTransport`, which auto-detect overwrites with the\n // RESOLVED value (\"rest\"/\"single\"). The idempotency guard compares against\n // this so re-applying the same mode (the provider effect re-applies \"auto\"\n // on every render) is a no-op instead of re-running the /info handshake.\n private _requestedTransport: CopilotRuntimeTransport = \"auto\";\n private _audioFileTranscriptionEnabled: boolean = false;\n private _runtimeMode: RuntimeMode = RUNTIME_MODE_SSE;\n private _intelligence?: IntelligenceRuntimeInfo;\n private _threadEndpoints?: ThreadEndpointRuntimeInfo;\n private _singleRouteResourceOperations = false;\n private _suggestions?: boolean;\n private _inspectorLearning: boolean = false;\n private _inspectorMetadata?: InspectorMetadataV1;\n private _inspectorMetadataSupported: boolean = false;\n private inspectorMetadataRefreshReady: boolean = false;\n private inspectorMetadataConnectionGeneration: number = 0;\n private inspectorMetadataGeneration: number = 0;\n private inspectorMetadataHeadersGeneration: number = 0;\n private inspectorMetadataCredentialsGeneration: number = 0;\n private inspectorMetadataAbortController?: AbortController;\n private inspectorMetadataNotificationQueue: Promise<void> = Promise.resolve();\n private _a2uiEnabled: boolean = false;\n private _a2uiAgents?: string[];\n private _openGenerativeUIEnabled: boolean = false;\n private _licenseStatus?: RuntimeLicenseStatus;\n private _runtimeEntitlements?: RuntimeEntitlementResponse;\n private _telemetryDisabled: boolean = false;\n private remoteAgentConnections = new WeakMap<\n ProxiedCopilotRuntimeAgent,\n RuntimeAgentConnection\n >();\n\n private runtimeFetch?: typeof fetch;\n private runtimeProbeInFlight: boolean = false;\n private runtimeProbeToken: number = 0;\n private runtimeProbeAbortController?: AbortController;\n private runtimeRecoveryRunning: boolean = false;\n private runtimeRecoveryPending: boolean = false;\n private runtimeHealthGeneration: number = 0;\n\n /**\n * The headers each HttpAgent was constructed with, captured on the first\n * `applyHeadersToAgent` call for that agent (which, for agents the registry\n * owns, happens at registration before any core headers are applied). Core\n * headers are merged ON TOP of this baseline so that headers configured\n * directly on an agent (e.g. an `Authorization` for a self-hosted backend)\n * survive registration instead of being silently replaced. The baseline is\n * captured once and never re-captured, so a later direct mutation of\n * `agent.headers` is not folded into it. See #5635.\n */\n private agentOwnHeaders = new WeakMap<HttpAgent, Record<string, string>>();\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Get all agents as a readonly record\n */\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this._agents;\n }\n\n get runtimeUrl(): string | undefined {\n return this._runtimeUrl;\n }\n\n get runtimeVersion(): string | undefined {\n return this._runtimeVersion;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this._runtimeConnectionStatus;\n }\n\n get runtimeTransport(): CopilotRuntimeTransport {\n return this._runtimeTransport;\n }\n\n get audioFileTranscriptionEnabled(): boolean {\n return this._audioFileTranscriptionEnabled;\n }\n\n get runtimeMode(): RuntimeMode {\n return this._runtimeMode;\n }\n\n get intelligence(): IntelligenceRuntimeInfo | undefined {\n return this._intelligence;\n }\n\n get threadEndpoints(): ThreadEndpointRuntimeInfo | undefined {\n return this._threadEndpoints;\n }\n\n get suggestions(): boolean | undefined {\n return this._suggestions;\n }\n\n get inspectorLearning(): boolean {\n return this._inspectorLearning;\n }\n\n get inspectorMetadata(): InspectorMetadataV1 | undefined {\n return this._inspectorMetadata;\n }\n\n get a2uiEnabled(): boolean {\n return this._a2uiEnabled;\n }\n\n /**\n * Agent ids the runtime applies A2UI to (#5369). `undefined` means A2UI\n * applies to every agent — or is disabled entirely; check `a2uiEnabled`.\n */\n get a2uiAgents(): string[] | undefined {\n return this._a2uiAgents;\n }\n\n get openGenerativeUIEnabled(): boolean {\n return this._openGenerativeUIEnabled;\n }\n\n get licenseStatus(): RuntimeLicenseStatus | undefined {\n return this._licenseStatus;\n }\n\n /** Structured Runtime entitlement authority advertised by `/info`. */\n get runtimeEntitlements(): RuntimeEntitlementResponse | undefined {\n return this._runtimeEntitlements;\n }\n\n get runtimeEntitlementRetryPending(): boolean {\n return (\n this._runtimeEntitlementRetryPendingKey === this.runtimeConnectionKey()\n );\n }\n\n get telemetryDisabled(): boolean {\n return this._telemetryDisabled;\n }\n\n /**\n * Initialize agents from configuration\n */\n initialize(agents: Record<string, AbstractAgent>): void {\n this.localAgents = this.assignAgentIds(agents);\n this.applyHeadersToAgents(this.localAgents);\n this.applyCredentialsToAgents(this.localAgents);\n this.applyMessageFilterToAgents(this.localAgents);\n this.applyRuntimeFetchToAgents(this.localAgents);\n this._agents = this.localAgents;\n }\n\n /**\n * Set the runtime URL and update connection\n */\n setRuntimeUrl(\n runtimeUrl: string | undefined,\n options?: { deferConnection?: boolean },\n ): void {\n const normalizedRuntimeUrl = runtimeUrl\n ? runtimeUrl.replace(/\\/$/, \"\")\n : undefined;\n const runtimeEndpointUrl = runtimeUrl || undefined;\n\n if (\n this._runtimeUrl === normalizedRuntimeUrl &&\n this._runtimeEndpointUrl === runtimeEndpointUrl\n ) {\n return;\n }\n\n this.invalidateInspectorMetadataConnection();\n this.abandonRuntimeHealthProbe();\n this.resetRuntimeEntitlementRetry();\n // Runtime authority is scoped to the target that advertised it. Clear it\n // before subscribers observe the replacement target connecting.\n this._licenseStatus = undefined;\n this._runtimeEntitlements = undefined;\n this._singleRouteResourceOperations = false;\n this._runtimeUrl = normalizedRuntimeUrl;\n this._runtimeEndpointUrl = runtimeEndpointUrl;\n\n // Deferred construction (see CopilotKitCore.connect / #5801): record the URL\n // so getters/hooks see it synchronously, but do NOT start the `/info` fetch\n // here. The host starts it from a commit-phase effect via `connect()`, so\n // renders discarded before commit never issue a request.\n if (options?.deferConnection) {\n return;\n }\n\n void this.updateRuntimeConnection({\n preserveOnFailure: this.hasLiveRuntimeKnowledgeToProtect(),\n });\n }\n\n /**\n * Start the initial runtime connection if it has not been started yet.\n *\n * Backs {@link CopilotKitCore.connect}. Idempotent: it only kicks off a fetch\n * when a `runtimeUrl` is set and the connection is still `Disconnected` (its\n * state before any connect attempt). `updateRuntimeConnection` flips the\n * status to `Connecting` synchronously, so a second call — e.g. React\n * StrictMode double-invoking the mount effect — bails here. A genuine config\n * change still reconnects through `setRuntimeUrl`/`setRuntimeTransport`. See\n * #5801.\n */\n connectRuntime(): void {\n if (typeof window === \"undefined\") {\n return;\n }\n if (!this._runtimeUrl) {\n return;\n }\n if (\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Disconnected\n ) {\n return;\n }\n void this.updateRuntimeConnection();\n }\n\n setRuntimeTransport(runtimeTransport: CopilotRuntimeTransport): void {\n // Guard on the requested MODE, not the resolved value: after auto-detect\n // writes `_runtimeTransport = \"rest\"`, re-applying the same requested\n // \"auto\" must not be treated as a change (otherwise every provider\n // re-render re-runs the /info handshake and rebuilds agents).\n if (this._requestedTransport === runtimeTransport) {\n return;\n }\n\n this.invalidateInspectorMetadataConnection();\n this.abandonRuntimeHealthProbe();\n this.resetRuntimeEntitlementRetry();\n this._requestedTransport = runtimeTransport;\n this._runtimeTransport = runtimeTransport;\n this._singleRouteResourceOperations = false;\n void this.updateRuntimeConnection({\n preserveOnFailure: this.hasLiveRuntimeKnowledgeToProtect(),\n });\n }\n\n private hasLiveRuntimeKnowledgeToProtect(): boolean {\n if (Object.keys(this.remoteAgents).length === 0) {\n return false;\n }\n return (\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n );\n }\n\n private reconcileRecoveredAgents(\n reported: Record<string, AbstractAgent>,\n ): Record<string, AbstractAgent> {\n const merged = { ...this.remoteAgents, ...reported };\n if (Object.keys(reported).length === 0) {\n return merged;\n }\n for (const [id, agent] of Object.entries(merged)) {\n if (Object.prototype.hasOwnProperty.call(reported, id)) {\n continue;\n }\n if (this.carriesConversationState(agent)) {\n continue;\n }\n delete merged[id];\n }\n return merged;\n }\n\n private carriesConversationState(agent: AbstractAgent): boolean {\n if (agent.messages.length > 0) {\n return true;\n }\n const mintedThreadId = this.mintedThreadIds.get(agent);\n return mintedThreadId === undefined || agent.threadId !== mintedThreadId;\n }\n\n private abandonRuntimeHealthProbe(): void {\n this.runtimeProbeToken += 1;\n this.runtimeProbeInFlight = false;\n this.runtimeHealthGeneration += 1;\n this.runtimeProbeAbortController?.abort();\n this.runtimeProbeAbortController = undefined;\n }\n\n /**\n * Set all agents at once (for development use)\n */\n setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void {\n // Validate all agents before making any changes\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent) {\n this.validateAndAssignAgentId(id, agent);\n }\n });\n this.localAgents = agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this.applyHeadersToAgents(this._agents);\n this.applyCredentialsToAgents(this._agents);\n this.applyMessageFilterToAgents(this._agents);\n this.applyRuntimeFetchToAgents(this._agents);\n void this.notifyAgentsChanged();\n }\n\n /**\n * Add a single agent (for development use)\n */\n addAgent__unsafe_dev_only({ id, agent }: CopilotKitCoreAddAgentParams): void {\n this.validateAndAssignAgentId(id, agent);\n this.localAgents[id] = agent;\n this.applyHeadersToAgent(agent);\n this.applyCredentialsToAgent(agent);\n this.applyRuntimeFetchToAgent(agent);\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n }\n\n /**\n * Remove an agent by ID (for development use)\n */\n removeAgent__unsafe_dev_only(id: string): void {\n delete this.localAgents[id];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n }\n\n /**\n * Register a proxied agent that routes outbound runtime requests to an\n * existing runtime agent (`runtimeAgentId`) while exposing a distinct local\n * registry id (`agentId`). Throws if `agentId` is already taken by either a\n * local or runtime-discovered agent.\n *\n * Use this to mount multiple frontend agents against a single runtime\n * agent (e.g. a chat-1 / chat-2 pair both proxying to \"default\") without\n * implicit per-thread cloning. The returned `unregister` removes the proxy\n * from the registry and emits `onAgentsChanged`.\n */\n registerProxiedAgent({\n agentId,\n runtimeAgentId,\n }: CopilotKitCoreRegisterProxiedAgentParams): CopilotKitCoreRegisterProxiedAgentResult {\n // Use hasOwnProperty rather than `in`: `in` walks the prototype chain,\n // so an agentId of \"__proto__\", \"constructor\", \"toString\" etc. would\n // falsely test as already-registered.\n if (Object.prototype.hasOwnProperty.call(this._agents, agentId)) {\n throw new Error(\n `CopilotKitCore.registerProxiedAgent: agentId \"${agentId}\" is already registered. ` +\n `Pick a different agentId, or unregister the existing agent first.`,\n );\n }\n\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const debug = friends.debug;\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this._runtimeEndpointUrl ?? this._runtimeUrl,\n agentId,\n runtimeAgentId,\n transport: this._runtimeTransport,\n credentials: friends.credentials,\n // If runtime info has already synced, mirror its mode/intelligence so\n // the proxy doesn't have to re-resolve. Otherwise stay \"pending\" until\n // /info lands.\n runtimeMode: this._runtimeUrl\n ? this._runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ? this._runtimeMode\n : \"pending\"\n : RUNTIME_MODE_SSE,\n intelligence: this._intelligence,\n debug: debug ? resolveDebugConfig(debug) : undefined,\n messageFilter: friends.messageFilter,\n });\n this.applyHeadersToAgent(agent);\n this.applyRuntimeFetchToAgent(agent);\n\n this.localAgents[agentId] = agent;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n\n return {\n agent,\n unregister: () => {\n // Only unregister if the same instance is still in place — guards\n // against double-unregister or against unregistering after a\n // subsequent register replaced the slot.\n if (this.localAgents[agentId] === agent) {\n delete this.localAgents[agentId];\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n void this.notifyAgentsChanged();\n }\n },\n };\n }\n\n /**\n * Get an agent by ID\n */\n getAgent(id: string): AbstractAgent | undefined {\n if (id in this._agents) {\n return this._agents[id] as AbstractAgent;\n }\n\n // Silently return undefined if we're still loading runtime agents\n if (\n this.runtimeUrl !== undefined &&\n (this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Disconnected ||\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connecting)\n ) {\n return undefined;\n }\n\n console.warn(`Agent ${id} not found`);\n return undefined;\n }\n\n /**\n * Shared core-and-own-header merge for a single agent. Captures the\n * agent's construction-time headers once (the per-agent baseline in\n * `agentOwnHeaders`), then either keeps only that baseline — a\n * `ProxiedCopilotRuntimeAgent`, whose core headers are added by\n * `ɵruntimeFetch` when each request is actually sent instead, so a key the\n * builder stops returning can never ride along from a stale copy baked\n * onto the agent (see #1937) — or merges `coreHeaders` on top of it (any\n * other `HttpAgent`; core wins on a key conflict, see #5635).\n */\n private applyHeaderRecordToAgent(\n agent: HttpAgent,\n coreHeaders: Record<string, string>,\n ): void {\n // On every apply we rebuild from this baseline so re-applying core\n // headers (e.g. via setHeaders) never loses the agent's own headers.\n if (!this.agentOwnHeaders.has(agent)) {\n this.agentOwnHeaders.set(agent, { ...agent.headers });\n }\n const own = this.agentOwnHeaders.get(agent)!;\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.headers = { ...own };\n this.applyRuntimeFetchToAgent(agent);\n return;\n }\n agent.headers = { ...own, ...coreHeaders };\n }\n\n /**\n * Apply the last resolved header snapshot to an agent, merged ON TOP of\n * the agent's own construction-time headers. Non-`HttpAgent` agents are\n * left untouched because only `HttpAgent` carries a `headers` field. See\n * #5635.\n *\n * Never invokes the headers builder — safe to call from anywhere (dev-only\n * registration helpers, a React effect that re-runs on every render)\n * without risking a synchronous throw or an unhandled async rejection from\n * a user-supplied builder. Use `prepareAgentHeadersForRun` (friends-only)\n * on the run/connect path, where a builder failure can be awaited and\n * reported once.\n */\n applyHeadersToAgent(agent: AbstractAgent): void {\n if (!ɵisHttpAgent(agent)) return;\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n this.applyHeaderRecordToAgent(agent, friends.headers);\n }\n\n /**\n * Apply the last resolved header snapshot to every agent, without\n * triggering a builder call per agent. Used by `initialize` and\n * `setHeaders`; a run re-applies with fresh headers anyway (see\n * `prepareAgentHeadersForRun`).\n */\n applyHeadersToAgents(agents: Record<string, AbstractAgent>): void {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n Object.values(agents).forEach((agent) => {\n if (ɵisHttpAgent(agent)) {\n this.applyHeaderRecordToAgent(agent, friends.headers);\n }\n });\n }\n\n /**\n * Resolve headers fresh and apply them to `agent` right before a run or\n * connect actually sends (#1937) — the resolving counterpart to\n * `applyHeadersToAgent`. Friends-only: only the run handler should call\n * this, since resolving can invoke a user-supplied builder that throws\n * synchronously or returns a rejecting promise. Resolution is synchronous\n * for a record or a sync builder; this returns a promise only when an\n * async builder must be awaited first, and callers that need the write to\n * have landed before continuing must await a returned promise.\n *\n * A `ProxiedCopilotRuntimeAgent` never invokes the builder here: its core\n * headers are added by `ɵruntimeFetch` at send time instead, so only its\n * own headers are (re)applied.\n */\n prepareAgentHeadersForRun(agent: AbstractAgent): void | Promise<void> {\n if (!ɵisHttpAgent(agent)) return;\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n this.applyHeaderRecordToAgent(agent, {});\n return;\n }\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const resolved = friends.resolveHeaders();\n if (isPromiseLike(resolved)) {\n return Promise.resolve(resolved).then((headers) => {\n this.applyHeaderRecordToAgent(agent, headers);\n });\n }\n this.applyHeaderRecordToAgent(agent, resolved);\n }\n\n /**\n * Apply current credentials to an agent\n */\n applyCredentialsToAgent(agent: AbstractAgent): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.credentials = (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).credentials;\n }\n }\n\n /**\n * Apply current credentials to all agents\n */\n applyCredentialsToAgents(agents: Record<string, AbstractAgent>): void {\n Object.values(agents).forEach((agent) => {\n this.applyCredentialsToAgent(agent);\n });\n }\n\n /**\n * Carry the mode a fresh `/info` reported onto a proxy this re-sync kept.\n *\n * `canReuseRuntimeAgent` deliberately ignores the mode: a preserved proxy is\n * backing an open conversation, and replacing the instance to change one\n * field would drop it. The mode is therefore pushed onto the survivor here,\n * the same way headers and credentials are. Without it the mode was fixed at\n * construction, so a runtime that flipped `intelligence` → `sse` under an\n * open page left every later run on the delegate path. See #7130.\n */\n applyRuntimeModeToAgent(\n agent: AbstractAgent,\n runtimeInfo: RuntimeInfo,\n ): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.adoptRuntimeMode(\n runtimeInfo.mode ?? RUNTIME_MODE_SSE,\n runtimeInfo.intelligence,\n );\n }\n }\n\n /**\n * Apply the core's message filter to an agent.\n *\n * The test is the class, not which bucket the agent is registered in: every\n * `ProxiedCopilotRuntimeAgent` gets the core filter, whether it came from\n * `/info` or from `registerProxiedAgent` (which files its proxy under\n * `localAgents`). Agents of any other class are left untouched — an\n * `AbstractAgent` the app built has no such hook, and its owner already has\n * the AG-UI middleware seam.\n *\n * This is the sole writer of `agent.messageFilter` in normal operation. The\n * public setter exists for the registry and for tests; a value written\n * directly onto an agent is replaced the next time the registry sweeps, the\n * same way per-agent credentials are.\n */\n applyMessageFilterToAgent(agent: AbstractAgent): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.messageFilter = (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).messageFilter;\n }\n }\n\n /**\n * Apply the core's message filter to all agents\n */\n applyMessageFilterToAgents(agents: Record<string, AbstractAgent>): void {\n Object.values(agents).forEach((agent) => {\n this.applyMessageFilterToAgent(agent);\n });\n }\n\n /** Preserve the exact configured URL when posting to a single endpoint. */\n get runtimeEndpointUrl(): string | undefined {\n return this._runtimeEndpointUrl;\n }\n\n createRuntimeFetch(): typeof fetch {\n if (!this.runtimeFetch) {\n this.runtimeFetch = (async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const coreHeaders = await abortable(\n friends.resolveHeaders(),\n init?.signal,\n );\n const requestHeaders = ɵoverlayCoreHeaders(\n init?.headers ??\n (input instanceof Request ? input.headers : undefined),\n coreHeaders,\n );\n init = { ...init, headers: requestHeaders };\n const meta = () => runtimeRequestMeta(init);\n const watchdog = this.armRuntimeRequestWatchdog(meta());\n try {\n const singleRouteRequest =\n this._runtimeTransport === \"single\" &&\n this._singleRouteResourceOperations &&\n this._runtimeUrl\n ? await createSingleRouteResourceRequest(\n input,\n init,\n // The endpoint itself is the POST target here, so it has to be\n // the caller's URL verbatim - a trailing slash can select a\n // different proxy location. `_runtimeUrl` is the slash-stripped\n // form kept for path joins (issue #7028).\n this._runtimeEndpointUrl ?? this._runtimeUrl,\n )\n : null;\n const response = singleRouteRequest\n ? await fetch(singleRouteRequest.input, singleRouteRequest.init)\n : await fetch(input, init);\n watchdog.clear();\n this.handleRuntimeRequestOutcome(\n response.ok ? \"ok\" : meta()?.nonCritical ? \"ignored\" : \"failed\",\n watchdog.checked,\n );\n return response;\n } catch (error) {\n watchdog.clear();\n this.handleRuntimeRequestOutcome(\n classifyRuntimeRequestFailure(error, meta()),\n watchdog.checked,\n );\n throw error;\n }\n }) as typeof fetch;\n }\n return this.runtimeFetch;\n }\n\n private armRuntimeRequestWatchdog(meta: RuntimeRequestMeta | undefined): {\n clear: () => void;\n checked: () => boolean;\n } {\n if (\n typeof window === \"undefined\" ||\n meta?.nonCritical ||\n meta?.selfBounded\n ) {\n return { clear: () => {}, checked: () => false };\n }\n let checked = false;\n const timeoutId = setTimeout(() => {\n checked = this.handleRuntimeRequestOutcome(\"failed\");\n }, RUNTIME_REQUEST_WATCHDOG_MS);\n return {\n clear: () => clearTimeout(timeoutId),\n checked: () => checked,\n };\n }\n\n applyRuntimeFetchToAgent(agent: AbstractAgent): void {\n if (agent instanceof ProxiedCopilotRuntimeAgent) {\n agent.fetch = this.createRuntimeFetch();\n }\n }\n\n applyRuntimeFetchToAgents(agents: Record<string, AbstractAgent>): void {\n Object.values(agents).forEach((agent) => {\n this.applyRuntimeFetchToAgent(agent);\n });\n }\n\n /** Refresh metadata after the Core header snapshot changes. */\n handleHeadersChanged(): void {\n this.inspectorMetadataHeadersGeneration += 1;\n this.setInspectorMetadata(undefined);\n void this.refreshInspectorMetadata();\n }\n\n /** Refresh metadata after the Core credentials mode changes. */\n handleCredentialsChanged(): void {\n this.inspectorMetadataCredentialsGeneration += 1;\n this.setInspectorMetadata(undefined);\n void this.refreshInspectorMetadata();\n }\n\n /**\n * Fetch trusted inspector metadata independently from runtime discovery.\n * Optional-route failures degrade to absent metadata and never affect the\n * runtime connection state.\n */\n async refreshInspectorMetadata(): Promise<void> {\n const generation = ++this.inspectorMetadataGeneration;\n this.inspectorMetadataAbortController?.abort();\n this.inspectorMetadataAbortController = undefined;\n\n if (\n !this._inspectorMetadataSupported ||\n !this.inspectorMetadataRefreshReady ||\n !this.runtimeUrl ||\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n this.setInspectorMetadata(undefined);\n return;\n }\n\n const runtimeUrl = this.runtimeUrl;\n const requestedTransport = this._requestedTransport;\n const resolvedTransport = this._runtimeTransport;\n const headersGeneration = this.inspectorMetadataHeadersGeneration;\n const credentialsGeneration = this.inspectorMetadataCredentialsGeneration;\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n\n // Resolve before creating the AbortController: a builder failure here\n // must degrade to absent metadata (like any other optional-route\n // failure) without ever leaving a dangling, never-aborted controller.\n // Resolution is synchronous for a record or a sync builder — only await\n // when it's actually async (there's no AbortSignal yet to make this\n // abortable), so a sync source never pays an extra microtask tick here.\n let headers: Record<string, string>;\n try {\n const resolved = friends.resolveHeaders();\n headers = {\n ...(isPromiseLike(resolved) ? await resolved : resolved),\n };\n } catch {\n if (generation === this.inspectorMetadataGeneration) {\n this.setInspectorMetadata(undefined);\n }\n return;\n }\n // A concurrent refresh (e.g. from setHeaders/setCredentials) may have\n // superseded this call while the builder above was pending — without\n // this check, a slower earlier call would still send a request with\n // stale headers and could replace the newer call's AbortController.\n if (generation !== this.inspectorMetadataGeneration) {\n return;\n }\n const credentials = friends.credentials;\n const abortController = new AbortController();\n this.inspectorMetadataAbortController = abortController;\n\n let timedOut = false;\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let rejectForAbort: ((reason: Error) => void) | undefined;\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectForAbort = reject;\n });\n const handleAbort = () => {\n rejectForAbort?.(new Error(\"Inspector metadata request aborted\"));\n };\n abortController.signal.addEventListener(\"abort\", handleAbort, {\n once: true,\n });\n const timeout = new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(() => {\n timedOut = true;\n reject(new Error(\"Inspector metadata request timed out\"));\n abortController.abort();\n }, INSPECTOR_METADATA_REQUEST_TIMEOUT_MS);\n });\n\n let nextMetadata: InspectorMetadataV1 | undefined;\n try {\n const request = (async () => {\n const response =\n resolvedTransport === \"single\"\n ? await this.fetchInspectorMetadataSingle({\n runtimeUrl: this.singleEndpointUrlFor(runtimeUrl),\n headers,\n credentials,\n signal: abortController.signal,\n })\n : await this.fetchInspectorMetadataRest({\n runtimeUrl,\n headers,\n credentials,\n signal: abortController.signal,\n });\n\n if (response.status === 204 || !response.ok) {\n return undefined;\n }\n return parseInspectorMetadataV1(await response.json());\n })();\n nextMetadata = await Promise.race([request, aborted, timeout]);\n } catch {\n nextMetadata = undefined;\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n abortController.signal.removeEventListener(\"abort\", handleAbort);\n }\n\n if (\n !this.isInspectorMetadataRequestCurrent({\n generation,\n runtimeUrl,\n requestedTransport,\n resolvedTransport,\n headersGeneration,\n credentialsGeneration,\n signal: abortController.signal,\n allowAbortedSignal: timedOut,\n })\n ) {\n return;\n }\n\n this.inspectorMetadataAbortController = undefined;\n this.setInspectorMetadata(nextMetadata);\n }\n\n private async fetchInspectorMetadataRest({\n runtimeUrl,\n headers,\n credentials,\n signal,\n }: {\n runtimeUrl: string;\n headers: Record<string, string>;\n credentials: RequestCredentials | undefined;\n signal: AbortSignal;\n }): Promise<Response> {\n return fetch(`${runtimeUrl}/inspector-metadata`, {\n method: \"GET\",\n headers,\n ...(credentials ? { credentials } : {}),\n signal,\n });\n }\n\n private async fetchInspectorMetadataSingle({\n runtimeUrl,\n headers,\n credentials,\n signal,\n }: {\n runtimeUrl: string;\n headers: Record<string, string>;\n credentials: RequestCredentials | undefined;\n signal: AbortSignal;\n }): Promise<Response> {\n return fetch(runtimeUrl, {\n method: \"POST\",\n headers: withJsonContentType(headers),\n body: JSON.stringify({ method: \"inspector/metadata\" }),\n ...(credentials ? { credentials } : {}),\n signal,\n });\n }\n\n private isInspectorMetadataRequestCurrent({\n generation,\n runtimeUrl,\n requestedTransport,\n resolvedTransport,\n headersGeneration,\n credentialsGeneration,\n signal,\n allowAbortedSignal = false,\n }: {\n generation: number;\n runtimeUrl: string;\n requestedTransport: CopilotRuntimeTransport;\n resolvedTransport: CopilotRuntimeTransport;\n headersGeneration: number;\n credentialsGeneration: number;\n signal: AbortSignal;\n allowAbortedSignal?: boolean;\n }): boolean {\n return (\n (allowAbortedSignal || !signal.aborted) &&\n generation === this.inspectorMetadataGeneration &&\n runtimeUrl === this.runtimeUrl &&\n requestedTransport === this._requestedTransport &&\n resolvedTransport === this._runtimeTransport &&\n headersGeneration === this.inspectorMetadataHeadersGeneration &&\n credentialsGeneration === this.inspectorMetadataCredentialsGeneration &&\n this._inspectorMetadataSupported &&\n this.inspectorMetadataRefreshReady &&\n this._runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n );\n }\n\n private invalidateInspectorMetadataConnection(): void {\n this._inspectorMetadataSupported = false;\n this._inspectorLearning = false;\n this.inspectorMetadataRefreshReady = false;\n this.inspectorMetadataConnectionGeneration += 1;\n this.inspectorMetadataGeneration += 1;\n this.inspectorMetadataAbortController?.abort();\n this.inspectorMetadataAbortController = undefined;\n this.setInspectorMetadata(undefined);\n }\n\n /**\n * Publish one state transition without making refreshes wait on subscribers.\n * Each queued callback closes over its readonly snapshot so reentrant changes\n * cannot replace the value that an older publication is still delivering.\n */\n private setInspectorMetadata(\n inspectorMetadata: InspectorMetadataV1 | undefined,\n ): void {\n if (\n JSON.stringify(this._inspectorMetadata) ===\n JSON.stringify(inspectorMetadata)\n ) {\n return;\n }\n\n this._inspectorMetadata = inspectorMetadata;\n const snapshot = inspectorMetadata;\n this.inspectorMetadataNotificationQueue =\n this.inspectorMetadataNotificationQueue\n .then(() => this.notifyInspectorMetadataChanged(snapshot))\n .catch((error: unknown) => {\n console.error(\n \"Subscriber onInspectorMetadataChanged queue error:\",\n error,\n );\n });\n }\n\n private setRuntimeConnectionStatus(\n status: CopilotKitCoreRuntimeConnectionStatus,\n ): void {\n this._runtimeConnectionStatus = status;\n this.runtimeHealthGeneration += 1;\n }\n\n private handleRuntimeRequestOutcome(\n outcome: RuntimeRequestOutcome,\n alreadyChecked: () => boolean = () => false,\n ): boolean {\n if (outcome === \"aborted\" || outcome === \"ignored\") {\n return false;\n }\n if (outcome === \"failed\" && alreadyChecked()) {\n return false;\n }\n if (typeof window === \"undefined\") {\n return false;\n }\n if (!this._runtimeUrl) {\n return false;\n }\n\n if (outcome === \"ok\") {\n this.runtimeHealthGeneration += 1;\n if (this.runtimeRecoveryRunning) {\n this.runtimeRecoveryPending = true;\n }\n if (\n this._runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Error\n ) {\n void this.recoverRuntimeConnection();\n }\n return false;\n }\n\n if (\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n return false;\n }\n if (this.runtimeProbeInFlight) {\n return false;\n }\n void this.probeRuntimeReachability();\n return true;\n }\n\n private async fetchRuntimeInfoWithTimeout(\n abortController: AbortController,\n runtimeUrl = this.runtimeUrl,\n runtimeTransport = this._runtimeTransport,\n ): Promise<RuntimeInfoFetchResult> {\n if (!runtimeUrl) {\n throw new Error(\"Runtime URL is not set\");\n }\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const request = this.fetchRuntimeInfo(\n runtimeUrl,\n runtimeTransport,\n abortController.signal,\n );\n void request.catch(() => {});\n try {\n const timedOut = new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(() => {\n abortController.abort();\n reject(\n new Error(\n `Runtime did not answer within ${ɵRUNTIME_PROBE_TIMEOUT_MS}ms`,\n ),\n );\n }, ɵRUNTIME_PROBE_TIMEOUT_MS);\n });\n return await Promise.race([request, timedOut]);\n } finally {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n }\n }\n\n private async probeRuntimeReachability(): Promise<void> {\n const generation = this.runtimeHealthGeneration;\n const token = ++this.runtimeProbeToken;\n this.runtimeProbeInFlight = true;\n const abortController = new AbortController();\n this.runtimeProbeAbortController = abortController;\n try {\n await this.fetchRuntimeInfoWithTimeout(abortController);\n } catch (error) {\n if (generation !== this.runtimeHealthGeneration) {\n return;\n }\n await this.markRuntimeUnreachable(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n if (this.runtimeProbeAbortController === abortController) {\n this.runtimeProbeAbortController = undefined;\n }\n if (this.runtimeProbeToken === token) {\n this.runtimeProbeInFlight = false;\n }\n }\n }\n\n private async markRuntimeUnreachable(error: Error): Promise<void> {\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n\n if (isHeaderResolutionError(error)) {\n logger.warn(\n `Could not resolve request headers for the identification request (${this._runtimeUrl}/info). Check the headers builder passed to CopilotKit.`,\n );\n return;\n }\n\n const runtimeStatus = isRuntimeInfoRequestError(error)\n ? error.runtimeInfoStatus\n : undefined;\n logger.warn(\n runtimeStatus === undefined\n ? `Runtime did not answer the identification request (${this._runtimeUrl}/info): ${error.message}. The runtime appears to be unreachable.`\n : `Runtime answered the identification request with status ${runtimeStatus} (${this._runtimeUrl}/info): ${error.message}. The runtime is reachable but refused the request — check credentials and authorisation before addresses and ports.`,\n );\n await (this.core as unknown as CopilotKitCoreFriendsAccess).emitError({\n error,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl: this._runtimeUrl,\n reason: runtimeStatus === undefined ? \"no-answer\" : \"answered\",\n ...(runtimeStatus === undefined ? {} : { runtimeStatus }),\n },\n });\n }\n\n private async recoverRuntimeConnection(): Promise<void> {\n if (this.runtimeRecoveryRunning) {\n this.runtimeRecoveryPending = true;\n return;\n }\n this.runtimeRecoveryRunning = true;\n try {\n do {\n this.runtimeRecoveryPending = false;\n await this.updateRuntimeConnection({\n preserveOnFailure: true,\n recovery: true,\n });\n } while (\n this.runtimeRecoveryPending &&\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n );\n } finally {\n this.runtimeRecoveryRunning = false;\n this.runtimeRecoveryPending = false;\n }\n }\n\n /**\n * Update runtime connection and fetch remote agents\n */\n private async updateRuntimeConnection(\n options?: RuntimeConnectionOptions,\n ): Promise<void> {\n // Skip fetching on the server (SSR)\n if (typeof window === \"undefined\") {\n return;\n }\n\n // In-flight guard: if a connection to the same target (runtime url +\n // requested transport) is already running, reuse it instead of starting a\n // second `/info` request. A change to a different target supersedes it. See\n // #5801.\n const key = this.runtimeConnectionKey();\n const inFlight = this._connectionInFlight;\n if (\n inFlight &&\n inFlight.attempt.key === key &&\n this.isCurrentRuntimeConnection(inFlight.attempt)\n ) {\n return inFlight.promise;\n }\n\n const attempt = {\n key,\n generation: ++this._runtimeConnectionGeneration,\n };\n this._activeRuntimeConnectionAttempt = attempt;\n const promise = this.performRuntimeConnection({\n attempt,\n runtimeUrl: this._runtimeUrl,\n transport: this._runtimeTransport,\n options,\n });\n this._connectionInFlight = { attempt, promise };\n void promise.finally(() => {\n if (this._connectionInFlight?.promise === promise) {\n this._connectionInFlight = undefined;\n }\n });\n return promise;\n }\n\n /** Return the stable key that scopes connection and entitlement retries. */\n private runtimeConnectionKey(): string {\n // The endpoint URL is part of the identity: a change that only adds or\n // drops the trailing slash targets a different single-route endpoint.\n return `${this._runtimeEndpointUrl ?? this._runtimeUrl ?? \"\"}::${this._requestedTransport}`;\n }\n\n /** Return whether a proxy still targets this Runtime connection. */\n private canReuseRuntimeAgent(\n agent: ProxiedCopilotRuntimeAgent,\n runtimeUrl: string | undefined,\n transport: CopilotRuntimeTransport,\n ): boolean {\n if (!runtimeUrl) {\n return false;\n }\n const connection = this.remoteAgentConnections.get(agent);\n return (\n connection?.runtimeUrl === runtimeUrl.replace(/\\/$/, \"\") &&\n connection.endpointUrl === this._runtimeEndpointUrl &&\n connection.transport === transport\n );\n }\n\n /** Return whether an async attempt still owns the active Runtime state. */\n private isCurrentRuntimeConnection(\n attempt: RuntimeConnectionAttempt,\n ): boolean {\n return (\n this._activeRuntimeConnectionAttempt?.generation === attempt.generation &&\n this.runtimeConnectionKey() === attempt.key\n );\n }\n\n /** Cancel a pending entitlement retry and allow a new target to retry. */\n private resetRuntimeEntitlementRetry(): void {\n if (this._runtimeEntitlementRetryTimer !== undefined) {\n clearTimeout(this._runtimeEntitlementRetryTimer);\n this._runtimeEntitlementRetryTimer = undefined;\n }\n this._runtimeEntitlementRetryAttemptedKey = undefined;\n this._runtimeEntitlementRetryPendingKey = undefined;\n }\n\n /** Schedule one retry after Runtime's short failed-entitlement cache. */\n private updateRuntimeEntitlementRetry(\n runtimeEntitlements: RuntimeEntitlementResponse | undefined,\n attempt: RuntimeConnectionAttempt,\n ): void {\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n const { key } = attempt;\n if (\n runtimeEntitlements?.status === \"ready\" ||\n runtimeEntitlements?.error.retryable !== true\n ) {\n this.resetRuntimeEntitlementRetry();\n return;\n }\n if (this._runtimeEntitlementRetryTimer !== undefined) {\n return;\n }\n if (this._runtimeEntitlementRetryAttemptedKey === key) {\n this._runtimeEntitlementRetryPendingKey = undefined;\n return;\n }\n\n this._runtimeEntitlementRetryAttemptedKey = key;\n this._runtimeEntitlementRetryPendingKey = key;\n this._runtimeEntitlementRetryTimer = setTimeout(() => {\n this._runtimeEntitlementRetryTimer = undefined;\n void this.executeRuntimeEntitlementRetry(attempt).catch(\n (error: unknown) => {\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to retry runtime info (${this.runtimeUrl}/info): ${message}`,\n );\n },\n );\n }, RUNTIME_ENTITLEMENT_RETRY_DELAY_MS);\n }\n\n /** Start the bounded retry after the original connection has settled. */\n private async executeRuntimeEntitlementRetry(\n attempt: RuntimeConnectionAttempt,\n ): Promise<void> {\n const inFlight = this._connectionInFlight;\n if (inFlight?.attempt.generation === attempt.generation) {\n await inFlight.promise;\n }\n if (!this._runtimeUrl || !this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n await this.updateRuntimeConnection();\n }\n\n private async performRuntimeConnection({\n attempt,\n runtimeUrl,\n transport,\n options,\n }: {\n attempt: RuntimeConnectionAttempt;\n runtimeUrl: string | undefined;\n transport: CopilotRuntimeTransport;\n options?: RuntimeConnectionOptions;\n }): Promise<void> {\n const { key } = attempt;\n if (!runtimeUrl) {\n this.invalidateInspectorMetadataConnection();\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n );\n this._runtimeVersion = undefined;\n this._audioFileTranscriptionEnabled = false;\n this._runtimeMode = RUNTIME_MODE_SSE;\n this._intelligence = undefined;\n this._threadEndpoints = undefined;\n this._singleRouteResourceOperations = false;\n this._suggestions = undefined;\n this._inspectorLearning = false;\n this._a2uiEnabled = false;\n this._a2uiAgents = undefined;\n this._openGenerativeUIEnabled = false;\n this._licenseStatus = undefined;\n this._runtimeEntitlements = undefined;\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Disconnected,\n );\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n await this.notifyAgentsChanged();\n return;\n }\n\n const inspectorMetadataConnectionGeneration =\n this.inspectorMetadataConnectionGeneration;\n\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Connecting,\n );\n const runtimeHealthGeneration = this.runtimeHealthGeneration;\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Connecting,\n );\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n\n try {\n if (\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration\n ) {\n return;\n }\n const { runtimeInfo: runtimeInfoResponse, resolvedTransport } =\n options?.recovery\n ? await this.fetchRuntimeInfoWithTimeout(\n new AbortController(),\n runtimeUrl,\n transport,\n )\n : await this.fetchRuntimeInfo(runtimeUrl, transport);\n if (\n !this.isCurrentRuntimeConnection(attempt) ||\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration\n ) {\n return;\n }\n\n this._runtimeTransport = resolvedTransport;\n const { version, ...runtimeInfo } = runtimeInfoResponse;\n\n const credentials = (this.core as unknown as CopilotKitCoreFriendsAccess)\n .credentials;\n const rawDebug = (this.core as unknown as CopilotKitCoreFriendsAccess)\n .debug;\n const agents: Record<string, AbstractAgent> = Object.fromEntries(\n Object.entries(runtimeInfo.agents).map(\n ([id, { description, capabilities }]) => {\n // Preserve a live proxy only when its baked request routes still\n // match this connection. A new Runtime URL or resolved transport\n // needs a new proxy so agent traffic cannot keep using the old\n // target.\n const existing = Object.prototype.hasOwnProperty.call(\n this.remoteAgents,\n id,\n )\n ? this.remoteAgents[id]\n : undefined;\n if (\n existing instanceof ProxiedCopilotRuntimeAgent &&\n this.canReuseRuntimeAgent(\n existing,\n runtimeUrl,\n this._runtimeTransport,\n )\n ) {\n this.applyHeadersToAgent(existing);\n this.applyCredentialsToAgent(existing);\n this.applyMessageFilterToAgent(existing);\n this.applyRuntimeFetchToAgent(existing);\n this.applyRuntimeModeToAgent(existing, runtimeInfoResponse);\n return [id, existing];\n }\n const agent = new ProxiedCopilotRuntimeAgent({\n runtimeUrl: this._runtimeEndpointUrl ?? runtimeUrl,\n agentId: id, // Runtime agents always have their ID set correctly\n description: description,\n transport: this._runtimeTransport,\n credentials,\n runtimeMode: runtimeInfoResponse.mode ?? RUNTIME_MODE_SSE,\n intelligence: runtimeInfoResponse.intelligence,\n capabilities,\n debug: rawDebug ? resolveDebugConfig(rawDebug) : undefined,\n messageFilter: (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).messageFilter,\n });\n this.applyHeadersToAgent(agent);\n this.applyRuntimeFetchToAgent(agent);\n this.mintedThreadIds.set(agent, agent.threadId);\n if (options?.preserveOnFailure === true && existing) {\n agent.threadId = existing.threadId;\n agent.setState(existing.state);\n agent.setMessages([...existing.messages]);\n }\n this.remoteAgentConnections.set(agent, {\n runtimeUrl,\n endpointUrl: this._runtimeEndpointUrl,\n transport: this._runtimeTransport,\n });\n return [id, agent];\n },\n ),\n );\n\n this.remoteAgents = options?.recovery\n ? this.reconcileRecoveredAgents(agents)\n : agents;\n this._agents = { ...this.localAgents, ...this.remoteAgents };\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Connected,\n );\n this._runtimeVersion = version;\n this._audioFileTranscriptionEnabled =\n runtimeInfoResponse.audioFileTranscriptionEnabled ?? false;\n this._runtimeMode = runtimeInfoResponse.mode ?? RUNTIME_MODE_SSE;\n this._intelligence = runtimeInfoResponse.intelligence;\n this._singleRouteResourceOperations =\n resolvedTransport === \"single\" &&\n runtimeInfoResponse.singleRoute?.resourceOperations === true;\n this._threadEndpoints = this._singleRouteResourceOperations\n ? runtimeInfoResponse.singleRoute?.threadEndpoints\n : runtimeInfoResponse.threadEndpoints;\n this._suggestions = runtimeInfoResponse.suggestions;\n this._inspectorLearning = runtimeInfoResponse.inspectorLearning === true;\n this._inspectorMetadataSupported =\n runtimeInfoResponse.inspectorMetadata === true;\n this.inspectorMetadataRefreshReady = false;\n if (!this._inspectorMetadataSupported) {\n this.setInspectorMetadata(undefined);\n }\n const a2uiInfo = runtimeInfoResponse.a2ui;\n this._a2uiEnabled =\n a2uiInfo?.enabled ?? runtimeInfoResponse.a2uiEnabled ?? false;\n this._a2uiAgents = a2uiInfo?.enabled ? a2uiInfo.agents : undefined;\n this._openGenerativeUIEnabled =\n runtimeInfoResponse.openGenerativeUIEnabled ?? false;\n this._licenseStatus = runtimeInfoResponse.licenseStatus;\n this._runtimeEntitlements = runtimeInfoResponse.runtimeEntitlements;\n this.updateRuntimeEntitlementRetry(\n runtimeInfoResponse.runtimeEntitlements,\n attempt,\n );\n this._telemetryDisabled = runtimeInfoResponse.telemetryDisabled ?? false;\n\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Connected,\n );\n if (!this.isCurrentRuntimeConnection(attempt)) {\n return;\n }\n await this.notifyAgentsChanged();\n if (\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration ||\n this._runtimeConnectionStatus !==\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ) {\n return;\n }\n this.inspectorMetadataRefreshReady = true;\n if (this._inspectorMetadataSupported) {\n void this.refreshInspectorMetadata();\n }\n } catch (error) {\n if (\n !this.isCurrentRuntimeConnection(attempt) ||\n inspectorMetadataConnectionGeneration !==\n this.inspectorMetadataConnectionGeneration\n ) {\n return;\n }\n const boundedEntitlementRetryFailed =\n this._runtimeEntitlementRetryTimer === undefined &&\n this._runtimeEntitlementRetryAttemptedKey === key &&\n this._runtimeEntitlementRetryPendingKey === key;\n if (boundedEntitlementRetryFailed) {\n this._runtimeEntitlementRetryPendingKey = undefined;\n }\n if (options?.preserveOnFailure) {\n if (\n options?.recovery &&\n runtimeHealthGeneration !== this.runtimeHealthGeneration\n ) {\n return;\n }\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n } else {\n this.invalidateInspectorMetadataConnection();\n this.setRuntimeConnectionStatus(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n this._runtimeVersion = undefined;\n this._audioFileTranscriptionEnabled = false;\n this._runtimeMode = RUNTIME_MODE_SSE;\n this._intelligence = undefined;\n this._threadEndpoints = undefined;\n this._singleRouteResourceOperations = false;\n this._suggestions = undefined;\n this._inspectorLearning = false;\n this._a2uiEnabled = false;\n this._a2uiAgents = undefined;\n this._openGenerativeUIEnabled = false;\n // A failed bounded retry must settle the authority that caused it. Keep\n // that retryable result so consumers can distinguish terminal denial\n // from the initial loading window. Other connection failures still\n // clear stale Runtime authority.\n if (!boundedEntitlementRetryFailed) {\n this._licenseStatus = undefined;\n this._runtimeEntitlements = undefined;\n }\n this.remoteAgents = {};\n this._agents = this.localAgents;\n\n await this.notifyRuntimeStatusChanged(\n CopilotKitCoreRuntimeConnectionStatus.Error,\n );\n await this.notifyAgentsChanged();\n }\n\n const message =\n error instanceof Error ? error.message : JSON.stringify(error);\n logger.warn(\n `Failed to load runtime info (${runtimeUrl}/info): ${message}`,\n );\n const runtimeError =\n error instanceof Error ? error : new Error(String(error));\n await (this.core as unknown as CopilotKitCoreFriendsAccess).emitError({\n error: runtimeError,\n code: CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED,\n context: {\n runtimeUrl,\n },\n });\n }\n }\n\n private async fetchRuntimeInfo(\n runtimeUrl: string,\n runtimeTransport: CopilotRuntimeTransport,\n signal?: AbortSignal,\n ): Promise<RuntimeInfoFetchResult> {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const credentials = friends.credentials;\n // Resolution is synchronous for a record or a sync builder — only await\n // when it's actually async, so a sync source never pays an extra\n // microtask tick here.\n const resolved = friends.resolveHeaders();\n const resolvedHeaders = isPromiseLike(resolved)\n ? await abortable(resolved, signal)\n : resolved;\n const headers: Record<string, string> = {\n ...resolvedHeaders,\n };\n\n if (runtimeTransport === \"single\") {\n return {\n runtimeInfo: await this.fetchRuntimeInfoSingle(\n this.singleEndpointUrlFor(runtimeUrl),\n headers,\n credentials,\n signal,\n ),\n resolvedTransport: \"single\",\n };\n }\n\n if (runtimeTransport === \"auto\") {\n return this.fetchRuntimeInfoAutoDetect(\n runtimeUrl,\n headers,\n credentials,\n signal,\n );\n }\n\n // REST transport\n const response = await fetch(`${runtimeUrl}/info`, {\n headers,\n ...(credentials ? { credentials } : {}),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n return {\n runtimeInfo: (await response.json()) as RuntimeInfo,\n resolvedTransport: \"rest\",\n };\n }\n\n /**\n * The URL a single-route request targets: the runtime URL as the caller\n * supplied it. `runtimeUrl` is the slash-stripped form used for path joins;\n * a trailing slash can select a different proxy location, so the endpoint\n * itself keeps it.\n */\n private singleEndpointUrlFor(runtimeUrl: string): string {\n return this._runtimeEndpointUrl !== undefined &&\n this._runtimeUrl === runtimeUrl\n ? this._runtimeEndpointUrl\n : runtimeUrl;\n }\n\n private async fetchRuntimeInfoSingle(\n runtimeUrl: string,\n headers: Record<string, string>,\n credentials: RequestCredentials | undefined,\n signal?: AbortSignal,\n ): Promise<RuntimeInfo> {\n const response = await fetch(runtimeUrl, {\n method: \"POST\",\n headers: withJsonContentType(headers),\n body: JSON.stringify({ method: \"info\" }),\n ...(credentials ? { credentials } : {}),\n ...(signal ? { signal } : {}),\n });\n if (!response.ok) {\n throw await runtimeInfoError(response);\n }\n return (await response.json()) as RuntimeInfo;\n }\n\n /**\n * Auto-detect transport by trying REST first, then falling back to single-endpoint.\n * The caller commits the detected transport only after confirming this\n * connection attempt is still current.\n */\n private async fetchRuntimeInfoAutoDetect(\n runtimeUrl: string,\n headers: Record<string, string>,\n credentials: RequestCredentials | undefined,\n signal?: AbortSignal,\n ): Promise<RuntimeInfoFetchResult> {\n // Try REST first (GET /info)\n try {\n const response = await fetch(`${runtimeUrl}/info`, {\n headers: { ...headers },\n ...(credentials ? { credentials } : {}),\n ...(signal ? { signal } : {}),\n });\n // Only treat a successful (2xx) response as a valid REST runtime.\n // 404/405 means the endpoint doesn't exist; other non-2xx errors\n // (500, 403, etc.) should also fall through to single-endpoint.\n if (response.status >= 200 && response.status < 300) {\n return {\n runtimeInfo: (await response.json()) as RuntimeInfo,\n resolvedTransport: \"rest\",\n };\n }\n // Non-2xx — try single-endpoint below\n } catch {\n // REST failed (network error, etc.) — fall through to single-endpoint attempt\n }\n\n const runtimeInfo = await this.fetchRuntimeInfoSingle(\n this.singleEndpointUrlFor(runtimeUrl),\n { ...headers },\n credentials,\n signal,\n );\n return { runtimeInfo, resolvedTransport: \"single\" };\n }\n\n /**\n * Assign agent IDs to a record of agents\n */\n private assignAgentIds(\n agents: Record<string, AbstractAgent>,\n ): Record<string, AbstractAgent> {\n Object.entries(agents).forEach(([id, agent]) => {\n if (agent) {\n this.validateAndAssignAgentId(id, agent);\n }\n });\n return agents;\n }\n\n /**\n * Validate and assign an agent ID\n */\n private validateAndAssignAgentId(\n registrationId: string,\n agent: AbstractAgent,\n ): void {\n if (agent.agentId && agent.agentId !== registrationId) {\n throw new Error(\n `Agent registration mismatch: Agent with ID \"${agent.agentId}\" cannot be registered under key \"${registrationId}\". ` +\n `The agent ID must match the registration key or be undefined.`,\n );\n }\n if (!agent.agentId) {\n agent.agentId = registrationId;\n }\n }\n\n /**\n * Notify subscribers of runtime status changes\n */\n private async notifyRuntimeStatusChanged(\n status: CopilotKitCoreRuntimeConnectionStatus,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onRuntimeConnectionStatusChanged?.({\n copilotkit: this.core,\n status,\n }),\n \"Error in CopilotKitCore subscriber (onRuntimeConnectionStatusChanged):\",\n );\n }\n\n /**\n * Notify subscribers of agent changes\n */\n private async notifyAgentsChanged(): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onAgentsChanged?.({\n copilotkit: this.core,\n agents: this._agents,\n }),\n \"Subscriber onAgentsChanged error:\",\n );\n }\n\n private async notifyInspectorMetadataChanged(\n inspectorMetadata: InspectorMetadataV1 | undefined,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onInspectorMetadataChanged?.({\n copilotkit: this.core,\n inspectorMetadata,\n }),\n \"Subscriber onInspectorMetadataChanged error:\",\n );\n }\n}\n","/**\n * True when an entry scoped to `agentIds` goes to a run of `agentId`. An\n * entry without `agentIds` goes to every agent; an entry with them does not\n * go to a run without an agent id. Internal, not exported.\n */\nexport function isForAgent(\n agentIds: readonly string[] | undefined,\n agentId: string | undefined,\n): boolean {\n return (\n agentIds === undefined ||\n (agentId !== undefined && agentIds.includes(agentId))\n );\n}\n","import type { Context } from \"@ag-ui/client\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport type { CopilotKitCore } from \"./core\";\nimport type { CopilotKitCoreFriendsAccess } from \"./core\";\nimport { isForAgent } from \"./agent-scope\";\n\n/**\n * A context entry with optional per-agent scoping.\n * When `agentIds` is set, the entry is forwarded only to runs of those agents;\n * when omitted, the entry is forwarded to every agent run.\n */\nexport interface ScopedContext extends Context {\n agentIds?: string[];\n}\n\n/**\n * Manages context storage and lifecycle for CopilotKitCore.\n * Context represents additional information available to agents during execution.\n */\nexport class ContextStore {\n private _context: Record<string, ScopedContext> = {};\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Get all context entries as a readonly record\n */\n get context(): Readonly<Record<string, ScopedContext>> {\n return this._context;\n }\n\n /**\n * Add a new context entry. Pass `agentIds` to restrict the entry to runs of\n * specific agents (#5369); omit it for context every agent should receive.\n * @returns The ID of the created context entry\n */\n addContext({ description, value, agentIds }: ScopedContext): string {\n const id = randomUUID();\n this._context[id] = {\n description,\n value,\n ...(agentIds ? { agentIds } : {}),\n };\n void this.notifySubscribers();\n return id;\n }\n\n /**\n * Build the context array for a run of the given agent: entries scoped to\n * other agents are dropped, and the scoping metadata is stripped so only\n * protocol-shaped `{ description, value }` entries go over the wire.\n */\n getContextForAgent(agentId?: string): Context[] {\n return Object.values(this._context)\n .filter((entry) => isForAgent(entry.agentIds, agentId))\n .map(({ description, value }) => ({ description, value }));\n }\n\n /**\n * Remove a context entry by ID\n */\n removeContext(id: string): void {\n delete this._context[id];\n void this.notifySubscribers();\n }\n\n /**\n * Notify all subscribers of context changes\n */\n private async notifySubscribers(): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onContextChanged?.({\n copilotkit: this.core,\n context: this._context,\n }),\n \"Subscriber onContextChanged error:\",\n );\n }\n}\n","import type { AbstractAgent, Message, Tool } from \"@ag-ui/client\";\nimport { HttpAgent } from \"@ag-ui/client\";\nimport { ProxiedCopilotRuntimeAgent } from \"../agent\";\nimport { randomUUID, partialJSONParse } from \"@copilotkit/shared\";\nimport type { CopilotKitCore } from \"./core\";\nimport type { CopilotKitCoreGetSuggestionsResult } from \"./core\";\nimport type { CopilotKitCoreFriendsAccess } from \"./core\";\nimport type {\n DynamicSuggestionsConfig,\n StaticSuggestionsConfig,\n Suggestion,\n SuggestionsConfig,\n} from \"../types\";\n\n/**\n * The minimal cancellation surface a running suggestion generation exposes.\n * Both a cloned `AbstractAgent` (via `abortRun`) and the stateless fetch shim\n * (which aborts an `AbortController`) satisfy this, so `clearSuggestions` can\n * cancel either uniformly.\n */\ninterface AbortableSuggestionRun {\n abortRun(): void;\n}\n\n/**\n * Manages suggestion generation, streaming, and lifecycle for CopilotKitCore.\n * Handles both dynamic (AI-generated) and static suggestions.\n */\nexport class SuggestionEngine {\n private _suggestionsConfig: Record<string, SuggestionsConfig> = {};\n private _suggestions: Record<string, Record<string, Suggestion[]>> = {};\n private _runningSuggestions: Record<string, AbortableSuggestionRun[]> = {};\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Initialize with suggestion configs\n */\n initialize(suggestionsConfig: SuggestionsConfig[]): void {\n for (const config of suggestionsConfig) {\n this._suggestionsConfig[randomUUID()] = config;\n }\n }\n\n /**\n * Add a suggestion configuration\n * @returns The ID of the created config\n */\n addSuggestionsConfig(config: SuggestionsConfig): string {\n const id = randomUUID();\n this._suggestionsConfig[id] = config;\n void this.notifySuggestionsConfigChanged();\n return id;\n }\n\n /**\n * Remove a suggestion configuration by ID\n */\n removeSuggestionsConfig(id: string): void {\n delete this._suggestionsConfig[id];\n void this.notifySuggestionsConfigChanged();\n }\n\n /**\n * Reload suggestions for a specific agent\n * This triggers generation of new suggestions based on current configs\n */\n public reloadSuggestions(agentId: string): void {\n this.clearSuggestions(agentId);\n\n // The agent may legitimately be missing here (e.g. runtime info still loading,\n // or the consumer agent is configured but not yet registered) — static suggestions\n // don't need it, only dynamic generation does. Treat that case as \"no messages yet\"\n // and process static configs anyway.\n const agent = (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).getAgent(agentId);\n\n const messageCount = agent?.messages?.length ?? 0;\n let hasAnySuggestions = false;\n\n for (const config of Object.values(this._suggestionsConfig)) {\n // Check if config applies to this agent\n if (\n config.consumerAgentId !== undefined &&\n config.consumerAgentId !== \"*\" &&\n config.consumerAgentId !== agentId\n ) {\n continue;\n }\n\n // Check availability based on message count\n if (!this.shouldShowSuggestions(config, messageCount)) {\n continue;\n }\n\n const suggestionId = randomUUID();\n\n if (isDynamicSuggestionsConfig(config)) {\n // Dynamic suggestions need a real agent (provider + consumer messages).\n // Skip when the agent isn't ready yet — `reloadSuggestions` will be\n // called again once it is.\n if (!agent) {\n continue;\n }\n if (!hasAnySuggestions) {\n hasAnySuggestions = true;\n void this.notifySuggestionsStartedLoading(agentId);\n }\n void this.generateSuggestions(suggestionId, config, agentId);\n } else if (isStaticSuggestionsConfig(config)) {\n this.addStaticSuggestions(suggestionId, config, agentId);\n }\n }\n }\n\n /**\n * Clear all suggestions for a specific agent\n */\n public clearSuggestions(agentId: string): void {\n const runningAgents = this._runningSuggestions[agentId];\n if (runningAgents) {\n for (const agent of runningAgents) {\n agent.abortRun();\n }\n delete this._runningSuggestions[agentId];\n }\n this._suggestions[agentId] = {};\n\n void this.notifySuggestionsChanged(agentId, []);\n }\n\n /**\n * Get current suggestions for an agent\n */\n public getSuggestions(agentId: string): CopilotKitCoreGetSuggestionsResult {\n const suggestions = Object.values(this._suggestions[agentId] ?? {}).flat();\n const isLoading = (this._runningSuggestions[agentId]?.length ?? 0) > 0;\n return { suggestions, isLoading };\n }\n\n /**\n * Generate suggestions by running a provider agent and extracting the\n * `copilotkitSuggest` tool call from its streamed messages.\n *\n * Two transports, one set of mechanics: both seed an agent with the\n * consumer's messages + state and the instruction, then `runAgent` with\n * forced `copilotkitSuggest` tool choice, parsing suggestions as messages\n * stream in via `onMessagesChanged`.\n *\n * - **Stateless** (runtime advertises `suggestions` and transport isn't\n * `single`): a stock `HttpAgent` pointed at `/agent/:id/suggest`. That\n * endpoint runs the provider directly and streams AG-UI SSE **without**\n * persisting a thread, and a plain `HttpAgent` only ever speaks REST SSE —\n * it never routes through the Intelligence websocket delegate (which would\n * persist a thread). This is the path that removes the thread flood.\n * - **Fallback** (capability absent → old runtime, or `single` transport):\n * clone the provider agent and run it client-side, as before.\n *\n * Gated to non-`single` transports because this client only builds the\n * multi-route `/agent/:id/suggest` URL; single-route deployments (not the\n * persisting-thread/Intelligence case) fall through to the clone fallback.\n */\n private async generateSuggestions(\n suggestionId: string,\n config: DynamicSuggestionsConfig,\n consumerAgentId: string,\n ): Promise<void> {\n // The cancellable handle for this generation, removed from the running set\n // in `finally`. `abortRun` flips `aborted` before cancelling the underlying\n // agent so the `catch` can distinguish a deliberate clear/reload from a real\n // failure — some engines (undici, some React Native) reject an aborted run\n // with a non-\"AbortError\" error that `isAbortError` alone would misclassify.\n let runHandle: AbortableSuggestionRun | undefined = undefined;\n let aborted = false;\n try {\n const friends = this.core as unknown as CopilotKitCoreFriendsAccess;\n const resolvedProviderAgentId = config.providerAgentId ?? \"default\";\n const suggestionsProviderAgent = friends.getAgent(\n resolvedProviderAgentId,\n );\n if (!suggestionsProviderAgent) {\n throw new Error(\n `Suggestions provider agent not found: ${resolvedProviderAgentId}`,\n );\n }\n const suggestionsConsumerAgent = friends.getAgent(consumerAgentId);\n if (!suggestionsConsumerAgent) {\n throw new Error(\n `Suggestions consumer agent not found: ${consumerAgentId}`,\n );\n }\n\n const instructionContent = [\n `Suggest what the user could say next. Provide clear, highly relevant suggestions by calling the \\`copilotkitSuggest\\` tool.`,\n `Provide at least ${config.minSuggestions ?? 1} and at most ${\n config.maxSuggestions ?? 3\n } suggestions.`,\n `The user has the following tools available: ${JSON.stringify(\n friends.buildFrontendTools(consumerAgentId),\n )}.`,\n ` ${config.instructions}`,\n ].join(\"\\n\");\n\n // Initialize suggestion storage for this agent/suggestion combo\n this._suggestions[consumerAgentId] = {\n ...this._suggestions[consumerAgentId],\n [suggestionId]: [],\n };\n\n // Deep-clone the consumer's messages + state so the suggestion run sees\n // the same context a real turn would, without sharing mutable references.\n const seededMessages: Message[] = JSON.parse(\n JSON.stringify(suggestionsConsumerAgent.messages),\n );\n const seededState: unknown = JSON.parse(\n JSON.stringify(suggestionsConsumerAgent.state ?? {}),\n );\n\n const useStateless =\n this.core.suggestions === true &&\n this.core.runtimeTransport !== \"single\";\n\n let suggestionAgent: AbstractAgent;\n // Tracks the stateless HttpAgent (when built) so its headers can be\n // resolved fresh right before the request is sent, without widening\n // `suggestionAgent`'s type below.\n let statelessAgent: HttpAgent | undefined;\n if (useStateless) {\n const suggestUrl = `${this.core.runtimeUrl}/agent/${encodeURIComponent(\n resolvedProviderAgentId,\n )}/suggest`;\n const credentials = this.core.credentials;\n statelessAgent = new HttpAgent({\n agentId: resolvedProviderAgentId,\n url: suggestUrl,\n // `HttpAgentConfig` has no `credentials` field; inject it via a fetch\n // wrapper so cookie-based / self-hosted auth still rides along on the\n // `/suggest` request.\n ...(credentials\n ? {\n fetch: (url: string, requestInit: RequestInit) =>\n fetch(url, { ...requestInit, credentials }),\n }\n : {}),\n });\n suggestionAgent = statelessAgent;\n } else {\n suggestionAgent = suggestionsProviderAgent.clone();\n // A suggestion run gets a brand-new thread id, so no backend store can\n // fill in history the client withheld. An app-level `messageFilter`\n // trimmed for a persisted conversation would therefore leave the\n // provider with only the tail of the seeded context and generate\n // suggestions about nothing. The seeded messages ARE the context here.\n if (suggestionAgent instanceof ProxiedCopilotRuntimeAgent) {\n suggestionAgent.messageFilter = undefined;\n }\n }\n\n suggestionAgent.threadId = suggestionId;\n suggestionAgent.setMessages(seededMessages);\n suggestionAgent.setState(seededState);\n\n runHandle = {\n abortRun: () => {\n aborted = true;\n suggestionAgent.abortRun();\n },\n };\n // Registered before the header resolution below (which can await) so\n // `isLoading` flips true in the same tick this generation starts,\n // matching the pre-#1937 timing: a caller inspecting it right after\n // `reloadSuggestions()` must see the run as already in flight.\n this._runningSuggestions[consumerAgentId] = [\n ...(this._runningSuggestions[consumerAgentId] ?? []),\n runHandle,\n ];\n\n if (statelessAgent) {\n // Resolved fresh (not the last snapshot) so a builder's current\n // token rides along on this stateless request, applied right before\n // the request is sent (#1937).\n statelessAgent.headers = { ...(await this.core.resolveHeaders()) };\n } else {\n // A clone of a plain `HttpAgent` carries the source agent's headers\n // from its last run, so apply fresh ones the way a normal run does.\n // A proxied runtime agent adds core headers at send time instead.\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).prepareAgentHeadersForRun(suggestionAgent);\n }\n\n // `clearSuggestions`/`abortRun` may have run while the header\n // resolution above was in flight. `HttpAgent.runAgent` always installs\n // a fresh `AbortController` for the run it starts, so an abort issued\n // against the (now-discarded) pre-run instance would NOT stop the\n // request below from being sent, and a completed run would write stale\n // suggestions into whatever the current turn has become. `finally`\n // still performs its cleanup on this early return.\n if (aborted) return;\n\n suggestionAgent.addMessage({\n id: suggestionId,\n role: \"user\",\n content: instructionContent,\n });\n\n await suggestionAgent.runAgent(\n {\n context: friends.getContextForAgent(consumerAgentId),\n forwardedProps: {\n ...friends.getPropertiesForAgent(consumerAgentId),\n toolChoice: {\n type: \"function\",\n function: { name: \"copilotkitSuggest\" },\n },\n },\n tools: [SUGGEST_TOOL],\n },\n {\n onMessagesChanged: ({ messages }) => {\n this.extractSuggestions(\n messages,\n suggestionId,\n consumerAgentId,\n true,\n );\n },\n },\n );\n } catch (error) {\n // An abort is expected when suggestions are cleared/reloaded mid-flight;\n // swallow it quietly rather than surfacing it as a failure. `isAbortError`\n // is the primary (name-based) check; `aborted` covers engines that reject\n // an aborted run with a differently-named error (or a `TypeError`).\n if (!isAbortError(error) && !aborted) {\n console.warn(\"Error generating suggestions:\", error);\n }\n } finally {\n // Finalize suggestions by marking them as no longer loading\n this.finalizeSuggestions(suggestionId, consumerAgentId);\n\n // Remove this run from the running set. `runHandle` may be undefined when\n // generation threw before it was assigned (e.g. provider/consumer agent\n // lookup failed); still perform cleanup so the loading balance holds. If\n // no runs remain for this consumer, emit finished-loading — otherwise a\n // subscriber that saw `started` would hang in the loading state.\n const runningAgents = this._runningSuggestions[consumerAgentId];\n const remaining = runHandle\n ? (runningAgents ?? []).filter((a) => a !== runHandle)\n : (runningAgents ?? []);\n\n if (remaining.length === 0) {\n delete this._runningSuggestions[consumerAgentId];\n await this.notifySuggestionsFinishedLoading(consumerAgentId);\n } else {\n this._runningSuggestions[consumerAgentId] = remaining;\n }\n }\n }\n\n /**\n * Finalize suggestions by marking them as no longer loading\n */\n private finalizeSuggestions(\n suggestionId: string,\n consumerAgentId: string,\n ): void {\n const agentSuggestions = this._suggestions[consumerAgentId];\n const currentSuggestions = agentSuggestions?.[suggestionId];\n\n if (\n agentSuggestions &&\n currentSuggestions &&\n currentSuggestions.length > 0\n ) {\n // Filter out empty suggestions and mark remaining as no longer loading\n const finalizedSuggestions = currentSuggestions\n .filter(\n (suggestion) => suggestion.title !== \"\" || suggestion.message !== \"\",\n )\n .map((suggestion) => ({\n ...suggestion,\n isLoading: false,\n }));\n\n if (finalizedSuggestions.length > 0) {\n agentSuggestions[suggestionId] = finalizedSuggestions;\n } else {\n delete agentSuggestions[suggestionId];\n }\n\n // Get all aggregated suggestions for this agent\n const allSuggestions = Object.values(\n this._suggestions[consumerAgentId] ?? {},\n ).flat();\n\n void this.notifySuggestionsChanged(\n consumerAgentId,\n allSuggestions,\n \"finalized\",\n );\n }\n }\n\n /**\n * Extract suggestions from messages (called during streaming)\n */\n extractSuggestions(\n messages: readonly Message[],\n suggestionId: string,\n consumerAgentId: string,\n isRunning: boolean,\n ): void {\n const idx = messages.findIndex((message) => message.id === suggestionId);\n if (idx == -1) {\n return;\n }\n\n const suggestions: Suggestion[] = [];\n const newMessages = messages.slice(idx + 1);\n\n for (const message of newMessages) {\n if (message.role === \"assistant\" && message.toolCalls) {\n for (const toolCall of message.toolCalls) {\n if (toolCall.function.name === \"copilotkitSuggest\") {\n // Join all argument chunks into a single string for parsing\n // arguments can be either a string or an array of strings\n const fullArgs = Array.isArray(toolCall.function.arguments)\n ? toolCall.function.arguments.join(\"\")\n : toolCall.function.arguments;\n const parsed = partialJSONParse(fullArgs);\n if (\n parsed &&\n typeof parsed === \"object\" &&\n \"suggestions\" in parsed\n ) {\n const parsedSuggestions = (parsed as any).suggestions;\n if (Array.isArray(parsedSuggestions)) {\n for (const item of parsedSuggestions) {\n if (item && typeof item === \"object\" && \"title\" in item) {\n suggestions.push({\n title: item.title ?? \"\",\n message: item.message ?? \"\",\n // Defaults to false; only the trailing item is flipped to\n // true below, and only while a streaming run is in flight.\n isLoading: false,\n });\n }\n }\n }\n }\n }\n }\n }\n }\n\n // Set isLoading for the last suggestion if still running\n if (isRunning && suggestions.length > 0) {\n suggestions[suggestions.length - 1]!.isLoading = true;\n }\n\n const agentSuggestions = this._suggestions[consumerAgentId];\n if (agentSuggestions) {\n agentSuggestions[suggestionId] = suggestions;\n\n // Get all aggregated suggestions for this agent\n const allSuggestions = Object.values(\n this._suggestions[consumerAgentId] ?? {},\n ).flat();\n\n void this.notifySuggestionsChanged(\n consumerAgentId,\n allSuggestions,\n \"suggestions changed\",\n );\n }\n }\n\n /**\n * Notify subscribers of suggestions config changes\n */\n private async notifySuggestionsConfigChanged(): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsConfigChanged?.({\n copilotkit: this.core,\n suggestionsConfig: this._suggestionsConfig,\n }),\n \"Subscriber onSuggestionsConfigChanged error:\",\n );\n }\n\n /**\n * Notify subscribers of suggestions changes\n */\n private async notifySuggestionsChanged(\n agentId: string,\n suggestions: Suggestion[],\n context: string = \"\",\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsChanged?.({\n copilotkit: this.core,\n agentId,\n suggestions,\n }),\n `Subscriber onSuggestionsChanged error: ${context}`,\n );\n }\n\n /**\n * Notify subscribers that suggestions started loading\n */\n private async notifySuggestionsStartedLoading(\n agentId: string,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsStartedLoading?.({\n copilotkit: this.core,\n agentId,\n }),\n \"Subscriber onSuggestionsStartedLoading error:\",\n );\n }\n\n /**\n * Notify subscribers that suggestions finished loading\n */\n private async notifySuggestionsFinishedLoading(\n agentId: string,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber) =>\n subscriber.onSuggestionsFinishedLoading?.({\n copilotkit: this.core,\n agentId,\n }),\n \"Subscriber onSuggestionsFinishedLoading error:\",\n );\n }\n\n /**\n * Check if suggestions should be shown based on availability and message count\n */\n private shouldShowSuggestions(\n config: SuggestionsConfig,\n messageCount: number,\n ): boolean {\n const availability = config.available;\n\n // Default behavior if no availability specified\n if (!availability) {\n if (isDynamicSuggestionsConfig(config)) {\n return messageCount > 0; // Default: after-first-message\n } else {\n return messageCount === 0; // Default: before-first-message\n }\n }\n\n switch (availability) {\n case \"disabled\":\n return false;\n case \"before-first-message\":\n return messageCount === 0;\n case \"after-first-message\":\n return messageCount > 0;\n case \"always\":\n return true;\n default:\n return false;\n }\n }\n\n /**\n * Add static suggestions directly without AI generation\n */\n private addStaticSuggestions(\n suggestionId: string,\n config: StaticSuggestionsConfig,\n consumerAgentId: string,\n ): void {\n // Mark all as not loading since they're static\n const suggestions = config.suggestions.map((s) => ({\n ...s,\n isLoading: false,\n }));\n\n // Store suggestions\n this._suggestions[consumerAgentId] = {\n ...this._suggestions[consumerAgentId],\n [suggestionId]: suggestions,\n };\n\n // Notify subscribers\n const allSuggestions = Object.values(\n this._suggestions[consumerAgentId] ?? {},\n ).flat();\n\n void this.notifySuggestionsChanged(\n consumerAgentId,\n allSuggestions,\n \"static suggestions added\",\n );\n }\n}\n\n/**\n * Detects an `AbortController`-driven cancellation so the stateless path can\n * treat it as an expected (non-error) outcome on clear/reload.\n */\nexport function isAbortError(error: unknown): boolean {\n // Detect purely by name: a `DOMException` is NOT `instanceof Error` in Safari\n // and older engines, so gating on `instanceof Error` would misclassify a real\n // user abort as a failure in the browser (this package runs client-side).\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"name\" in error &&\n (error as { name?: unknown }).name === \"AbortError\"\n );\n}\n\n/**\n * Type guard for dynamic suggestions config\n */\nfunction isDynamicSuggestionsConfig(\n config: SuggestionsConfig,\n): config is DynamicSuggestionsConfig {\n return \"instructions\" in config;\n}\n\n/**\n * Type guard for static suggestions config\n */\nfunction isStaticSuggestionsConfig(\n config: SuggestionsConfig,\n): config is StaticSuggestionsConfig {\n return \"suggestions\" in config;\n}\n\n/**\n * The tool definition for AI-generated suggestions\n */\nconst SUGGEST_TOOL: Tool = {\n name: \"copilotkitSuggest\",\n description: \"Suggest what the user could say next\",\n parameters: {\n type: \"object\",\n properties: {\n suggestions: {\n type: \"array\",\n description: \"List of suggestions shown to the user as buttons.\",\n items: {\n type: \"object\",\n properties: {\n title: {\n type: \"string\",\n description:\n \"The title of the suggestion. This is shown as a button and should be short.\",\n },\n message: {\n type: \"string\",\n description:\n \"The message to send when the suggestion is clicked. This should be a clear, complete sentence \" +\n \"and will be sent as an instruction to the AI.\",\n },\n },\n required: [\"title\", \"message\"],\n },\n },\n },\n required: [\"suggestions\"],\n },\n};\n","import type { ContentPart } from \"@ag-ui/client\";\n\n/**\n * Single authority for the forwarded-to-client sentinel used by StateManager\n * and RunHandler.\n */\nexport const FORWARDED_TO_CLIENT = \"Forwarded to client\";\n\nexport function normalizeToolResultContent(content: unknown): string | null {\n if (typeof content === \"string\") return content.trim();\n\n if (Array.isArray(content)) {\n const text = content\n .flatMap((part) => {\n if (typeof part === \"string\") return [part];\n if (\n part &&\n typeof part === \"object\" &&\n \"text\" in part &&\n typeof (part as { text?: unknown }).text === \"string\"\n ) {\n return [(part as { text: string }).text];\n }\n return [];\n })\n .join(\"\")\n .trim();\n return text.length > 0 ? text : null;\n }\n\n if (\n content &&\n typeof content === \"object\" &&\n \"text\" in content &&\n typeof (content as { text?: unknown }).text === \"string\"\n ) {\n return (content as { text: string }).text.trim();\n }\n\n return null;\n}\n\nexport function isForwardedToClientPlaceholder(content: unknown): boolean {\n return normalizeToolResultContent(content) === FORWARDED_TO_CLIENT;\n}\n\nconst MEDIA_PART_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\nfunction isOptionalString(value: unknown): boolean {\n return value === undefined || typeof value === \"string\";\n}\n\nfunction isPartSource(value: unknown): boolean {\n if (!value || typeof value !== \"object\") return false;\n const source = value as Record<string, unknown>;\n if (typeof source.value !== \"string\") return false;\n switch (source.type) {\n case \"data\":\n return typeof source.mimeType === \"string\";\n case \"url\":\n return isOptionalString(source.mimeType);\n case \"file\":\n return (\n isOptionalString(source.provider) && isOptionalString(source.mimeType)\n );\n default:\n return false;\n }\n}\n\n/**\n * Mirrors `ContentPartSchema` from `@ag-ui/core/schemas`. The runtime parses\n * the request with that schema, and one invalid part there fails the whole run.\n * Core does not import the schema because the UMD build has no global for it.\n * A test checks this function against the schema.\n */\nexport function isContentPart(value: unknown): value is ContentPart {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const part = value as Record<string, unknown>;\n if (!isOptionalString(part.id) || part.metadata === null) return false;\n if (part.type === \"text\") return typeof part.text === \"string\";\n return (\n typeof part.type === \"string\" &&\n MEDIA_PART_TYPES.has(part.type) &&\n isPartSource(part.source)\n );\n}\n\n/**\n * Converts what a frontend tool handler returned into tool message content.\n * A non-empty array of AG-UI content parts passes through unchanged, so an\n * image reaches the model as media. Everything else becomes a string, as before.\n *\n * `text` is the string form, for surfaces typed as `result: string`\n * (`runTool`, `onToolExecutionEnd`). For content parts it is the JSON text they\n * received before. It is computed here, so a part that cannot be serialized\n * throws inside the caller's handler error boundary.\n */\nexport function toToolResultContent(result: unknown): {\n content: string | ContentPart[];\n text: string;\n} {\n if (result === undefined || result === null) return { content: \"\", text: \"\" };\n if (typeof result === \"string\") return { content: result, text: result };\n const text = JSON.stringify(result);\n if (\n Array.isArray(result) &&\n result.length > 0 &&\n result.every(isContentPart)\n ) {\n return { content: result, text };\n }\n return { content: text, text };\n}\n","import { schemaToJsonSchema } from \"@copilotkit/shared\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { FrontendTool } from \"../types\";\n\n/**\n * Empty tool schema constant\n */\nconst EMPTY_TOOL_SCHEMA = {\n type: \"object\",\n properties: {},\n} as const satisfies Record<string, unknown>;\n\n/**\n * Create a JSON schema from a tool's parameters\n */\nexport function createToolSchema(\n tool: FrontendTool<any>,\n): Record<string, unknown> {\n if (!tool.parameters) {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const rawSchema = schemaToJsonSchema(tool.parameters, {\n zodToJsonSchema: (schema, options) =>\n zodToJsonSchema(\n schema as Parameters<typeof zodToJsonSchema>[0],\n options as Parameters<typeof zodToJsonSchema>[1],\n ),\n });\n\n if (!rawSchema || typeof rawSchema !== \"object\") {\n return { ...EMPTY_TOOL_SCHEMA };\n }\n\n const { $schema: _$schema, ...schema } = rawSchema as Record<string, unknown>;\n\n if (typeof schema.type !== \"string\") {\n schema.type = \"object\";\n }\n if (typeof schema.properties !== \"object\" || schema.properties === null) {\n schema.properties = {};\n }\n\n stripAdditionalProperties(schema);\n return schema;\n}\n\n/**\n * Remove every `additionalProperties` key from a JSON schema tree, in place.\n * Some LLM providers reject schemas that carry it.\n */\nfunction stripAdditionalProperties(schema: unknown): void {\n if (!schema || typeof schema !== \"object\") {\n return;\n }\n\n if (Array.isArray(schema)) {\n schema.forEach(stripAdditionalProperties);\n return;\n }\n\n const record = schema as Record<string, unknown>;\n\n if (record.additionalProperties !== undefined) {\n delete record.additionalProperties;\n }\n\n for (const value of Object.values(record)) {\n stripAdditionalProperties(value);\n }\n}\n","import { buildResumeArray, isInterruptExpired } from \"@ag-ui/client\";\nimport type {\n AbstractAgent,\n Interrupt,\n ResumeEntry,\n Message,\n} from \"@ag-ui/client\";\n\nimport { isForwardedToClientPlaceholder } from \"./core/tool-result-content\";\n\ntype ResumeResponse =\n | { status: \"resolved\"; payload?: unknown }\n | { status: \"cancelled\" };\n\n/** @internal Application authors must not depend on this contract. */\nexport interface ɵInterruptEvent<TValue = unknown> {\n name: string;\n value: TValue;\n}\n\n/** @internal Application authors must not depend on this contract. */\nexport type ɵPendingInterrupt<TValue = unknown> =\n | { kind: \"legacy\"; event: ɵInterruptEvent<TValue> }\n | { kind: \"standard\"; interrupts: readonly Interrupt[] };\n\n/** @internal Application authors must not depend on this contract. */\nexport interface ɵInterruptToolResult {\n toolCallId: string;\n content: Extract<Message, { role: \"tool\" }>[\"content\"];\n}\n\n/** @internal Application authors must not depend on this contract. */\nexport type ɵInterruptDecision =\n | { kind: \"ignored\" }\n | { kind: \"waiting\" }\n | { kind: \"dismiss\" }\n | {\n kind: \"expired\";\n interrupt: Interrupt;\n }\n | {\n kind: \"legacy-resume\";\n payload: unknown;\n interruptValue: unknown;\n }\n | {\n kind: \"resume\";\n resume: ResumeEntry[];\n toolResults: ɵInterruptToolResult[];\n };\n\n/** Serialize a newly answered frontend call for the canonical message history. */\nfunction toolResultContent(response: ResumeResponse): string {\n if (response.status === \"cancelled\") {\n return JSON.stringify({ status: \"cancelled\" });\n }\n return JSON.stringify(response.payload ?? { status: \"resolved\" });\n}\n\n/**\n * @internal Framework-neutral interrupt response state shared by framework\n * adapters. Application authors must not depend on this API.\n */\nexport class ɵInterruptState<TValue = unknown> {\n readonly #responses: Record<string, ResumeResponse> = Object.create(null);\n #adoptedContent = new Map<string, ɵInterruptToolResult[\"content\"]>();\n #pending: ɵPendingInterrupt<TValue> | null = null;\n #sealed = false;\n\n /** Return the active normalized interrupt without exposing mutable state. */\n get pending(): ɵPendingInterrupt<TValue> | null {\n const pending = this.#pending;\n if (pending?.kind === \"standard\") {\n return { kind: \"standard\", interrupts: [...pending.interrupts] };\n }\n return pending;\n }\n\n /** Replace the current interrupt with a legacy custom-event interrupt. */\n setLegacy(event: ɵInterruptEvent<TValue>): void {\n this.#replace({ kind: \"legacy\", event });\n }\n\n /** Replace the current interrupt with an AG-UI standard interrupt set. */\n setStandard(interrupts: readonly Interrupt[]): void {\n const ids = new Set<string>();\n const callIds = new Set<string>();\n for (const interrupt of interrupts) {\n if (ids.has(interrupt.id))\n throw new Error(`Duplicate interrupt id: ${interrupt.id}`);\n ids.add(interrupt.id);\n if (interrupt.reason === \"tool_call\" && interrupt.toolCallId) {\n if (callIds.has(interrupt.toolCallId))\n throw new Error(\n `Duplicate interrupt tool call: ${interrupt.toolCallId}`,\n );\n callIds.add(interrupt.toolCallId);\n }\n }\n this.#replace({ kind: \"standard\", interrupts: [...interrupts] });\n }\n\n /** Clear all pending interrupt data and accumulated responses. */\n clear(): void {\n this.#pending = null;\n this.#sealed = false;\n this.#adoptedContent.clear();\n for (const id of Object.keys(this.#responses)) delete this.#responses[id];\n }\n\n /** Record a resolved response and return the next framework action. */\n resolve(\n payload?: unknown,\n interruptId?: string,\n messages: readonly Message[] = [],\n ): ɵInterruptDecision {\n const pending = this.#pending;\n if (!pending || this.#sealed) return { kind: \"ignored\" };\n if (pending.kind === \"legacy\") {\n this.#sealed = true;\n return {\n kind: \"legacy-resume\",\n payload,\n interruptValue: pending.event.value,\n };\n }\n return this.#respond(\n pending.interrupts,\n interruptId,\n {\n status: \"resolved\",\n payload,\n },\n messages,\n );\n }\n\n /** Record a cancelled response and return the next framework action. */\n cancel(\n interruptId?: string,\n messages: readonly Message[] = [],\n ): ɵInterruptDecision {\n const pending = this.#pending;\n if (!pending || this.#sealed) return { kind: \"ignored\" };\n if (pending.kind === \"legacy\") {\n this.#sealed = true;\n return { kind: \"dismiss\" };\n }\n return this.#respond(\n pending.interrupts,\n interruptId,\n {\n status: \"cancelled\",\n },\n messages,\n );\n }\n\n /** Reject ambiguous assistant definitions before executing or answering a call. */\n validateToolCalls(messages: readonly Message[]): void {\n if (this.#pending?.kind !== \"standard\") return;\n const pendingCalls = new Set(\n this.#pending.interrupts\n .filter((interrupt) => interrupt.reason === \"tool_call\")\n .map((interrupt) => interrupt.toolCallId),\n );\n const seen = new Set<string>();\n for (const message of messages) {\n if (message.role !== \"assistant\") continue;\n for (const call of message.toolCalls ?? []) {\n if (!pendingCalls.has(call.id)) continue;\n if (seen.has(call.id))\n throw new Error(`Duplicate tool call definition: ${call.id}`);\n seen.add(call.id);\n }\n }\n }\n\n /** Let UI adapters ignore answers for exactly one successful frontend result. */\n isCompletedToolCall(\n interruptId: string | undefined,\n messages: readonly Message[],\n ): boolean {\n const pending = this.#pending;\n if (pending?.kind !== \"standard\") return false;\n const id = interruptId ?? pending.interrupts[0]?.id;\n const interrupt = pending.interrupts.find((entry) => entry.id === id);\n if (interrupt?.reason !== \"tool_call\" || !interrupt.toolCallId)\n return false;\n // Do not hide duplicate results: resolve/cancel still reaches #decide's error.\n const results = messages.filter(\n (message) =>\n message.role === \"tool\" &&\n message.toolCallId === interrupt.toolCallId &&\n !isForwardedToClientPlaceholder(message.content),\n );\n const result = results[0];\n return (\n results.length === 1 &&\n result?.role === \"tool\" &&\n result.error === undefined\n );\n }\n\n /** Resume only when saved frontend results answer every pending interrupt. */\n resumeWithToolResults(messages: readonly Message[]): ɵInterruptDecision {\n const pending = this.#pending;\n if (pending?.kind !== \"standard\" || this.#sealed)\n return { kind: \"ignored\" };\n return this.#decide(pending.interrupts, { ...this.#responses }, messages);\n }\n\n /** Start a new batch with no decisions retained from the preceding run. */\n #replace(pending: ɵPendingInterrupt<TValue>): void {\n this.clear();\n this.#pending = pending;\n }\n\n /** Record one explicit answer and reconcile it with saved frontend results. */\n #respond(\n interrupts: readonly Interrupt[],\n interruptId: string | undefined,\n response: ResumeResponse,\n messages: readonly Message[],\n ): ɵInterruptDecision {\n const id = interruptId ?? interrupts[0]?.id;\n if (!id || !interrupts.some((interrupt) => interrupt.id === id)) {\n return { kind: \"ignored\" };\n }\n return this.#decide(\n interrupts,\n { ...this.#responses, [id]: response },\n messages,\n );\n }\n\n /** Claim a complete batch once, preserving saved results and partial answers. */\n #decide(\n interrupts: readonly Interrupt[],\n responses: Record<string, ResumeResponse>,\n messages: readonly Message[],\n ): ɵInterruptDecision {\n this.validateToolCalls(messages);\n const completed = new Set<string>();\n // Stage adoption until every response validates, so a rejected decision\n // cannot leave cached content out of sync with accumulated responses.\n const adoptedContent = new Map(this.#adoptedContent);\n for (const interrupt of interrupts) {\n if (interrupt.reason !== \"tool_call\" || !interrupt.toolCallId) continue;\n const results = messages.filter(\n (message): message is Extract<Message, { role: \"tool\" }> =>\n message.role === \"tool\" &&\n message.toolCallId === interrupt.toolCallId &&\n !isForwardedToClientPlaceholder(message.content),\n );\n if (results.length > 1)\n throw new Error(`Duplicate tool results for ${interrupt.toolCallId}`);\n const result = results[0];\n if (!result && !adoptedContent.has(interrupt.id)) continue;\n const response = Object.prototype.hasOwnProperty.call(\n responses,\n interrupt.id,\n )\n ? responses[interrupt.id]\n : undefined;\n if (result?.role === \"tool\" && result.error !== undefined) {\n // Failure history remains intact; only an explicit decision can recover\n // this call. Do not append a second result for the same call ID.\n adoptedContent.delete(interrupt.id);\n completed.add(interrupt.id);\n continue;\n }\n const content = result\n ? result.content\n : adoptedContent.get(interrupt.id)!;\n if (\n response &&\n (response.status !== \"resolved\" ||\n (!sameValue(response.payload, content) &&\n toolResultContent(response) !== content))\n ) {\n throw new Error(\n `Interrupt response conflicts with existing tool result for ${interrupt.toolCallId}`,\n );\n }\n // Preserve actual result bytes, including the empty string. Never create\n // another tool message for a call already answered by a frontend handler.\n responses[interrupt.id] = { status: \"resolved\", payload: content };\n adoptedContent.set(interrupt.id, content);\n if (result) completed.add(interrupt.id);\n }\n Object.assign(this.#responses, responses);\n this.#adoptedContent = adoptedContent;\n if (\n !interrupts.every((interrupt) =>\n Object.prototype.hasOwnProperty.call(responses, interrupt.id),\n )\n ) {\n return { kind: \"waiting\" };\n }\n\n const expired = interrupts.find(\n (interrupt) =>\n responses[interrupt.id]?.status !== \"cancelled\" &&\n isInterruptExpired(interrupt),\n );\n if (expired) {\n this.#sealed = true;\n return { kind: \"expired\", interrupt: expired };\n }\n\n const mutableInterrupts = [...interrupts];\n const resume = buildResumeArray(mutableInterrupts, responses);\n const toolResults = mutableInterrupts.flatMap((interrupt) => {\n if (\n !interrupt.toolCallId ||\n interrupt.reason !== \"tool_call\" ||\n completed.has(interrupt.id)\n )\n return [];\n return [\n {\n toolCallId: interrupt.toolCallId,\n content: adoptedContent.has(interrupt.id)\n ? adoptedContent.get(interrupt.id)!\n : toolResultContent(responses[interrupt.id]!),\n },\n ];\n });\n this.#sealed = true;\n return { kind: \"resume\", resume, toolResults };\n }\n}\n\n/** Compare JSON protocol values without depending on object key insertion order. */\nfunction sameValue(left: unknown, right: unknown): boolean {\n if (left === right) return true;\n if (!left || !right || typeof left !== \"object\" || typeof right !== \"object\")\n return false;\n if (Array.isArray(left) || Array.isArray(right)) {\n return (\n Array.isArray(left) &&\n Array.isArray(right) &&\n left.length === right.length &&\n left.every((value, index) => sameValue(value, right[index]))\n );\n }\n const a = left as Record<string, unknown>;\n const b = right as Record<string, unknown>;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(\n (key) =>\n Object.prototype.hasOwnProperty.call(b, key) &&\n sameValue(a[key], b[key]),\n )\n );\n}\n\nconst agentInterruptStates = new WeakMap<\n AbstractAgent,\n {\n threadId: string;\n interrupts: readonly Interrupt[];\n state: ɵInterruptState;\n }\n>();\n\n/** @internal Share decisions and the single resume claim for an agent's pending batch. */\nexport function ɵgetAgentInterruptState(\n agent: AbstractAgent,\n interrupts: readonly Interrupt[] = agent.pendingInterrupts,\n): ɵInterruptState {\n const current = agentInterruptStates.get(agent);\n if (\n current &&\n current.threadId === agent.threadId &&\n current.state.pending &&\n sameValue(current.interrupts, interrupts)\n )\n return current.state;\n const state = new ɵInterruptState();\n state.setStandard(interrupts);\n agentInterruptStates.set(agent, {\n threadId: agent.threadId,\n interrupts: structuredClone(interrupts),\n state,\n });\n return state;\n}\n\n/** @internal A new run owns a new batch, even if the server reuses interrupt IDs. */\nexport function ɵclearAgentInterruptState(agent: AbstractAgent): void {\n agentInterruptStates.delete(agent);\n}\n","import type { ToolCall } from \"@ag-ui/client\";\nimport { logger, randomUUID } from \"@copilotkit/shared\";\nimport type { FrontendTool, WebMCPToolAnnotations } from \"../types\";\nimport { createToolSchema } from \"./tool-schema\";\n\n/**\n * The subset of the WebMCP `ModelContext` API\n * (https://webmachinelearning.github.io/webmcp/) that the registry depends on.\n * Kept structural so the code works against the real browser API and test\n * doubles alike. Aborting the registration signal unregisters the tool.\n */\nexport interface WebMCPModelContext {\n registerTool(\n tool: {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n options: { signal?: AbortSignal },\n ) => Promise<unknown>;\n annotations?: WebMCPToolAnnotations;\n },\n options: { signal: AbortSignal },\n ): Promise<undefined>;\n}\n\n/**\n * Return the page's `document.modelContext`, or null when WebMCP is not\n * available (SSR, React Native, browsers without the API enabled).\n */\nexport function getWebMCPModelContext(): WebMCPModelContext | null {\n if (typeof document === \"undefined\") {\n return null;\n }\n const modelContext = (\n document as Document & { modelContext?: WebMCPModelContext }\n ).modelContext;\n return modelContext ?? null;\n}\n\ninterface WebMCPRegistryEntry {\n tool: FrontendTool<any>;\n controller: AbortController;\n}\n\n/**\n * Keeps a set of frontend tools registered on the page's WebMCP model context.\n *\n * `sync(desired)` reconciles the registrations with the desired set: tools that\n * are gone (or were re-registered with a new tool object) are unregistered by\n * aborting their registration signal, and new tools are registered with an\n * `execute` that delegates to the frontend tool's own handler.\n *\n * All WebMCP-API constraints live here so callers only supply the desired set:\n * a tool without a description is skipped with a warning (the spec rejects\n * empty descriptions), and failures from `registerTool` (duplicate name,\n * unsupported context, ...) are warned rather than thrown.\n */\nexport class WebMCPRegistry {\n private entries = new Map<string, WebMCPRegistryEntry>();\n private warnedNames = new Set<string>();\n\n /** Names currently kept registered on the model context. */\n get registeredNames(): string[] {\n return [...this.entries.keys()];\n }\n\n /** Reconcile the registered tools with the desired set. */\n sync(desired: Map<string, FrontendTool<any>>): void {\n const modelContext = getWebMCPModelContext();\n if (!modelContext) {\n return;\n }\n\n for (const [name, entry] of [...this.entries]) {\n if (desired.get(name) !== entry.tool) {\n entry.controller.abort();\n this.entries.delete(name);\n }\n }\n\n for (const [name, tool] of desired) {\n if (this.entries.has(name)) {\n continue;\n }\n if (!tool.description) {\n this.warnOnce(\n name,\n `Skipping WebMCP registration for tool '${name}': WebMCP requires a description.`,\n );\n continue;\n }\n\n const controller = new AbortController();\n this.entries.set(name, { tool, controller });\n modelContext\n .registerTool(\n this.buildModelContextTool(\n tool as FrontendTool<any> & { description: string },\n ),\n { signal: controller.signal },\n )\n .catch((error) => {\n // Registration failed (duplicate name, insecure context, permission\n // policy, ...). Drop the bookkeeping; the browser never registered.\n // Only delete while this is still the active registration: an\n // aborted registration can reject after a newer one already replaced\n // it, and that replacement's bookkeeping must survive.\n if (this.entries.get(name)?.controller !== controller) {\n return;\n }\n this.entries.delete(name);\n const message =\n error instanceof Error ? error.message : String(error);\n this.warnOnce(\n name,\n `WebMCP registration failed for tool '${name}': ${message}`,\n );\n });\n }\n }\n\n /**\n * Build the WebMCP model-context tool for a frontend tool. The `execute`\n * callback delegates to the frontend tool's own handler, so a browser agent\n * call runs the same application code as an agent call.\n */\n private buildModelContextTool(\n tool: FrontendTool<any> & { description: string },\n ): {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n execute: (\n args: Record<string, unknown>,\n options: { signal?: AbortSignal },\n ) => Promise<unknown>;\n annotations?: WebMCPToolAnnotations;\n } {\n const annotations =\n typeof tool.webmcp === \"object\" ? tool.webmcp.annotations : undefined;\n return {\n name: tool.name,\n description: tool.description,\n inputSchema: createToolSchema(tool),\n execute: async (args, options) => {\n if (!tool.handler) {\n // Mirrors core's empty tool result for a display-only tool.\n return \"\";\n }\n const toolCall: ToolCall = {\n id: randomUUID(),\n type: \"function\",\n function: {\n name: tool.name,\n arguments: JSON.stringify(args ?? {}),\n },\n };\n return await tool.handler(args as any, {\n toolCall,\n signal: options?.signal,\n });\n },\n ...(annotations ? { annotations } : {}),\n };\n }\n\n /** Log `message` once per tool name. Repeated syncs must not spam the log. */\n private warnOnce(name: string, message: string): void {\n if (this.warnedNames.has(name)) {\n return;\n }\n this.warnedNames.add(name);\n logger.warn(`[CopilotKit] ${message}`);\n }\n}\n","import type {\n AbstractAgent,\n AgentSubscriber,\n Message,\n RunAgentResult,\n ResumeEntry,\n Tool,\n ToolCall,\n ContentPart,\n} from \"@ag-ui/client\";\nimport {\n randomUUID,\n logger,\n THREAD_ALREADY_RUNNING_ERROR_CODE,\n} from \"@copilotkit/shared\";\nimport type { CopilotKitCore, CopilotKitCoreFriendsAccess } from \"./core\";\nimport { CopilotKitCoreErrorCode } from \"./core\";\nimport { AgentThreadLockedError } from \"../intelligence-agent\";\nimport type { FrontendTool } from \"../types\";\nimport { isAbortError } from \"../utils/abort-error\";\nimport { ɵgetConnectRunErrorPhase } from \"../utils/connect-replay\";\nimport type { CopilotKitCoreContinuationHandoff } from \"./state-manager\";\nimport {\n isForwardedToClientPlaceholder,\n toToolResultContent,\n} from \"./tool-result-content\";\nimport { createToolSchema } from \"./tool-schema\";\nimport {\n ɵgetAgentInterruptState,\n ɵclearAgentInterruptState,\n} from \"../interrupt-state\";\nimport { WebMCPRegistry } from \"./webmcp\";\n\n/**\n * Live approvals cancelled by stopping their own run, keyed by the handler's\n * signal. The value reports whether that stop is still current: no reconnect\n * has started and the thread is unchanged, so nothing will restore the call.\n *\n * Kept here rather than in `AbortSignal.reason`: React Native's global\n * `AbortController` is the `abort-controller@3` polyfill, whose `abort()`\n * takes no reason and whose signals never expose one.\n */\nconst liveHITLStops = new WeakMap<AbortSignal, () => boolean>();\n\n/**\n * Edits `agent.messages` by replacing the array instead of changing it in\n * place. The current array may be the one the agent emitted with its last\n * update, which subscribers and stored snapshots still hold. Like the in-place\n * edit it replaces, this notifies no subscriber.\n */\nfunction editAgentMessages(\n agent: AbstractAgent,\n edit: (messages: Message[]) => void,\n): void {\n const messages = [...agent.messages];\n edit(messages);\n agent.messages = messages;\n}\n\n// Explicitly stopping a live approval must retain its error result. History\n// restoration and thread-switch cancellation instead discard the old result.\n/**\n * The message a failed tool call reports. An error thrown with an empty\n * message still means the call failed, so it gets a fallback rather than an\n * empty string, which everything downstream reads as success.\n */\nfunction toolFailureMessage(error: Error): string {\n return error.message || \"Tool call failed\";\n}\n\nfunction discardAbortedResult(\n signal: AbortSignal | undefined,\n discardOnAbort: boolean,\n errorMessage?: string,\n): boolean {\n return !!(\n discardOnAbort &&\n signal?.aborted &&\n !(liveHITLStops.get(signal)?.() && errorMessage)\n );\n}\n\nexport interface CopilotKitCoreRunAgentParams {\n agent: AbstractAgent;\n forwardedProps?: Record<string, unknown>;\n /**\n * Optional caller-supplied run identifier forwarded to the underlying AG-UI\n * agent. When omitted, the agent creates one.\n */\n runId?: string;\n /**\n * Per-interrupt responses addressing every open AG-UI interrupt from the\n * previous run. Forwarded to the agent as the standard `resume` array.\n */\n resume?: ResumeEntry[];\n}\n\nexport interface CopilotKitCoreConnectAgentParams {\n agent: AbstractAgent;\n}\n\nexport interface CopilotKitCoreGetToolParams {\n toolName: string;\n agentId?: string;\n}\n\n/**\n * Parameters for programmatic tool execution via `copilotkit.runTool()`.\n */\nexport interface CopilotKitCoreRunToolParams {\n /** Name of the registered frontend tool to execute. */\n name: string;\n /** Optional agent ID. If omitted, uses the default agent lookup. */\n agentId?: string;\n /** Parameters to pass to the tool handler. */\n parameters?: Record<string, unknown>;\n /**\n * Whether to trigger an LLM follow-up after tool execution.\n * - `false` (default): execute tool, add messages to history, done.\n * - `\"generate\"`: after execution, trigger another agent run so the LLM responds to the tool result.\n * - Any other string: add a user message with this text, then trigger another agent run.\n */\n followUp?: string | false;\n}\n\n/**\n * Result of programmatic tool execution via `copilotkit.runTool()`.\n */\nexport interface CopilotKitCoreRunToolResult {\n /** The unique ID of the tool call. */\n toolCallId: string;\n /** The stringified result from the tool handler. */\n result: string;\n /** Error message if the handler failed. */\n error?: string;\n}\n\n/**\n * Internal result from the shared tool handler execution logic.\n */\ninterface ExecuteToolHandlerResult {\n /** The tool message content: a string, or content parts from the handler. */\n content: string | ContentPart[];\n /** The string form of `content`, for surfaces typed as `result: string`. */\n result: string;\n error?: string;\n isArgumentError: boolean;\n}\n\n/**\n * A registered A2UI catalog component, as exposed to the inspector via\n * `CopilotKitCore.catalogComponents`. `schema` is an opaque JSON-schema-ish\n * value (the built catalog's Zod schema or a serialized form); the inspector\n * treats it as unknown. `description` is optional because the built\n * `ComponentApi` does not carry descriptions.\n */\nexport interface CopilotKitCoreCatalogComponent {\n name: string;\n description?: string;\n schema: unknown;\n}\n\n/** How many recent runs keep their request ID for a later approval resume. */\nconst MAX_REMEMBERED_REQUEST_IDS = 100;\n\n/**\n * Absolute safety cap on the depth of recursive follow-up runs triggered by\n * `processAgentResult`. Without this, any scenario that keeps\n * `needsFollowUp = true` (e.g. the LLM repeatedly calling the same tool, a\n * backend that errors after receiving tool results, or input processors that\n * reprocess tool messages) would loop indefinitely, silently consuming API\n * quota and potentially DOS'ing the backend.\n *\n * The cap is deliberately high so that legitimate multi-step agent workflows\n * (search → fill form → confirm → update → send email, etc.) are never\n * affected; it only trips on runaway recursion.\n */\nconst MAX_FOLLOW_UP_DEPTH = 100;\n\n/**\n * Name of the catch-all frontend tool. A tool registered under this name\n * handles any tool call that has no exact match (see `executeWildcardTool`),\n * and is never advertised to the agent.\n */\nconst WILDCARD_TOOL_NAME = \"*\";\n\n/**\n * Handles agent execution, tool calling, and agent connectivity for CopilotKitCore.\n * Manages the complete lifecycle of agent runs including tool execution and follow-ups.\n */\nexport class RunHandler {\n /**\n * Tools owned by the framework provider, replaced wholesale by\n * {@link initialize} and {@link setTools} whenever the provider re-syncs its\n * props or runtime feature flags.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _propTools: FrontendTool<any>[] = [];\n\n /**\n * Tools registered imperatively via {@link addTool} — `useFrontendTool`,\n * `useHumanInTheLoop`, and direct `core.addTool()` callers. Held separately\n * from {@link _propTools} so a provider re-sync cannot wipe them: they shared\n * one array before, so the `/info` response flipping `openGenerativeUI` (or\n * any other provider-prop change) silently dropped every hook-registered\n * tool (#4952). Key = `capabilityKey(name, agentId)`.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _hookTools: Map<string, FrontendTool<any>> = new Map();\n\n /**\n * Memoized merge of both buckets, invalidated on every registry write.\n *\n * This is about identity, not speed: `tools` is public and used to return the\n * same array instance until something mutated the registry, so consumers can\n * hold it or use it as an effect dependency. Rebuilding the merge on every\n * read would hand out a new array each time.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private _cachedMergedTools: FrontendTool<any>[] | null = null;\n\n /**\n * The full list of A2UI catalog components registered by the provider.\n * Order is preserved for display in the inspector.\n */\n private _catalogComponents: CopilotKitCoreCatalogComponent[] = [];\n\n /**\n * Names of catalog components the caller has explicitly disabled. A name\n * absent from this set is enabled (default). Survives re-registration so a\n * catalog identity change does not silently re-enable a disabled component.\n */\n private _disabledCatalogComponents: Set<string> = new Set();\n\n /**\n * Keys of frontend tools explicitly disabled at runtime via the Inspector's\n * Capabilities tool (`setToolEnabled`). Kept independently of each tool's own\n * `available` flag so a hook re-registering the tool (which resets\n * `available`) does not clobber the override. Key = `capabilityKey(name, agentId)`.\n */\n private _disabledToolKeys = new Set<string>();\n\n /**\n * Registry keys already reported by {@link warnOnMissingToolParameters}.\n * Development only, and per instance rather than per module so tests and\n * multiple cores stay independent. Deliberately NOT cleared by\n * {@link removeTool}: `useFrontendTool` tears down and re-registers on every\n * dependency change, so clearing it would turn one warning into one per\n * render. Key = `capabilityKey(name, agentId)`.\n */\n private _warnedMissingToolParameters = new Set<string>();\n\n /**\n * Abort controllers of each agent's in-flight run chains (a run plus its\n * recursive follow-ups), recording whether a chain, including its tool\n * execution, was aborted via `stopAgent()` or `agent.abortRun()`. Every run\n * that is not a follow-up gets a fresh controller, so a run started after\n * Stop is not born aborted while the stopped chain is still settling. Keyed\n * by agent so that stopping one agent never cancels another agent's run on\n * the same core.\n */\n private _runAbortControllers = new WeakMap<\n AbstractAgent,\n Set<AbortController>\n >();\n\n /**\n * Per-agent `runAgent` depth (in-flight runs plus their recursive\n * follow-ups), so that the `agent.abortRun()` intercept is installed while\n * any of the agent's runs is in flight and removed once none is, and so\n * that runaway follow-up chains trip `MAX_FOLLOW_UP_DEPTH`.\n */\n private _runDepths = new WeakMap<AbstractAgent, number>();\n\n /**\n * Each agent's own `abortRun`, saved while RunHandler's intercept is\n * installed. Restored only once none of the agent's runs is in flight, so an\n * overlapping run keeps the intercept after an earlier run finishes.\n */\n private _originalAbortRuns = new WeakMap<AbstractAgent, () => void>();\n\n /**\n * The request each agent's in-flight run belongs to. Its follow-up runs\n * send the same ID, so Intelligence counts the chain as one request.\n */\n private _activeRequestIds = new WeakMap<AbstractAgent, string>();\n\n /**\n * Request IDs of recent logical runs, so an approval that resumes a paused\n * run sends the ID of the request that paused. Oldest entries go first.\n */\n private _requestIdByRun = new Map<string, string>();\n\n /**\n * Keeps tools that opt in via `webmcp` registered on the page's WebMCP model\n * context (`document.modelContext`), in addition to the normal agent\n * registration. Reconciled on every tool registry mutation.\n */\n private _webmcpRegistry = new WebMCPRegistry();\n\n /**\n * Tracks the threadId of the most recent `connectAgent` call so we\n * can distinguish a fresh thread restore (different threadId than\n * last time — chat is rebuilding state from scratch, must clear\n * messages/state and ask the gateway for a full replay) from a\n * same-thread churn re-connect (effect-dep churn or transient\n * disconnect — local messages/state are still meaningful, must\n * preserve them and let the gateway resume from\n * `lastSeenEventId`).\n *\n * Tyler's bug fired because every `connectAgent` was treated as a\n * fresh restore, which forced the gateway to replay the full\n * thread history on every churn re-connect and amplified the\n * downstream churn into duplicate `cpki_event_id` rows in the\n * inspector and intermittent \"Message not found\" toasts.\n */\n private _lastConnectedThreadIdsByAgent = new Map<string, string | null>();\n private _lastActiveThreadIdsByAgent = new Map<string, string | null>();\n private _anonymousAgentIds = new WeakMap<AbstractAgent, string>();\n private _nextAnonymousAgentId = 0;\n\n /** Prevent reconnects from starting an interaction already executing locally. */\n private _executingToolCalls = new WeakMap<AbstractAgent, Set<string>>();\n\n private _connectionGenerations = new WeakMap<AbstractAgent, object>();\n private _runGenerations = new WeakMap<AbstractAgent, object>();\n\n private _interactionAbortControllers = new WeakMap<\n AbstractAgent,\n {\n threadId: string | null;\n controllers: Set<AbortController>;\n }\n >();\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Abort the current run. Called by `CopilotKitCore.stopAgent()` to signal\n * that in-flight tool handlers should stop and `processAgentResult` should\n * not start a follow-up run.\n */\n abortCurrentRun(agent: AbstractAgent): void {\n this.abortAgentRuns(agent);\n const replay = this._interactionAbortControllers.get(agent);\n if (replay) {\n for (const controller of replay.controllers) controller.abort();\n this._interactionAbortControllers.delete(agent);\n // Cancellation is cooperative: an old handler may never settle. Let a\n // reconnect restore it without waiting for its execution marker to clear.\n this._executingToolCalls.delete(agent);\n }\n }\n\n private abortAgentRuns(agent: AbstractAgent): void {\n for (const controller of this._runAbortControllers.get(agent) ?? []) {\n controller.abort();\n }\n }\n\n /** Signal of the agent's most recently started in-flight run, if any. */\n private latestRunSignal(agent: AbstractAgent): AbortSignal | undefined {\n let latest: AbortController | undefined;\n for (const controller of this._runAbortControllers.get(agent) ?? []) {\n latest = controller;\n }\n return latest?.signal;\n }\n\n /**\n * Typed access to CopilotKitCore's internal (\"friend\") methods.\n * Centralises the single unavoidable cast so call-sites stay clean.\n */\n private get _internal(): CopilotKitCoreFriendsAccess {\n return this.core as unknown as CopilotKitCoreFriendsAccess;\n }\n\n /**\n * Return a stable restore-tracking key for the logical agent being\n * connected. Named agents share their last-thread marker across proxy\n * instances; anonymous agents fall back to object identity.\n */\n private getConnectRestoreKey(agent: AbstractAgent): string {\n if (agent.agentId) {\n return `agent:${agent.agentId}`;\n }\n\n const existing = this._anonymousAgentIds.get(agent);\n if (existing) {\n return existing;\n }\n\n const anonymousId = `anonymous:${this._nextAnonymousAgentId}`;\n this._nextAnonymousAgentId += 1;\n this._anonymousAgentIds.set(agent, anonymousId);\n return anonymousId;\n }\n\n /**\n * Get all tools as a readonly array: provider-owned tools in registration\n * order, with imperatively-added tools appended and taking precedence over a\n * provider tool of the same name + agentId.\n */\n get tools(): Readonly<FrontendTool<any>[]> {\n if (this._hookTools.size === 0) {\n return this._propTools;\n }\n if (this._cachedMergedTools) {\n return this._cachedMergedTools;\n }\n // Merge: hook entries override prop entries with the same key. Overriding\n // an existing key keeps the prop entry's position, so provider order is\n // preserved and only genuinely new hook tools land at the end.\n const merged = new Map<string, FrontendTool<any>>();\n for (const tool of this._propTools) {\n merged.set(this.capabilityKey(tool.name, tool.agentId), tool);\n }\n for (const [key, tool] of this._hookTools) {\n merged.set(key, tool);\n }\n this._cachedMergedTools = Array.from(merged.values());\n return this._cachedMergedTools;\n }\n\n /**\n * Initialize with tools\n */\n initialize(tools: FrontendTool<any>[]): void {\n // Copied, like `setTools` does: the merged view is memoized, so holding the\n // caller's array would let an in-place mutation of it go unnoticed. (It\n // also used to be mutated from this side — `addTool` pushed straight onto\n // the array the provider passed in.)\n this._propTools = [...tools];\n this._cachedMergedTools = null;\n this.warnOnMissingToolParameters(this._propTools);\n this.syncWebMCP();\n }\n\n /**\n * Add a tool to the registry. Survives provider re-syncs ({@link setTools}),\n * and shadows a provider tool of the same name + agentId.\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>,\n ): void {\n const key = this.capabilityKey(tool.name, tool.agentId);\n\n // Only a competing imperative registration is a conflict. A provider tool\n // of the same name is shadowed rather than treated as a duplicate — hooks\n // mount after the provider and are the more specific registration.\n if (this._hookTools.has(key)) {\n logger.warn(\n `Tool already exists: '${tool.name}' for agent '${tool.agentId || \"global\"}', skipping.`,\n );\n return;\n }\n\n this._hookTools.set(key, tool);\n this._cachedMergedTools = null;\n this.warnOnMissingToolParameters([tool]);\n this.syncWebMCP();\n }\n\n /**\n * Report, once per tool and at development time only, a tool registered with\n * no `parameters` schema.\n *\n * `createToolSchema` substitutes `{ type: \"object\", properties: {} }` for a\n * missing `parameters` and returns silently, and `parameters` is optional on\n * `FrontendTool`, so nothing — not the compiler, not the runtime — tells the\n * developer that the model was handed a tool with nothing to fill in. It then\n * calls the tool with no arguments. `useComponent`, `useFrontendTool` and\n * `useHumanInTheLoop` all funnel into {@link addTool}; the provider's `tools`\n * prop funnels into {@link initialize} and {@link setTools}.\n *\n * A parameterless tool is legitimate (a HITL confirm dialog, say), so this\n * stays a warning rather than an error. An explicit empty schema\n * (`parameters: z.object({})`) is the way to say \"takes none on purpose\": it\n * satisfies the check below and `createToolSchema` reduces it to the same\n * advertised `{ type: \"object\", properties: {} }` that omitting `parameters`\n * produces, so silencing the warning costs nothing on the wire.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private warnOnMissingToolParameters(tools: FrontendTool<any>[]): void {\n if (process.env.NODE_ENV === \"production\") {\n return;\n }\n\n for (const tool of tools) {\n if (tool.parameters) {\n continue;\n }\n const key = this.capabilityKey(tool.name, tool.agentId);\n if (this._warnedMissingToolParameters.has(key)) {\n continue;\n }\n this._warnedMissingToolParameters.add(key);\n logger.warn(\n `Tool has no parameters schema: '${tool.name}' for agent '${tool.agentId || \"global\"}'. ` +\n `The model is told it takes no arguments and will call it with none. ` +\n `Add \\`parameters\\` (a Zod or Standard Schema object) if it should ` +\n `receive arguments, or \\`parameters: z.object({})\\` to declare that it ` +\n `takes none and silence this warning.`,\n );\n }\n }\n\n /**\n * Remove a tool by name and optionally by agentId\n */\n removeTool(id: string, agentId?: string): void {\n this._hookTools.delete(this.capabilityKey(id, agentId));\n this._propTools = this._propTools.filter((tool) => {\n // Remove tool if both name and agentId match\n if (agentId !== undefined) {\n return !(tool.name === id && tool.agentId === agentId);\n }\n // If no agentId specified, only remove global tools with matching name\n return !(tool.name === id && !tool.agentId);\n });\n this._cachedMergedTools = null;\n this.syncWebMCP();\n }\n\n /**\n * Get a tool by name and optionally by agentId.\n * If agentId is provided, it will first look for an agent-specific tool,\n * then fall back to a global tool with the same name.\n */\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n const { toolName, agentId } = params;\n const tools = this.tools;\n\n // If agentId is provided, first look for agent-specific tool\n if (agentId) {\n const agentTool = tools.find(\n (tool) => tool.name === toolName && tool.agentId === agentId,\n );\n if (agentTool) {\n return agentTool;\n }\n }\n\n // Fall back to global tool (no agentId)\n return tools.find((tool) => tool.name === toolName && !tool.agentId);\n }\n\n /**\n * Set all provider-owned tools at once. Replaces the previous provider set;\n * tools registered via {@link addTool} are unaffected.\n */\n setTools(tools: FrontendTool<any>[]): void {\n this._propTools = [...tools];\n this._cachedMergedTools = null;\n this.warnOnMissingToolParameters(this._propTools);\n this.syncWebMCP();\n }\n\n /**\n * Return the registered A2UI catalog components (readonly).\n */\n get catalogComponents(): ReadonlyArray<CopilotKitCoreCatalogComponent> {\n return this._catalogComponents;\n }\n\n /**\n * Replace the registered catalog component list. Preserves the disabled set\n * (by name) so re-registration does not re-enable disabled components.\n */\n setCatalogComponents(components: CopilotKitCoreCatalogComponent[]): void {\n this._catalogComponents = [...components];\n }\n\n /**\n * Enable or disable a catalog component by name.\n */\n setCatalogComponentEnabled(name: string, enabled: boolean): void {\n if (enabled) {\n this._disabledCatalogComponents.delete(name);\n } else {\n this._disabledCatalogComponents.add(name);\n }\n }\n\n /**\n * Whether a catalog component is enabled. Unknown names default to enabled.\n */\n isCatalogComponentEnabled(name: string): boolean {\n return !this._disabledCatalogComponents.has(name);\n }\n\n /**\n * Connect an agent (establish initial connection)\n */\n async connectAgent({\n agent,\n }: CopilotKitCoreConnectAgentParams): Promise<RunAgentResult> {\n const connection = {};\n this._connectionGenerations.set(agent, connection);\n const incomingThreadId = agent.threadId ?? null;\n const previousReplay = this._interactionAbortControllers.get(agent);\n if (previousReplay && previousReplay.threadId !== incomingThreadId) {\n for (const controller of previousReplay.controllers) controller.abort();\n this._interactionAbortControllers.delete(agent);\n // Old handlers retain their own set until they settle. They must not\n // prevent a fresh restoration when navigating back to this thread.\n this._executingToolCalls.delete(agent);\n }\n try {\n const restoreKey = this.getConnectRestoreKey(agent);\n const previousThreadId = this._lastActiveThreadIdsByAgent.get(restoreKey);\n const isFreshRestore =\n incomingThreadId !==\n (previousThreadId ??\n this._lastConnectedThreadIdsByAgent.get(restoreKey) ??\n null);\n\n // Detach any active run before connecting to avoid previous runs\n // interfering. This stays unconditional — both fresh restores and\n // churn re-connects need the previous socket torn down before a new\n // one can open.\n await agent.detachActiveRun();\n if (\n this._connectionGenerations.get(agent) !== connection ||\n (agent.threadId ?? null) !== incomingThreadId\n ) {\n return { result: undefined, newMessages: [] };\n }\n this._lastConnectedThreadIdsByAgent.set(restoreKey, incomingThreadId);\n this._lastActiveThreadIdsByAgent.set(restoreKey, incomingThreadId);\n\n // State reset + replay-cursor clear are gated on actually moving\n // to a different thread. On same-thread churn, the local\n // messages/state are still the right view of the thread, and the\n // gateway can resume from `lastSeenEventId` instead of replaying\n // the full history.\n if (isFreshRestore) {\n agent.setMessages([]);\n agent.setState({});\n if (\n previousThreadId !== undefined &&\n previousThreadId !== incomingThreadId\n ) {\n agent.pendingInterrupts = [];\n }\n const cursorAware = agent as {\n clearReconnectCursor?: (id: string) => void;\n clearReplayCursor?: (id: string) => void;\n };\n if (incomingThreadId) {\n if (typeof cursorAware.clearReplayCursor === \"function\") {\n cursorAware.clearReplayCursor(incomingThreadId);\n }\n if (typeof cursorAware.clearReconnectCursor === \"function\") {\n cursorAware.clearReconnectCursor(incomingThreadId);\n }\n }\n }\n\n // Re-apply current headers (merged on top of the agent's own headers)\n // so the token in effect right now is what this connect carries — not\n // a value resolved earlier (#1937).\n const headersApplied = this._internal.prepareAgentHeadersForRun(agent);\n if (headersApplied) await headersApplied;\n\n // Notify subscribers (e.g. the inspector) about the agent that is about\n // to run. Per-thread clones are not in the agent registry, so\n // onAgentsChanged never fires for them and they would otherwise be\n // invisible to subscribers.\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentRunStarted?.({\n copilotkit: this.core,\n agent,\n }),\n \"Subscriber onAgentRunStarted error:\",\n );\n if (\n this._connectionGenerations.get(agent) !== connection ||\n (agent.threadId ?? null) !== incomingThreadId\n ) {\n return { result: undefined, newMessages: [] };\n }\n\n const runAgentResult = await agent.connectAgent(\n {\n forwardedProps: this._internal.getPropertiesForAgent(agent.agentId),\n tools: this.buildFrontendTools(agent.agentId),\n context: this._internal.getContextForAgent(agent.agentId),\n },\n this.createAgentErrorSubscriber(agent, \"connect\"),\n );\n\n // Connecting ends when history is restored, not when a human answers.\n // Keeping this promise open would block run-activity reconnects while\n // another client answers the same interaction.\n if (\n this._connectionGenerations.get(agent) !== connection ||\n (agent.threadId ?? null) !== incomingThreadId\n )\n return runAgentResult;\n const controller = new AbortController();\n const replay = this._interactionAbortControllers.get(agent) ?? {\n threadId: incomingThreadId,\n controllers: new Set<AbortController>(),\n };\n replay.controllers.add(controller);\n this._interactionAbortControllers.set(agent, replay);\n void this.processAgentResult({\n runAgentResult,\n agent,\n toolExecutionMode: \"restore\",\n connectionGeneration: connection,\n signal: controller.signal,\n })\n .catch(async (error: unknown) => {\n await this._internal.emitError({\n error: error instanceof Error ? error : new Error(String(error)),\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context: { agentId: agent.agentId, threadId: incomingThreadId },\n });\n })\n .finally(() => {\n replay.controllers.delete(controller);\n if (\n replay.controllers.size === 0 &&\n this._interactionAbortControllers.get(agent) === replay\n ) {\n this._interactionAbortControllers.delete(agent);\n }\n });\n return runAgentResult;\n } catch (error) {\n const connectError =\n error instanceof Error ? error : new Error(String(error));\n // Silently ignore abort errors (e.g. from navigation during active\n // requests).\n if (!isAbortError(connectError)) {\n const context: Record<string, any> = {};\n if (agent.agentId) {\n context.agentId = agent.agentId;\n }\n if (incomingThreadId) {\n context.threadId = incomingThreadId;\n }\n await this._internal.emitError({\n error: connectError,\n code: CopilotKitCoreErrorCode.AGENT_CONNECT_FAILED,\n context,\n });\n }\n return { result: undefined, newMessages: [] };\n }\n }\n\n /**\n * Run an agent\n */\n async runAgent(\n { agent, forwardedProps, resume, runId }: CopilotKitCoreRunAgentParams,\n continuationHandoff?: CopilotKitCoreContinuationHandoff,\n /**\n * Set only by `processAgentResult` for a recursive follow-up: the\n * controller of the run being followed up, which the follow-up shares.\n */\n followUpOf?: AbortController,\n ): Promise<RunAgentResult> {\n this._connectionGenerations.set(agent, {});\n this._runGenerations.set(agent, {});\n ɵclearAgentInterruptState(agent);\n // Agent ID is guaranteed to be set by validateAndAssignAgentId\n if (agent.agentId) {\n void this._internal.suggestionEngine.clearSuggestions(agent.agentId);\n }\n\n // Re-apply current headers (merged on top of the agent's own headers) so\n // the token in effect right now is what this run carries — not a value\n // resolved earlier (#1937).\n try {\n const headersApplied = this._internal.prepareAgentHeadersForRun(agent);\n if (headersApplied) await headersApplied;\n } catch {\n // Already reported as HEADER_RESOLUTION_FAILED by the resolver.\n continuationHandoff?.cancel();\n return { result: undefined, newMessages: [] };\n }\n\n // Detach any active run (e.g. a long-lived connectAgent pipeline) before\n // starting a new run. We await the detach to ensure the previous pipeline\n // has fully finalized — its activeRunCompletionPromise resolves once the\n // observable finalize block runs, which happens synchronously after the\n // takeUntil signal completes the chain. This prevents a race where the new\n // runAgent() overwrites activeRunDetach$ / activeRunCompletionPromise before\n // the old pipeline can clean up, causing dropped runs.\n //\n // Historical note: an earlier version used fire-and-forget (`void`) here\n // because awaiting caused a deadlock when connectAgent's\n // ConnectNotImplementedError cleanup was still in-flight. That deadlock\n // was resolved in @ag-ui/client ≥0.0.42 where the catchError path\n // (ConnectNotImplementedError → EMPTY) always runs the finalize block,\n // so the completion promise now resolves reliably.\n if (agent.detachActiveRun) {\n try {\n await agent.detachActiveRun();\n } catch (error) {\n continuationHandoff?.cancel();\n throw error;\n }\n }\n\n const resumedRunId = this._internal.stateManager.getContinuationRunId(\n agent,\n {\n threadId: agent.threadId,\n resume,\n forwardedProps,\n },\n );\n const logicalHandoff =\n continuationHandoff ??\n (resumedRunId\n ? this._internal.stateManager.markNextRunAsContinuation(\n agent,\n resumedRunId,\n )\n : undefined);\n\n // Every run that is not a recursive follow-up gets its own controller;\n // follow-ups share the controller of the run they continue. Whether a\n // call is a follow-up is passed explicitly rather than inferred from the\n // depth, because a run started after Stop, while the stopped run's tool\n // handlers are still settling, must not inherit the aborted controller.\n const isFollowUp = followUpOf !== undefined;\n const controller = followUpOf ?? new AbortController();\n // The depth is claimed in the same synchronous step as the intercept\n // decision, so two runs started in one tick cannot both see depth 0.\n const depth = this._runDepths.get(agent) ?? 0;\n this._runDepths.set(agent, depth + 1);\n\n // A follow-up or a resume continues the request that started it. Anything\n // else is a new request.\n const continuedRunId =\n resumedRunId ?? (continuationHandoff ? runId : undefined);\n const requestId =\n (continuationHandoff ? this._activeRequestIds.get(agent) : undefined) ??\n (continuedRunId !== undefined\n ? this._requestIdByRun.get(continuedRunId)\n : undefined) ??\n randomUUID();\n\n if (!isFollowUp) {\n const controllers =\n this._runAbortControllers.get(agent) ?? new Set<AbortController>();\n controllers.add(controller);\n this._runAbortControllers.set(agent, controllers);\n }\n\n if (depth === 0) {\n // Intercept agent.abortRun() so that calling it directly (not via\n // stopAgent) also aborts in-flight tool execution and prevents\n // follow-up runs.\n const originalAbortRun = agent.abortRun;\n this._originalAbortRuns.set(agent, originalAbortRun);\n agent.abortRun = () => {\n this.abortAgentRuns(agent);\n originalAbortRun.call(agent);\n };\n }\n\n const previousRequestId = this._activeRequestIds.get(agent);\n this._activeRequestIds.set(agent, requestId);\n\n try {\n if (depth === 0) {\n // Notify subscribers (e.g. the inspector) about the agent that is\n // about to run. Per-thread clones are not in the agent registry, so\n // onAgentsChanged never fires for them and they would otherwise be\n // invisible to subscribers. Fired once while the agent has runs in\n // flight; follow-ups and overlapping runs reuse the same instance and\n // need no re-notification.\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onAgentRunStarted?.({\n copilotkit: this.core,\n agent,\n }),\n \"Subscriber onAgentRunStarted error:\",\n );\n }\n\n let logicalRunId = resumedRunId ?? runId;\n const agentSubscriber = this.createAgentErrorSubscriber(\n agent,\n \"run\",\n controller.signal,\n );\n let started = false;\n const onRunStartedEvent = agentSubscriber.onRunStartedEvent;\n const onRunInitialized = agentSubscriber.onRunInitialized;\n agentSubscriber.onRunInitialized = async (params) => {\n this._lastActiveThreadIdsByAgent.set(\n this.getConnectRestoreKey(agent),\n params.input.threadId,\n );\n logicalHandoff?.bind(params.input);\n return onRunInitialized?.(params);\n };\n agentSubscriber.onRunStartedEvent = async (params) => {\n started = true;\n // A continuation keeps reporting under the run it continues; only an\n // ordinary run adopts the id the transport assigned it.\n if (!logicalHandoff) {\n logicalRunId = params.input.runId;\n }\n return onRunStartedEvent?.(params);\n };\n // An internal continuation (a human-in-the-loop tool resolved and this is\n // the recursive follow-up) deliberately does NOT pin the originating run\n // id on the wire. Pinning it made the transport treat the follow-up as a\n // resumption of a run it had already completed: it re-delivered that\n // run's applied half — duplicating every tool call already on the\n // message, each duplicate carrying empty arguments — and the follow-up's\n // own tool call never reached client state, so its card never rendered.\n //\n // One logical run is still what everything downstream sees: the state\n // manager re-stamps the continuation's events onto `runId` (passed to\n // markNextRunAsContinuation), and `logicalRunId` below keeps the result\n // reported under it. So external tracing still gets a single run without\n // the wire having to lie about which invocation this is.\n const pinRunIdOnWire = runId !== undefined && !continuationHandoff;\n const agentRunInput = {\n forwardedProps: {\n ...this._internal.getPropertiesForAgent(agent.agentId),\n ...forwardedProps,\n __copilotkitRequestId: requestId,\n },\n ...(resume !== undefined ? { resume } : {}),\n ...(pinRunIdOnWire ? { runId } : {}),\n tools: this.buildFrontendTools(agent.agentId),\n context: this._internal.getContextForAgent(agent.agentId),\n };\n const runAgentResult = await agent.runAgent(\n agentRunInput,\n agentSubscriber,\n );\n if (!started) {\n logicalHandoff?.cancel();\n }\n if (logicalRunId !== undefined) {\n this.rememberRequestId(logicalRunId, requestId);\n }\n return await this.processAgentResult({\n runAgentResult,\n agent,\n runId: logicalRunId,\n runController: controller,\n });\n } catch (error) {\n logicalHandoff?.cancel();\n const runError =\n error instanceof Error ? error : new Error(String(error));\n const context: Record<string, any> = {};\n if (agent.agentId) {\n context.agentId = agent.agentId;\n }\n await this._internal.emitError({\n error: runError,\n code: CopilotKitCoreErrorCode.AGENT_RUN_FAILED,\n context,\n });\n return { result: undefined, newMessages: [] };\n } finally {\n const remainingDepth = (this._runDepths.get(agent) ?? 1) - 1;\n this._runDepths.set(agent, remainingDepth);\n // Drop this chain's controller once the chain ends, so a finished,\n // aborted run does not mark later errors as user-aborted.\n if (!isFollowUp) {\n const controllers = this._runAbortControllers.get(agent);\n controllers?.delete(controller);\n if (controllers?.size === 0) this._runAbortControllers.delete(agent);\n }\n // Restore the original abortRun only once none of the agent's runs is\n // in flight: an overlapping run on the same agent still needs it.\n if (remainingDepth === 0) {\n const originalAbortRun = this._originalAbortRuns.get(agent);\n if (originalAbortRun) {\n agent.abortRun = originalAbortRun;\n this._originalAbortRuns.delete(agent);\n }\n }\n if (previousRequestId === undefined) {\n this._activeRequestIds.delete(agent);\n } else {\n this._activeRequestIds.set(agent, previousRequestId);\n }\n }\n }\n\n private rememberRequestId(runId: string, requestId: string): void {\n this._requestIdByRun.delete(runId);\n this._requestIdByRun.set(runId, requestId);\n if (this._requestIdByRun.size > MAX_REMEMBERED_REQUEST_IDS) {\n const oldest = this._requestIdByRun.keys().next().value;\n if (oldest !== undefined) this._requestIdByRun.delete(oldest);\n }\n }\n\n /**\n * Process agent result and execute tools\n */\n private async processAgentResult({\n runAgentResult,\n agent,\n runId,\n toolExecutionMode = \"all\",\n runController,\n signal = runController?.signal,\n connectionGeneration,\n }: {\n runAgentResult: RunAgentResult;\n agent: AbstractAgent;\n runId?: string;\n toolExecutionMode?: \"all\" | \"restore\";\n /** Controller of the run that produced this result; follow-ups share it. */\n runController?: AbortController;\n signal?: AbortSignal;\n connectionGeneration?: object;\n }): Promise<RunAgentResult> {\n const { newMessages } = runAgentResult;\n // Agent ID is guaranteed to be set by validateAndAssignAgentId\n const agentId = agent.agentId!;\n\n let needsFollowUp = false;\n // Same-thread reconnects leave an executing handler in charge of its\n // eventual follow-up; a new explicit run still supersedes that ownership.\n let ownsHandlerFollowUp = false;\n const runGeneration = this._runGenerations.get(agent);\n\n const threadId = agent.threadId;\n const interruptState = agent.pendingInterrupts?.length\n ? ɵgetAgentInterruptState(agent)\n : undefined;\n interruptState?.validateToolCalls(agent.messages);\n const executing = this._executingToolCalls.get(agent) ?? new Set<string>();\n this._executingToolCalls.set(agent, executing);\n\n // Reconnect deltas omit messages hydrated by earlier replays. Restore only\n // the latest user turn: an unanswered call before a later user message is\n // historical, not permission to resume work. Keep every assistant message\n // in that turn, and snapshot because handlers insert results.\n const messagesToProcess =\n toolExecutionMode === \"restore\"\n ? agent.messages.filter(\n (message) =>\n message.role === \"assistant\" &&\n this.isInLatestUserTurn(agent.messages, message.id),\n )\n : newMessages;\n\n // One restoration pass owns the pending sequence. Skipping only the first\n // executing call would start later calls concurrently and replace a HITL\n // hook's response resolver. A saved remote answer releases this barrier.\n if (\n toolExecutionMode === \"restore\" &&\n messagesToProcess.some(\n (message) =>\n message.role === \"assistant\" &&\n message.toolCalls?.some(\n (call) =>\n executing.has(JSON.stringify([threadId, call.id])) &&\n !agent.messages.some(\n (result) =>\n result.role === \"tool\" &&\n result.toolCallId === call.id &&\n !this.isFrontendPlaceholderResult(result),\n ),\n ),\n )\n ) {\n return runAgentResult;\n }\n\n for (const message of messagesToProcess) {\n if (message.role === \"assistant\") {\n for (const toolCall of message.toolCalls || []) {\n const tool = this.getTool({\n toolName: toolCall.function.name,\n agentId: agent.agentId,\n });\n\n let wildcardTool: FrontendTool<any> | undefined;\n const getWildcardTool = () => {\n if (tool || wildcardTool) {\n return wildcardTool;\n }\n wildcardTool = this.getTool({\n toolName: WILDCARD_TOOL_NAME,\n agentId: agent.agentId,\n });\n return wildcardTool;\n };\n\n const executableTool = tool ?? getWildcardTool();\n const executionKey = JSON.stringify([threadId, toolCall.id]);\n if (\n signal?.aborted ||\n agent.threadId !== threadId ||\n (toolExecutionMode === \"restore\" &&\n !this.isInLatestUserTurn(agent.messages, message.id)) ||\n executing.has(executionKey)\n ) {\n continue;\n }\n\n const existingResultIndex = newMessages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n );\n // Live messages may contain a remote answer received while an\n // earlier handler awaited input; never replace it with stale replay.\n let existingResult =\n agent.messages.find(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n ) ?? newMessages[existingResultIndex];\n\n // Reusing a completed result is not handler execution. Passive tools\n // may resume saved successes but must keep unanswered placeholders.\n if (\n existingResult &&\n !this.isFrontendPlaceholderResult(existingResult)\n ) {\n if (\n executableTool &&\n executableTool.followUp !== false &&\n agent.pendingInterrupts?.some(\n (interrupt) =>\n interrupt.reason === \"tool_call\" &&\n interrupt.toolCallId === toolCall.id,\n )\n )\n needsFollowUp = true;\n continue;\n }\n // Handlerless frontend tools (e.g. chart components) must recreate\n // missing empty results using their original call IDs. Handlers still\n // run only for HITL prompts or an explicit \"resume-pending\" opt-in,\n // so restoring history never repeats other tools' side effects.\n if (\n toolExecutionMode === \"restore\" &&\n (!executableTool ||\n (executableTool.handler &&\n executableTool.type !== \"human-in-the-loop\" &&\n executableTool.reconnectBehavior !== \"resume-pending\"))\n ) {\n continue;\n }\n if (\n existingResult &&\n this.isFrontendPlaceholderResult(existingResult) &&\n (toolExecutionMode === \"restore\" || executableTool?.handler)\n ) {\n if (existingResultIndex !== -1)\n newMessages.splice(existingResultIndex, 1);\n existingResult = undefined;\n\n const agentMsgIdx = agent.messages.findIndex(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n );\n if (agentMsgIdx !== -1) {\n editAgentMessages(agent, (messages) =>\n messages.splice(agentMsgIdx, 1),\n );\n }\n }\n\n if (!existingResult) {\n executing.add(executionKey);\n // Live HITL handlers need the same thread-switch cancellation as\n // restored ones, so returning to this thread can open a fresh UI.\n const interactionController =\n toolExecutionMode === \"all\" &&\n executableTool?.type === \"human-in-the-loop\"\n ? new AbortController()\n : undefined;\n const interactions = this._interactionAbortControllers.get(\n agent,\n ) ?? {\n threadId: threadId ?? null,\n controllers: new Set<AbortController>(),\n };\n const abortInteraction = () => {\n if (!interactionController) return;\n const stopConnectionGeneration =\n this._connectionGenerations.get(agent);\n liveHITLStops.set(\n interactionController.signal,\n () =>\n this._connectionGenerations.get(agent) ===\n stopConnectionGeneration && agent.threadId === threadId,\n );\n interactionController.abort();\n };\n if (interactionController) {\n interactions.controllers.add(interactionController);\n this._interactionAbortControllers.set(agent, interactions);\n signal?.addEventListener(\"abort\", abortInteraction, {\n once: true,\n });\n if (signal?.aborted) abortInteraction();\n }\n const executionSignal = interactionController?.signal ?? signal;\n const discardOnAbort =\n toolExecutionMode === \"restore\" || !!interactionController;\n try {\n if (tool) {\n const followUp = await this.executeSpecificTool(\n tool,\n toolCall,\n message,\n agent,\n agentId,\n executionSignal,\n discardOnAbort,\n toolExecutionMode === \"restore\",\n );\n if (followUp) {\n ownsHandlerFollowUp ||= !!tool.handler;\n needsFollowUp = true;\n }\n } else {\n const fallbackTool = getWildcardTool();\n if (fallbackTool) {\n const followUp = await this.executeWildcardTool(\n fallbackTool,\n toolCall,\n message,\n agent,\n agentId,\n executionSignal,\n discardOnAbort,\n toolExecutionMode === \"restore\",\n );\n if (followUp) {\n ownsHandlerFollowUp ||= !!fallbackTool.handler;\n needsFollowUp = true;\n }\n }\n }\n } finally {\n executing.delete(executionKey);\n if (interactionController) {\n signal?.removeEventListener(\"abort\", abortInteraction);\n interactions.controllers.delete(interactionController);\n if (\n interactions.controllers.size === 0 &&\n this._interactionAbortControllers.get(agent) === interactions\n ) {\n this._interactionAbortControllers.delete(agent);\n }\n }\n }\n if (interactionController?.signal.aborted) return runAgentResult;\n }\n }\n }\n }\n\n if (needsFollowUp && agent.threadId === threadId && !signal?.aborted) {\n // Circuit breaker: bail out instead of recursing once the follow-up\n // chain exceeds an absolute safety cap. `_runDepths` holds this agent's\n // current depth of nested runAgent calls (it is incremented in runAgent and\n // decremented in its finally block), so a runaway loop — repeated\n // identical tool calls, a backend that keeps erroring after tool\n // results, reprocessed tool messages, etc. — eventually trips this\n // guard rather than looping forever and exhausting API quota.\n if ((this._runDepths.get(agent) ?? 0) >= MAX_FOLLOW_UP_DEPTH) {\n logger.warn(\n `[CopilotKit] Follow-up depth limit (${MAX_FOLLOW_UP_DEPTH}) reached for agent \"${agentId}\". ` +\n `Stopping recursive follow-up runs to prevent an infinite loop. ` +\n `This usually indicates a tool that keeps requesting a follow-up (e.g. the LLM repeatedly ` +\n `calling the same tool). Consider setting \"followUp: false\" on the offending tool.`,\n );\n } else {\n // Yield to the framework scheduler before the follow-up run so that any\n // deferred state updates (e.g. React useEffect in useAgentContext) can\n // complete and write fresh values into the context store before runAgent\n // reads it. The base implementation is a no-op; React overrides this.\n await this._internal.waitForPendingFrameworkUpdates();\n if (\n signal?.aborted ||\n agent.threadId !== threadId ||\n this._runGenerations.get(agent) !== runGeneration ||\n (connectionGeneration &&\n !ownsHandlerFollowUp &&\n this._connectionGenerations.get(agent) !== connectionGeneration) ||\n (interruptState && ɵgetAgentInterruptState(agent) !== interruptState)\n )\n return runAgentResult;\n\n if (\n toolExecutionMode === \"restore\" &&\n !messagesToProcess.some((message) =>\n this.isInLatestUserTurn(agent.messages, message.id),\n )\n ) {\n return runAgentResult;\n }\n let resume: ResumeEntry[] | undefined;\n if (agent.pendingInterrupts?.length) {\n // The shared state requires an explicit decision for failed results,\n // including Stop, while retaining decisions made before handlers finish.\n const decision = ɵgetAgentInterruptState(agent).resumeWithToolResults(\n agent.messages,\n );\n // A completed frontend call is not permission to answer a native\n // approval or a child question. Keep the full interrupt set pending.\n if (decision.kind !== \"resume\") return runAgentResult;\n resume = decision.resume;\n for (const result of decision.toolResults) {\n agent.addMessage({ id: randomUUID(), role: \"tool\", ...result });\n }\n }\n const continuationHandoff =\n this._internal.stateManager.markNextRunAsContinuation(agent, runId);\n return await this.runAgent(\n {\n agent,\n ...(runId !== undefined ? { runId } : {}),\n ...(resume ? { resume } : {}),\n },\n continuationHandoff,\n runController,\n );\n }\n }\n\n void this._internal.suggestionEngine.reloadSuggestions(agentId);\n\n return runAgentResult;\n }\n\n /** A later user message supersedes pending work from an older turn. */\n private isInLatestUserTurn(messages: Message[], messageId: string): boolean {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === \"user\") return false;\n if (message?.id === messageId) return true;\n }\n return false;\n }\n\n /** Locate a missing result before saved results for later calls in its batch. */\n private toolResultInsertionIndex(\n messages: Message[],\n messageIndex: number,\n toolCallId: string,\n ): number {\n const parent = messages[messageIndex];\n const calls = parent?.role === \"assistant\" ? (parent.toolCalls ?? []) : [];\n const callIndex = calls.findIndex((call) => call.id === toolCallId);\n let insertAt = messageIndex + 1;\n while (insertAt < messages.length) {\n const result = messages[insertAt];\n if (result?.role !== \"tool\") break;\n const resultIndex = calls.findIndex(\n (call) => call.id === result.toolCallId,\n );\n // Results from earlier batches may follow this assistant in replayed\n // history. Preserve their position; only stop for a later sibling call.\n if (resultIndex > callIndex) break;\n insertAt++;\n }\n return insertAt;\n }\n\n /** Identify transport placeholders that must not count as completed answers. */\n private isFrontendPlaceholderResult(message: Message): boolean {\n return (\n message.role === \"tool\" && isForwardedToClientPlaceholder(message.content)\n );\n }\n\n /**\n * Shared handler execution logic used by executeSpecificTool, executeWildcardTool, and runTool.\n * Handles arg parsing, subscriber notifications, handler invocation, result stringification,\n * and error handling.\n */\n private async executeToolHandler({\n tool,\n toolCall,\n agent,\n agentId,\n handlerArgs,\n toolType,\n messageId,\n signal = this.latestRunSignal(agent),\n discardOnAbort = false,\n isReplay = false,\n }: {\n tool: FrontendTool<any>;\n toolCall: { id: string; function: { name: string; arguments: string } };\n agent: AbstractAgent;\n agentId: string;\n handlerArgs: unknown;\n toolType: string;\n messageId?: string;\n signal?: AbortSignal;\n discardOnAbort?: boolean;\n isReplay?: boolean;\n }): Promise<ExecuteToolHandlerResult> {\n let toolCallResult: string | ContentPart[] = \"\";\n let toolCallText = \"\";\n let errorMessage: string | undefined;\n let isArgumentError = false;\n\n let parsedArgs: unknown;\n try {\n parsedArgs = parseToolArguments(handlerArgs, toolCall.function.name);\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(parseError);\n isArgumentError = true;\n await this._internal.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: handlerArgs,\n toolType,\n ...(messageId ? { messageId } : {}),\n },\n });\n }\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId,\n toolName: toolCall.function.name,\n args: parsedArgs,\n }),\n \"Subscriber onToolExecutionStart error:\",\n );\n\n if (!errorMessage) {\n try {\n const result = await tool.handler!(parsedArgs as any, {\n toolCall: toolCall as any,\n agent,\n signal,\n ...(isReplay ? { isReplay } : {}),\n });\n ({ content: toolCallResult, text: toolCallText } =\n toToolResultContent(result));\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(handlerError);\n if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) {\n await this._internal.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs,\n toolType,\n ...(messageId ? { messageId } : {}),\n },\n });\n }\n }\n }\n\n if (errorMessage) {\n toolCallResult = toolCallText = `Error: ${errorMessage}`;\n }\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallText,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\",\n );\n\n return {\n content: toolCallResult,\n result: toolCallText,\n error: errorMessage,\n isArgumentError,\n };\n }\n\n /**\n * Execute a specific tool\n */\n private async executeSpecificTool(\n tool: FrontendTool<any>,\n toolCall: ToolCall,\n message: Message,\n agent: AbstractAgent,\n agentId: string,\n signal?: AbortSignal,\n discardOnAbort = false,\n isReplay = false,\n ): Promise<boolean> {\n const threadId = agent.threadId;\n // Check if tool is constrained to a specific agent\n if (tool?.agentId && tool.agentId !== agent.agentId) {\n // Tool is not available for this agent, skip it\n return false;\n }\n\n let handlerResult: ExecuteToolHandlerResult = {\n content: \"\",\n result: \"\",\n error: undefined,\n isArgumentError: false,\n };\n\n if (tool?.handler) {\n handlerResult = await this.executeToolHandler({\n tool,\n toolCall,\n agent,\n agentId,\n handlerArgs: toolCall.function.arguments,\n toolType: \"specific\",\n messageId: message.id,\n signal,\n discardOnAbort,\n isReplay,\n });\n }\n\n {\n const messageIndex = agent.messages.findIndex((m) => m.id === message.id);\n if (\n discardAbortedResult(signal, discardOnAbort, handlerResult.error) ||\n agent.threadId !== threadId ||\n messageIndex === -1 ||\n (isReplay && !this.isInLatestUserTurn(agent.messages, message.id)) ||\n agent.messages.some(\n (m) =>\n m.role === \"tool\" &&\n m.toolCallId === toolCall.id &&\n !this.isFrontendPlaceholderResult(m),\n )\n ) {\n // The interaction was removed, the thread changed, or another client\n // already answered. Do not insert a stale answer or start a follow-up.\n return false;\n }\n const insertAt = this.toolResultInsertionIndex(\n agent.messages,\n messageIndex,\n toolCall.id,\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: handlerResult.content,\n ...(handlerResult.error ? { error: handlerResult.error } : {}),\n };\n editAgentMessages(agent, (messages) =>\n messages.splice(insertAt, 0, toolMessage),\n );\n\n if (!handlerResult.error && tool?.followUp !== false) {\n return true; // Needs follow-up\n }\n }\n\n return false;\n }\n\n /**\n * Execute a wildcard tool.\n * Wildcard tools receive args wrapped as `{toolName, args}`, which differs from\n * specific tools, so this method keeps its own arg-wrapping logic rather than\n * delegating to `executeToolHandler`.\n */\n private async executeWildcardTool(\n wildcardTool: FrontendTool<any>,\n toolCall: ToolCall,\n message: Message,\n agent: AbstractAgent,\n agentId: string,\n signal?: AbortSignal,\n discardOnAbort = false,\n isReplay = false,\n ): Promise<boolean> {\n const threadId = agent.threadId;\n // Check if wildcard tool is constrained to a specific agent\n if (wildcardTool?.agentId && wildcardTool.agentId !== agent.agentId) {\n // Wildcard tool is not available for this agent, skip it\n return false;\n }\n\n let toolCallResult: string | ContentPart[] = \"\";\n let toolCallText = \"\";\n let errorMessage: string | undefined;\n\n if (wildcardTool?.handler) {\n let parsedArgs: unknown;\n try {\n parsedArgs = parseToolArguments(\n toolCall.function.arguments,\n toolCall.function.name,\n );\n } catch (error) {\n const parseError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(parseError);\n await this._internal.emitError({\n error: parseError,\n code: CopilotKitCoreErrorCode.TOOL_ARGUMENT_PARSE_FAILED,\n context: {\n agentId: agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n rawArguments: toolCall.function.arguments,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n\n const wildcardArgs = {\n toolName: toolCall.function.name,\n args: parsedArgs,\n };\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionStart?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId: agentId,\n toolName: toolCall.function.name,\n args: wildcardArgs,\n }),\n \"Subscriber onToolExecutionStart error:\",\n );\n\n if (!errorMessage) {\n try {\n const result = await wildcardTool.handler(wildcardArgs as any, {\n toolCall,\n agent,\n // Use the same execution signal as named tools, including the\n // replay-specific signal when restoring a wildcard HITL handler.\n signal,\n ...(isReplay ? { isReplay } : {}),\n });\n ({ content: toolCallResult, text: toolCallText } =\n toToolResultContent(result));\n } catch (error) {\n const handlerError =\n error instanceof Error ? error : new Error(String(error));\n errorMessage = toolFailureMessage(handlerError);\n if (!discardAbortedResult(signal, discardOnAbort, errorMessage)) {\n await this._internal.emitError({\n error: handlerError,\n code: CopilotKitCoreErrorCode.TOOL_HANDLER_FAILED,\n context: {\n agentId: agentId,\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n parsedArgs: wildcardArgs,\n toolType: \"wildcard\",\n messageId: message.id,\n },\n });\n }\n }\n }\n\n if (errorMessage) {\n toolCallResult = toolCallText = `Error: ${errorMessage}`;\n }\n\n await this._internal.notifySubscribers(\n (subscriber) =>\n subscriber.onToolExecutionEnd?.({\n copilotkit: this.core,\n toolCallId: toolCall.id,\n agentId: agentId,\n toolName: toolCall.function.name,\n result: errorMessage ? \"\" : toolCallText,\n error: errorMessage,\n }),\n \"Subscriber onToolExecutionEnd error:\",\n );\n }\n\n {\n const messageIndex = agent.messages.findIndex((m) => m.id === message.id);\n if (\n discardAbortedResult(signal, discardOnAbort, errorMessage) ||\n agent.threadId !== threadId ||\n messageIndex === -1 ||\n (isReplay && !this.isInLatestUserTurn(agent.messages, message.id)) ||\n agent.messages.some(\n (m) =>\n m.role === \"tool\" &&\n m.toolCallId === toolCall.id &&\n !this.isFrontendPlaceholderResult(m),\n )\n ) {\n // The interaction was removed, the thread changed, or another client\n // already answered. Do not insert a stale answer or start a follow-up.\n return false;\n }\n const insertAt = this.toolResultInsertionIndex(\n agent.messages,\n messageIndex,\n toolCall.id,\n );\n const toolMessage = {\n id: randomUUID(),\n role: \"tool\" as const,\n toolCallId: toolCall.id,\n content: toolCallResult,\n ...(errorMessage ? { error: errorMessage } : {}),\n };\n editAgentMessages(agent, (messages) =>\n messages.splice(insertAt, 0, toolMessage),\n );\n\n if (!errorMessage && wildcardTool?.followUp !== false) {\n return true; // Needs follow-up\n }\n }\n\n return false;\n }\n\n /**\n * Programmatically execute a registered frontend tool without going through an LLM turn.\n * The handler runs, render components show up in the UI, and both the tool call and\n * result messages are added to `agent.messages`.\n */\n async runTool(\n params: CopilotKitCoreRunToolParams,\n ): Promise<CopilotKitCoreRunToolResult> {\n const { name, agentId, parameters = {}, followUp = false } = params;\n\n // 1. Look up the tool\n const tool = this.getTool({ toolName: name, agentId });\n if (!tool) {\n const error = new Error(`Tool not found: ${name}`);\n await this._internal.emitError({\n error,\n code: CopilotKitCoreErrorCode.TOOL_NOT_FOUND,\n context: { toolName: name, agentId },\n });\n throw error;\n }\n\n // 2. Look up the agent\n const resolvedAgentId = agentId ?? \"default\";\n const agent = this._internal.getAgent(resolvedAgentId);\n if (!agent) {\n const error = new Error(`Agent not found: ${resolvedAgentId}`);\n await this._internal.emitError({\n error,\n code: CopilotKitCoreErrorCode.AGENT_NOT_FOUND,\n context: { agentId: resolvedAgentId },\n });\n throw error;\n }\n\n // 3. Create assistant message with tool call\n const toolCallId = randomUUID();\n const assistantToolCall = {\n id: toolCallId,\n type: \"function\" as const,\n function: {\n name,\n arguments: JSON.stringify(parameters),\n },\n };\n const assistantMessage: Message = {\n id: randomUUID(),\n role: \"assistant\",\n content: \"\",\n toolCalls: [assistantToolCall],\n };\n\n // 4. Push assistant message into agent's messages\n editAgentMessages(agent, (messages) => messages.push(assistantMessage));\n\n // 5. Execute the tool handler (if it has one)\n let handlerResult: ExecuteToolHandlerResult = {\n content: \"\",\n result: \"\",\n error: undefined,\n isArgumentError: false,\n };\n\n if (tool.handler) {\n handlerResult = await this.executeToolHandler({\n tool,\n toolCall: assistantToolCall,\n agent,\n agentId: resolvedAgentId,\n handlerArgs: parameters,\n toolType: \"runTool\",\n });\n }\n\n // 6. Create and insert tool result message\n const toolResultMessage: Message = {\n id: randomUUID(),\n role: \"tool\",\n toolCallId,\n content: handlerResult.content,\n ...(handlerResult.error ? { error: handlerResult.error } : {}),\n };\n\n const assistantIndex = agent.messages.findIndex(\n (m) => m.id === assistantMessage.id,\n );\n if (assistantIndex !== -1) {\n editAgentMessages(agent, (messages) =>\n messages.splice(assistantIndex + 1, 0, toolResultMessage),\n );\n } else {\n // Fallback: push to end if assistant message was removed\n editAgentMessages(agent, (messages) => messages.push(toolResultMessage));\n }\n\n // 7. Handle followUp (only if no error)\n if (!handlerResult.error && followUp !== false) {\n if (typeof followUp === \"string\" && followUp !== \"generate\") {\n // Custom text: add a user message first\n const userMessage: Message = {\n id: randomUUID(),\n role: \"user\",\n content: followUp,\n };\n editAgentMessages(agent, (messages) => messages.push(userMessage));\n }\n // Yield to the framework scheduler so deferred state updates (e.g. React\n // useEffect in useAgentContext) can complete before the follow-up run reads\n // the context store. Mirrors the same yield in processAgentResult.\n await this._internal.waitForPendingFrameworkUpdates();\n // Trigger agent run for both \"generate\" and custom text\n await this.runAgent({ agent });\n }\n\n // 8. Return result\n return {\n toolCallId,\n result: handlerResult.result,\n error: handlerResult.error,\n };\n }\n\n /** Stable identity for a tool override: agent-scope + name (NUL-separated). */\n private capabilityKey(name: string, agentId?: string): string {\n return `${agentId ?? \"\"}\\u0000${name}`;\n }\n\n /**\n * Enable/disable a registered frontend tool at runtime without unregistering\n * it. A disabled tool is omitted from {@link buildFrontendTools}, so the agent\n * never receives it. Unlike the per-tool `available` flag, this override\n * survives the tool being re-registered.\n */\n setToolEnabled(name: string, enabled: boolean, agentId?: string): void {\n const key = this.capabilityKey(name, agentId);\n if (enabled) {\n this._disabledToolKeys.delete(key);\n } else {\n this._disabledToolKeys.add(key);\n }\n this.syncWebMCP();\n }\n\n /** Whether a tool is currently enabled (not overridden off). Defaults true. */\n isToolEnabled(name: string, agentId?: string): boolean {\n return !this._disabledToolKeys.has(this.capabilityKey(name, agentId));\n }\n\n /**\n * Build frontend tools for an agent\n */\n buildFrontendTools(agentId?: string): Tool[] {\n return this.tools\n .filter(\n (tool) =>\n // A wildcard tool is a local catch-all handler (see\n // `executeWildcardTool`), not something the model can call —\n // advertising it would offer the agent a tool named `*`.\n tool.name !== WILDCARD_TOOL_NAME &&\n tool.available !== false &&\n (tool.available as boolean | string | undefined) !== \"disabled\" &&\n (!tool.agentId || tool.agentId === agentId) &&\n this.isToolEnabled(tool.name, tool.agentId),\n )\n .map((tool) => ({\n name: tool.name,\n description: tool.description ?? \"\",\n parameters: createToolSchema(tool),\n }));\n }\n\n /**\n * Reconcile the WebMCP registrations with the current tool registry. Tools\n * opt in via `webmcp: true` or `webmcp: { annotations }`; the same\n * availability rules as `buildFrontendTools` apply. WebMCP tools are\n * page-level, so unlike the agent tool list they are not filtered by\n * agentId — a name collision across agentIds keeps the first registration.\n */\n private syncWebMCP(): void {\n const desired = new Map<string, FrontendTool<any>>();\n const warnedCollisions = new Set<string>();\n for (const tool of this.tools) {\n if (!tool.webmcp) {\n continue;\n }\n if (tool.name === WILDCARD_TOOL_NAME) {\n continue;\n }\n if (\n tool.available === false ||\n (tool.available as boolean | string | undefined) === \"disabled\"\n ) {\n continue;\n }\n if (!this.isToolEnabled(tool.name, tool.agentId)) {\n continue;\n }\n if (desired.has(tool.name)) {\n if (!warnedCollisions.has(tool.name)) {\n warnedCollisions.add(tool.name);\n logger.warn(\n `[CopilotKit] Multiple WebMCP tools share the name '${tool.name}'. ` +\n `Only the first registration is exposed to browser agents.`,\n );\n }\n continue;\n }\n desired.set(tool.name, tool);\n }\n this._webmcpRegistry.sync(desired);\n }\n\n /**\n * Create an agent error subscriber\n */\n private createAgentErrorSubscriber(\n agent: AbstractAgent,\n stream: \"run\" | \"connect\",\n runSignal?: AbortSignal,\n ): AgentSubscriber {\n const emitAgentError = async (\n error: Error,\n code: CopilotKitCoreErrorCode,\n extraContext: Record<string, any> = {},\n ) => {\n const context: Record<string, any> = { ...extraContext };\n if (agent.agentId) {\n context.agentId = agent.agentId;\n }\n await this._internal.emitError({\n error,\n code,\n context,\n });\n };\n\n return {\n onRunFailed: async ({ error }: { error: Error }) => {\n const code =\n error instanceof AgentThreadLockedError\n ? CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED\n : CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT;\n await emitAgentError(error, code, {\n source: \"onRunFailed\",\n });\n },\n onRunErrorEvent: async ({ event }) => {\n // A user-initiated stop (stopAgent / agent.abortRun) makes the agent\n // emit a terminal RUN_ERROR — often code \"abort\" — as its cancellation\n // signal. That is expected, not a failure: surfacing it would pop an\n // error banner on Stop (#5966, follow-up to #5812). Mirror the\n // local-abort suppression on the runAgent/connectAgent paths and skip\n // it. Prefer the abort controller (the client's own record that it\n // initiated the stop) over the agent-supplied `code`, which is not\n // standardized across agents.\n // Only this run's own signal counts: a connect has none, and another\n // run on the same agent being stopped says nothing about this error.\n const runWasAborted = runSignal?.aborted ?? false;\n if (runWasAborted || event?.code === \"abort\") {\n return;\n }\n\n // The SSE runtime rejected the run because the thread already has\n // one in flight. Report it like Intelligence's 409 so one onError\n // branch covers both transports.\n if (event?.code === THREAD_ALREADY_RUNNING_ERROR_CODE) {\n await emitAgentError(\n new AgentThreadLockedError(agent.threadId),\n CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED,\n { source: \"onRunErrorEvent\", event },\n );\n return;\n }\n\n const eventError =\n event?.rawEvent instanceof Error\n ? event.rawEvent\n : event?.rawEvent?.error instanceof Error\n ? event.rawEvent.error\n : undefined;\n\n const errorMessage =\n typeof event?.rawEvent?.error === \"string\"\n ? event.rawEvent.error\n : (event?.message ?? \"Agent run error\");\n\n const rawError = eventError ?? new Error(errorMessage);\n\n if (event?.code && !(rawError as any).code) {\n (rawError as any).code = event.code;\n }\n\n await emitAgentError(\n rawError,\n CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,\n {\n source: \"onRunErrorEvent\",\n event,\n runtimeErrorCode: event?.code,\n // A connect replays stored history, so an old run's RUN_ERROR\n // arrives here too. `phase` tells it apart from a live failure;\n // a run stream only carries the run it started.\n phase: stream === \"run\" ? \"live\" : ɵgetConnectRunErrorPhase(event),\n },\n );\n },\n };\n }\n}\n\n/**\n * Ensures parsed tool arguments are a plain object.\n * Throws for non-object values so the caller's catch block can emit\n * a structured TOOL_ARGUMENT_PARSE_FAILED error.\n *\n * @internal Exported for testing only.\n */\nexport function ensureObjectArgs(\n parsed: unknown,\n toolName: string,\n): Record<string, unknown> {\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n throw new Error(\n `Tool arguments for ${toolName} parsed to non-object (${typeof parsed})`,\n );\n}\n\n/**\n * Parses raw tool call arguments into a validated object.\n *\n * Some LLM providers (e.g. @ai-sdk/openai-compatible) may send empty string \"\",\n * null, or undefined instead of \"{}\". This function normalises those cases to an\n * empty object so callers don't crash on JSON.parse(\"\").\n *\n * A debug-level warning is emitted when the fallback triggers so silent coercion\n * is observable in logs.\n *\n * @internal Exported for testing only.\n */\nexport function parseToolArguments(\n rawArgs: unknown,\n toolName: string,\n): Record<string, unknown> {\n if (rawArgs === \"\" || rawArgs === null || rawArgs === undefined) {\n logger.debug(\n `[parseToolArguments] Tool \"${toolName}\" received empty/null/undefined arguments — defaulting to {}`,\n );\n return {};\n }\n const parsed = typeof rawArgs === \"string\" ? JSON.parse(rawArgs) : rawArgs;\n return ensureObjectArgs(parsed, toolName);\n}\n","import type {\n AbstractAgent,\n Message,\n State,\n RunAgentInput,\n StateSnapshotEvent,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n TextMessageStartEvent,\n ToolCallResultEvent,\n ToolMessage,\n} from \"@ag-ui/client\";\nimport { randomUUID, structuredClone_ } from \"@ag-ui/client\";\nimport type { CopilotKitCore } from \"./core\";\nimport { isForwardedToClientPlaceholder } from \"./tool-result-content\";\n\nconst isContinuation = (\n input: Pick<RunAgentInput, \"resume\" | \"forwardedProps\">,\n): boolean =>\n input.resume !== undefined ||\n Object.prototype.hasOwnProperty.call(\n (input.forwardedProps as { command?: object } | undefined)?.command ?? {},\n \"resume\",\n );\n\nexport interface CopilotKitCoreContinuationHandoff {\n cancel(): void;\n bind(input: object): void;\n}\n\ninterface PendingContinuation extends CopilotKitCoreContinuationHandoff {\n expectedInput?: object;\n active: boolean;\n /**\n * The logical run id this continuation belongs to. Events arriving on the\n * continuation are re-stamped with it, so the run reads as ONE run to\n * everything downstream (state/message association, external tracing) even\n * though the transport minted a fresh id for the follow-up invocation.\n */\n expectedRunId?: string;\n}\n\n/**\n * Manages state and message tracking by run for CopilotKitCore.\n * Tracks agent state snapshots and message-to-run associations.\n */\nexport class StateManager {\n // State tracking: agentId -> threadId -> runId -> state\n private stateByRun: Map<string, Map<string, Map<string, State>>> = new Map();\n\n // Message tracking: agentId -> threadId -> messageId -> runId\n private messageToRun: Map<string, Map<string, Map<string, string>>> =\n new Map();\n\n // Direct text-start metadata: agentId -> threadId -> messageId -> rawEvent\n private rawEventByMessage: Map<string, Map<string, Map<string, unknown>>> =\n new Map();\n\n // Active run tracking: `agentId:threadId` -> runId (used when messages arrive without input)\n private activeRun: Map<string, string> = new Map();\n\n private agentSubscriptions: Map<\n string,\n { agent: AbstractAgent; unsubscribe: () => void }\n > = new Map();\n\n // Internal follow-ups are marked in memory so the marker never reaches a\n // runtime or becomes user-controlled forwardedProps data.\n private pendingContinuations = new WeakMap<\n AbstractAgent,\n Set<PendingContinuation>\n >();\n\n private interruptedRuns = new WeakMap<\n AbstractAgent,\n Map<string, { runId: string; interruptIds: string[] | null }>\n >();\n\n /** Find the interrupted logical run without consuming its pending answers. */\n getContinuationRunId(\n agent: AbstractAgent,\n input: Pick<RunAgentInput, \"threadId\" | \"resume\" | \"forwardedProps\">,\n ) {\n const pending = this.interruptedRuns.get(agent)?.get(input.threadId);\n if (!pending) return undefined;\n if (pending.interruptIds === null) {\n return input.resume === undefined && isContinuation(input)\n ? pending.runId\n : undefined;\n }\n const submitted = new Set(input.resume?.map((entry) => entry.interruptId));\n const matches =\n submitted.size > 0 &&\n submitted.size === input.resume?.length &&\n submitted.size === pending.interruptIds.length &&\n pending.interruptIds.every((id) => submitted.has(id));\n return matches ? pending.runId : undefined;\n }\n\n constructor(private core: CopilotKitCore) {}\n\n /**\n * Initialize state tracking for an agent\n */\n initialize(): void {\n // Will be called when CopilotKitCore is initialized\n }\n\n markNextRunAsContinuation(\n agent: AbstractAgent,\n expectedRunId?: string,\n ): CopilotKitCoreContinuationHandoff {\n let pendingForAgent = this.pendingContinuations.get(agent);\n if (!pendingForAgent) {\n pendingForAgent = new Set();\n this.pendingContinuations.set(agent, pendingForAgent);\n }\n\n const pending: PendingContinuation = {\n active: true,\n expectedRunId,\n bind: (input) => {\n if (pending.active) pending.expectedInput = input;\n },\n cancel: () => {\n if (!pending.active) return;\n pending.active = false;\n pendingForAgent!.delete(pending);\n if (pendingForAgent!.size === 0) {\n this.pendingContinuations.delete(agent);\n }\n },\n };\n pendingForAgent.add(pending);\n return pending;\n }\n\n /**\n * Subscribe to an agent's events to track state and messages.\n */\n subscribeToAgent(agent: AbstractAgent): void {\n if (!agent.agentId) {\n return; // Skip agents without IDs\n }\n\n const agentId = agent.agentId;\n\n const existing = this.agentSubscriptions.get(agentId);\n if (existing) {\n if (existing.agent === agent) {\n return;\n }\n existing.unsubscribe();\n this.agentSubscriptions.delete(agentId);\n }\n\n // Subscribe to agent events.\n //\n // Two invariants this subscription must uphold:\n //\n // 1. Revocation: the ag-ui pipeline captures `o = [...agent.subscribers]` at\n // runAgent() start. If this subscription is replaced by a newer one before\n // the pipeline finishes, the old pipeline may still call these callbacks\n // with the old input.runId. `revoked = true` turns them into no-ops once\n // the replacement subscription is in place. Only a replacement revokes —\n // see the same-instance guard above.\n //\n // 2. Run isolation within one subscription: in tests (and edge cases), a new\n // run's events can arrive through the same subscription before the new\n // pipeline is set up. An explicit standard or legacy resume input is a\n // continuation, so only an ordinary new run gets a fresh ID after\n // RUN_FINISHED.\n let revoked = false;\n let subRunId: string | undefined; // runId assigned to the current logical run\n let legacyInterrupted = false;\n let runFinished = false; // true after RUN_FINISHED, reset on next RUN_STARTED\n const pendingResults = new WeakMap<\n RunAgentInput,\n Map<string, ToolCallResultEvent>\n >();\n\n const reconcilePendingResults = (\n historyMessages: readonly Message[],\n input: RunAgentInput,\n ): { messages: Message[] } | undefined => {\n const events = pendingResults.get(input);\n if (!events) return undefined;\n\n const messages = [...historyMessages];\n let changed = false;\n\n for (const event of events.values()) {\n const ownerIndex = messages.findIndex(\n (message) =>\n message.role === \"assistant\" &&\n message.toolCalls?.some(\n (toolCall) => toolCall.id === event.toolCallId,\n ),\n );\n if (ownerIndex < 0) continue;\n\n const matchingIndexes = messages.reduce<number[]>(\n (indexes, message, index) => {\n if (\n message.role === \"tool\" &&\n message.toolCallId === event.toolCallId\n ) {\n indexes.push(index);\n }\n return indexes;\n },\n [],\n );\n const realIndex = matchingIndexes.find(\n (index) => !isForwardedToClientPlaceholder(messages[index]?.content),\n );\n if (realIndex !== undefined) {\n for (const duplicateIndex of matchingIndexes\n .filter((candidateIndex) => candidateIndex !== realIndex)\n .sort((a, b) => b - a)) {\n messages.splice(duplicateIndex, 1);\n changed = true;\n }\n continue;\n }\n\n const placeholderIndex = matchingIndexes.find((index) =>\n isForwardedToClientPlaceholder(messages[index]?.content),\n );\n if (placeholderIndex !== undefined) {\n if (isForwardedToClientPlaceholder(event.content)) {\n for (const duplicateIndex of matchingIndexes\n .slice(1)\n .sort((a, b) => b - a)) {\n messages.splice(duplicateIndex, 1);\n changed = true;\n }\n continue;\n }\n messages[placeholderIndex] = {\n ...messages[placeholderIndex],\n id: event.messageId,\n content: event.content,\n } as ToolMessage;\n changed = true;\n for (const duplicateIndex of matchingIndexes\n .filter(\n (candidateIndex) =>\n candidateIndex !== placeholderIndex &&\n isForwardedToClientPlaceholder(\n messages[candidateIndex]?.content,\n ),\n )\n .sort((a, b) => b - a)) {\n messages.splice(duplicateIndex, 1);\n }\n continue;\n }\n\n const result: ToolMessage = {\n id: event.messageId,\n role: \"tool\",\n toolCallId: event.toolCallId,\n content: event.content,\n };\n let insertIndex = ownerIndex + 1;\n while (messages[insertIndex]?.role === \"tool\") insertIndex++;\n messages.splice(insertIndex, 0, result);\n changed = true;\n }\n\n return changed ? { messages } : undefined;\n };\n\n const clearPendingResults = (input: RunAgentInput): void => {\n pendingResults.delete(input);\n };\n\n const effectiveInput = (input: RunAgentInput): RunAgentInput => ({\n ...input,\n runId: subRunId ?? input.runId,\n });\n\n const { unsubscribe } = agent.subscribe({\n onRunStartedEvent: ({ event, input, state }) => {\n if (revoked) return;\n const pendingForAgent = this.pendingContinuations.get(agent);\n const internalContinuation = [...(pendingForAgent ?? [])].find(\n (pending) => pending.expectedInput === input,\n );\n internalContinuation?.cancel();\n const startedInput = event.input ?? {\n ...input,\n threadId: event.threadId,\n };\n const resumedRunId = this.getContinuationRunId(agent, startedInput);\n this.interruptedRuns.get(agent)?.delete(startedInput.threadId);\n legacyInterrupted = false;\n\n if (internalContinuation) {\n // An internal continuation re-stamps onto the run id it continues, so\n // the follow-up does not have to reuse that id on the wire.\n subRunId =\n internalContinuation.expectedRunId ?? event.runId ?? input.runId;\n } else if (resumedRunId) {\n subRunId = resumedRunId;\n } else if (\n runFinished &&\n input.runId === subRunId &&\n !isContinuation(input) &&\n (event.runId == null || event.runId === subRunId)\n ) {\n // A new logical run's events are arriving through this same (old)\n // subscription. This happens when the test emits events before\n // copilotkit.runAgent() has had a chance to set up the new pipeline:\n // the old pipeline reuses input1.runId for all events, so\n // input.runId equals the previous run's runId. Generate a fresh\n // runId so the new run's state doesn't collide with the old one.\n subRunId = randomUUID();\n } else {\n // A connect replay may contain multiple server runs under one input.runId.\n subRunId = event.runId || input.runId;\n }\n runFinished = false;\n this.handleRunStarted(agent, effectiveInput(input), state);\n },\n onRunFinishedEvent: ({ event, input, state, messages }) => {\n if (revoked) return;\n runFinished = true;\n const effective = effectiveInput(input);\n let interrupted = this.interruptedRuns.get(agent);\n if (event.outcome?.type === \"interrupt\" || legacyInterrupted) {\n if (!interrupted) {\n interrupted = new Map();\n this.interruptedRuns.set(agent, interrupted);\n }\n interrupted.set(event.threadId, {\n runId: effective.runId,\n interruptIds:\n event.outcome?.type === \"interrupt\"\n ? event.outcome.interrupts.map((interrupt) => interrupt.id)\n : null,\n });\n } else {\n interrupted?.delete(event.threadId);\n }\n const mutation = reconcilePendingResults(messages, input);\n clearPendingResults(input);\n this.handleRunFinished(agent, effective, state);\n return mutation;\n },\n onCustomEvent: ({ event }) => {\n if (!revoked && event.name === \"on_interrupt\") legacyInterrupted = true;\n },\n // A run error terminates the run — treat identically to finished for cleanup\n onRunErrorEvent: ({ input, state, messages }) => {\n if (revoked) return;\n runFinished = true;\n const effective = effectiveInput(input);\n const mutation = reconcilePendingResults(messages, input);\n this.handleRunFinished(agent, effective, state);\n return mutation;\n },\n onRunFailed: ({ input, messages }) => {\n if (revoked) return;\n return reconcilePendingResults(messages, input);\n },\n onRunFinalized: ({ input }) => {\n if (revoked) return;\n clearPendingResults(input);\n },\n onToolCallResultEvent: ({ event, input }) => {\n if (revoked) return;\n let events = pendingResults.get(input);\n if (!events) {\n events = new Map();\n pendingResults.set(input, events);\n }\n events.set(event.toolCallId, event);\n },\n onStateSnapshotEvent: ({ event, input, state }) => {\n if (revoked) return;\n this.handleStateSnapshot(agent, event, effectiveInput(input), state);\n },\n onStateDeltaEvent: ({ event, input, state }) => {\n if (revoked) return;\n this.handleStateDelta(agent, event, effectiveInput(input), state);\n },\n onTextMessageStartEvent: ({ event, input }) => {\n if (revoked) return;\n this.handleTextMessageStart(agent, event, effectiveInput(input));\n },\n onMessagesSnapshotEvent: ({ event, input, messages }) => {\n if (revoked) return;\n this.handleMessagesSnapshot(\n agent,\n event,\n effectiveInput(input),\n messages,\n );\n this.pruneRawEvents(\n agent.agentId!,\n input.threadId,\n event.messages,\n effectiveInput(input),\n );\n },\n onNewMessage: ({ message, input }) => {\n if (revoked) return;\n this.handleNewMessage(\n agent,\n message,\n input ? effectiveInput(input) : undefined,\n );\n },\n onMessagesChanged: ({ messages, input }) => {\n if (revoked) return;\n if (!input) {\n this.pruneRawEvents(agent.agentId!, agent.threadId, messages);\n }\n },\n });\n\n this.agentSubscriptions.set(agentId, {\n agent,\n unsubscribe: () => {\n revoked = true;\n this.pendingContinuations.delete(agent);\n this.interruptedRuns.delete(agent);\n unsubscribe();\n },\n });\n }\n\n /**\n * Unsubscribe an agent's subscription.\n */\n unsubscribeFromAgent(agentId: string): void {\n const existing = this.agentSubscriptions.get(agentId);\n if (existing) {\n existing.unsubscribe();\n this.agentSubscriptions.delete(agentId);\n }\n this.rawEventByMessage.delete(agentId);\n }\n\n /**\n * Get state for a specific run\n * Returns a deep copy to prevent external mutations\n */\n getStateByRun(\n agentId: string,\n threadId: string,\n runId: string,\n ): State | undefined {\n const state = this.stateByRun.get(agentId)?.get(threadId)?.get(runId);\n if (!state) return undefined;\n // Return a deep copy to prevent mutations\n return JSON.parse(JSON.stringify(state));\n }\n\n /**\n * Get runId associated with a message\n */\n getRunIdForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): string | undefined {\n return this.messageToRun.get(agentId)?.get(threadId)?.get(messageId);\n }\n\n /**\n * Get direct text-start metadata associated with a message.\n */\n getRawEventForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): unknown {\n const rawEvent = this.rawEventByMessage\n .get(agentId)\n ?.get(threadId)\n ?.get(messageId);\n return rawEvent === undefined ? undefined : structuredClone_(rawEvent);\n }\n\n /**\n * Get all states for an agent's thread\n */\n getStatesForThread(agentId: string, threadId: string): Map<string, State> {\n return this.stateByRun.get(agentId)?.get(threadId) ?? new Map();\n }\n\n /**\n * Get all run IDs for an agent's thread\n */\n getRunIdsForThread(agentId: string, threadId: string): string[] {\n const threadStates = this.stateByRun.get(agentId)?.get(threadId);\n return threadStates ? Array.from(threadStates.keys()) : [];\n }\n\n /**\n * Handle run started event\n */\n private handleRunStarted(\n agent: AbstractAgent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n this.activeRun.set(`${agent.agentId}:${threadId}`, runId);\n // Only persist state when it carries real data. An empty {} from an\n // initial-state-less run would cause getStateByRun to return {} instead\n // of undefined, breaking renderers that rely on undefined to mean \"no\n // state snapshot received yet\".\n if (state && Object.keys(state).length > 0) {\n this.saveState(agent.agentId, threadId, runId, state);\n }\n }\n\n /**\n * Handle run finished event\n */\n private handleRunFinished(\n agent: AbstractAgent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n this.activeRun.delete(`${agent.agentId}:${threadId}`);\n if (state && Object.keys(state).length > 0) {\n this.saveState(agent.agentId, threadId, runId, state);\n }\n }\n\n /**\n * Handle state snapshot event\n */\n private handleStateSnapshot(\n agent: AbstractAgent,\n event: StateSnapshotEvent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n // Merge snapshot into current state\n const mergedState = { ...state, ...event.snapshot };\n this.saveState(agent.agentId, threadId, runId, mergedState);\n }\n\n /**\n * Handle state delta event\n */\n private handleStateDelta(\n agent: AbstractAgent,\n event: StateDeltaEvent,\n input: RunAgentInput,\n state: State,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n // State is already updated by the agent, just save it\n this.saveState(agent.agentId, threadId, runId, state);\n }\n\n /**\n * Capture only defined metadata from a normalized direct text-start event.\n */\n private handleTextMessageStart(\n agent: AbstractAgent,\n event: TextMessageStartEvent,\n input: RunAgentInput,\n ): void {\n if (!agent.agentId) return;\n\n const { threadId } = input;\n if (event.rawEvent === undefined) {\n const threadEvents = this.rawEventByMessage\n .get(agent.agentId)\n ?.get(threadId);\n threadEvents?.delete(event.messageId);\n if (threadEvents?.size === 0) {\n this.rawEventByMessage.get(agent.agentId)?.delete(threadId);\n }\n if (this.rawEventByMessage.get(agent.agentId)?.size === 0) {\n this.rawEventByMessage.delete(agent.agentId);\n }\n return;\n }\n\n if (!this.rawEventByMessage.has(agent.agentId)) {\n this.rawEventByMessage.set(agent.agentId, new Map());\n }\n const agentEvents = this.rawEventByMessage.get(agent.agentId)!;\n if (!agentEvents.has(threadId)) {\n agentEvents.set(threadId, new Map());\n }\n agentEvents.get(threadId)!.set(event.messageId, event.rawEvent);\n }\n\n /**\n * Handle messages snapshot event\n */\n private handleMessagesSnapshot(\n agent: AbstractAgent,\n event: MessagesSnapshotEvent,\n input: RunAgentInput,\n _messages: readonly Message[],\n ): void {\n if (!agent.agentId) return;\n\n const { threadId, runId } = input;\n\n // Cumulative snapshots repeat messages from earlier runs, so only assign\n // messages that do not already have a run association.\n for (const message of event.messages) {\n if (\n this.getRunIdForMessage(agent.agentId, threadId, message.id) ===\n undefined\n ) {\n this.associateMessageWithRun(\n agent.agentId,\n threadId,\n message.id,\n runId,\n );\n }\n }\n }\n\n /**\n * Handle new message event\n */\n private handleNewMessage(\n agent: AbstractAgent,\n message: Message,\n input?: RunAgentInput,\n ): void {\n if (!agent.agentId) return;\n\n if (!input) {\n // ag-ui calls addMessage() without input, so input is undefined here.\n // Fall back to the currently-active run for this agent's thread.\n const threadId = agent.threadId ?? \"\";\n const runId = this.activeRun.get(`${agent.agentId}:${threadId}`);\n if (runId) {\n this.associateMessageWithRun(\n agent.agentId,\n threadId,\n message.id,\n runId,\n );\n }\n return;\n }\n\n const { threadId, runId } = input;\n this.associateMessageWithRun(agent.agentId, threadId, message.id, runId);\n }\n\n /**\n * Save state for a specific run\n */\n private saveState(\n agentId: string,\n threadId: string,\n runId: string,\n state: State,\n ): void {\n // Ensure nested maps exist\n if (!this.stateByRun.has(agentId)) {\n this.stateByRun.set(agentId, new Map());\n }\n const agentStates = this.stateByRun.get(agentId)!;\n\n if (!agentStates.has(threadId)) {\n agentStates.set(threadId, new Map());\n }\n const threadStates = agentStates.get(threadId)!;\n\n // Deep copy the state to prevent mutations\n threadStates.set(runId, JSON.parse(JSON.stringify(state)));\n }\n\n /**\n * Associate a message with a run\n */\n private associateMessageWithRun(\n agentId: string,\n threadId: string,\n messageId: string,\n runId: string,\n ): void {\n // Ensure nested maps exist\n if (!this.messageToRun.has(agentId)) {\n this.messageToRun.set(agentId, new Map());\n }\n const agentMessages = this.messageToRun.get(agentId)!;\n\n if (!agentMessages.has(threadId)) {\n agentMessages.set(threadId, new Map());\n }\n const threadMessages = agentMessages.get(threadId)!;\n\n threadMessages.set(messageId, runId);\n }\n\n private pruneRawEvents(\n agentId: string,\n fallbackThreadId: string | undefined,\n messages: ReadonlyArray<Readonly<Message>>,\n input?: RunAgentInput,\n ): void {\n const threadId = input?.threadId ?? fallbackThreadId;\n if (!threadId) return;\n\n const threadEvents = this.rawEventByMessage.get(agentId)?.get(threadId);\n if (!threadEvents) return;\n\n const messageIds = new Set(messages.map((message) => message.id));\n for (const messageId of threadEvents.keys()) {\n if (!messageIds.has(messageId)) threadEvents.delete(messageId);\n }\n if (threadEvents.size === 0) {\n this.rawEventByMessage.get(agentId)?.delete(threadId);\n }\n if (this.rawEventByMessage.get(agentId)?.size === 0) {\n this.rawEventByMessage.delete(agentId);\n }\n }\n\n /**\n * Clear all state for an agent\n */\n clearAgentState(agentId: string): void {\n const agent = this.agentSubscriptions.get(agentId)?.agent;\n if (agent) this.interruptedRuns.delete(agent);\n this.stateByRun.delete(agentId);\n this.messageToRun.delete(agentId);\n this.rawEventByMessage.delete(agentId);\n }\n\n /**\n * Clear all state for a thread\n */\n clearThreadState(agentId: string, threadId: string): void {\n const agent = this.agentSubscriptions.get(agentId)?.agent;\n if (agent) this.interruptedRuns.get(agent)?.delete(threadId);\n this.stateByRun.get(agentId)?.delete(threadId);\n this.messageToRun.get(agentId)?.delete(threadId);\n this.rawEventByMessage.get(agentId)?.delete(threadId);\n }\n}\n","import { type ɵThreadStore } from \"../threads\";\nimport type { CopilotKitCore } from \"./core\";\nimport { CopilotKitCoreFriendsAccess, CopilotKitCoreSubscriber } from \"./core\";\n\nexport class ThreadStoreRegistry {\n private _stores: Record<string, ɵThreadStore> = {};\n // Cached frozen snapshot of `_stores`. Invalidated to `null` on every\n // `register`/`unregister` so the next `getAll()` rebuilds it. Stable\n // references between mutations matter for `useSyncExternalStore` consumers\n // that compare snapshot identity to decide whether to re-render.\n private _snapshot: Readonly<Record<string, ɵThreadStore>> | null = null;\n\n constructor(private core: CopilotKitCore) {}\n\n register(agentId: string, store: ɵThreadStore): void {\n if (agentId in this._stores) {\n // Capture the previous store before deleting it. `notifyUnregistered`\n // dispatches via `Promise.all` and returns control to this synchronous\n // body before async subscribers resume — by then `this._stores[agentId]`\n // already holds the new store, so the previous store must be forwarded\n // explicitly via the payload. Subscribers MUST NOT call\n // `registry.get(agentId)` from `onThreadStoreUnregistered` to recover\n // the previous store; use the `prevStore` field on the payload instead.\n const prevStore = this._stores[agentId]!;\n delete this._stores[agentId];\n this._snapshot = null;\n this.notifyUnregistered(agentId, prevStore).catch((err) => {\n console.error(\"ThreadStoreRegistry notifyUnregistered failed:\", err);\n });\n }\n this._stores[agentId] = store;\n this._snapshot = null;\n this.notifyRegistered(agentId, store).catch((err) => {\n console.error(\"ThreadStoreRegistry notifyRegistered failed:\", err);\n });\n }\n\n unregister(agentId: string): void {\n if (!(agentId in this._stores)) return;\n // Capture before delete for the same reason as `register()` above.\n const prevStore = this._stores[agentId]!;\n delete this._stores[agentId];\n this._snapshot = null;\n this.notifyUnregistered(agentId, prevStore).catch((err) => {\n console.error(\"ThreadStoreRegistry notifyUnregistered failed:\", err);\n });\n }\n\n get(agentId: string): ɵThreadStore | undefined {\n return this._stores[agentId];\n }\n\n getAll(): Readonly<Record<string, ɵThreadStore>> {\n // Cache a frozen snapshot so consecutive calls return the same reference.\n // `useSyncExternalStore` and other identity-comparing consumers depend on\n // this stability to skip re-renders when nothing has actually changed.\n // `Object.freeze` makes the `Readonly<>` claim true at runtime, not just\n // at the type level — attempts to mutate the snapshot throw in strict\n // mode and are silently ignored in sloppy mode (rather than corrupting\n // the registry). Invalidated to `null` by `register`/`unregister`.\n if (this._snapshot === null) {\n this._snapshot = Object.freeze({ ...this._stores });\n }\n return this._snapshot;\n }\n\n private async notifyRegistered(\n agentId: string,\n store: ɵThreadStore,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber: CopilotKitCoreSubscriber) =>\n subscriber.onThreadStoreRegistered?.({\n copilotkit: this.core,\n agentId,\n store,\n }),\n \"Subscriber onThreadStoreRegistered error:\",\n );\n }\n\n private async notifyUnregistered(\n agentId: string,\n prevStore: ɵThreadStore,\n ): Promise<void> {\n await (\n this.core as unknown as CopilotKitCoreFriendsAccess\n ).notifySubscribers(\n (subscriber: CopilotKitCoreSubscriber) =>\n subscriber.onThreadStoreUnregistered?.({\n copilotkit: this.core,\n agentId,\n prevStore,\n }),\n \"Subscriber onThreadStoreUnregistered error:\",\n );\n }\n}\n","import { Socket } from \"phoenix\";\nimport type { Channel } from \"phoenix\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport { phoenixExponentialBackoff } from \"@copilotkit/shared\";\nimport { createTrajectoryCollector } from \"@copilotkit/learning\";\nimport type {\n ConnectionGrant,\n JsonValue,\n StartResult,\n TrajectoryCaptureOptions,\n TrajectoryEvent,\n} from \"@copilotkit/learning\";\nimport type { CopilotKitCore } from \"./core\";\nimport type { CopilotRuntimeTransport } from \"../types\";\nimport { abortable, isPromiseLike } from \"./header-source\";\n\nconst TIMEOUT_MS = 10_000;\nconst BATCH_INTERVAL_MS = 2_000;\nconst MAX_BATCH_EVENTS = 50;\nconst MAX_BATCH_BYTES = 64 * 1024;\nconst MAX_EVENT_BYTES = 16 * 1024;\n\ntype WireEvent = TrajectoryEvent<Record<string, JsonValue>>;\ninterface EventBatch {\n events: WireEvent[];\n dropped: number;\n}\nconst byteLength = (value: unknown) =>\n new TextEncoder().encode(JSON.stringify(value)).byteLength;\nconst reconnectDelay = phoenixExponentialBackoff(1_000, 10_000);\n\n// Fixed client-side hints. Server messages are never shown in the browser.\nconst SETUP_HINTS: Record<string, string> = {\n RUNTIME_REQUIRED:\n \"Set runtimeUrl: capture connects through the CopilotKit runtime.\",\n INTELLIGENCE_RUNTIME_REQUIRED:\n \"Configure the CopilotRuntime with `intelligence` to accept capture.\",\n CONNECTION_FAILED:\n \"Check that the CopilotRuntime is configured with `intelligence` and valid Intelligence credentials, and check the runtime logs.\",\n IDENTITY_REQUIRED:\n \"The runtime could not identify the user. Configure `identifyUser` on the CopilotRuntime and send the app's session with runtime requests.\",\n TRAJECTORIES_NOT_ENABLED:\n \"Trajectories are not enabled for this Intelligence project.\",\n TRAJECTORIES_UNAVAILABLE:\n \"This Intelligence deployment does not serve Trajectory capture.\",\n TRAJECTORIES_ENTITLEMENT_UNAVAILABLE:\n \"Intelligence could not confirm that Trajectories are enabled for this project; try again later.\",\n MARKETPLACE_LICENSE_REQUIRED:\n \"Trajectory capture requires a CopilotKit license for this project.\",\n};\n\ninterface PendingPush {\n timer: ReturnType<typeof setTimeout>;\n finish(code?: string, knownRollback?: boolean, flushNext?: boolean): void;\n}\n\ninterface Connection {\n abort: AbortController;\n timer?: ReturnType<typeof setTimeout>;\n socket?: Socket;\n channel?: Channel;\n socketRefs: string[];\n channelRefs: Array<[string, number]>;\n pending: Set<PendingPush>;\n}\n\ninterface Session {\n trajectoryId: string;\n config: TrajectoryCaptureOptions;\n promise: Promise<StartResult>;\n resolve(result: StartResult): void;\n collector?: ReturnType<typeof createTrajectoryCollector>;\n connection?: Connection;\n retry?: ReturnType<typeof setTimeout>;\n retries: number;\n queue: WireEvent[];\n flushTimer?: ReturnType<typeof setTimeout>;\n dropped: number;\n ready: boolean;\n started: boolean;\n offline: boolean;\n onOffline(): void;\n onOnline(): void;\n /** Threads already linked to this Trajectory. */\n linkedThreads: Set<string>;\n runWatch?: { unsubscribe(): void };\n agentWatches: Map<AbstractAgent, { unsubscribe(): void }>;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\ninterface BatchAcknowledgement {\n highestSeq: number | null;\n accepted: number;\n rejected: number;\n}\n\nfunction isNonNegativeInteger(value: unknown): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction isBatchAcknowledgement(\n value: unknown,\n eventCount: number,\n): value is BatchAcknowledgement {\n return (\n isObject(value) &&\n isNonNegativeInteger(value.accepted) &&\n isNonNegativeInteger(value.rejected) &&\n value.accepted + value.rejected === eventCount &&\n (value.highestSeq === null || isNonNegativeInteger(value.highestSeq)) &&\n (value.accepted === 0 || value.highestSeq !== null)\n );\n}\n\nfunction isGrant(value: unknown): value is ConnectionGrant {\n return (\n isObject(value) &&\n typeof value.joinToken === \"string\" &&\n value.joinToken.length > 0 &&\n isObject(value.realtime) &&\n typeof value.realtime.clientUrl === \"string\" &&\n value.realtime.clientUrl.length > 0 &&\n typeof value.realtime.topic === \"string\" &&\n value.realtime.topic.length > 0\n );\n}\n\n// The Gateway refuses a join with a lowercase reason and no code.\nconst JOIN_REFUSAL_CODES: Record<string, string> = {\n trajectories_unavailable: \"TRAJECTORIES_UNAVAILABLE\",\n trajectories_not_enabled: \"TRAJECTORIES_NOT_ENABLED\",\n entitlement_unavailable: \"TRAJECTORIES_ENTITLEMENT_UNAVAILABLE\",\n marketplace_license_required: \"MARKETPLACE_LICENSE_REQUIRED\",\n};\n\nfunction joinErrorCode(value: unknown): string {\n const reason = isObject(value) ? value.reason : undefined;\n const code =\n typeof reason === \"string\" && Object.hasOwn(JOIN_REFUSAL_CODES, reason)\n ? JOIN_REFUSAL_CODES[reason]\n : undefined;\n return code ?? errorCode(value, \"JOIN_FAILED\");\n}\n\nfunction errorCode(value: unknown, fallback: string): string {\n return isObject(value) &&\n typeof value.code === \"string\" &&\n /^[A-Z][A-Z0-9_]{0,63}$/.test(value.code)\n ? value.code\n : fallback;\n}\n\n/** Owns bounded, connected-only capture batches. Failed batches are never resent. */\nexport class TrajectoryConnection {\n private session: Session | undefined;\n private readonly warned = new Set<string>();\n // Core-scoped high water mark prevents collisions after reconnect or stop/start.\n // Gateway drops a seq it already stored for the Trajectory yet acknowledges it\n // as accepted, and a reload or second tab can reuse the id. Starting at the\n // creation time in microseconds keeps later Cores above earlier ones and\n // stays a safe integer until about 2255. Seqs can still collide only if two\n // Cores start the same Trajectory in one millisecond, or if a Core averages\n // more than 1000 events per millisecond, or if the clock goes back.\n private nextSeq = Math.floor(Date.now()) * 1000;\n\n constructor(\n private readonly core: CopilotKitCore,\n private readonly onChange: () => void,\n ) {}\n\n get trajectoryId(): string | null {\n return this.session?.ready ? this.session.trajectoryId : null;\n }\n\n start(\n trajectoryId: string | undefined,\n config: TrajectoryCaptureOptions,\n ): Promise<StartResult> {\n if (\n this.session &&\n (trajectoryId === undefined || trajectoryId === this.session.trajectoryId)\n ) {\n return this.session.promise;\n }\n this.stop();\n const id = trajectoryId ?? crypto.randomUUID();\n let resolveStart!: (result: StartResult) => void;\n const promise = new Promise<StartResult>((resolve) => {\n resolveStart = resolve;\n });\n const session: Session = {\n trajectoryId: id,\n config,\n promise,\n resolve: resolveStart,\n retries: 0,\n queue: [],\n dropped: 0,\n ready: false,\n started: false,\n offline: typeof navigator !== \"undefined\" && navigator.onLine === false,\n onOffline: () => {\n if (this.session !== session) return;\n session.offline = true;\n if (session.connection)\n this.fail(session, session.connection, \"CONNECTION_LOST\");\n clearTimeout(session.retry);\n session.retry = undefined;\n },\n onOnline: () => {\n if (this.session !== session) return;\n session.offline = false;\n if (!session.connection) {\n clearTimeout(session.retry);\n session.retry = undefined;\n void this.connect(session);\n }\n },\n linkedThreads: new Set(),\n agentWatches: new Map(),\n };\n this.session = session;\n // Runtime creates the Thread before RUN_STARTED reaches the browser, so a\n // link sent from that event names a Thread that Intelligence can store.\n session.runWatch = this.core.subscribe({\n onAgentRunStarted: ({ agent }) => this.watchAgent(session, agent),\n });\n if (\n typeof window !== \"undefined\" &&\n typeof window.addEventListener === \"function\"\n ) {\n window.addEventListener(\"offline\", session.onOffline);\n window.addEventListener(\"online\", session.onOnline);\n }\n if (session.offline) {\n this.report(session, \"CONNECTION_LOST\");\n this.end(session, { status: \"error\", code: \"CONNECTION_LOST\" });\n } else {\n void this.connect(session);\n }\n return promise;\n }\n\n stop(): void {\n const session = this.session;\n if (!session) return;\n // Drain settled input while this session can still enqueue it, before the\n // best-effort transport flush. Stop stays synchronous and never waits for ACK.\n const collector = session.collector;\n session.collector = undefined;\n collector?.stop();\n if (session.ready && session.connection)\n this.flush(session, session.connection);\n this.end(session, { status: \"error\", code: \"CANCELLED\" });\n }\n\n emit(name: string, value: JsonValue): void {\n const session = this.session;\n if (session?.ready) session.collector?.emit(name, value);\n else if (session?.started) {\n // An explicit developer event during recovery is observable loss. Its\n // contents are discarded immediately; only the count survives reconnect.\n this.addDropped(session, 1, false);\n }\n }\n\n private watchAgent(session: Session, agent: AbstractAgent): void {\n if (this.session !== session || session.agentWatches.has(agent)) return;\n session.agentWatches.set(\n agent,\n agent.subscribe({\n onRunStartedEvent: ({ event }) => this.linkThread(session, event),\n }),\n );\n }\n\n /** Sends one `thread.linked` per Thread. A link that cannot be sent waits for the next run. */\n private linkThread(\n session: Session,\n { threadId }: { threadId: string },\n ): void {\n const connection = session.connection;\n if (\n !session.ready ||\n !connection ||\n !threadId ||\n session.linkedThreads.has(threadId)\n )\n return;\n session.linkedThreads.add(threadId);\n // `thread.linked` is a built-in name, so it skips the collector's\n // developer-event check. The host's beforeSend filter still applies.\n const event: TrajectoryEvent = {\n type: \"CUSTOM\",\n name: \"thread.linked\",\n timestamp: Date.now(),\n value: { threadId },\n };\n try {\n const { beforeSend } = session.config;\n const kept = beforeSend === undefined ? event : beforeSend(event);\n if (kept !== null) this.send(session, connection, kept);\n } catch {\n this.report(session, \"INVALID_EVENT\");\n }\n }\n\n private report(session: Session, code: string): void {\n try {\n session.config.onError?.({\n code,\n message: `Trajectory capture: ${code}.`,\n });\n } catch {\n // Telemetry errors, including a host callback, cannot interrupt the app.\n }\n }\n\n private current(session: Session, connection: Connection): boolean {\n return this.session === session && session.connection === connection;\n }\n\n private end(session: Session, result: StartResult): void {\n if (this.session !== session) return;\n this.session = undefined;\n clearTimeout(session.retry);\n session.runWatch?.unsubscribe();\n for (const watch of session.agentWatches.values()) watch.unsubscribe();\n session.agentWatches.clear();\n session.collector?.stop();\n session.ready = false;\n if (session.queue.length > 0) this.report(session, \"EVENTS_DROPPED\");\n this.discardQueue(session);\n if (session.connection) {\n // Stop prevents retry, but cannot prove whether an in-flight event persisted.\n for (const pending of session.connection.pending) {\n pending.finish(\"PERSISTENCE_UNKNOWN\");\n this.report(session, \"PERSISTENCE_UNKNOWN\");\n }\n this.cleanup(session, session.connection);\n }\n if (\n typeof window !== \"undefined\" &&\n typeof window.removeEventListener === \"function\"\n ) {\n window.removeEventListener(\"offline\", session.onOffline);\n window.removeEventListener(\"online\", session.onOnline);\n }\n if (result.status === \"error\" && result.code !== \"CANCELLED\")\n this.warnEnded(session, result.code);\n session.resolve(result);\n this.onChange();\n }\n\n /**\n * Without an app handler, a capture that ends on its own would otherwise fail\n * silently. Each outcome warns once per Core, so StrictMode replays and\n * repeated starts against the same misconfigured Runtime stay quiet.\n */\n private warnEnded(session: Session, code: string): void {\n if (session.config.onError !== undefined) return;\n const summary = session.started\n ? `Trajectory capture stopped (${code}).`\n : `Trajectory capture did not start (${code}).`;\n if (this.warned.has(summary)) return;\n this.warned.add(summary);\n const hint = SETUP_HINTS[code];\n console.warn(\n `[CopilotKit] ${summary}${hint === undefined ? \"\" : ` ${hint}`} Set learning.onError to handle capture errors in the app.`,\n );\n }\n\n private cleanup(session: Session, connection: Connection): void {\n session.connection = undefined;\n clearTimeout(connection.timer);\n connection.abort.abort();\n for (const pending of connection.pending) {\n clearTimeout(pending.timer);\n }\n connection.pending.clear();\n const { socket, channel } = connection;\n try {\n if (channel) {\n for (const [event, ref] of connection.channelRefs)\n channel.off(event, ref);\n // leave() cancels Phoenix's channel rejoin timer and pending join push.\n channel.leave();\n }\n } finally {\n if (socket) {\n socket.off(connection.socketRefs);\n // Phoenix's heartbeat timeout can schedule a reconnect after disconnect\n // returns. Retire this one-use socket; recovery needs a fresh grant.\n socket.connect = () => undefined;\n socket.disconnect();\n }\n }\n }\n\n private fail(\n session: Session,\n connection: Connection,\n code: string,\n retryable = true,\n ): void {\n if (!this.current(session, connection)) return;\n if (session.ready && session.started) {\n // A new start during recovery must await a fresh join, not an old success.\n session.promise = new Promise((resolve) => {\n session.resolve = resolve;\n });\n }\n // Closing capture may drain a pending edit; it must not reach a failed\n // connection or fill a batch while recovery is discarding queued events.\n session.ready = false;\n session.collector?.stop();\n session.collector = undefined;\n this.discardQueue(session);\n // A discarded or unconfirmed link is sent again on the next run.\n session.linkedThreads.clear();\n for (const pending of connection.pending)\n pending.finish(\"PERSISTENCE_UNKNOWN\");\n if (!this.current(session, connection)) return;\n this.cleanup(session, connection);\n this.onChange();\n this.report(session, code);\n if (this.session !== session) return;\n if (!session.started || !retryable) {\n this.end(session, { status: \"error\", code });\n return;\n }\n if (session.offline || this.session !== session) return;\n session.retry = setTimeout(\n () => {\n session.retry = undefined;\n if (this.session === session && !session.offline)\n void this.connect(session);\n },\n reconnectDelay(++session.retries),\n );\n }\n\n private async connect(session: Session): Promise<void> {\n if (this.session !== session || session.offline || session.connection)\n return;\n const connection: Connection = {\n abort: new AbortController(),\n socketRefs: [],\n channelRefs: [],\n pending: new Set(),\n };\n session.connection = connection;\n connection.timer = setTimeout(\n () => this.fail(session, connection, \"CONNECTION_TIMEOUT\"),\n TIMEOUT_MS,\n );\n try {\n const runtimeUrl = this.core.runtimeUrl;\n if (!runtimeUrl) {\n this.fail(session, connection, \"RUNTIME_REQUIRED\", false);\n return;\n }\n // \"auto\" stays unresolved until `/info` answers, and providers start capture\n // right after mount. Wait for detection, or a REST runtime gets a\n // single-endpoint request it cannot route.\n let transport = this.core.runtimeTransport;\n if (transport === \"auto\") {\n transport = await this.detectedTransport(connection.abort.signal);\n if (!this.current(session, connection)) return;\n }\n const rest = transport === \"rest\";\n // Resolved fresh, not the last snapshot: with a builder, `core.headers`\n // is `{}` before the first request and an old token after that (#1937).\n // Only an async builder is awaited, so a sync source still sends in the\n // same tick.\n const resolved = this.core.resolveHeaders();\n const coreHeaders = isPromiseLike(resolved)\n ? await abortable(resolved, connection.abort.signal)\n : resolved;\n if (!this.current(session, connection)) return;\n const response = await fetch(\n rest\n ? `${runtimeUrl}/trajectory/${encodeURIComponent(session.trajectoryId)}/connect`\n : (this.core.ɵruntimeEndpointUrl ?? runtimeUrl),\n {\n method: \"POST\",\n redirect: \"error\",\n signal: connection.abort.signal,\n headers: { ...coreHeaders, \"Content-Type\": \"application/json\" },\n credentials: this.core.credentials,\n body: JSON.stringify(\n rest\n ? {}\n : {\n method: \"trajectory/connect\",\n params: { trajectoryId: session.trajectoryId },\n body: {},\n },\n ),\n },\n );\n if (!this.current(session, connection)) return;\n const payload: unknown = await response.json().catch(() => undefined);\n if (!this.current(session, connection)) return;\n if (!response.ok) {\n this.fail(\n session,\n connection,\n errorCode(payload, \"CONNECTION_FAILED\"),\n response.status >= 500 ||\n response.status === 408 ||\n response.status === 429,\n );\n return;\n }\n if (!isGrant(payload)) {\n this.fail(session, connection, \"INVALID_GRANT\", false);\n return;\n }\n const socket = new Socket(payload.realtime.clientUrl, {\n params: { join_token: payload.joinToken },\n timeout: TIMEOUT_MS,\n });\n connection.socket = socket;\n const lost = () => this.fail(session, connection, \"CONNECTION_LOST\");\n connection.socketRefs.push(socket.onError(lost), socket.onClose(lost));\n const channel = socket.channel(payload.realtime.topic, {});\n connection.channel = channel;\n connection.channelRefs.push(\n [\"phx_error\", channel.onError(lost)],\n [\"phx_close\", channel.onClose(lost)],\n );\n socket.connect();\n if (!this.current(session, connection)) return;\n channel\n .join(TIMEOUT_MS)\n .receive(\"ok\", () => {\n if (!this.current(session, connection)) return;\n try {\n clearTimeout(connection.timer);\n session.ready = true;\n session.retries = 0;\n session.collector = createTrajectoryCollector({\n ...session.config,\n // Exclude SDK transport traffic so capture cannot record its own\n // authorization calls or CopilotKit telemetry and announcements.\n ignoreUrls: [\n ...(session.config.ignoreUrls ?? []),\n ...(this.core.runtimeUrl ? [this.core.runtimeUrl] : []),\n ...(this.core.ɵruntimeEndpointUrl\n ? [this.core.ɵruntimeEndpointUrl]\n : []),\n \"https://telemetry.copilotkit.ai/\",\n \"https://cdn.copilotkit.ai/\",\n ],\n onError: (error) => {\n if (error.code === \"CAPTURE_FAILED\")\n this.fail(session, connection, error.code, false);\n else {\n if (\n error.code === \"INVALID_EVENT\" ||\n error.code === \"EVENT_TOO_LARGE\"\n )\n this.addDropped(session, 1);\n session.config.onError?.(error);\n }\n },\n send: (event) => this.send(session, connection, event),\n });\n session.collector.start();\n if (!this.current(session, connection)) return;\n if (session.dropped > 0) this.scheduleFlush(session, connection);\n session.started = true;\n session.resolve({\n status: \"started\",\n trajectoryId: session.trajectoryId,\n });\n this.onChange();\n } catch {\n this.fail(session, connection, \"CAPTURE_FAILED\", false);\n }\n })\n .receive(\"error\", (joinError: unknown) =>\n this.fail(session, connection, joinErrorCode(joinError)),\n )\n .receive(\"timeout\", () =>\n this.fail(session, connection, \"CONNECTION_TIMEOUT\"),\n );\n } catch {\n this.fail(session, connection, \"CONNECTION_FAILED\");\n }\n }\n\n /** Resolves once auto-detection picks a transport, or with \"auto\" when the attempt is aborted. */\n private detectedTransport(signal: AbortSignal) {\n return new Promise<CopilotRuntimeTransport>((resolve) => {\n const finish = () => {\n subscription.unsubscribe();\n signal.removeEventListener(\"abort\", finish);\n resolve(this.core.runtimeTransport);\n };\n const subscription = this.core.subscribe({\n onRuntimeConnectionStatusChanged: () => {\n if (this.core.runtimeTransport !== \"auto\") finish();\n },\n });\n signal.addEventListener(\"abort\", finish, { once: true });\n });\n }\n\n private addDropped(session: Session, count: number, schedule = true): void {\n session.dropped = Math.min(\n Number.MAX_SAFE_INTEGER,\n session.dropped + count,\n );\n if (schedule && count > 0 && session.ready && session.connection)\n this.scheduleFlush(session, session.connection);\n }\n\n private scheduleFlush(session: Session, connection: Connection): void {\n if (session.flushTimer !== undefined || !this.current(session, connection))\n return;\n session.flushTimer = setTimeout(() => {\n session.flushTimer = undefined;\n this.flush(session, connection);\n }, BATCH_INTERVAL_MS);\n }\n\n private discardQueue(session: Session): void {\n clearTimeout(session.flushTimer);\n session.flushTimer = undefined;\n this.addDropped(session, session.queue.length, false);\n session.queue = [];\n }\n\n private connected(connection: Connection): boolean {\n return (\n connection.socket?.isConnected() === true &&\n connection.channel?.state === \"joined\"\n );\n }\n\n private send(\n session: Session,\n connection: Connection,\n event: TrajectoryEvent,\n ): void {\n if (!this.current(session, connection)) return;\n if (!session.ready) {\n this.addDropped(session, 1, false);\n return;\n }\n if (!this.connected(connection)) {\n this.addDropped(session, 1);\n this.fail(session, connection, \"CONNECTION_LOST\");\n return;\n }\n if (!Number.isSafeInteger(this.nextSeq)) {\n this.addDropped(session, 1);\n this.report(session, \"SEQUENCE_EXHAUSTED\");\n return;\n }\n const original = event.value;\n const fields =\n isObject(original) &&\n !Array.isArray(original) &&\n !Object.hasOwn(original, \"seq\")\n ? (original as Record<string, JsonValue>)\n : { data: original };\n const wire: WireEvent = {\n ...event,\n value: { ...fields, seq: this.nextSeq++ },\n };\n if (byteLength(wire) > MAX_EVENT_BYTES) {\n this.addDropped(session, 1);\n this.report(session, \"EVENT_TOO_LARGE\");\n return;\n }\n // Reserve the maximum dropped-counter width so later local losses cannot\n // grow an already-full payload over the wire limit.\n const fits = () =>\n session.queue.length < MAX_BATCH_EVENTS &&\n byteLength({\n events: [...session.queue, wire],\n dropped: Number.MAX_SAFE_INTEGER,\n }) <= MAX_BATCH_BYTES;\n if (!fits()) this.flush(session, connection);\n if (!this.current(session, connection) || !session.ready) return;\n if (!fits()) {\n this.addDropped(session, 1);\n this.report(session, \"EVENTS_DROPPED\");\n return;\n }\n session.queue.push(wire);\n if (session.queue.length === MAX_BATCH_EVENTS)\n this.flush(session, connection);\n else this.scheduleFlush(session, connection);\n }\n\n private flush(session: Session, connection: Connection): void {\n if (\n !this.current(session, connection) ||\n !session.ready ||\n (session.queue.length === 0 && session.dropped === 0)\n )\n return;\n if (!this.connected(connection)) {\n this.fail(session, connection, \"CONNECTION_LOST\");\n return;\n }\n // One in-flight batch and one bounded queue; never let Phoenix buffer offline.\n if (connection.pending.size > 0) return;\n clearTimeout(session.flushTimer);\n session.flushTimer = undefined;\n const batch: EventBatch = {\n events: session.queue,\n dropped: session.dropped,\n };\n session.queue = [];\n session.dropped = 0;\n let finished = false;\n const pending: PendingPush = {\n timer: setTimeout(\n () => pending.finish(\"PERSISTENCE_UNKNOWN\"),\n TIMEOUT_MS,\n ),\n finish: (code, knownRollback = false, flushNext = true) => {\n if (finished) return;\n finished = true;\n clearTimeout(pending.timer);\n connection.pending.delete(pending);\n // A missing ACK may already be accepted by Redis. Never count uncertainty\n // as a known drop, and never replay a batch or its dropped counter.\n if (knownRollback)\n this.addDropped(session, batch.events.length + batch.dropped, false);\n if (code && this.current(session, connection))\n this.report(session, code);\n if (\n flushNext &&\n this.current(session, connection) &&\n session.ready &&\n (session.queue.length > 0 || (!knownRollback && session.dropped > 0))\n )\n this.flush(session, connection);\n },\n };\n connection.pending.add(pending);\n try {\n connection\n .channel!.push(\"events\", batch, TIMEOUT_MS)\n .receive(\"ok\", (payload: unknown) => {\n // Rejected rows are already counted by Gateway; don't also mark them\n // as client drops. The aggregate reply cannot identify rejected rows.\n pending.finish(\n !isBatchAcknowledgement(payload, batch.events.length)\n ? \"PERSISTENCE_UNKNOWN\"\n : payload.rejected > 0\n ? \"EVENTS_REJECTED\"\n : undefined,\n );\n })\n .receive(\"error\", (payload: unknown) => {\n if (!this.current(session, connection)) return;\n const reason = isObject(payload) ? payload.reason : undefined;\n if (reason === \"unauthorized\" || reason === \"trajectory_mismatch\") {\n // Finish the known rollback without flushing the queued tail onto\n // a channel whose scope has just been refused.\n pending.finish(undefined, true, false);\n this.fail(session, connection, reason.toUpperCase(), false);\n return;\n }\n const rollback =\n typeof reason === \"string\" &&\n [\n \"invalid_batch\",\n \"batch_too_large\",\n \"batch_too_many_events\",\n \"trajectory_over_share\",\n \"trajectory_outbox_full\",\n \"unsupported_event\",\n ].includes(reason);\n // storage_unavailable includes Redis timeouts after a possible write.\n // retryable:true cannot make a repeated dropped counter idempotent.\n pending.finish(\n rollback ? (reason as string).toUpperCase() : \"PERSISTENCE_UNKNOWN\",\n rollback,\n );\n })\n .receive(\"timeout\", () => pending.finish(\"PERSISTENCE_UNKNOWN\"));\n } catch {\n pending.finish(\"PERSISTENCE_UNKNOWN\");\n }\n }\n}\n","import { createCollector } from \"@copilotkit/learning\";\nimport type {\n CaptureOptions,\n Collector,\n CollectorOptions,\n JsonValue,\n StartResult,\n TrajectoryCaptureOptions,\n} from \"@copilotkit/learning\";\nimport type { AbstractAgent, AgentSubscriber, Message } from \"@ag-ui/client\";\nimport type { CopilotKitCore } from \"./core\";\nimport { TrajectoryConnection } from \"./trajectory-connection\";\n\n/** Interaction capture settings for {@link CopilotKitCore}. See `@copilotkit/learning`. */\nexport interface LegacyLearningConfig extends Omit<\n CollectorOptions,\n \"enrich\" | \"capture\"\n> {\n /** Capture modules, plus `agentText: false` to omit message text (included in full by default). */\n capture?: CaptureOptions & { agentText?: boolean };\n}\n\nexport type LearningConfig =\n | LegacyLearningConfig\n | (TrajectoryCaptureOptions & { sink?: undefined });\nexport type TrajectoryStartOptions = {\n trajectoryId?: string;\n /**\n * Used only by explicit custom sinks. Authenticated capture warns and ignores\n * this option; assign Learning Spaces on the server with\n * `getTrajectoryLearningContainerIds` on `CopilotKitIntelligence`.\n */\n learningContainerIds?: string[];\n};\n\n/** Returned by {@link CopilotKitCore.registerOpenThread}. */\nexport interface OpenThreadRegistration {\n /** The view now shows another Thread. */\n update(threadId: string): void;\n /** The view that showed this Thread is gone. */\n unregister(): void;\n}\n\n/** The part of a DOM element the enricher reads. Elements satisfy it. */\ninterface ClosestTarget {\n closest(\n selector: string,\n ): { getAttribute(name: string): string | null } | null;\n}\n\ninterface OpenThread {\n agentId: string;\n threadId: string;\n}\n\ninterface ToolCallOrigin {\n agentId: string;\n threadId: string;\n messageId: string | undefined;\n runId: string | undefined;\n}\n\n// CopilotKit's own browser traffic (Inspector telemetry and announcements) is not app activity.\nconst COPILOTKIT_OWN_URLS = [\n \"https://telemetry.copilotkit.ai/\",\n \"https://cdn.copilotkit.ai/\",\n];\n\n/**\n * Wires `@copilotkit/learning` into Core. Default capture uses Runtime and Phoenix;\n * explicit legacy sinks also use agent events and open-Thread attribution.\n */\nexport class LearningBridge {\n private collector: Collector | null = null;\n private readonly agents = new Map<\n AbstractAgent,\n ReturnType<AbstractAgent[\"subscribe\"]>\n >();\n private readonly openThreads = new Set<OpenThread>();\n private readonly toolCalls = new Map<string, ToolCallOrigin>();\n private readonly executingTools = new Map<string, number>();\n private readonly lastRunIds = new WeakMap<AbstractAgent, string>();\n private lastLinkedThreadId: string | null = null;\n private coreSubscription: ReturnType<CopilotKitCore[\"subscribe\"]> | null =\n null;\n private seq = 0;\n private activeConfig: LegacyLearningConfig | undefined;\n private readonly connection: TrajectoryConnection;\n\n constructor(\n private readonly core: CopilotKitCore,\n private config: LearningConfig | undefined,\n onChange: () => void = () => {},\n ) {\n this.connection = new TrajectoryConnection(core, onChange);\n this.setConfig(config);\n }\n\n setConfig(config: LearningConfig | undefined) {\n this.config = config;\n if (config === undefined) this.stop();\n }\n\n get isConfigured() {\n return this.config !== undefined;\n }\n\n /**\n * Whether events may carry agent message text: not when the capture's config\n * sets `capture.agentText` to false. A running custom-sink capture keeps the\n * choice it started with; otherwise the current config decides.\n */\n get capturesAgentText() {\n const config = this.activeConfig ?? this.config;\n if (config === undefined) return false;\n // Typed for custom sinks only, but honored for authenticated capture too.\n const capture: unknown = config.capture;\n return !(\n typeof capture === \"object\" &&\n capture !== null &&\n (capture as { agentText?: unknown }).agentText === false\n );\n }\n\n private get isLegacyCaptureActive() {\n return this.collector !== null && this.collector.trajectoryId !== null;\n }\n\n private startTracking() {\n if (this.coreSubscription !== null || !this.isLegacyCaptureActive) return;\n this.coreSubscription = this.core.subscribe({\n onAgentsChanged: ({ agents }) => {\n for (const agent of Object.values(agents)) this.track(agent);\n },\n // Per-thread clones are not in `core.agents`; track the running instance too.\n onAgentRunStarted: ({ agent }) => this.track(agent),\n onToolExecutionStart: ({ toolCallId, agentId, toolName }) => {\n if (!this.isLegacyCaptureActive) return;\n this.executingTools.set(toolCallId, Date.now());\n this.emitToolCall(\"executing\", toolCallId, agentId, toolName, {});\n },\n onToolExecutionEnd: ({ toolCallId, agentId, toolName, error }) => {\n if (!this.isLegacyCaptureActive) return;\n const startedAt = this.executingTools.get(toolCallId);\n this.executingTools.delete(toolCallId);\n this.emitToolCall(\"completed\", toolCallId, agentId, toolName, {\n durationMs:\n startedAt === undefined ? undefined : Date.now() - startedAt,\n outcome: error === undefined ? \"ok\" : \"error\",\n });\n this.toolCalls.delete(toolCallId);\n },\n });\n for (const agent of Object.values(this.core.agents)) this.track(agent);\n }\n\n get trajectoryId(): string | null {\n return this.connection.trajectoryId ?? this.collector?.trajectoryId ?? null;\n }\n\n start(options: TrajectoryStartOptions = {}): Promise<StartResult> {\n const config = this.config;\n if (config === undefined) {\n console.warn(\n \"[CopilotKit] startTrajectory() needs the `learning` option on CopilotKitCore (or the CopilotKitProvider `learning` prop).\",\n );\n return Promise.resolve({ status: \"error\", code: \"LEARNING_DISABLED\" });\n }\n if (config.sink === undefined) {\n if (options.learningContainerIds !== undefined) {\n console.warn(\n \"[CopilotKit] learningContainerIds is supported only with a custom sink. Authenticated Trajectory capture ignores it; assign Learning Spaces on the server with getTrajectoryLearningContainerIds on CopilotKitIntelligence, and remove learningContainerIds from the capture options.\",\n );\n }\n this.stopLegacy();\n return this.connection.start(options.trajectoryId, config);\n }\n this.connection.stop();\n const trajectoryId =\n options.trajectoryId ??\n this.collector?.trajectoryId ??\n crypto.randomUUID();\n if (this.collector === null) {\n this.activeConfig = config;\n const runtimeUrl = this.core.runtimeUrl;\n this.collector = createCollector({\n ...config,\n beforeSend: (event) => {\n const sequenced = {\n ...event,\n value: { ...event.value, seq: ++this.seq },\n };\n return config.beforeSend === undefined\n ? sequenced\n : config.beforeSend(sequenced);\n },\n ignoreUrls: [\n ...(config.ignoreUrls ?? []),\n ...COPILOTKIT_OWN_URLS,\n ...(runtimeUrl === undefined ? [] : [runtimeUrl]),\n ],\n enrich: (target) => this.enrich(target),\n });\n }\n const wasActive = this.collector.trajectoryId !== null;\n this.collector.start({ ...options, trajectoryId });\n if (wasActive)\n return Promise.resolve(\n this.collector.trajectoryId === trajectoryId\n ? { status: \"started\", trajectoryId }\n : { status: \"error\", code: \"TRAJECTORY_ACTIVE\" },\n );\n this.startTracking();\n this.lastLinkedThreadId = null;\n for (const threadId of this.distinctOpenThreadIds())\n this.emitThreadLinked(threadId, \"start\");\n return Promise.resolve({ status: \"started\", trajectoryId });\n }\n\n stop() {\n this.connection.stop();\n this.stopLegacy();\n }\n\n private stopLegacy() {\n this.collector?.stop();\n this.collector = null;\n this.activeConfig = undefined;\n this.coreSubscription?.unsubscribe();\n this.coreSubscription = null;\n for (const subscription of this.agents.values()) subscription.unsubscribe();\n this.agents.clear();\n this.toolCalls.clear();\n this.executingTools.clear();\n }\n\n /**\n * A developer event. Only an explicit legacy sink adds open-Thread context;\n * an event that names its own Thread gets no ambiguity next to it.\n */\n emit(name: string, value: JsonValue) {\n this.connection.emit(name, value);\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n const context =\n typeof value[\"threadId\"] === \"string\" ? {} : this.openThreadContext();\n this.collector?.emit(name, { ...context, ...value });\n }\n }\n\n registerOpenThread(params: OpenThread) {\n const entry: OpenThread = { ...params };\n const isNew = !this.distinctOpenThreadIds().includes(entry.threadId);\n this.openThreads.add(entry);\n if (isNew) this.emitThreadLinked(entry.threadId, \"open\");\n const registration: OpenThreadRegistration = {\n update: (threadId) => {\n if (threadId === entry.threadId) return;\n entry.threadId = threadId;\n const others = [...this.openThreads].filter((other) => other !== entry);\n const isOpenElsewhere = others.some(\n (other) => other.threadId === threadId,\n );\n if (!isOpenElsewhere) this.emitThreadLinked(threadId, \"switch\");\n },\n unregister: () => {\n this.openThreads.delete(entry);\n },\n };\n return registration;\n }\n\n private distinctOpenThreadIds() {\n return [...new Set([...this.openThreads].map((open) => open.threadId))];\n }\n\n private emitThreadLinked(\n threadId: string,\n reason: \"start\" | \"open\" | \"switch\",\n ) {\n const isActive =\n this.collector !== null && this.collector.trajectoryId !== null;\n // React StrictMode unregisters and registers again in dev; one link per change is enough.\n if (!isActive || threadId === this.lastLinkedThreadId) return;\n this.lastLinkedThreadId = threadId;\n const owner = [...this.openThreads].find(\n (open) => open.threadId === threadId,\n );\n const agent = this.findAgentForThread(threadId);\n this.collector?.ɵemit(\"thread.linked\", {\n threadId,\n agentId: owner?.agentId ?? agent?.agentId ?? null,\n hasMessages: (agent?.messages.length ?? 0) > 0,\n reason,\n });\n }\n\n private findAgentForThread(threadId: string) {\n return [...this.agents.keys()].find((agent) => agent.threadId === threadId);\n }\n\n private track(agent: AbstractAgent) {\n const agentId = agent.agentId;\n if (\n !this.isLegacyCaptureActive ||\n this.agents.has(agent) ||\n agentId === undefined\n )\n return;\n this.agents.set(\n agent,\n agent.subscribe(this.agentSubscriber(agent, agentId)),\n );\n }\n\n private agentSubscriber(agent: AbstractAgent, agentId: string) {\n const runIdFor = () => this.lastRunIds.get(agent);\n const subscriber: AgentSubscriber = {\n onRunStartedEvent: ({ event }) => {\n this.lastRunIds.set(agent, event.runId);\n this.emitRun(\"started\", agent, event.threadId, event.runId);\n },\n onRunFinishedEvent: ({ event }) => {\n this.emitRun(\"finished\", agent, event.threadId, event.runId);\n },\n onRunErrorEvent: () => {\n this.emitRun(\"error\", agent, agent.threadId, runIdFor() ?? null);\n },\n onToolCallStartEvent: ({ event }) => {\n if (!this.isLegacyCaptureActive) return;\n const origin: ToolCallOrigin = {\n agentId,\n threadId: agent.threadId,\n messageId: event.parentMessageId,\n runId: runIdFor(),\n };\n this.toolCalls.set(event.toolCallId, origin);\n this.emitToolCall(\n \"started\",\n event.toolCallId,\n origin.agentId,\n event.toolCallName,\n {},\n );\n },\n onToolCallResultEvent: ({ event }) => {\n if (!this.executingTools.has(event.toolCallId)) {\n this.toolCalls.delete(event.toolCallId);\n }\n },\n onNewMessage: ({ message }) => this.emitMessage(agent, message),\n };\n return subscriber;\n }\n\n private emitRun(\n phase: \"started\" | \"finished\" | \"error\",\n agent: AbstractAgent,\n threadId: string,\n runId: string | null,\n ) {\n this.collector?.ɵemit(\"agent.run\", {\n phase,\n runId,\n threadId,\n agentId: agent.agentId,\n });\n }\n\n private emitMessage(agent: AbstractAgent, message: Message) {\n // No tool names here: this fires when the text ends, before tool calls stream in.\n // `tool.call` events carry the tool name and this `messageId`.\n const content = typeof message.content === \"string\" ? message.content : \"\";\n const includeText =\n this.capturesAgentText && typeof message.content === \"string\";\n this.collector?.ɵemit(\"agent.message\", {\n messageId: message.id,\n runId: this.runIdForMessage(agent, message.id),\n threadId: agent.threadId,\n agentId: agent.agentId,\n role: message.role,\n textLength: content.length,\n ...(includeText ? { text: content } : {}),\n });\n }\n\n private emitToolCall(\n phase: \"started\" | \"executing\" | \"completed\",\n toolCallId: string,\n agentId: string,\n toolName: string,\n extra: { durationMs?: number; outcome?: \"ok\" | \"error\" },\n ) {\n const origin = this.toolCalls.get(toolCallId);\n this.collector?.ɵemit(\"tool.call\", {\n phase,\n toolCallId,\n toolName,\n agentId,\n threadId: origin?.threadId ?? null,\n messageId: origin?.messageId,\n runId: origin?.runId,\n ...extra,\n });\n }\n\n private runIdForMessage(agent: AbstractAgent, messageId: string) {\n const agentId = agent.agentId;\n if (agentId === undefined) return null;\n return (\n this.core.getRunIdForMessage(agentId, agent.threadId, messageId) ??\n this.lastRunIds.get(agent) ??\n null\n );\n }\n\n private findMessage(messageId: string) {\n for (const agent of this.agents.keys()) {\n const message = agent.messages.find(\n (candidate) => candidate.id === messageId,\n );\n if (message !== undefined) return { agent, message };\n }\n return null;\n }\n\n private toolStatus(agent: AbstractAgent, toolCallId: string) {\n if (this.executingTools.has(toolCallId)) return \"executing\";\n const hasResult = agent.messages.some(\n (message) => message.role === \"tool\" && message.toolCallId === toolCallId,\n );\n return hasResult ? \"complete\" : \"inProgress\";\n }\n\n /** Adds agent context to a click: exact message first, then the single open Thread. */\n enrich(target: ClosestTarget) {\n const messageId =\n target.closest(\"[data-message-id]\")?.getAttribute(\"data-message-id\") ??\n null;\n const toolCallId =\n target\n .closest(\"[data-tool-call-id]\")\n ?.getAttribute(\"data-tool-call-id\") ?? null;\n const found = messageId === null ? null : this.findMessage(messageId);\n if (found !== null) {\n const { agent, message } = found;\n const toolCall =\n toolCallId !== null && message.role === \"assistant\"\n ? message.toolCalls?.find((call) => call.id === toolCallId)\n : undefined;\n return {\n threadId: agent.threadId,\n agentId: agent.agentId,\n messageId: message.id,\n runId: this.runIdForMessage(agent, message.id),\n ...(toolCall === undefined\n ? {}\n : {\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n toolStatus: this.toolStatus(agent, toolCall.id),\n }),\n };\n }\n return this.openThreadContext();\n }\n\n /** The single open Thread, or `null` with the candidates when several are open. */\n private openThreadContext() {\n const openIds = this.distinctOpenThreadIds();\n if (openIds.length > 1) {\n return {\n threadId: null,\n threadAmbiguity: { reason: \"multiple-open\", candidates: openIds },\n };\n }\n return { threadId: openIds[0] ?? null };\n }\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n BehaviorSubject,\n Observable,\n OperatorFunction,\n Subject,\n Subscription,\n asapScheduler,\n} from \"rxjs\";\nimport { distinctUntilChanged, filter, map, observeOn } from \"rxjs/operators\";\n\n/**\n * The minimal action shape used by this micro-redux implementation.\n */\nexport interface AnyAction {\n type: string;\n}\n\n/**\n * A typed action creator function with a `type` literal and runtime matcher.\n */\nexport type ActionCreator<\n Type extends string,\n Args extends unknown[] = unknown[],\n Action extends AnyAction & { type: Type } = { type: Type },\n> = ((...args: Args) => Action) & {\n type: Type;\n match(action: AnyAction): action is Action;\n};\n\n/**\n * Extracts the action type produced by an action creator.\n */\nexport type ActionFromCreator<T> = T extends (...args: any[]) => infer A\n ? A\n : never;\n\n/**\n * Extracts a union of actions produced by a tuple/array of action creators.\n */\nexport type ActionFromCreators<\n Creators extends readonly ActionCreator<string, any[], any>[],\n> = ActionFromCreator<Creators[number]>;\n\n/**\n * A reducer transforms state in response to actions.\n */\nexport type Reducer<State, Action extends AnyAction = AnyAction> = (\n state: State | undefined,\n action: Action,\n) => State;\n\n/**\n * A selector derives a value from state.\n */\nexport type Selector<State, Result> = (state: State) => Result;\n\n/**\n * Marker config for action creators that accept no payload.\n */\nexport interface EmptyActionConfig {\n readonly kind: \"empty\";\n}\n\nconst PROPS_MARKER: unique symbol = Symbol(\"props_marker\");\n\n/**\n * Marker config for action creators that require payload props.\n */\nexport interface PropsActionConfig<Props extends Record<string, unknown>> {\n readonly kind: \"props\";\n readonly [PROPS_MARKER]?: Props;\n}\n\n/**\n * Supported action creator config node in an action group.\n */\nexport type ActionConfig =\n | EmptyActionConfig\n | PropsActionConfig<Record<string, unknown>>;\n\n/**\n * Shape of an action group declaration object.\n */\nexport type ActionGroupConfig = Record<string, ActionConfig>;\n\n/**\n * Maps an action group declaration to a strongly typed action-creator object.\n */\nexport type ActionGroupResult<\n Source extends string,\n Config extends ActionGroupConfig,\n> = {\n [K in keyof Config & string]: Config[K] extends PropsActionConfig<infer P>\n ? ActionCreator<`[${Source}] ${K}`, [P], { type: `[${Source}] ${K}` } & P>\n : ActionCreator<`[${Source}] ${K}`, [], { type: `[${Source}] ${K}` }>;\n};\n\ninterface OnReducerEntry<\n State,\n Action extends AnyAction = AnyAction,\n Creators extends readonly ActionCreator<string, any[], any>[] =\n readonly ActionCreator<string, any[], any>[],\n> {\n creators: Creators;\n reducer: (state: State, action: Action) => State;\n}\n\ntype ActionFromOnReducerEntry<TEntry> =\n TEntry extends OnReducerEntry<any, infer TAction, any> ? TAction : never;\n\n/**\n * Effect contract for streams that emit actions to dispatch.\n */\nexport interface DispatchingEffect<\n State,\n InputAction extends AnyAction = AnyAction,\n OutputAction extends AnyAction = AnyAction,\n> {\n run: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<OutputAction>;\n dispatch: true;\n}\n\n/**\n * Effect contract for side-effect-only streams whose emissions are ignored.\n */\nexport interface NonDispatchingEffect<\n State,\n InputAction extends AnyAction = AnyAction,\n> {\n run: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<unknown>;\n dispatch: false;\n}\n\n/**\n * Union of supported effect shapes.\n */\nexport type Effect<\n State,\n InputAction extends AnyAction = AnyAction,\n OutputAction extends AnyAction = AnyAction,\n> =\n | DispatchingEffect<State, InputAction, OutputAction>\n | NonDispatchingEffect<State, InputAction>;\n\n/**\n * Lifecycle actions dispatched by the store.\n */\nexport type StoreLifecycleAction =\n | { type: \"@@micro-redux/init\" }\n | { type: \"@@micro-redux/stop\" };\n\n/**\n * Options for a dispatching effect.\n */\nexport interface DispatchingEffectOptions {\n dispatch?: true;\n}\n\n/**\n * Options for a non-dispatching effect.\n */\nexport interface NonDispatchingEffectOptions {\n dispatch: false;\n}\n\nconst INTERNAL_ACTION_TYPES = {\n boot: \"@@micro-redux/boot\",\n init: \"@@micro-redux/init\",\n stop: \"@@micro-redux/stop\",\n} as const;\n\nconst INTERNAL_BOOT_ACTION: AnyAction = { type: INTERNAL_ACTION_TYPES.boot };\n\n/**\n * Builds a typed action creator from a type string and payload factory.\n */\nfunction createTypedActionCreator<\n Type extends string,\n Args extends unknown[],\n Payload extends Record<string, unknown>,\n>(\n type: Type,\n factory: (...args: Args) => Payload,\n): ActionCreator<Type, Args, { type: Type } & Payload> {\n const creator = ((...args: Args) => ({\n ...factory(...args),\n type,\n })) as ActionCreator<Type, Args, { type: Type } & Payload>;\n\n creator.type = type;\n creator.match = (action: AnyAction): action is { type: Type } & Payload =>\n action.type === type;\n\n return creator;\n}\n\n/**\n * Declares a payload-based action config for `createActionGroup`.\n *\n * @example\n * ```ts\n * const actions = createActionGroup(\"User\", {\n * loaded: props<{ id: string }>(),\n * });\n * ```\n */\nexport function props<\n Props extends Record<string, unknown>,\n>(): PropsActionConfig<Props> {\n return { kind: \"props\" };\n}\n\n/**\n * Declares a no-payload action config for `createActionGroup`.\n *\n * @example\n * ```ts\n * const actions = createActionGroup(\"User\", {\n * reset: empty(),\n * });\n * ```\n */\nexport function empty(): EmptyActionConfig {\n return { kind: \"empty\" };\n}\n\n/**\n * Creates a namespaced group of typed action creators.\n *\n * Action types are formatted as: `[Source] actionName`.\n */\nexport function createActionGroup<\n const Source extends string,\n const Config extends ActionGroupConfig,\n>(source: Source, config: Config): ActionGroupResult<Source, Config> {\n const group = {} as ActionGroupResult<Source, Config>;\n\n for (const eventName of Object.keys(config) as Array<keyof Config & string>) {\n const eventConfig = config[eventName];\n if (!eventConfig) {\n continue;\n }\n\n const actionType = `[${source}] ${eventName}` as const;\n\n if (eventConfig.kind === \"props\") {\n group[eventName] = createTypedActionCreator(\n actionType,\n (payload: Record<string, unknown>) => ({ ...payload }),\n ) as ActionGroupResult<Source, Config>[typeof eventName];\n continue;\n }\n\n group[eventName] = createTypedActionCreator(\n actionType,\n () => ({}),\n ) as ActionGroupResult<Source, Config>[typeof eventName];\n }\n\n return group;\n}\n\n/**\n * Registers one reducer handler for one or more action creators.\n *\n * @throws Error when called without at least one action creator and reducer.\n */\nexport function on<\n State,\n const Creators extends readonly ActionCreator<string, any[], any>[],\n Action extends ActionFromCreators<Creators>,\n>(\n ...args: [\n ...creators: Creators,\n reducer: (state: State, action: Action) => State,\n ]\n): OnReducerEntry<State, Action, Creators> {\n if (args.length < 2) {\n throw new Error(\"on requires at least one action creator and one reducer\");\n }\n\n const reducer = args[args.length - 1] as (\n state: State,\n action: Action,\n ) => State;\n const creators = args.slice(0, -1) as unknown as Creators;\n\n return {\n creators,\n reducer,\n };\n}\n\n/**\n * Creates a reducer from an initial state and `on(...)` handler entries.\n *\n * Unknown action types return the current state unchanged.\n */\nexport function createReducer<\n State,\n const Entries extends readonly OnReducerEntry<any, any, any>[],\n>(\n initialState: State,\n ...entries: Entries\n): Reducer<State, ActionFromOnReducerEntry<Entries[number]>> {\n type ReducerAction = ActionFromOnReducerEntry<Entries[number]>;\n\n const reducerMap = new Map<\n string,\n Array<(state: State, action: ReducerAction) => State>\n >();\n\n for (const entry of entries) {\n for (const creator of entry.creators) {\n const handlers = reducerMap.get(creator.type) ?? [];\n handlers.push(\n entry.reducer as unknown as (\n state: State,\n action: ReducerAction,\n ) => State,\n );\n reducerMap.set(creator.type, handlers);\n }\n }\n\n return (state: State | undefined, action: ReducerAction): State => {\n const currentState = state ?? initialState;\n const handlers = reducerMap.get(action.type);\n\n if (!handlers || handlers.length === 0) {\n return currentState;\n }\n\n let nextState = currentState;\n for (const handler of handlers) {\n nextState = handler(nextState, action);\n }\n return nextState;\n };\n}\n\n/**\n * Creates a memoized selector from a single projector.\n */\nexport function createSelector<State, Result>(\n projector: (state: State) => Result,\n): Selector<State, Result>;\n\n/**\n * Creates a memoized selector from input selectors and a projector.\n *\n * Memoization uses one-entry caching over the latest input selector values.\n */\nexport function createSelector<\n State,\n const Selectors extends readonly Selector<State, unknown>[],\n Result,\n>(\n ...args: [\n ...selectors: Selectors,\n projector: (\n ...inputs: { [K in keyof Selectors]: ReturnType<Selectors[K]> }\n ) => Result,\n ]\n): Selector<State, Result>;\n\n/**\n * Creates a selector that caches and reuses the last computed result\n * when all input references are unchanged.\n */\nexport function createSelector<State, Result>(\n ...args:\n | [(state: State) => Result]\n | [\n ...selectors: Array<Selector<State, unknown>>,\n projector: (...inputs: unknown[]) => Result,\n ]\n): Selector<State, Result> {\n if (args.length === 1) {\n const projector = args[0] as (state: State) => Result;\n let hasCached = false;\n let lastState: State | undefined;\n let lastResult: Result;\n\n return (state: State): Result => {\n if (hasCached && state === lastState) {\n return lastResult;\n }\n\n lastState = state;\n lastResult = projector(state);\n hasCached = true;\n return lastResult;\n };\n }\n\n const projector = args[args.length - 1] as (...inputs: unknown[]) => Result;\n const selectors = args.slice(0, -1) as Array<Selector<State, unknown>>;\n\n let hasCached = false;\n let lastInputs: unknown[] = [];\n let lastResult: Result;\n\n return (state: State): Result => {\n const inputs = selectors.map((selector) => selector(state));\n\n if (\n hasCached &&\n inputs.length === lastInputs.length &&\n inputs.every((value, index) => value === lastInputs[index])\n ) {\n return lastResult;\n }\n\n lastInputs = inputs;\n lastResult = projector(...inputs);\n hasCached = true;\n return lastResult;\n };\n}\n\n/**\n * RxJS operator that maps state emissions through a selector and suppresses\n * unchanged projected values via reference equality.\n */\nexport function select<State, Result>(\n selector: Selector<State, Result>,\n): OperatorFunction<State, Result> {\n return (source$) => source$.pipe(map(selector), distinctUntilChanged());\n}\n\n/**\n * RxJS operator that filters an action stream by action creators and narrows\n * the output action type to the matched creator union.\n *\n * @throws Error when called without at least one action creator.\n */\nexport function ofType<\n const Creators extends readonly ActionCreator<string, any[], AnyAction>[],\n>(\n ...creators: Creators\n): OperatorFunction<AnyAction, ActionFromCreators<Creators>> {\n if (creators.length === 0) {\n throw new Error(\"ofType requires at least one action creator\");\n }\n\n const actionTypes = new Set(creators.map((creator) => creator.type));\n return (source$) => {\n return source$.pipe(\n filter((action: AnyAction): action is ActionFromCreators<Creators> => {\n return actionTypes.has(action.type);\n }),\n );\n };\n}\n\n/**\n * Creates a dispatching effect. Emitted actions are automatically dispatched.\n */\nexport function createEffect<\n State,\n InputAction extends AnyAction,\n OutputAction extends AnyAction,\n>(\n factory: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<OutputAction>,\n options?: DispatchingEffectOptions,\n): DispatchingEffect<State, InputAction, OutputAction>;\n\n/**\n * Creates a non-dispatching effect. Emitted values are ignored.\n */\nexport function createEffect<State, InputAction extends AnyAction>(\n factory: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<unknown>,\n options: NonDispatchingEffectOptions,\n): NonDispatchingEffect<State, InputAction>;\n\n/**\n * Creates an effect descriptor consumed by `createStore`.\n */\nexport function createEffect<\n State,\n InputAction extends AnyAction,\n OutputAction extends AnyAction,\n>(\n factory: (\n actions$: Observable<InputAction>,\n state$: Observable<State>,\n ) => Observable<OutputAction>,\n options: DispatchingEffectOptions | NonDispatchingEffectOptions = {},\n): Effect<State, InputAction, OutputAction> {\n if (options.dispatch === false) {\n return {\n run: factory,\n dispatch: false,\n };\n }\n\n return {\n run: factory,\n dispatch: true,\n };\n}\n\n/**\n * Store interface returned by `createStore`.\n */\nexport interface Store<State, Action extends AnyAction = AnyAction> {\n dispatch(action: Action): void;\n getState(): State;\n readonly state$: Observable<State>;\n readonly actions$: Observable<Action | StoreLifecycleAction>;\n select<Result>(selector: Selector<State, Result>): Observable<Result>;\n init(): void;\n stop(): void;\n}\n\n/**\n * Creates a small observable store with reducer + effects.\n *\n * Behavior:\n * - `init()` starts effects and dispatches `@@micro-redux/init`.\n * - `stop()` dispatches `@@micro-redux/stop` and unsubscribes all effects.\n * - Effect action observation is scheduled on `asapScheduler` to avoid\n * synchronous re-entrancy in the effect loop.\n * - Any effect error triggers fail-fast teardown and errors both `actions$`\n * and `state$`.\n */\nexport function createStore<\n State,\n Action extends AnyAction = AnyAction,\n>(options: {\n reducer: Reducer<State, Action | StoreLifecycleAction>;\n effects?: Array<Effect<State, Action | StoreLifecycleAction, Action>>;\n}): Store<State, Action> {\n const reducer = options.reducer;\n const effects = options.effects ?? [];\n\n let hasFatalError = false;\n let isRunning = false;\n let effectSubscriptions = new Subscription();\n\n let currentState = reducer(\n undefined,\n INTERNAL_BOOT_ACTION as Action | StoreLifecycleAction,\n );\n const stateSubject = new BehaviorSubject<State>(currentState);\n const actionsSubject = new Subject<Action | StoreLifecycleAction>();\n\n const dispatchInternal = (action: Action | StoreLifecycleAction): void => {\n if (hasFatalError) {\n throw new Error(\"Store is in a failed state due to an effect error\");\n }\n\n currentState = reducer(currentState, action);\n stateSubject.next(currentState);\n actionsSubject.next(action);\n };\n\n const failFast = (error: unknown): void => {\n if (hasFatalError) {\n return;\n }\n\n hasFatalError = true;\n isRunning = false;\n effectSubscriptions.unsubscribe();\n effectSubscriptions = new Subscription();\n\n actionsSubject.error(error);\n stateSubject.error(error);\n };\n\n const startEffects = (): void => {\n for (const effect of effects) {\n const scheduledActions$ = actionsSubject\n .asObservable()\n .pipe(observeOn(asapScheduler));\n const state$ = stateSubject.asObservable();\n\n if (effect.dispatch) {\n const subscription = effect.run(scheduledActions$, state$).subscribe({\n next: (effectAction) => {\n if (hasFatalError) {\n return;\n }\n dispatchInternal(effectAction);\n },\n error: (error) => {\n failFast(error);\n },\n });\n\n effectSubscriptions.add(subscription);\n continue;\n }\n\n const subscription = effect.run(scheduledActions$, state$).subscribe({\n error: (error) => {\n failFast(error);\n },\n });\n\n effectSubscriptions.add(subscription);\n }\n };\n\n return {\n dispatch(action: Action): void {\n dispatchInternal(action);\n },\n getState(): State {\n return currentState;\n },\n get state$(): Observable<State> {\n return stateSubject.asObservable();\n },\n get actions$(): Observable<Action | StoreLifecycleAction> {\n return actionsSubject.asObservable();\n },\n select<Result>(selector: Selector<State, Result>): Observable<Result> {\n return stateSubject.asObservable().pipe(select(selector));\n },\n init(): void {\n if (hasFatalError || isRunning) {\n return;\n }\n\n isRunning = true;\n startEffects();\n\n if (hasFatalError) {\n return;\n }\n\n dispatchInternal({ type: INTERNAL_ACTION_TYPES.init });\n },\n stop(): void {\n if (hasFatalError || !isRunning) {\n return;\n }\n\n dispatchInternal({ type: INTERNAL_ACTION_TYPES.stop });\n effectSubscriptions.unsubscribe();\n effectSubscriptions = new Subscription();\n isRunning = false;\n },\n };\n}\n","/**\n * Memory error registry — stable codes for the errors the memory store throws.\n *\n * The memory store (`memory.ts`) used to throw bare `new Error(\"Failed to fetch\n * memories: 500\")` / `\"Request timed out\"` / `\"Request failed: <status>\"`. Those\n * reach the `error` selector (and the consumer UI via `useMemories` /\n * `injectMemories`) verbatim, with no machine-readable `code`/`category`/\n * `retryable`, so they cannot be grouped in observability or branched on by\n * consumers.\n *\n * Per the repo's error-handling architecture standard (AGENTS.md: \"Each project\n * must maintain an explicit error registry\"), this file is the explicit registry\n * for the memory feature. It is deliberately scoped to memory — not a repo-wide\n * registry refactor — because `packages/core` has no pre-existing\n * code/category/retryable registry convention to plug into (the runtime's\n * `lib/error-messages.ts` is a message-templating table, not a typed\n * code/category/retryable registry). It mirrors the existing\n * `AgentThreadLockedError extends Error` precedent in\n * `intelligence-agent.ts`: a real `Error` subclass so `instanceof Error` holds\n * and the public `MemoryState.error: Error | null` contract is preserved.\n *\n * `docsPath` is recorded per entry per the standard; there is no\n * `docs/errors/<project>.md` in this repo, so this docblock plus the registry\n * are the source of truth.\n *\n * Each registry entry carries:\n * - `code`: stable identifier (e.g. `MEMORY_LIST_FAILED`).\n * - `category`: one of the standard categories\n * (`validation`|`auth`|`permission`|`not_found`|`conflict`|`rate_limit`|`internal`|`dependency`).\n * - `retryable`: whether a retry could plausibly succeed (timeouts + transient\n * dependency failures are retryable; client-caused 4xx are not).\n * - `message`: the default human-readable message (callers may override with a\n * status-bearing string to preserve the prior wording).\n * - `docsPath`: documentation pointer for the code.\n */\n\n/** Standard error categories from the repo error-handling architecture. */\nexport type MemoryErrorCategory =\n | \"validation\"\n | \"auth\"\n | \"permission\"\n | \"not_found\"\n | \"conflict\"\n | \"rate_limit\"\n | \"internal\"\n | \"dependency\";\n\n/** Stable codes for the memory store's surfaced errors. */\nexport type MemoryErrorCode =\n | \"MEMORY_LIST_FAILED\"\n | \"MEMORY_RECALL_FAILED\"\n | \"MEMORY_CREDENTIALS_FAILED\"\n | \"MEMORY_MUTATION_FAILED\"\n | \"MEMORY_REQUEST_TIMEOUT\";\n\n/** A single registry entry describing one memory error code. */\nexport interface MemoryErrorRegistryEntry {\n readonly code: MemoryErrorCode;\n readonly category: MemoryErrorCategory;\n readonly retryable: boolean;\n readonly message: string;\n readonly docsPath: string;\n}\n\n/**\n * The memory error registry: the single source of truth for memory error\n * metadata. Keyed by `code` so a code maps to exactly one category/retryable\n * default.\n *\n * Categories/retryable rationale:\n * - List/credentials/mutation failures are `dependency` (the runtime/platform\n * the store calls failed). A 5xx is transient (`retryable: true`); a 4xx is\n * caller-caused, so the helpers below downgrade those to non-retryable.\n * - Timeouts are `dependency` and `retryable: true` (the request may simply be\n * slow).\n */\nexport const MEMORY_ERROR_REGISTRY: Readonly<\n Record<MemoryErrorCode, MemoryErrorRegistryEntry>\n> = Object.freeze({\n MEMORY_LIST_FAILED: {\n code: \"MEMORY_LIST_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Failed to fetch memories\",\n docsPath: \"docs/errors/memory.md#memory_list_failed\",\n },\n MEMORY_RECALL_FAILED: {\n code: \"MEMORY_RECALL_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Failed to recall memories\",\n docsPath: \"docs/errors/memory.md#memory_recall_failed\",\n },\n MEMORY_CREDENTIALS_FAILED: {\n code: \"MEMORY_CREDENTIALS_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Failed to fetch memory subscribe credentials\",\n docsPath: \"docs/errors/memory.md#memory_credentials_failed\",\n },\n MEMORY_MUTATION_FAILED: {\n code: \"MEMORY_MUTATION_FAILED\",\n category: \"dependency\",\n retryable: true,\n message: \"Memory mutation request failed\",\n docsPath: \"docs/errors/memory.md#memory_mutation_failed\",\n },\n MEMORY_REQUEST_TIMEOUT: {\n code: \"MEMORY_REQUEST_TIMEOUT\",\n category: \"dependency\",\n retryable: true,\n message: \"Request timed out\",\n docsPath: \"docs/errors/memory.md#memory_request_timeout\",\n },\n});\n\n/**\n * An `Error` carrying a stable memory error `code`, `category`, and `retryable`\n * flag so consumers and observability can branch on it without string-matching\n * the message.\n *\n * It is a real `Error` subclass: `instanceof Error` is true, so the public\n * `MemoryState.error: Error | null` contract (and the `error: Error | null`\n * surfaced by `useMemories` / `injectMemories`) holds unchanged. Existing\n * consumers that only read `.message` keep working; the richer fields are\n * additive.\n */\nexport class MemoryError extends Error {\n /** Stable, machine-readable error identifier. */\n readonly code: MemoryErrorCode;\n /** Coarse error category for grouping/observability. */\n readonly category: MemoryErrorCategory;\n /** Whether retrying the operation could plausibly succeed. */\n readonly retryable: boolean;\n\n /**\n * @param code - Registry code identifying this error.\n * @param options - Optional overrides:\n * - `message`: human-readable message (defaults to the registry message;\n * callers pass a status-bearing string to preserve prior wording).\n * - `retryable`: overrides the registry default (e.g. a 4xx list failure is\n * not retryable even though the code's default is).\n * - `cause`: the underlying error, preserved for debugging.\n */\n constructor(\n code: MemoryErrorCode,\n options?: { message?: string; retryable?: boolean; cause?: unknown },\n ) {\n const entry = MEMORY_ERROR_REGISTRY[code];\n super(options?.message ?? entry.message, { cause: options?.cause });\n this.name = \"MemoryError\";\n this.code = code;\n this.category = entry.category;\n this.retryable = options?.retryable ?? entry.retryable;\n // Restore the prototype chain for environments that downlevel `extends`\n // (matches the pattern the SDK relies on for cross-target `instanceof`).\n Object.setPrototypeOf(this, MemoryError.prototype);\n }\n}\n\n/**\n * Narrows an HTTP status to whether the failure is worth retrying: a 5xx (or a\n * missing/0 status) is a transient dependency failure and retryable; a 4xx is\n * caller-caused and not. Used so a `MEMORY_LIST_FAILED`/`MEMORY_MUTATION_FAILED`\n * carries an accurate `retryable` flag derived from the response status.\n */\nexport function isRetryableStatus(status: number): boolean {\n return !(Number.isInteger(status) && status >= 400 && status <= 499);\n}\n","import { phoenixExponentialBackoff } from \"@copilotkit/shared\";\nimport {\n EMPTY,\n asapScheduler,\n defer,\n firstValueFrom,\n from,\n merge,\n Observable,\n observeOn,\n of,\n} from \"rxjs\";\nimport {\n catchError,\n concatWith,\n filter,\n finalize,\n map,\n mergeMap,\n share,\n shareReplay,\n switchMap,\n take,\n takeUntil,\n timeout,\n withLatestFrom,\n} from \"rxjs/operators\";\nimport {\n createActionGroup,\n createEffect,\n createReducer,\n createSelector,\n createStore,\n empty,\n ofType,\n on,\n props,\n} from \"./utils/micro-redux\";\nimport type { Reducer, Store } from \"./utils/micro-redux\";\nimport { MemoryError, isRetryableStatus } from \"./memory-errors\";\nimport {\n ɵphoenixChannel$,\n ɵphoenixSocket$,\n ɵjoinPhoenixChannel$,\n ɵobservePhoenixEvent$,\n ɵobservePhoenixSocketHealth$,\n ɵobservePhoenixSocketSignals$,\n} from \"./utils/phoenix-observable\";\nimport type { ɵPhoenixChannelSession } from \"./utils/phoenix-observable\";\n\n// Runtime-relative path, mirroring the thread store's `/threads` (NOT\n// `/api/threads`): `runtimeUrl` is the CopilotKit runtime mount (e.g.\n// `/api/copilotkit`), and the runtime maps `/memories` to the app-api's\n// `/api/memories` the same way it maps `/threads` -> `/api/threads`.\nconst MEMORIES_PATH = \"/memories\";\nconst MEMORIES_SUBSCRIBE_PATH = \"/memories/subscribe\";\nconst MEMORIES_RECALL_PATH = \"/memories/recall\";\nconst REQUEST_TIMEOUT_MS = 15_000;\n/** Consecutive socket errors tolerated before the realtime stream gives up. */\nconst MAX_SOCKET_RETRIES = 5;\n/**\n * HTTP status codes that indicate memory routes are not configured (non-fatal).\n * 404/501 mean the route is absent/unimplemented; 422 is the runtime's\n * MISSING_INTELLIGENCE signal (intelligence not configured on the deployment —\n * see packages/runtime/.../handlers/intelligence/memories.ts). All three map to\n * the graceful \"not available\" locked-teaser path, not a hard error.\n */\nconst ROUTE_UNAVAILABLE_STATUSES = new Set([404, 422, 501]);\n/**\n * Thrown when a memory route returns a 404/422/501 — treated as \"not\n * configured\" (422 is the runtime's MISSING_INTELLIGENCE signal).\n */\nclass MemoryRouteUnavailableError extends Error {}\n\n/** Public, customer-facing memory kind vocabulary (single taxonomy, no mapping). */\nexport type MemoryKind = \"topical\" | \"episodic\" | \"operational\";\n\n/** Visibility scope of a memory. */\nexport type MemoryScope = \"user\" | \"project\";\n\n/**\n * Health of the realtime (`user_meta:memories:<code>`) connection that streams\n * live `memory_metadata` deltas. Distinct from `available`/`error`, which\n * describe the REST list route: `realtimeStatus` reports ONLY whether the\n * realtime socket/channel is live so the UI can stop showing a \"live\" indicator\n * over a frozen snapshot once the socket permanently gives up.\n *\n * - `\"connecting\"` — fetching join credentials / opening the socket / joining\n * the channel (the default, and the state every `contextChanged`/`stopped`\n * resets to).\n * - `\"connected\"` — the channel join succeeded; live deltas are flowing.\n * - `\"unavailable\"` — the socket exhausted its retries or the join failed\n * permanently; the snapshot is frozen and no deltas will arrive. This is a\n * silent degrade for `available`/`error` (those stay untouched) — only this\n * signal flips.\n */\nexport type MemoryRealtimeStatus = \"connecting\" | \"connected\" | \"unavailable\";\n\n/**\n * A memory as projected across the public REST/realtime boundary — the minimal\n * shape the SDK surfaces. Mirrors the server's `PublicMemory` projection.\n */\nexport interface Memory {\n id: string;\n kind: MemoryKind;\n scope: MemoryScope;\n content: string;\n sourceThreadIds: readonly string[];\n invalidatedAt: string | null;\n /** Relevance score from a `recall()` (hybrid RAG) query; `undefined` for list/realtime/mutation memories. */\n score?: number;\n}\n\n/** Input for creating a memory; `scope` defaults to `\"user\"` (v1 is user-scoped). */\nexport interface NewMemory {\n content: string;\n kind: MemoryKind;\n scope?: MemoryScope;\n sourceThreadIds?: readonly string[];\n}\n\n/**\n * New values for superseding (updating) a memory — same shape as create.\n *\n * Supersede is a FULL replacement, not a partial patch: this is the complete\n * definition of the new memory that replaces the old one. `content` and `kind`\n * are required and must be re-supplied, and an omitted `sourceThreadIds` resets\n * the new memory's source threads to `[]` — it does NOT preserve the prior\n * memory's value.\n */\nexport type MemoryChanges = NewMemory;\n\n/** Outcome of a mutation, tracked so the caller's promise resolves/rejects. */\ntype MemoryMutationOutcome =\n | { requestId: string; sessionId: number; ok: true; memory: Memory | null }\n | { requestId: string; sessionId: number; ok: false; error: Error };\n\n/**\n * Runtime wiring for the memory store: where to reach the REST surface and the\n * headers (auth + `X-Cpki-User-Id`) to send. Scoped to the current user; v1\n * surfaces user-scoped memories only.\n */\ninterface MemoryRuntimeContext {\n runtimeUrl: string;\n /** WebSocket URL for the realtime gateway (e.g. `wss://gw.example.com/client`). */\n wsUrl: string;\n /**\n * Optional: `environment.fetch` is expected to be `ɵruntimeFetch`, which\n * already resolves and overlays the current core headers at send time\n * (#1937). Set explicitly only when the store's `fetch` does NOT already\n * carry headers.\n */\n headers?: Record<string, string>;\n includeInvalidated?: boolean;\n}\n\n/**\n * In-memory state for the memory store. Session-guarded like the thread store:\n * `sessionId` is bumped whenever the runtime context changes so that responses\n * and realtime deltas from a previous context are ignored.\n */\ninterface MemoryState {\n memories: Memory[];\n isLoading: boolean;\n inFlightMutationCount: number;\n error: Error | null;\n context: MemoryRuntimeContext | null;\n sessionId: number;\n available: boolean;\n realtimeStatus: MemoryRealtimeStatus;\n}\n\n// Deep-frozen so `getServerState()` (which returns this exact reference) cannot\n// be mutated by any caller; a single in-place write would otherwise corrupt\n// every SSR snapshot process-wide. The freeze covers the nested `memories`\n// array too — a shallow `Object.freeze` would leave `getServerState().memories`\n// mutable (`.push(...)` would silently succeed), so the empty array is frozen\n// before being sealed into the state. The reducers always build NEW state\n// objects/arrays (they spread, never mutate in place), so they are unaffected\n// and runtime behavior is unchanged.\nconst initialMemoryState: MemoryState = Object.freeze({\n memories: Object.freeze([]) as unknown as Memory[],\n isLoading: false,\n inFlightMutationCount: 0,\n error: null,\n context: null,\n sessionId: 0,\n available: true,\n realtimeStatus: \"connecting\",\n});\n\nconst memoryAdapterEvents = createActionGroup(\"Memory Adapter\", {\n started: empty(),\n stopped: empty(),\n contextChanged: props<{ context: MemoryRuntimeContext | null }>(),\n addRequested: props<{ requestId: string; input: NewMemory }>(),\n updateRequested: props<{\n requestId: string;\n id: string;\n changes: MemoryChanges;\n }>(),\n removeRequested: props<{ requestId: string; id: string }>(),\n});\n\nconst memoryRestEvents = createActionGroup(\"Memory REST\", {\n listRequested: props<{ sessionId: number }>(),\n listSucceeded: props<{ sessionId: number; memories: Memory[] }>(),\n listFailed: props<{ sessionId: number; error: Error }>(),\n listUnavailable: props<{ sessionId: number }>(),\n mutationFinished: props<{ outcome: MemoryMutationOutcome }>(),\n credentialsRequested: props<{ sessionId: number }>(),\n credentialsSucceeded: props<{\n sessionId: number;\n joinToken?: string;\n joinCode?: string;\n // Optional project-scoped realtime credentials. Present only when the\n // caller's API key resolves a project scope (B1b `/memories/subscribe`\n // returns them alongside the user credentials); omitted otherwise. When\n // present, the socket effect opens a SECOND `project_meta:memories:<code>`\n // channel so project rows stay live. Absent -> user-only (silent degrade).\n projectJoinToken?: string;\n projectJoinCode?: string;\n }>(),\n // Credentials outcomes are a SILENT degrade: they feed only the realtime\n // socket effect and deliberately do NOT touch the reducer's `available`/\n // `error`, which describe the REST list route. See the reducer note near the\n // list handlers.\n credentialsFailed: props<{ sessionId: number; error: Error }>(),\n credentialsUnavailable: props<{ sessionId: number }>(),\n});\n\nconst memoryDomainEvents = createActionGroup(\"Memory Domain\", {\n memoryUpserted: props<{ sessionId: number; memory: Memory }>(),\n memoryInvalidated: props<{ sessionId: number; memoryId: string }>(),\n // Realtime-connection health transitions, session-stamped like every other\n // realtime delta so the reducer's session guard drops transitions left over\n // from a superseded context. These flip ONLY `realtimeStatus`; they never\n // touch `available`/`error` (the realtime path is a silent degrade for those).\n realtimeConnecting: props<{ sessionId: number }>(),\n realtimeConnected: props<{ sessionId: number }>(),\n realtimeUnavailable: props<{ sessionId: number }>(),\n});\n\n/** Wire shape of a memory inside a `memory_metadata` payload (carries tenant ids). */\ninterface MemoryMetadataPayloadMemory extends Memory {\n organizationId: string;\n projectId: string;\n}\n\n/**\n * The realtime `memory_metadata` event broadcast on a memory channel:\n * `created`/`updated` carry the full memory, `invalidated` carries only its id.\n * The same wire shape is delivered on both the user channel\n * (`user_meta:memories:<code>`, current user's memories) and the optional\n * project channel (`project_meta:memories:<code>`, memories shared across the\n * project); the store reduces both into one id-keyed list.\n */\ntype MemoryMetadataEvent =\n | {\n operation: \"created\" | \"updated\";\n memoryId: string;\n organizationId: string;\n projectId: string;\n occurredAt: string;\n memory: MemoryMetadataPayloadMemory;\n }\n | {\n operation: \"invalidated\";\n memoryId: string;\n organizationId: string;\n projectId: string;\n occurredAt: string;\n invalidated: { id: string };\n };\n\n/** Projects a wire memory to the public {@link Memory} shape (drops tenant ids). */\nfunction toMemory(memory: MemoryMetadataPayloadMemory): Memory {\n return {\n id: memory.id,\n kind: memory.kind,\n scope: memory.scope,\n content: memory.content,\n sourceThreadIds: memory.sourceThreadIds,\n invalidatedAt: memory.invalidatedAt,\n };\n}\n\n/**\n * Maps a realtime `memory_metadata` event to the domain action that applies it:\n * `created`/`updated` upsert the projected memory, `invalidated` removes it by\n * id. Carries the current `sessionId` so the reducer's session guard can drop\n * deltas left over from a previous context.\n */\nfunction mapMemoryMetadataEvent(\n event: MemoryMetadataEvent,\n sessionId: number,\n):\n | ReturnType<typeof memoryDomainEvents.memoryUpserted>\n | ReturnType<typeof memoryDomainEvents.memoryInvalidated> {\n if (event.operation === \"invalidated\") {\n return memoryDomainEvents.memoryInvalidated({\n sessionId,\n memoryId: event.invalidated.id,\n });\n }\n\n return memoryDomainEvents.memoryUpserted({\n sessionId,\n memory: toMemory(event.memory),\n });\n}\n\n/**\n * Inserts or replaces a memory by id. A new memory is prepended (newest first,\n * matching the REST list's `created_at DESC` ordering without needing a date\n * field on the public projection); an existing memory is replaced in place.\n */\nfunction upsertMemory(memories: Memory[], memory: Memory): Memory[] {\n const existingIndex = memories.findIndex((item) => item.id === memory.id);\n if (existingIndex === -1) {\n return [memory, ...memories];\n }\n\n const next = [...memories];\n next[existingIndex] = memory;\n return next;\n}\n\nconst memoryReducer = createReducer(\n initialMemoryState,\n on(memoryAdapterEvents.contextChanged, (state: MemoryState, { context }) => ({\n ...state,\n context,\n sessionId: state.sessionId + 1,\n memories: [],\n isLoading: Boolean(context),\n inFlightMutationCount: 0,\n error: null,\n available: true,\n // A new context re-opens the realtime socket from scratch, so the connection\n // is \"connecting\" again until the new channel joins.\n realtimeStatus: \"connecting\" as MemoryRealtimeStatus,\n })),\n on(memoryAdapterEvents.stopped, (state: MemoryState) => ({\n ...state,\n memories: [],\n isLoading: false,\n inFlightMutationCount: 0,\n error: null,\n // Reset to the default (`true`), matching `contextChanged`. Otherwise a\n // `stop()` then `start()` WITHOUT a new `setContext` would retain a stale\n // `available: false` from a prior unconfigured session.\n available: true,\n // Reset to the default (\"connecting\"), matching `contextChanged`. A later\n // `start()` re-opens the socket; a stale \"unavailable\"/\"connected\" from the\n // prior session must not leak into the next.\n realtimeStatus: \"connecting\" as MemoryRealtimeStatus,\n })),\n on(memoryRestEvents.listRequested, (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId || !state.context) {\n return state;\n }\n\n return {\n ...state,\n isLoading: true,\n error: null,\n available: true,\n };\n }),\n on(\n memoryRestEvents.listFailed,\n (state: MemoryState, { sessionId, error }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n isLoading: false,\n error,\n };\n },\n ),\n on(memoryRestEvents.listUnavailable, (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories: [],\n isLoading: false,\n error: null,\n available: false,\n };\n }),\n on(\n memoryAdapterEvents.addRequested,\n memoryAdapterEvents.updateRequested,\n memoryAdapterEvents.removeRequested,\n (state: MemoryState) => ({\n ...state,\n inFlightMutationCount: state.inFlightMutationCount + 1,\n }),\n ),\n on(memoryRestEvents.mutationFinished, (state: MemoryState, { outcome }) => {\n // Drop results from a superseded session. `contextChanged`/`stopped` already\n // reset `inFlightMutationCount`, so a mutation that resolves after the\n // context switched must not write a stale error into the new session.\n // Mirrors every other session-scoped handler (and threads.ts).\n if (outcome.sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n inFlightMutationCount: Math.max(0, state.inFlightMutationCount - 1),\n // On success clear any previously surfaced mutation error so a later\n // successful mutation does not leave a phantom sticky error banner.\n error: outcome.ok ? null : outcome.error,\n };\n }),\n on(\n memoryRestEvents.listSucceeded,\n (state: MemoryState, { sessionId, memories }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories,\n isLoading: false,\n error: null,\n // A successful list proves the memory route is available.\n available: true,\n };\n },\n ),\n // NOTE: `credentialsFailed` and `credentialsUnavailable` intentionally have NO\n // reducer cases. `available`/`error` describe the REST list route only and are\n // driven exclusively by the list events above. The credentials/realtime path\n // is a silent degrade by design: a missing/unconfigured `/memories/subscribe`\n // route (404/501/422) or a credentials error must not flip `available` or\n // surface an `error`, because the list route can still be perfectly healthy.\n // Otherwise `available` would be order-dependent on whichever of the two\n // concurrent `contextChanged` bootstraps responds last. Realtime failures are\n // handled where they occur (the socket effect retries and gives up via\n // console.warn); they do not belong in the REST availability state.\n on(\n memoryDomainEvents.memoryUpserted,\n (state: MemoryState, { sessionId, memory }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories: upsertMemory(state.memories, memory),\n };\n },\n ),\n on(\n memoryDomainEvents.memoryInvalidated,\n (state: MemoryState, { sessionId, memoryId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n memories: state.memories.filter((memory) => memory.id !== memoryId),\n };\n },\n ),\n // Realtime-connection health. Session-guarded so a transition from a\n // superseded context is ignored. These flip ONLY `realtimeStatus`; `available`\n // and `error` describe the REST list route and are intentionally untouched.\n on(\n memoryDomainEvents.realtimeConnecting,\n (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n realtimeStatus: \"connecting\" as MemoryRealtimeStatus,\n };\n },\n ),\n on(\n memoryDomainEvents.realtimeConnected,\n (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n realtimeStatus: \"connected\" as MemoryRealtimeStatus,\n };\n },\n ),\n on(\n memoryDomainEvents.realtimeUnavailable,\n (state: MemoryState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n realtimeStatus: \"unavailable\" as MemoryRealtimeStatus,\n };\n },\n ),\n) as Reducer<MemoryState>;\n\nconst selectMemories = createSelector((state: MemoryState) => state.memories);\nconst selectMemoriesIsLoading = createSelector(\n (state: MemoryState) => state.isLoading,\n);\nconst selectMemoriesError = createSelector((state: MemoryState) => state.error);\n/**\n * Reports whether at least one mutation is in flight. Derived from\n * `inFlightMutationCount` so concurrent mutations stay correct: the boolean\n * only clears once every in-flight mutation has settled.\n */\nconst selectMemoriesIsMutating = createSelector(\n (state: MemoryState) => state.inFlightMutationCount > 0,\n);\n/**\n * Reports whether the memory routes are available. Becomes `false` after a\n * 404, 422 (the runtime's MISSING_INTELLIGENCE signal), or 501 response during\n * an auto-activation read; defaults to `true`.\n */\nconst selectMemoriesAvailable = createSelector(\n (state: MemoryState) => state.available,\n);\n/**\n * Reports the realtime-connection health (see {@link MemoryRealtimeStatus}).\n * Distinct from `available`/`error`: it reflects ONLY the live socket/channel,\n * so the UI can suppress a \"live\" indicator once realtime permanently dies even\n * while the REST list route stays healthy. Defaults to `\"connecting\"`.\n */\nconst selectMemoriesRealtimeStatus = createSelector(\n (state: MemoryState) => state.realtimeStatus,\n);\n\n/**\n * Dependencies injected into the memory store. The store opens its own\n * `user_meta:memories:<joinCode>` socket/channel and does not share the\n * thread store's socket, so only a `fetch` implementation is required.\n */\ninterface MemoryEnvironment {\n fetch: typeof fetch;\n}\n\ninterface MemoryStore {\n start(): void;\n stop(): void;\n setContext(context: MemoryRuntimeContext | null): void;\n /**\n * Re-fetches the REST snapshot without clearing the current list. Resolves\n * once the re-pull settles (success or failure) for the current context, so\n * callers (e.g. a `useMemories` `refresh()`) can await it. Resolves\n * immediately when no context is set.\n */\n refresh(): Promise<void>;\n /**\n * Semantically recalls memories via `POST {runtimeUrl}/memories/recall`\n * (hybrid RAG). Returns memories ordered by relevance, each carrying a\n * `score`. Does NOT mutate the snapshot — a one-shot query. Rejects when no\n * context is set or the request fails.\n */\n recall(\n query: string,\n opts?: { limit?: number; scope?: MemoryScope },\n ): Promise<Memory[]>;\n /** Creates a memory; resolves to the stored memory (server-authoritative). */\n addMemory(input: NewMemory): Promise<Memory>;\n /** Supersedes a memory; resolves to the new memory (its id changes). */\n updateMemory(id: string, changes: MemoryChanges): Promise<Memory>;\n /** Retires a memory (non-lossy delete). */\n removeMemory(id: string): Promise<void>;\n getState(): MemoryState;\n /**\n * Stable, render-safe state for SSR/prerender. React's\n * `useSyncExternalStore` requires a `getServerSnapshot` during SSR/prerender\n * (e.g. Next.js); without one React throws \"Missing getServerSnapshot\". The\n * returned reference is stable across calls so React does not loop. There is\n * no client-side memory data during prerender, so this is the empty initial\n * state (no memories, not loading, no error).\n */\n getServerState(): MemoryState;\n select: Store<MemoryState>[\"select\"];\n}\n\nconst MEMORY_METADATA_EVENT = \"memory_metadata\";\n\n/** Runs a memory request through the injected fetch and aborts on unsubscribe. */\nfunction memoryFromFetch<T>(\n input: string,\n init: RequestInit & {\n selector: (response: Response) => Promise<T>;\n fetch: typeof fetch;\n },\n): Observable<T> {\n const {\n selector,\n fetch: fetchImplementation,\n signal: outerSignal,\n ...requestInit\n } = init;\n\n return new Observable<T>((subscriber) => {\n const controller = new AbortController();\n const abort = () => controller.abort();\n if (outerSignal?.aborted) {\n controller.abort();\n } else {\n outerSignal?.addEventListener(\"abort\", abort);\n }\n\n const subscription = from(\n fetchImplementation(input, {\n ...requestInit,\n signal: controller.signal,\n }),\n )\n .pipe(mergeMap((response) => from(selector(response))))\n .subscribe(subscriber);\n\n return () => {\n outerSignal?.removeEventListener(\"abort\", abort);\n controller.abort();\n subscription.unsubscribe();\n };\n });\n}\n\n/**\n * Fetches the memory snapshot and maps it to a success/failure action. Both\n * user- and project-scoped rows are kept: the store now opens a second\n * `project_meta:memories:<code>` realtime channel (when project credentials are\n * available) that keeps project rows in sync, so surfacing them in the snapshot\n * no longer risks a stale list. Rows are keyed by id across both channels, so\n * realtime deltas reconcile either scope idempotently.\n */\nfunction createMemoryFetchObservable(\n environment: MemoryEnvironment,\n context: MemoryRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof memoryRestEvents.listSucceeded>\n | ReturnType<typeof memoryRestEvents.listFailed>\n | ReturnType<typeof memoryRestEvents.listUnavailable>\n> {\n return defer(() => {\n const qs = context.includeInvalidated ? \"?includeInvalidated=true\" : \"\";\n return memoryFromFetch(`${context.runtimeUrl}${MEMORIES_PATH}${qs}`, {\n selector: (response) => {\n if (!response.ok) {\n if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) {\n throw new MemoryRouteUnavailableError(String(response.status));\n }\n throw new MemoryError(\"MEMORY_LIST_FAILED\", {\n message: `Failed to fetch memories: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n\n return response.json() as Promise<{ memories: Memory[] }>;\n },\n fetch: environment.fetch,\n method: \"GET\",\n headers: { ...context.headers },\n }).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n map((data) =>\n memoryRestEvents.listSucceeded({\n sessionId,\n memories: data.memories,\n }),\n ),\n catchError((error) => {\n if (error instanceof MemoryRouteUnavailableError) {\n return of(memoryRestEvents.listUnavailable({ sessionId }));\n }\n return of(\n memoryRestEvents.listFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n );\n });\n}\n\n/**\n * Fetches join credentials from the `/memories/subscribe` endpoint and maps\n * the response to a success/failure action. Requires both `joinToken` and\n * `joinCode` to be non-empty strings; throws otherwise so the `catchError`\n * path emits `credentialsFailed`.\n */\nfunction createMemoryCredentialsFetchObservable(\n environment: MemoryEnvironment,\n context: MemoryRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof memoryRestEvents.credentialsSucceeded>\n | ReturnType<typeof memoryRestEvents.credentialsFailed>\n | ReturnType<typeof memoryRestEvents.credentialsUnavailable>\n> {\n return defer(() =>\n memoryFromFetch(`${context.runtimeUrl}${MEMORIES_SUBSCRIBE_PATH}`, {\n selector: async (response) => {\n if (!response.ok) {\n if (ROUTE_UNAVAILABLE_STATUSES.has(response.status)) {\n throw new MemoryRouteUnavailableError(String(response.status));\n }\n throw new MemoryError(\"MEMORY_CREDENTIALS_FAILED\", {\n message: `Failed to fetch memory subscribe credentials: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n\n return response.json() as Promise<{\n joinToken?: string;\n joinCode?: string;\n projectJoinToken?: string;\n projectJoinCode?: string;\n }>;\n },\n fetch: environment.fetch,\n method: \"POST\",\n headers: { ...context.headers, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({}),\n }).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n map((data) => {\n const hasUserCreds =\n typeof data.joinToken === \"string\" &&\n data.joinToken.length > 0 &&\n typeof data.joinCode === \"string\" &&\n data.joinCode.length > 0;\n\n // Project credentials are optional and only forwarded when BOTH are\n // non-empty strings (the silent-degrade contract): a partial/malformed\n // pair is treated as \"no project scope\", so the store falls back to the\n // user channel only rather than erroring. A missing project scope must\n // never fail credentials — the user channel is the baseline.\n const hasProjectCreds =\n typeof data.projectJoinToken === \"string\" &&\n data.projectJoinToken.length > 0 &&\n typeof data.projectJoinCode === \"string\" &&\n data.projectJoinCode.length > 0;\n if (!hasUserCreds && !hasProjectCreds) {\n throw new Error(\"missing memory realtime credentials\");\n }\n\n return memoryRestEvents.credentialsSucceeded({\n sessionId,\n ...(hasUserCreds\n ? { joinToken: data.joinToken, joinCode: data.joinCode }\n : {}),\n ...(hasProjectCreds\n ? {\n projectJoinToken: data.projectJoinToken,\n projectJoinCode: data.projectJoinCode,\n }\n : {}),\n });\n }),\n catchError((error) => {\n if (error instanceof MemoryRouteUnavailableError) {\n return of(memoryRestEvents.credentialsUnavailable({ sessionId }));\n }\n return of(\n memoryRestEvents.credentialsFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n ),\n );\n}\n\ntype MemoryMutationAction =\n | ReturnType<typeof memoryDomainEvents.memoryUpserted>\n | ReturnType<typeof memoryDomainEvents.memoryInvalidated>\n | ReturnType<typeof memoryRestEvents.mutationFinished>;\n\ntype MemoryMutationRequest =\n | {\n requestId: string;\n sessionId: number;\n kind: \"add\";\n body: Record<string, unknown>;\n }\n | {\n requestId: string;\n sessionId: number;\n kind: \"update\";\n id: string;\n body: Record<string, unknown>;\n }\n | { requestId: string; sessionId: number; kind: \"remove\"; id: string };\n\n/** Projects a REST mutation response to the public {@link Memory} shape. */\nfunction responseToMemory(data: {\n id: string;\n kind: MemoryKind;\n scope: MemoryScope;\n content: string;\n sourceThreadIds: readonly string[];\n invalidatedAt: string | null;\n}): Memory {\n return {\n id: data.id,\n kind: data.kind,\n scope: data.scope,\n content: data.content,\n sourceThreadIds: data.sourceThreadIds,\n invalidatedAt: data.invalidatedAt,\n };\n}\n\n/**\n * Projects a recall REST response memory (which carries a relevance `score`)\n * to the public {@link Memory} shape. `score` is copied through when supplied.\n */\nfunction recallResponseToMemory(data: {\n id: string;\n kind: MemoryKind;\n scope: MemoryScope;\n content: string;\n sourceThreadIds: readonly string[];\n invalidatedAt: string | null;\n score?: number;\n}): Memory {\n return {\n id: data.id,\n kind: data.kind,\n scope: data.scope,\n content: data.content,\n sourceThreadIds: data.sourceThreadIds,\n invalidatedAt: data.invalidatedAt,\n ...(typeof data.score === \"number\" ? { score: data.score } : {}),\n };\n}\n\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Validates the required fields of a create/supersede REST response before it is\n * projected to a {@link Memory}. Returns an `Error` describing the first\n * missing/invalid field, or `null` when the body is well-formed. Without this a\n * malformed 200 body yields a Memory with undefined fields that gets upserted.\n */\nfunction validateMutationResponse(\n data: Record<string, unknown> | null,\n): Error | null {\n if (!data || typeof data !== \"object\") {\n return new Error(\"memory mutation response missing/invalid body\");\n }\n if (typeof data.id !== \"string\" || data.id.length === 0) {\n return new Error(\"memory mutation response missing/invalid id\");\n }\n if (typeof data.kind !== \"string\" || !MEMORY_KINDS.has(data.kind)) {\n return new Error(\"memory mutation response missing/invalid kind\");\n }\n if (typeof data.scope !== \"string\" || !MEMORY_SCOPES.has(data.scope)) {\n return new Error(\"memory mutation response missing/invalid scope\");\n }\n if (typeof data.content !== \"string\") {\n return new Error(\"memory mutation response missing/invalid content\");\n }\n // `sourceThreadIds` is `readonly string[]` on the public Memory; a malformed\n // 200 that omits it (or sends a non-array) would otherwise yield a Memory\n // whose `sourceThreadIds` is `undefined`, violating the type for every\n // consumer that maps over it.\n if (\n !Array.isArray(data.sourceThreadIds) ||\n !data.sourceThreadIds.every((id) => typeof id === \"string\")\n ) {\n return new Error(\n \"memory mutation response missing/invalid sourceThreadIds\",\n );\n }\n // `invalidatedAt` is `string | null`; reject any other type so it is not\n // copied through as `undefined`.\n if (data.invalidatedAt !== null && typeof data.invalidatedAt !== \"string\") {\n return new Error(\"memory mutation response missing/invalid invalidatedAt\");\n }\n return null;\n}\n\n/**\n * Request body for create/supersede. `scope` is forwarded only when the caller\n * supplies it: the platform owns the default (`scope` defaults to `\"user\"` in\n * the `/api/memories` schema), so the store does not second-guess it here —\n * one default, at the contract owner. `sourceThreadIds` defaults to `[]`.\n */\nfunction toMutationBody(input: NewMemory): Record<string, unknown> {\n return {\n content: input.content,\n kind: input.kind,\n ...(input.scope !== undefined ? { scope: input.scope } : {}),\n sourceThreadIds: input.sourceThreadIds ?? [],\n };\n}\n\n/**\n * Builds the actions a successful mutation dispatches (server-authoritative):\n * the REST response is applied to local state immediately, and the realtime\n * event reconciles idempotently (upsert-by-id). `mutationFinished` resolves the\n * caller's promise.\n */\nfunction buildMutationSuccessActions(\n request: MemoryMutationRequest,\n data: Record<string, unknown> | null,\n): MemoryMutationAction[] {\n const { requestId, sessionId } = request;\n\n if (request.kind === \"remove\") {\n // The platform's DELETE returns a bare 204 with NO body (the runtime\n // handler responds `new Response(null, { status: 204 })` and the client's\n // `removeMemory` is `Promise<void>`), so there is no confirmation field to\n // validate here — removal is status-code-confirmed. We optimistically remove\n // the row locally on any 2xx; the realtime `memory_metadata` `invalidated`\n // event (and the next REST refresh) reconcile idempotently.\n return [\n memoryDomainEvents.memoryInvalidated({ sessionId, memoryId: request.id }),\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: true, memory: null },\n }),\n ];\n }\n\n // Validate the required fields before projecting. A malformed 200 body would\n // otherwise yield a Memory with undefined fields that gets upserted into\n // state. Fail the mutation instead, mirroring the `retiredId` validation\n // below and the credentials path's joinToken/joinCode validation.\n const validationError = validateMutationResponse(data);\n if (validationError) {\n return [\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: false, error: validationError },\n }),\n ];\n }\n\n const memory = responseToMemory(\n data as Parameters<typeof responseToMemory>[0],\n );\n\n if (request.kind === \"update\") {\n // `retiredId` is optional on the server type. Without it the\n // `memoryInvalidated` would be a no-op (no id to remove), leaving the old\n // memory as a duplicate next to the new one. Validate it like the\n // credentials path validates joinToken/joinCode, and fail the mutation\n // rather than apply a half-baked supersede.\n const retiredId = (data as { retiredId?: string }).retiredId;\n if (typeof retiredId !== \"string\" || retiredId.length === 0) {\n return [\n memoryRestEvents.mutationFinished({\n outcome: {\n requestId,\n sessionId,\n ok: false,\n error: new Error(\"supersede response missing retiredId\"),\n },\n }),\n ];\n }\n\n return [\n memoryDomainEvents.memoryInvalidated({ sessionId, memoryId: retiredId }),\n memoryDomainEvents.memoryUpserted({ sessionId, memory }),\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: true, memory },\n }),\n ];\n }\n\n return [\n memoryDomainEvents.memoryUpserted({ sessionId, memory }),\n memoryRestEvents.mutationFinished({\n outcome: { requestId, sessionId, ok: true, memory },\n }),\n ];\n}\n\n/** Performs a create/supersede/retire HTTP call and emits its resulting actions. */\nfunction createMemoryMutationObservable(\n environment: MemoryEnvironment,\n context: MemoryRuntimeContext,\n request: MemoryMutationRequest,\n): Observable<MemoryMutationAction> {\n const method =\n request.kind === \"add\"\n ? \"POST\"\n : request.kind === \"update\"\n ? \"PATCH\"\n : \"DELETE\";\n const path =\n request.kind === \"add\"\n ? MEMORIES_PATH\n : `${MEMORIES_PATH}/${encodeURIComponent(request.id)}`;\n\n return defer(() =>\n memoryFromFetch(`${context.runtimeUrl}${path}`, {\n selector: async (response) => {\n if (!response.ok) {\n throw new MemoryError(\"MEMORY_MUTATION_FAILED\", {\n message: `Request failed: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n\n return request.kind === \"remove\"\n ? null\n : ((await response.json()) as Record<string, unknown>);\n },\n fetch: environment.fetch,\n method,\n headers: { ...context.headers, \"Content-Type\": \"application/json\" },\n body:\n request.kind === \"remove\" ? undefined : JSON.stringify(request.body),\n }).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n mergeMap((data) => of(...buildMutationSuccessActions(request, data))),\n catchError((error) =>\n of(\n memoryRestEvents.mutationFinished({\n outcome: {\n requestId: request.requestId,\n sessionId: request.sessionId,\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n }),\n ),\n ),\n ),\n );\n}\n\n/**\n * Creates the framework-agnostic memory store: a REST snapshot on `setContext`,\n * server-authoritative add/update/remove mutations, and realtime\n * `memory_metadata` deltas off the injected `user_meta` event source — all\n * reduced into observable state.\n */\nfunction createMemoryStore(environment: MemoryEnvironment): MemoryStore {\n // Per-store request-id counter. Kept as a closure variable (not a\n // module-level global) so each store instance has its own monotonic sequence:\n // sharing one global across instances is a latent cross-instance/SSR hazard\n // and makes request ids non-reproducible in tests that reset a single store.\n let memoryRequestId = 0;\n const createMemoryRequestId = (): string => {\n memoryRequestId += 1;\n return `memory-request-${memoryRequestId}`;\n };\n\n const bootstrapEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryAdapterEvents.contextChanged),\n withLatestFrom(state$),\n filter(([, state]) => Boolean(state.context)),\n map(([, state]) =>\n memoryRestEvents.listRequested({ sessionId: state.sessionId }),\n ),\n ),\n );\n\n const credentialsBootstrapEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryAdapterEvents.contextChanged),\n withLatestFrom(state$),\n filter(([, state]) => Boolean(state.context)),\n map(([, state]) =>\n memoryRestEvents.credentialsRequested({ sessionId: state.sessionId }),\n ),\n ),\n );\n\n const credentialsFetchEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryRestEvents.credentialsRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is MemoryRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n memoryAdapterEvents.contextChanged,\n memoryAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createMemoryCredentialsFetchObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const fetchEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryRestEvents.listRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is MemoryRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n memoryAdapterEvents.contextChanged,\n memoryAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createMemoryFetchObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const mutationEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(\n memoryAdapterEvents.addRequested,\n memoryAdapterEvents.updateRequested,\n memoryAdapterEvents.removeRequested,\n ),\n withLatestFrom(state$),\n mergeMap(([action, state]) => {\n const context = state.context;\n const sessionId = state.sessionId;\n if (!context?.runtimeUrl) {\n return of(\n memoryRestEvents.mutationFinished({\n outcome: {\n requestId: action.requestId,\n sessionId,\n ok: false,\n error: new Error(\"Runtime URL is not configured\"),\n },\n }),\n );\n }\n\n if (memoryAdapterEvents.addRequested.match(action)) {\n return createMemoryMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n kind: \"add\",\n body: toMutationBody(action.input),\n });\n }\n if (memoryAdapterEvents.updateRequested.match(action)) {\n return createMemoryMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n kind: \"update\",\n id: action.id,\n body: toMutationBody(action.changes),\n });\n }\n return createMemoryMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n kind: \"remove\",\n id: action.id,\n });\n }),\n ),\n );\n\n const socketEffect = createEffect(\n (actions$, state$: Observable<MemoryState>) =>\n actions$.pipe(\n ofType(memoryRestEvents.credentialsSucceeded),\n withLatestFrom(state$),\n filter(([action, state]) => {\n return (\n action.sessionId === state.sessionId &&\n Boolean(state.context?.wsUrl)\n );\n }),\n switchMap(([action, state]) => {\n const context = state.context as MemoryRuntimeContext;\n const { joinToken, joinCode, projectJoinToken, projectJoinCode } =\n action;\n const primaryJoinToken = joinToken ?? projectJoinToken!;\n const primaryTopic =\n joinToken && joinCode\n ? `user_meta:memories:${joinCode}`\n : `project_meta:memories:${projectJoinCode!}`;\n const sessionId = action.sessionId;\n const shutdown$ = actions$.pipe(\n ofType(\n memoryAdapterEvents.contextChanged,\n memoryAdapterEvents.stopped,\n ),\n );\n\n // Builds the live `memory_metadata` delta stream for one realtime\n // channel (its own socket, keyed by that channel's join token). Both\n // the user channel and the optional project channel feed the SAME\n // reducer through this, and — critically — both stamp their deltas\n // with the SAME `sessionId` (the D4 landmine): the reducer's\n // superseded-context guard therefore drops stale deltas from BOTH\n // channels identically the moment the context changes. The reducer's\n // upsert/invalidate already key by memory id, so interleaving user\n // and project rows is safe (no per-channel bookkeeping needed).\n const channelMetadata$ = (\n channelJoinToken: string,\n topic: string,\n ): Observable<\n | ReturnType<typeof memoryDomainEvents.memoryUpserted>\n | ReturnType<typeof memoryDomainEvents.memoryInvalidated>\n > => {\n const socket$ = ɵphoenixSocket$({\n url: context.wsUrl,\n options: {\n params: { join_token: channelJoinToken },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const channel$ = ɵphoenixChannel$({ socket$, topic }).pipe(\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n const metadata$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<MemoryMetadataEvent>(\n channel,\n MEMORY_METADATA_EVENT,\n ),\n ),\n map((event) => mapMemoryMetadataEvent(event, sessionId)),\n );\n // Drive the join (see the user-channel note below) but swallow its\n // outcome: the project channel deliberately does NOT emit realtime\n // status deltas — `realtimeStatus` is owned by the user channel so\n // a project-channel join failure never regresses the user-facing\n // \"live\" indicator (silent degrade). On failure the metadata stream\n // stays alive for Phoenix's automatic rejoin on reconnect.\n const join$ = ɵjoinPhoenixChannel$(channel$).pipe(\n catchError((error) => {\n console.warn(`[memory] failed to join ${topic}`, error);\n return EMPTY;\n }),\n );\n return merge(metadata$, join$);\n };\n\n return defer(() => {\n const socket$ = ɵphoenixSocket$({\n url: context.wsUrl,\n options: {\n params: { join_token: primaryJoinToken },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const channel$ = ɵphoenixChannel$({\n socket$,\n topic: primaryTopic,\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const socketSignals$ =\n ɵobservePhoenixSocketSignals$(socket$).pipe(share());\n // The socket give-up signal: completes the realtime stream after the\n // health check throws. ALSO surfaces the give-up as a status delta\n // (`realtimeUnavailable`) so the UI can drop its \"live\" indicator —\n // this is the permanent-death signal that was previously only a\n // `console.warn`. `available`/`error` stay untouched by design (the\n // realtime path is a silent degrade for the REST list route).\n const fatalSocketShutdown$ = ɵobservePhoenixSocketHealth$(\n socketSignals$,\n MAX_SOCKET_RETRIES,\n ).pipe(\n catchError(() => {\n console.warn(\n `[memory] WebSocket failed after ${MAX_SOCKET_RETRIES} attempts, giving up`,\n );\n return of(undefined);\n }),\n share(),\n );\n // The give-up mapped to a status delta. Emitted from the merged stream\n // (not the `takeUntil` notifier) so the `realtimeUnavailable` action is\n // dispatched BEFORE teardown: the merged stream is `takeUntil`'d by a\n // microtask-deferred copy of the give-up signal, so this synchronous\n // emission always wins the race and the action reaches the reducer.\n const fatalStatus$ = fatalSocketShutdown$.pipe(\n map(() => memoryDomainEvents.realtimeUnavailable({ sessionId })),\n );\n const metadata$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<MemoryMetadataEvent>(\n channel,\n MEMORY_METADATA_EVENT,\n ),\n ),\n map((event) => mapMemoryMetadataEvent(event, action.sessionId)),\n );\n\n // Drives the actual `channel.join()` AND maps the join outcome to a\n // realtime-status delta. `ɵphoenixChannel$` only creates the channel +\n // a lazy join-outcome stream; the join is sent when that stream is\n // subscribed. Observing channel events (`metadata$`) alone does NOT\n // subscribe it, so without this the socket connects but never joins\n // `user_meta:memories:<code>` and no realtime deltas arrive. The thread\n // store joins for the same reason (its merged `joinOutcome$`).\n //\n // On a successful join -> `realtimeConnected` (the \"live\" signal). On a\n // failed/timed-out join we KEEP the `console.warn` and emit\n // `realtimeUnavailable`, then swallow the error so a transient\n // rejection doesn't tear down the metadata stream (Phoenix re-attempts\n // the join on socket reconnect); the next successful join re-emits\n // `realtimeConnected`.\n const join$ = ɵjoinPhoenixChannel$(channel$).pipe(\n // `ɵjoinPhoenixChannel$` emits `never` (it completes on success), so\n // this concat surfaces the connected status once the join resolves.\n concatWith(\n of(memoryDomainEvents.realtimeConnected({ sessionId })),\n ),\n catchError((error) => {\n console.warn(`[memory] failed to join ${primaryTopic}`, error);\n return of(\n memoryDomainEvents.realtimeUnavailable({ sessionId }),\n );\n }),\n );\n\n // Open the project channel alongside the user channel when project\n // credentials are present. It feeds the SAME reducer with the SAME\n // session stamp (see `channelMetadata$`), so project rows stay live\n // without going stale. Absent project creds -> `EMPTY`: user-only,\n // no second socket, no status regression (silent degrade).\n const projectMetadata$ =\n joinToken && joinCode && projectJoinToken && projectJoinCode\n ? channelMetadata$(\n projectJoinToken,\n `project_meta:memories:${projectJoinCode}`,\n )\n : EMPTY;\n\n return merge(\n // Surface \"connecting\" immediately when the realtime stream starts\n // (credentials succeeded -> socket subscribing/joining). Reset to\n // this on every (re)subscribe so a prior session's terminal status\n // can't bleed through before the new join resolves.\n of(memoryDomainEvents.realtimeConnecting({ sessionId })),\n metadata$,\n join$,\n projectMetadata$,\n fatalStatus$,\n ).pipe(\n takeUntil(\n merge(\n shutdown$,\n // Defer the give-up teardown by a microtask so `fatalStatus$`'s\n // synchronous `realtimeUnavailable` emission is dispatched before\n // the stream is torn down. `observeOn(asapScheduler)` schedules\n // the teardown after the current microtask drains.\n fatalSocketShutdown$.pipe(observeOn(asapScheduler)),\n ),\n ),\n finalize(() => {\n // Socket/channel teardown is handled by the `finalize` operators\n // inside `ɵphoenixSocket$`/`ɵphoenixChannel$`; this hook exists to\n // mirror the thread store's socket-effect lifecycle shape.\n }),\n );\n });\n }),\n ),\n );\n\n const store = createStore<MemoryState>({\n reducer: memoryReducer,\n effects: [\n bootstrapEffect,\n credentialsBootstrapEffect,\n fetchEffect,\n credentialsFetchEffect,\n mutationEffect,\n socketEffect,\n ],\n });\n\n function trackMutation<T>(\n dispatchAction:\n | ReturnType<typeof memoryAdapterEvents.addRequested>\n | ReturnType<typeof memoryAdapterEvents.updateRequested>\n | ReturnType<typeof memoryAdapterEvents.removeRequested>,\n extract: (outcome: Extract<MemoryMutationOutcome, { ok: true }>) => T,\n ): Promise<T> {\n const { requestId } = dispatchAction;\n const completion$ = merge(\n store.actions$.pipe(\n ofType(memoryRestEvents.mutationFinished),\n filter((action) => action.outcome.requestId === requestId),\n map((action) => action.outcome),\n ),\n store.actions$.pipe(\n ofType(memoryAdapterEvents.stopped),\n map(\n () =>\n ({\n requestId,\n sessionId: store.getState().sessionId,\n ok: false,\n error: new Error(\n \"Memory store stopped before mutation completed\",\n ),\n }) satisfies MemoryMutationOutcome,\n ),\n ),\n ).pipe(take(1));\n\n const resultPromise = firstValueFrom(completion$).then((outcome) => {\n if (!outcome.ok) {\n throw outcome.error;\n }\n return extract(outcome);\n });\n\n store.dispatch(dispatchAction);\n return resultPromise;\n }\n\n return {\n start(): void {\n store.init();\n store.dispatch(memoryAdapterEvents.started());\n },\n stop(): void {\n store.dispatch(memoryAdapterEvents.stopped());\n store.stop();\n },\n setContext(context: MemoryRuntimeContext | null): void {\n store.dispatch(memoryAdapterEvents.contextChanged({ context }));\n },\n refresh(): Promise<void> {\n const { sessionId, context } = store.getState();\n if (!context) return Promise.resolve();\n\n // Settle when the re-pulled snapshot completes for this session (success\n // or failure), or if the store is stopped first. Subscribe before\n // dispatching so the resulting list action can't slip past, mirroring\n // trackMutation.\n const completion$ = merge(\n store.actions$.pipe(\n ofType(\n memoryRestEvents.listSucceeded,\n memoryRestEvents.listFailed,\n // `listUnavailable` (404/501/422) is the third terminal outcome of\n // the list fetch. Without it `await refresh()` would hang forever\n // against an unconfigured route.\n memoryRestEvents.listUnavailable,\n ),\n filter((action) => action.sessionId === sessionId),\n ),\n store.actions$.pipe(ofType(memoryAdapterEvents.stopped)),\n // The list `fetchEffect` has `takeUntil(contextChanged, stopped)`, so a\n // `contextChanged` fired after this `listRequested` but before the fetch\n // settles tears down the fetch with NO terminal list action for our\n // session — `await refresh()` would hang forever. Settle on it too.\n store.actions$.pipe(ofType(memoryAdapterEvents.contextChanged)),\n ).pipe(take(1));\n\n // `await refresh()` resolving must mean the snapshot actually refreshed,\n // so reject on anything that isn't a successful re-pull — a failed list\n // (its error also lands in the `error` selector) or the store being\n // stopped mid-flight. This keeps `refresh` fully symmetric with the\n // mutation methods, which reject on both failure and stop via\n // `trackMutation`.\n const done = firstValueFrom(completion$).then((action) => {\n if (memoryRestEvents.listFailed.match(action)) {\n throw action.error;\n }\n if (memoryAdapterEvents.stopped.match(action)) {\n throw new Error(\"Memory store stopped before refresh completed\");\n }\n // A `contextChanged` superseded this refresh: a new context is loading\n // its own snapshot, so this refresh is moot. RESOLVE (do not reject) —\n // resolving is the least-surprising outcome for a superseded refresh.\n if (memoryAdapterEvents.contextChanged.match(action)) {\n return;\n }\n // `listSucceeded` and `listUnavailable` both RESOLVE: an unavailable\n // (not-configured) route is a non-fatal terminal state, consistent with\n // the auto-load path which leaves `available: false` without erroring.\n });\n store.dispatch(memoryRestEvents.listRequested({ sessionId }));\n return done;\n },\n recall(\n query: string,\n opts?: { limit?: number; scope?: MemoryScope },\n ): Promise<Memory[]> {\n const { context } = store.getState();\n if (!context?.runtimeUrl) {\n return Promise.reject(new Error(\"Runtime URL is not configured\"));\n }\n const body: Record<string, unknown> = { query };\n if (opts?.limit !== undefined) body.limit = opts.limit;\n if (opts?.scope !== undefined) body.scope = opts.scope;\n\n const recall$ = memoryFromFetch(\n `${context.runtimeUrl}${MEMORIES_RECALL_PATH}`,\n {\n selector: async (response) => {\n if (!response.ok) {\n throw new MemoryError(\"MEMORY_RECALL_FAILED\", {\n message: `Failed to recall memories: ${response.status}`,\n retryable: isRetryableStatus(response.status),\n });\n }\n return (await response.json()) as { memories: unknown[] };\n },\n fetch: environment.fetch,\n method: \"POST\",\n headers: { ...context.headers, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n },\n ).pipe(\n timeout({\n first: REQUEST_TIMEOUT_MS,\n with: () => {\n throw new MemoryError(\"MEMORY_REQUEST_TIMEOUT\");\n },\n }),\n map((data) =>\n (data.memories ?? []).map((m) =>\n recallResponseToMemory(\n m as Parameters<typeof recallResponseToMemory>[0],\n ),\n ),\n ),\n );\n return firstValueFrom(recall$);\n },\n addMemory(input: NewMemory): Promise<Memory> {\n return trackMutation(\n memoryAdapterEvents.addRequested({\n requestId: createMemoryRequestId(),\n input,\n }),\n (outcome) => {\n if (outcome.memory == null) {\n throw new Error(\"add resolved without a memory\");\n }\n return outcome.memory;\n },\n );\n },\n updateMemory(id: string, changes: MemoryChanges): Promise<Memory> {\n return trackMutation(\n memoryAdapterEvents.updateRequested({\n requestId: createMemoryRequestId(),\n id,\n changes,\n }),\n (outcome) => {\n if (outcome.memory == null) {\n throw new Error(\"update resolved without a memory\");\n }\n return outcome.memory;\n },\n );\n },\n removeMemory(id: string): Promise<void> {\n return trackMutation(\n memoryAdapterEvents.removeRequested({\n requestId: createMemoryRequestId(),\n id,\n }),\n () => undefined,\n );\n },\n getState(): MemoryState {\n return store.getState();\n },\n getServerState(): MemoryState {\n return initialMemoryState;\n },\n select: store.select.bind(store),\n };\n}\n\n// `Memory`, `MemoryKind`, `MemoryScope`, `NewMemory`, and `MemoryChanges` are\n// the consumer-facing memory types surfaced by the framework hooks\n// (`useMemories` / `injectMemories`); they are exported unprefixed from their\n// declarations above. The remaining memory internals keep the `ɵ` prefix.\n// The memory error registry surface is consumer-facing: `MemoryError` is what\n// `MemoryState.error` (and the `error: Error | null` from `useMemories` /\n// `injectMemories`) carries on a failure, and consumers branch on its\n// `code`/`category`/`retryable`. Re-exported unprefixed here so it ships through\n// `index.ts` (`export * from \"./memory\"`) alongside the memory types.\nexport {\n MemoryError,\n MEMORY_ERROR_REGISTRY,\n isRetryableStatus as ɵisRetryableMemoryStatus,\n} from \"./memory-errors\";\nexport type {\n MemoryErrorCode,\n MemoryErrorCategory,\n MemoryErrorRegistryEntry,\n} from \"./memory-errors\";\n\nexport type ɵMemoryState = MemoryState;\nexport type ɵMemoryRuntimeContext = MemoryRuntimeContext;\nexport type ɵMemoryMetadataEvent = MemoryMetadataEvent;\nexport type ɵMemoryEnvironment = MemoryEnvironment;\nexport type ɵMemoryStore = MemoryStore;\nexport const ɵmemoryAdapterEvents = memoryAdapterEvents;\nexport const ɵmemoryRestEvents = memoryRestEvents;\nexport const ɵmemoryDomainEvents = memoryDomainEvents;\nexport const ɵmemoryReducer = memoryReducer;\nexport const ɵmapMemoryMetadataEvent = mapMemoryMetadataEvent;\nexport const ɵselectMemories = selectMemories;\nexport const ɵselectMemoriesIsLoading = selectMemoriesIsLoading;\nexport const ɵselectMemoriesError = selectMemoriesError;\nexport const ɵselectMemoriesIsMutating = selectMemoriesIsMutating;\nexport const ɵselectMemoriesAvailable = selectMemoriesAvailable;\nexport const ɵselectMemoriesRealtimeStatus = selectMemoriesRealtimeStatus;\nexport { createMemoryStore as ɵcreateMemoryStore };\n","import type {\n AbstractAgent,\n Context,\n State,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { Throttler } from \"@tanstack/pacer\";\nimport type {\n FrontendTool,\n SuggestionsConfig,\n Suggestion,\n CopilotRuntimeTransport,\n RuntimeMode,\n RuntimeLicenseStatus,\n IntelligenceRuntimeInfo,\n InspectorMetadataV1,\n ThreadEndpointRuntimeInfo,\n} from \"../types\";\nimport type {\n CopilotKitCoreAddAgentParams,\n CopilotKitCoreRegisterProxiedAgentParams,\n CopilotKitCoreRegisterProxiedAgentResult,\n} from \"./agent-registry\";\nimport type { CopilotKitMessageFilter } from \"./message-filter\";\nimport { AgentRegistry } from \"./agent-registry\";\nimport type { ScopedContext } from \"./context-store\";\nimport { ContextStore } from \"./context-store\";\nimport { isForAgent } from \"./agent-scope\";\nimport { SuggestionEngine } from \"./suggestion-engine\";\nimport type {\n CopilotKitCoreRunAgentParams,\n CopilotKitCoreConnectAgentParams,\n CopilotKitCoreGetToolParams,\n CopilotKitCoreRunToolParams,\n CopilotKitCoreRunToolResult,\n CopilotKitCoreCatalogComponent,\n} from \"./run-handler\";\nimport { RunHandler } from \"./run-handler\";\nimport type {\n DebugConfig,\n RuntimeEntitlementResponse,\n} from \"@copilotkit/shared\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport { StateManager } from \"./state-manager\";\nimport type { CopilotKitCoreContinuationHandoff } from \"./state-manager\";\nimport { ThreadStoreRegistry } from \"./thread-store-registry\";\nimport { LearningBridge } from \"./learning-bridge\";\nimport type { LearningConfig, TrajectoryStartOptions } from \"./learning-bridge\";\nimport type { JsonValue, StartResult } from \"@copilotkit/learning\";\nimport type { ɵThreadStore } from \"../threads\";\nimport { ɵcreateMemoryStore } from \"../memory\";\nimport type { ɵGenerativeUIDebugSource } from \"./generative-ui-debug\";\nimport type { ɵMemoryStore } from \"../memory\";\nimport { HeaderSourceResolver, isHeaderResolutionError } from \"./header-source\";\nimport type { CopilotKitHeadersSource } from \"./header-source\";\n\n/**\n * Run properties that go only to the runs of some agents.\n * See `CopilotKitCore.addScopedProperties`.\n */\nexport interface ScopedProperties {\n /** The properties to merge on top of the base run properties. */\n properties: Record<string, unknown>;\n /** The agents that get these properties. When omitted, every agent gets them. */\n agentIds?: string[];\n}\n\n/** True for an object literal. Arrays, `null`, and class instances are not plain objects. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n/** Configuration options for `CopilotKitCore`. */\nexport interface CopilotKitCoreConfig {\n /** The endpoint of the CopilotRuntime. */\n runtimeUrl?: string;\n /** Transport style for CopilotRuntime endpoints. Defaults to REST. */\n runtimeTransport?: CopilotRuntimeTransport;\n /**\n * When true, the constructor sets the runtime config but does NOT start the\n * `/info` connection. Call {@link CopilotKitCore.connect} to start it —\n * typically from a host's commit-phase effect. This prevents a burst of\n * duplicate `/info` requests when a host constructs (and discards) the core\n * during render, e.g. React concurrent rendering / Suspense / StrictMode.\n * See https://github.com/CopilotKit/CopilotKit/issues/5801.\n */\n deferInitialConnection?: boolean;\n /** Mapping from agent name to its `AbstractAgent` instance. For development only - production requires CopilotRuntime. */\n agents__unsafe_dev_only?: Record<string, AbstractAgent>;\n /**\n * Headers sent with every runtime request: a record, or a sync or async\n * builder that runs when each request is sent. Merged on top of each\n * `HttpAgent`'s own headers (core wins on a key conflict). See `setHeaders`.\n */\n headers?: CopilotKitHeadersSource;\n /** Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies). */\n credentials?: RequestCredentials;\n /**\n * Rewrites the message list sent to runtime agents on every run. Use it when\n * the backend already stores the conversation and re-sending it is waste or\n * duplication. See `setMessageFilter` and {@link CopilotKitMessageFilter}.\n */\n messageFilter?: CopilotKitMessageFilter;\n /** Properties sent as `forwardedProps` to the AG-UI agent. */\n properties?: Record<string, unknown>;\n /** Ordered collection of frontend tools available to the core. */\n tools?: FrontendTool<any>[];\n /** Suggestions config for the core. */\n suggestionsConfig?: SuggestionsConfig[];\n /** Enable debug logging for the client-side event pipeline. */\n debug?: DebugConfig;\n /**\n * Turns on interaction capture (`@copilotkit/learning`). Capture starts only\n * when {@link CopilotKitCore.startTrajectory} authenticates and joins the\n * capture channel. The default path captures outside-chat activity. An explicit\n * legacy sink also receives Thread, message, tool call, and run context.\n * Update future captures with\n * {@link CopilotKitCore.setLearningConfig}.\n */\n learning?: LearningConfig;\n}\n\nexport type { CopilotKitMessageFilter } from \"./message-filter\";\nexport type {\n LearningConfig,\n LegacyLearningConfig,\n TrajectoryStartOptions,\n OpenThreadRegistration,\n} from \"./learning-bridge\";\nexport type { JsonValue, StartResult } from \"@copilotkit/learning\";\n\nexport type {\n CopilotKitCoreAddAgentParams,\n CopilotKitCoreRegisterProxiedAgentParams,\n CopilotKitCoreRegisterProxiedAgentResult,\n};\nexport type {\n CopilotKitCoreRunAgentParams,\n CopilotKitCoreConnectAgentParams,\n CopilotKitCoreGetToolParams,\n CopilotKitCoreRunToolParams,\n CopilotKitCoreRunToolResult,\n CopilotKitCoreCatalogComponent,\n};\n\nexport interface CopilotKitCoreStopAgentParams {\n agent: AbstractAgent;\n}\n\nexport type CopilotKitCoreGetSuggestionsResult = {\n suggestions: Suggestion[];\n isLoading: boolean;\n};\n\nexport enum CopilotKitCoreErrorCode {\n RUNTIME_INFO_FETCH_FAILED = \"runtime_info_fetch_failed\",\n AGENT_CONNECT_FAILED = \"agent_connect_failed\",\n AGENT_RUN_FAILED = \"agent_run_failed\",\n AGENT_RUN_FAILED_EVENT = \"agent_run_failed_event\",\n /**\n * An agent emitted RUN_ERROR. `context.phase` (`RunErrorPhase`) is\n * `\"replay\"` when the error belongs to stored thread history replayed on\n * connect, `\"live\"` when the run is happening now, and `\"unknown\"` when the\n * transport cannot tell. Show a live-failure notice only for `\"live\"`.\n */\n AGENT_RUN_ERROR_EVENT = \"agent_run_error_event\",\n TOOL_ARGUMENT_PARSE_FAILED = \"tool_argument_parse_failed\",\n TOOL_HANDLER_FAILED = \"tool_handler_failed\",\n TOOL_NOT_FOUND = \"tool_not_found\",\n AGENT_NOT_FOUND = \"agent_not_found\",\n /**\n * Emitted when an agent run fails because the thread is already locked\n * by another active run.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider\n * onError={({ code, error, context }) => {\n * if (code === \"agent_thread_locked\") {\n * // Show \"Agent is busy, retry?\" UI\n * }\n * }}\n * />\n * ```\n */\n AGENT_THREAD_LOCKED = \"agent_thread_locked\",\n // Transcription errors\n TRANSCRIPTION_FAILED = \"transcription_failed\",\n TRANSCRIPTION_SERVICE_NOT_CONFIGURED = \"transcription_service_not_configured\",\n TRANSCRIPTION_INVALID_AUDIO = \"transcription_invalid_audio\",\n TRANSCRIPTION_RATE_LIMITED = \"transcription_rate_limited\",\n TRANSCRIPTION_AUTH_FAILED = \"transcription_auth_failed\",\n TRANSCRIPTION_NETWORK_ERROR = \"transcription_network_error\",\n SUBSCRIBER_CALLBACK_FAILED = \"subscriber_callback_failed\",\n /**\n * The `headers` builder threw, rejected, or returned something other than\n * an object. The request was not sent. `error.cause` is the builder's error.\n */\n HEADER_RESOLUTION_FAILED = \"header_resolution_failed\",\n}\n\nexport interface CopilotKitCoreSubscriber {\n onTrajectoryChanged?: (event: {\n copilotkit: CopilotKitCore;\n trajectoryId: string | null;\n }) => void | Promise<void>;\n onRuntimeConnectionStatusChanged?: (event: {\n copilotkit: CopilotKitCore;\n status: CopilotKitCoreRuntimeConnectionStatus;\n }) => void | Promise<void>;\n onToolExecutionStart?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n args: unknown;\n }) => void | Promise<void>;\n onToolExecutionEnd?: (event: {\n copilotkit: CopilotKitCore;\n toolCallId: string;\n agentId: string;\n toolName: string;\n result: string;\n error?: string;\n }) => void | Promise<void>;\n onAgentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agents: Readonly<Record<string, AbstractAgent>>;\n }) => void | Promise<void>;\n /**\n * Fired when an agent run or connect begins. The `agent` may be a per-thread\n * clone that is not present in `core.agents`, so `onAgentsChanged` never fires\n * for it. Subscribers (e.g. the inspector) can use this to subscribe to the\n * running instance's AG-UI events.\n */\n onAgentRunStarted?: (event: {\n copilotkit: CopilotKitCore;\n agent: AbstractAgent;\n }) => void | Promise<void>;\n onContextChanged?: (event: {\n copilotkit: CopilotKitCore;\n context: Readonly<Record<string, Context>>;\n }) => void | Promise<void>;\n /**\n * Fired when the A2UI catalog component list changes (registration) or when\n * a component is enabled/disabled. Consumers (the provider, the inspector)\n * re-derive the filtered catalog from this event.\n */\n onCatalogComponentsChanged?: (event: {\n copilotkit: CopilotKitCore;\n catalogComponents: ReadonlyArray<CopilotKitCoreCatalogComponent>;\n }) => void | Promise<void>;\n onSuggestionsConfigChanged?: (event: {\n copilotkit: CopilotKitCore;\n suggestionsConfig: Readonly<Record<string, SuggestionsConfig>>;\n }) => void | Promise<void>;\n onSuggestionsChanged?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n suggestions: Suggestion[];\n }) => void | Promise<void>;\n onSuggestionsStartedLoading?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n }) => void | Promise<void>;\n onSuggestionsFinishedLoading?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n }) => void | Promise<void>;\n onPropertiesChanged?: (event: {\n copilotkit: CopilotKitCore;\n properties: Readonly<Record<string, unknown>>;\n }) => void | Promise<void>;\n onHeadersChanged?: (event: {\n copilotkit: CopilotKitCore;\n headers: Readonly<Record<string, string>>;\n }) => void | Promise<void>;\n onInspectorMetadataChanged?: (event: {\n copilotkit: CopilotKitCore;\n inspectorMetadata: InspectorMetadataV1 | undefined;\n }) => void | Promise<void>;\n onError?: (event: {\n copilotkit: CopilotKitCore;\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n onThreadStoreRegistered?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n store: ɵThreadStore;\n }) => void | Promise<void>;\n /**\n * Fired when a thread store is removed from the registry, either by an\n * explicit `unregister()` call or by a `register()` call that replaces an\n * existing store for the same `agentId`.\n *\n * The previous store is delivered via `prevStore` so subscribers can tear\n * down state that depends on the concrete instance (e.g. cancel an active\n * subscription) without consulting the registry. By the time async\n * subscribers resume after an `await`, a replacement `register()` may have\n * already installed the new store under the same key, so calling\n * `registry.get(agentId)` inside this callback is unsafe and may return\n * the new store instead of the unregistered one.\n */\n onThreadStoreUnregistered?: (event: {\n copilotkit: CopilotKitCore;\n agentId: string;\n prevStore: ɵThreadStore;\n }) => void | Promise<void>;\n}\n\n// Subscription object returned by subscribe() and subscribeToAgentWithOptions()\nexport interface CopilotKitCoreSubscription {\n unsubscribe: () => void;\n}\n\n/**\n * The callback keys accepted by {@link CopilotKitCore.subscribeToAgentWithOptions}.\n * This tuple is the single source of truth — both the\n * `SubscribeToAgentSubscriber` type and the runtime `ALLOWED_KEYS` set\n * are derived from it, so they cannot desynchronise.\n */\nconst SUBSCRIBE_TO_AGENT_KEYS = [\n \"onMessagesChanged\",\n \"onStateChanged\",\n \"onRunInitialized\",\n \"onRunStartedEvent\",\n \"onRunFinalized\",\n \"onRunFailed\",\n \"onRunErrorEvent\",\n] as const satisfies readonly (keyof AgentSubscriber)[];\n\n/**\n * Runtime allowlist derived from {@link SUBSCRIBE_TO_AGENT_KEYS}. Hoisted\n * to module scope so the Set is allocated once, not per-subscription.\n */\nconst ALLOWED_KEYS: ReadonlySet<(typeof SUBSCRIBE_TO_AGENT_KEYS)[number]> =\n new Set(SUBSCRIBE_TO_AGENT_KEYS);\n\n/**\n * The subset of `AgentSubscriber` callbacks accepted by\n * {@link CopilotKitCore.subscribeToAgentWithOptions}. Only the callbacks\n * listed in {@link SUBSCRIBE_TO_AGENT_KEYS} are supported:\n * `onMessagesChanged`, `onStateChanged`, and the run lifecycle\n * callbacks (`onRunInitialized`, `onRunStartedEvent`, `onRunFinalized`, `onRunFailed`,\n * `onRunErrorEvent`).\n *\n * Two categories of `AgentSubscriber` members are excluded:\n *\n * - **AG-UI event handlers** (`onEvent`, `onToolCallStartEvent`, etc.)\n * return `AgentStateMutation` with `stopPropagation` — semantics that\n * the throttle and error-protection wrappers cannot safely mediate.\n *\n * - **Per-item notification callbacks** (`onNewMessage`, `onNewToolCall`)\n * return `void` and have no mutation concerns, but are excluded to keep\n * the surface area minimal — `onMessagesChanged` already covers the\n * same data at a coarser granularity, and throttling per-item callbacks\n * would have different semantic expectations.\n *\n * `onRunErrorEvent` and `onRunStartedEvent` are AG-UI event handlers whose\n * return types include `stopPropagation`. They are included so framework\n * consumers can reflect running-state changes while a connection stays open:\n * a live error clears busy and a successor run marks it busy again. Consumers\n * use these callbacks for notification and return `void`.\n *\n * Note: the included lifecycle callbacks return\n * `Omit<AgentStateMutation, \"stopPropagation\">` (or full\n * `AgentStateMutation` for the included AG-UI event handlers). On the error\n * path, `safeCall` discards those return values (see its inline\n * documentation).\n *\n * Use `agent.subscribe()` directly when event mutation or per-item\n * notification semantics are needed.\n */\nexport type SubscribeToAgentSubscriber = Pick<\n AgentSubscriber,\n (typeof SUBSCRIBE_TO_AGENT_KEYS)[number]\n>;\n\n/** Options for {@link CopilotKitCore.subscribeToAgentWithOptions}. */\nexport interface SubscribeToAgentOptions {\n /**\n * Throttle interval (ms) for `onMessagesChanged` / `onStateChanged`.\n * Non-negative finite number; `0` explicitly disables throttling.\n * Falls back to `defaultThrottleMs` when `undefined`.\n */\n throttleMs?: number;\n}\n\nexport enum CopilotKitCoreRuntimeConnectionStatus {\n Disconnected = \"disconnected\",\n Connected = \"connected\",\n Connecting = \"connecting\",\n Error = \"error\",\n}\n\n/**\n * Internal interface for delegate classes to access CopilotKitCore methods.\n * This provides type safety while allowing controlled access to private functionality.\n */\nexport interface CopilotKitCoreFriendsAccess {\n // Notification methods\n notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string,\n ): Promise<void>;\n\n emitError(params: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }): Promise<void>;\n\n // Getters for internal state\n readonly headers: Readonly<Record<string, string>>;\n resolveHeaders():\n | Readonly<Record<string, string>>\n | Promise<Readonly<Record<string, string>>>;\n readonly credentials: RequestCredentials | undefined;\n readonly messageFilter: CopilotKitMessageFilter | undefined;\n readonly properties: Readonly<Record<string, unknown>>;\n readonly context: Readonly<Record<string, Context>>;\n readonly debug?: DebugConfig;\n\n // Internal methods\n buildFrontendTools(agentId?: string): import(\"@ag-ui/client\").Tool[];\n getContextForAgent(agentId?: string): Context[];\n getPropertiesForAgent(agentId?: string): Record<string, unknown>;\n getAgent(id: string): AbstractAgent | undefined;\n /**\n * Re-apply the last resolved header snapshot to a single agent, merged on\n * top of the headers the agent was constructed with (see #5635). Never\n * invokes the headers builder — safe to call from anywhere without risking\n * a synchronous throw or an unhandled async rejection from a user-supplied\n * builder.\n */\n applyHeadersToAgent(agent: AbstractAgent): void;\n\n /**\n * Resolve headers fresh (including invoking a sync/async builder) and\n * apply them to `agent` right before a run or connect actually sends\n * (#1937). Friends-only — only the run handler should call this, since\n * unlike `applyHeadersToAgent` it can throw synchronously or return a\n * rejecting promise. Returns a promise only when an async builder must be\n * awaited first; callers that need the write to have landed before\n * continuing must await a returned promise.\n */\n prepareAgentHeadersForRun(agent: AbstractAgent): void | Promise<void>;\n\n // References to delegate subsystems\n readonly suggestionEngine: {\n clearSuggestions(agentId: string): void;\n reloadSuggestions(agentId: string): void;\n };\n\n /**\n * Called before each follow-up agent run (after tool execution).\n * See CopilotKitCore.waitForPendingFrameworkUpdates for details.\n */\n waitForPendingFrameworkUpdates(): Promise<void>;\n\n readonly stateManager: {\n getContinuationRunId(\n agent: AbstractAgent,\n input: Pick<RunAgentInput, \"threadId\" | \"resume\" | \"forwardedProps\">,\n ): string | undefined;\n markNextRunAsContinuation(\n agent: AbstractAgent,\n expectedRunId?: string,\n ): CopilotKitCoreContinuationHandoff;\n };\n}\n\nexport class CopilotKitCore {\n private headerSource: HeaderSourceResolver;\n private _credentials?: RequestCredentials;\n private _messageFilter?: CopilotKitMessageFilter;\n private _properties: Record<string, unknown>;\n private _scopedProperties: Map<string, ScopedProperties> = new Map();\n private _defaultThrottleMs?: number;\n private _debug?: DebugConfig;\n\n private subscribers: Set<CopilotKitCoreSubscriber> = new Set();\n\n // Delegate classes\n private agentRegistry: AgentRegistry;\n private contextStore: ContextStore;\n private suggestionEngine: SuggestionEngine;\n private runHandler: RunHandler;\n private stateManager: StateManager;\n private threadStoreRegistry: ThreadStoreRegistry;\n private learningBridge: LearningBridge;\n private notifiedTrajectoryId: string | null = null;\n private readonly learningConfiguredListeners = new Set<() => void>();\n private _generativeUIDebugSource: ɵGenerativeUIDebugSource | undefined;\n private readonly generativeUIDebugListeners = new Set<() => void>();\n /**\n * The single core-owned memory store, created lazily on first\n * `getMemoryStore()` and kept user-scoped for the lifetime of the core.\n * Its runtime context is wired by the core itself (see `syncMemoryContext`),\n * so callers never register or look it up by `agentId`.\n */\n private _memoryStore?: ɵMemoryStore;\n /**\n * Tracks the agent IDs from the most recent `onAgentsChanged` notification.\n * Used to gate thread-store auto-unregister so the FIRST empty-agents\n * notification (before published agents are merged in) does not rip out a\n * store that was registered prior to that initial notification.\n */\n private previousAgentIds: Set<string> = new Set();\n\n constructor({\n runtimeUrl,\n runtimeTransport = \"auto\",\n deferInitialConnection = false,\n headers = {},\n credentials,\n messageFilter,\n properties = {},\n agents__unsafe_dev_only = {},\n tools = [],\n suggestionsConfig = [],\n debug,\n learning,\n }: CopilotKitCoreConfig) {\n this.headerSource = new HeaderSourceResolver((error) => {\n void this.emitError({\n error,\n code: CopilotKitCoreErrorCode.HEADER_RESOLUTION_FAILED,\n context: { source: \"headers\" },\n });\n });\n this.headerSource.setSource(headers);\n this._credentials = credentials;\n this._messageFilter = messageFilter;\n this._properties = properties;\n this._debug = debug;\n\n // Initialize delegate classes\n this.agentRegistry = new AgentRegistry(this);\n this.contextStore = new ContextStore(this);\n this.suggestionEngine = new SuggestionEngine(this);\n this.runHandler = new RunHandler(this);\n this.stateManager = new StateManager(this);\n this.threadStoreRegistry = new ThreadStoreRegistry(this);\n\n // Initialize each subsystem\n this.agentRegistry.initialize(agents__unsafe_dev_only);\n this.runHandler.initialize(tools);\n this.suggestionEngine.initialize(suggestionsConfig);\n this.stateManager.initialize();\n // After agent initialization: the bridge reads the initial agents.\n this.learningBridge = new LearningBridge(this, learning, () =>\n this.notifyTrajectoryChanged(),\n );\n\n this.agentRegistry.setRuntimeTransport(runtimeTransport);\n this.agentRegistry.setRuntimeUrl(runtimeUrl, {\n deferConnection: deferInitialConnection,\n });\n\n // Seed the previous-agents snapshot from the constructor-supplied agents.\n // `agentRegistry.initialize` does not emit `onAgentsChanged`, so the\n // subscriber below would otherwise see its first non-empty notification\n // as an \"addition\" relative to an empty baseline — and a later removal\n // of those same agents would NOT trigger the auto-unregister branch\n // because the guard would think the agentId was never previously\n // present. Seeding the set here keeps the guard honest.\n this.previousAgentIds = new Set(Object.keys(agents__unsafe_dev_only));\n\n // Subscribe to agent changes to track state for new agents\n this.subscribe({\n // Re-sync the memory store's runtime context whenever the runtime\n // connection status changes. The `/info` fetch sets the connection\n // status and `intelligence` together before firing this notification,\n // so this single hook covers both connection and intelligence changes.\n // Guarded so we never instantiate the store just to sync it.\n onRuntimeConnectionStatusChanged: () => {\n if (this._memoryStore) this.syncMemoryContext();\n },\n onAgentsChanged: ({ agents }) => {\n Object.values(agents).forEach((agent) => {\n if (agent.agentId) {\n this.stateManager.subscribeToAgent(agent);\n }\n });\n\n // Unregister thread stores for agents that have been removed.\n //\n // Critically, only unregister an agentId that was present in the\n // PREVIOUS agents snapshot AND is missing from the new one. Without\n // the \"previously had\" guard, the FIRST `onAgentsChanged({ agents: {} })`\n // delivered to a freshly-published core would tear out a thread store\n // that a consumer (e.g. useThreads) just registered — `core.agents`\n // is asynchronously populated and the empty-map notification fires\n // before the published agents are merged in.\n const currentAgentIds = new Set(Object.keys(agents));\n // Each iteration is wrapped so a throw on one id does not stall\n // cleanup for the rest of the set. Both registries' unregister\n // paths are idempotent, so re-attempts on the next\n // onAgentsChanged are safe.\n for (const agentId of Object.keys(this.threadStoreRegistry.getAll())) {\n if (\n this.previousAgentIds.has(agentId) &&\n !currentAgentIds.has(agentId)\n ) {\n try {\n this.threadStoreRegistry.unregister(agentId);\n } catch (err) {\n console.error(\n `CopilotKitCore.onAgentsChanged: threadStoreRegistry.unregister failed for \"${agentId}\":`,\n err,\n );\n }\n }\n }\n\n // Symmetric cleanup for state-manager subscriptions: any agentId\n // that disappeared from the registry (e.g. via `unregister()` from\n // a registerProxiedAgent caller) should release its StateManager\n // subscription. Without this, the subscription leaks — events from\n // a still-running observable on the removed agent would continue\n // to populate stateByRun/messageToRun for the dead id.\n for (const agentId of this.previousAgentIds) {\n if (!currentAgentIds.has(agentId)) {\n try {\n this.stateManager.unsubscribeFromAgent(agentId);\n } catch (err) {\n console.error(\n `CopilotKitCore.onAgentsChanged: stateManager.unsubscribeFromAgent failed for \"${agentId}\":`,\n err,\n );\n }\n }\n }\n\n this.previousAgentIds = currentAgentIds;\n },\n });\n }\n\n /**\n * Internal method used by delegate classes and subclasses to notify subscribers\n */\n protected async notifySubscribers(\n handler: (subscriber: CopilotKitCoreSubscriber) => void | Promise<void>,\n errorMessage: string,\n ): Promise<void> {\n await Promise.all(\n Array.from(this.subscribers).map(async (subscriber) => {\n try {\n await handler(subscriber);\n } catch (error) {\n console.error(errorMessage, error);\n }\n }),\n );\n }\n\n /**\n * Internal method used by delegate classes to emit errors\n */\n private async emitError({\n error,\n code,\n context = {},\n }: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n }): Promise<void> {\n if (\n code !== CopilotKitCoreErrorCode.HEADER_RESOLUTION_FAILED &&\n isHeaderResolutionError(error)\n ) {\n // Already reported once as HEADER_RESOLUTION_FAILED.\n return;\n }\n await this.notifySubscribers(\n (subscriber) =>\n subscriber.onError?.({\n copilotkit: this,\n error,\n code,\n context,\n }),\n \"Subscriber onError error:\",\n );\n }\n\n /**\n * Log a message to the console and emit an error to subscribers.\n * Catches failures from `emitError` itself to prevent unhandled rejections.\n */\n private logAndEmitError(\n message: string,\n params: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context?: Record<string, any>;\n },\n logLevel: \"error\" | \"warn\" = \"error\",\n ): void {\n console[logLevel](message, params.error);\n this.emitError(params).catch((emitErr: unknown) => {\n console.error(message + \" — emitError itself failed:\", emitErr);\n });\n }\n\n /**\n * Snapshot accessors\n */\n get context(): Readonly<Record<string, ScopedContext>> {\n return this.contextStore.context;\n }\n\n get agents(): Readonly<Record<string, AbstractAgent>> {\n return this.agentRegistry.agents;\n }\n\n get tools(): Readonly<FrontendTool<any>[]> {\n return this.runHandler.tools;\n }\n\n get catalogComponents(): ReadonlyArray<CopilotKitCoreCatalogComponent> {\n return this.runHandler.catalogComponents;\n }\n\n get runtimeUrl(): string | undefined {\n return this.agentRegistry.runtimeUrl;\n }\n\n setRuntimeUrl(runtimeUrl: string | undefined): void {\n this.agentRegistry.setRuntimeUrl(runtimeUrl);\n }\n\n /**\n * Start the runtime `/info` connection if it has not been started yet.\n *\n * Intended to be driven from a host's commit-phase effect when the core was\n * constructed with {@link CopilotKitCoreConfig.deferInitialConnection}. Safe\n * to call repeatedly — it is a no-op once a connection is in progress or\n * settled, so a double-invoked mount effect (React StrictMode) collapses to a\n * single request. See #5801.\n */\n connect(): void {\n this.agentRegistry.connectRuntime();\n }\n\n get runtimeTransport(): CopilotRuntimeTransport {\n return this.agentRegistry.runtimeTransport;\n }\n\n setRuntimeTransport(runtimeTransport: CopilotRuntimeTransport): void {\n this.agentRegistry.setRuntimeTransport(runtimeTransport);\n }\n\n get runtimeVersion(): string | undefined {\n return this.agentRegistry.runtimeVersion;\n }\n\n /**\n * The last resolved headers. With a builder this is the value from the most\n * recent request, not necessarily current; call `resolveHeaders()` for that.\n */\n get headers(): Readonly<Record<string, string>> {\n return this.headerSource.headers;\n }\n\n /**\n * Resolve the current headers. Synchronous for a record or a sync builder,\n * a promise for an async builder. Concurrent calls share one builder call.\n * The returned object is shared; copy it before modifying.\n */\n resolveHeaders():\n | Readonly<Record<string, string>>\n | Promise<Readonly<Record<string, string>>> {\n return this.headerSource.resolve();\n }\n\n /** Changes only on `setHeaders` or a new source, never on a new token. */\n get ɵheadersGeneration(): number {\n return this.headerSource.generation;\n }\n\n get credentials(): RequestCredentials | undefined {\n return this._credentials;\n }\n\n get messageFilter(): CopilotKitMessageFilter | undefined {\n return this._messageFilter;\n }\n\n get properties(): Readonly<Record<string, unknown>> {\n return this._properties;\n }\n\n /**\n * Default throttle interval (ms) used by `subscribeToAgentWithOptions()`\n * when the caller does not specify an explicit `throttleMs`.\n * `undefined` means no default is configured; `0` means no throttling.\n */\n get defaultThrottleMs(): number | undefined {\n return this._defaultThrottleMs;\n }\n\n /**\n * Set the default throttle interval (ms) for `subscribeToAgentWithOptions()`.\n *\n * Accepts a non-negative finite number or `undefined` (to clear the\n * default). Invalid values (NaN, Infinity, negative) are logged as\n * errors and ignored — the previous valid value is preserved.\n */\n setDefaultThrottleMs(value: number | undefined): void {\n if (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n this.logAndEmitError(\n `CopilotKitCore.setDefaultThrottleMs: value must be a non-negative finite number or undefined, ` +\n `got ${value}. Keeping current value (${this._defaultThrottleMs}).`,\n {\n error: new Error(\n `setDefaultThrottleMs: invalid value (${value}), keeping current value (${this._defaultThrottleMs})`,\n ),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { value, currentValue: this._defaultThrottleMs },\n },\n );\n return;\n }\n this._defaultThrottleMs = value;\n }\n\n get debug(): DebugConfig | undefined {\n return this._debug;\n }\n\n setDebug(debug: DebugConfig | undefined): void {\n this._debug = debug;\n }\n\n get runtimeConnectionStatus(): CopilotKitCoreRuntimeConnectionStatus {\n return this.agentRegistry.runtimeConnectionStatus;\n }\n\n /** @internal The verbatim single-endpoint URL, including any trailing slash. */\n get ɵruntimeEndpointUrl(): string | undefined {\n return this.agentRegistry.runtimeEndpointUrl;\n }\n\n get ɵruntimeFetch(): typeof fetch {\n return this.agentRegistry.createRuntimeFetch();\n }\n\n get audioFileTranscriptionEnabled(): boolean {\n return this.agentRegistry.audioFileTranscriptionEnabled;\n }\n\n get runtimeMode(): RuntimeMode {\n return this.agentRegistry.runtimeMode;\n }\n\n get intelligence(): IntelligenceRuntimeInfo | undefined {\n return this.agentRegistry.intelligence;\n }\n\n get threadEndpoints(): ThreadEndpointRuntimeInfo | undefined {\n return this.agentRegistry.threadEndpoints;\n }\n\n get suggestions(): boolean | undefined {\n return this.agentRegistry.suggestions;\n }\n\n /** Whether the connected Runtime exposes debug-authorized Learning data. */\n get inspectorLearning(): boolean {\n return this.agentRegistry.inspectorLearning;\n }\n\n /** Trusted, optional metadata advertised by the connected runtime. */\n get inspectorMetadata(): InspectorMetadataV1 | undefined {\n return this.agentRegistry.inspectorMetadata;\n }\n\n /** Refresh trusted inspector metadata without reconnecting runtime agents. */\n async refreshInspectorMetadata(): Promise<void> {\n await this.agentRegistry.refreshInspectorMetadata();\n }\n\n get a2uiEnabled(): boolean {\n return this.agentRegistry.a2uiEnabled;\n }\n\n /**\n * Agent ids the runtime applies A2UI to. `undefined` means A2UI applies to\n * every agent (or is disabled — check `a2uiEnabled`).\n */\n get a2uiAgents(): string[] | undefined {\n return this.agentRegistry.a2uiAgents;\n }\n\n get openGenerativeUIEnabled(): boolean {\n return this.agentRegistry.openGenerativeUIEnabled;\n }\n\n get licenseStatus(): RuntimeLicenseStatus | undefined {\n return this.agentRegistry.licenseStatus;\n }\n\n /** Structured Runtime entitlement authority advertised by `/info`. */\n get runtimeEntitlements(): RuntimeEntitlementResponse | undefined {\n return this.agentRegistry.runtimeEntitlements;\n }\n\n /** Whether Core still has a bounded Runtime entitlement retry to settle. */\n get runtimeEntitlementRetryPending(): boolean {\n return this.agentRegistry.runtimeEntitlementRetryPending;\n }\n\n get telemetryDisabled(): boolean {\n return this.agentRegistry.telemetryDisabled;\n }\n\n /**\n * Configuration updates\n */\n /**\n * Replace the headers sent with every runtime request.\n *\n * This is an overwrite, not a merge — the supplied object becomes the\n * complete header set. Entries whose value is `null` or `undefined` are\n * dropped, which is how you clear a header (e.g. removing `Authorization`\n * on logout) without leaving an empty-string value behind:\n *\n * ```ts\n * copilotkit.setHeaders({\n * ...copilotkit.headers,\n * Authorization: token ? `Bearer ${token}` : null,\n * });\n * ```\n *\n * The resulting header set is also re-applied to every agent in the registry\n * and `onHeadersChanged` subscribers are notified. These headers are merged\n * ON TOP of the headers each `HttpAgent` was constructed with, so per-agent\n * headers (e.g. an `Authorization` for a self-hosted backend) are preserved;\n * on a key conflict the core-level value wins.\n *\n * Because the agent's construction-time headers form the merge baseline, this\n * method can override a per-agent header but cannot REMOVE one: clearing a\n * core key here only drops the core-level override, after which the agent's\n * own value (if any) re-surfaces. To change a header an agent was constructed\n * with, set it at the provider/core level instead of on the agent, or update\n * it on the agent directly. The clear-on-logout pattern above is for\n * core-level headers.\n *\n * Pass a function to have headers evaluated when each request is sent\n * (sync or async). Setting the same function again is a no-op. A new token\n * from the builder doesn't notify `onHeadersChanged`. On a user switch,\n * call `setHeaders` with a NEW function (or a record), or remount.\n *\n * Passing a record equal (by value) to the currently applied record is\n * also a no-op — safe to call on every render with a fresh object literal.\n */\n setHeaders(headers: CopilotKitHeadersSource): void {\n if (!this.headerSource.setSource(headers)) return;\n if (this._memoryStore) this.syncMemoryContext();\n this.agentRegistry.applyHeadersToAgents(\n this.agentRegistry.agents as Record<string, AbstractAgent>,\n );\n this.agentRegistry.handleHeadersChanged();\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onHeadersChanged?.({\n copilotkit: this,\n headers: this.headers,\n }),\n \"Subscriber onHeadersChanged error:\",\n );\n }\n\n setCredentials(credentials: RequestCredentials | undefined): void {\n this._credentials = credentials;\n this.agentRegistry.applyCredentialsToAgents(\n this.agentRegistry.agents as Record<string, AbstractAgent>,\n );\n this.agentRegistry.handleCredentialsChanged();\n }\n\n /**\n * Replace the message filter applied to every runtime agent.\n *\n * Applies to agents already discovered as well as ones discovered later, so\n * a filter set before `/info` lands is not lost. Pass `undefined` to go back\n * to sending the full thread.\n */\n setMessageFilter(messageFilter: CopilotKitMessageFilter | undefined): void {\n this._messageFilter = messageFilter;\n this.agentRegistry.applyMessageFilterToAgents(\n this.agentRegistry.agents as Record<string, AbstractAgent>,\n );\n }\n\n /**\n * Add run properties that go only to the runs of `agentIds`. When\n * `agentIds` is omitted, every agent gets them. They merge on top of the\n * base `properties`.\n *\n * When an entry value and the existing value under the same key are both\n * plain objects, their keys merge one level deep. So several entries can\n * add keys under one namespace (for example `copilotkit`).\n *\n * @param entry - The properties and the optional agent ids.\n * @returns The id to pass to `removeScopedProperties`.\n *\n * @example\n * const id = copilotkit.addScopedProperties({\n * properties: { copilotkit: { theme: \"dark\" } },\n * agentIds: [\"research\"],\n * });\n * copilotkit.removeScopedProperties(id);\n */\n addScopedProperties({ properties, agentIds }: ScopedProperties) {\n let id = randomUUID();\n // An id source that repeats itself (a mock, say) must not replace an\n // earlier entry: every call adds one.\n for (let n = 1; this._scopedProperties.has(id); n++) id = `${id}-${n}`;\n this._scopedProperties.set(id, {\n properties,\n ...(agentIds ? { agentIds } : {}),\n });\n return id;\n }\n\n /** Remove an entry that `addScopedProperties` added. An unknown id does nothing. */\n removeScopedProperties(id: string) {\n this._scopedProperties.delete(id);\n }\n\n /**\n * Build the forwarded properties for a run of the given agent: the base\n * properties plus every scoped entry that matches the agent. An entry with\n * `agentIds` does not match when `agentId` is omitted.\n */\n getPropertiesForAgent(agentId?: string) {\n const merged: Record<string, unknown> = { ...this._properties };\n const entries = this._scopedProperties.values();\n for (const entry of entries) {\n if (!isForAgent(entry.agentIds, agentId)) continue;\n\n const properties = Object.entries(entry.properties);\n for (const [key, value] of properties) {\n const base = merged[key];\n merged[key] =\n isPlainObject(base) && isPlainObject(value)\n ? { ...base, ...value }\n : value;\n }\n }\n return merged;\n }\n\n setProperties(properties: Record<string, unknown>): void {\n this._properties = properties;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onPropertiesChanged?.({\n copilotkit: this,\n properties: this.properties,\n }),\n \"Subscriber onPropertiesChanged error:\",\n );\n }\n\n /**\n * Agent management (delegated to AgentRegistry)\n */\n setAgents__unsafe_dev_only(agents: Record<string, AbstractAgent>): void {\n this.agentRegistry.setAgents__unsafe_dev_only(agents);\n }\n\n addAgent__unsafe_dev_only(params: CopilotKitCoreAddAgentParams): void {\n this.agentRegistry.addAgent__unsafe_dev_only(params);\n }\n\n removeAgent__unsafe_dev_only(id: string): void {\n this.agentRegistry.removeAgent__unsafe_dev_only(id);\n }\n\n /**\n * Register a proxied agent against an existing runtime agent. The proxy is\n * exposed under `agentId` (local registry id) and routes outbound runtime\n * requests to `runtimeAgentId`. Throws if `agentId` is already taken.\n *\n * Returns the minted proxy and an `unregister` handle for cleanup.\n *\n * Use this to mount multiple frontend agents against a single runtime\n * agent (e.g. one per chat window) without implicit per-thread cloning.\n *\n * @example\n * const { agent, unregister } = copilotkit.registerProxiedAgent({\n * agentId: \"chat-1\",\n * runtimeAgentId: \"default\",\n * });\n * // ... <CopilotChat agentId=\"chat-1\" />\n * // on cleanup:\n * unregister();\n */\n registerProxiedAgent(\n params: CopilotKitCoreRegisterProxiedAgentParams,\n ): CopilotKitCoreRegisterProxiedAgentResult {\n return this.agentRegistry.registerProxiedAgent(params);\n }\n\n getAgent(id: string): AbstractAgent | undefined {\n return this.agentRegistry.getAgent(id);\n }\n\n /** Updates settings for the next capture. Removing the config stops capture. */\n setLearningConfig(config: LearningConfig | undefined): void {\n const wasConfigured = this.ɵlearningConfigured;\n this.learningBridge.setConfig(config);\n this.notifyTrajectoryChanged();\n if (this.ɵlearningConfigured === wasConfigured) return;\n for (const listener of this.learningConfiguredListeners) {\n try {\n listener();\n } catch (error) {\n console.error(\"Learning configured listener error:\", error);\n }\n }\n }\n\n /**\n * @internal Whether a `learning` config is set. Unlike {@link trajectoryId},\n * it does not change with capture start, connection failures or reconnects.\n */\n get ɵlearningConfigured(): boolean {\n return this.learningBridge.isConfigured;\n }\n\n /**\n * @internal Whether captured events may carry agent message text: false\n * without a `learning` config, or when a custom sink sets\n * `capture.agentText` to false. A running custom-sink capture keeps the\n * choice it started with.\n */\n get ɵlearningCapturesAgentText(): boolean {\n return this.learningBridge.capturesAgentText;\n }\n\n /** @internal Calls `listener` when {@link ɵlearningConfigured} changes. */\n ɵsubscribeToLearningConfigured(listener: () => void): () => void {\n this.learningConfiguredListeners.add(listener);\n return () => {\n this.learningConfiguredListeners.delete(listener);\n };\n }\n\n /**\n * @internal The generative UI of the framework package, for the inspector.\n * `undefined` when no provider has a `generativeUI` config.\n */\n get ɵgenerativeUIDebugSource(): ɵGenerativeUIDebugSource | undefined {\n return this._generativeUIDebugSource;\n }\n\n /** @internal Set by the framework package. `undefined` removes it. */\n ɵsetGenerativeUIDebugSource(source: ɵGenerativeUIDebugSource | undefined) {\n if (source === this._generativeUIDebugSource) return;\n this._generativeUIDebugSource = source;\n for (const listener of [...this.generativeUIDebugListeners]) {\n try {\n listener();\n } catch (error) {\n console.error(\"Generative UI debug listener error:\", error);\n }\n }\n }\n\n /** @internal Calls `listener` when {@link ɵgenerativeUIDebugSource} is set or removed. */\n ɵsubscribeToGenerativeUIDebugSource(listener: () => void): () => void {\n this.generativeUIDebugListeners.add(listener);\n return () => {\n this.generativeUIDebugListeners.delete(listener);\n };\n }\n\n /** The active capture's Trajectory ID, or null while capture is stopped. */\n get trajectoryId(): string | null {\n return this.learningBridge.trajectoryId;\n }\n\n private notifyTrajectoryChanged(): void {\n const trajectoryId = this.trajectoryId;\n if (trajectoryId === this.notifiedTrajectoryId) return;\n this.notifiedTrajectoryId = trajectoryId;\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onTrajectoryChanged?.({ copilotkit: this, trajectoryId }),\n \"Subscriber onTrajectoryChanged error:\",\n );\n }\n\n /**\n * Starts one Trajectory after Runtime authorization and the Gateway join.\n * Omit the ID to create one. Repeated starts await the active connection;\n * a different ID stops the previous capture. Explicit sinks retain the\n * prototype's synchronous capture and require a stop before changing IDs.\n *\n * @example copilotkit.startTrajectory({ trajectoryId: crypto.randomUUID() })\n */\n startTrajectory(options: TrajectoryStartOptions = {}): Promise<StartResult> {\n const result = this.learningBridge.start(options);\n this.notifyTrajectoryChanged();\n return result;\n }\n\n /** Cancels pending work and stops capture, attempting one final batch without waiting for its ACK. */\n stopTrajectory() {\n this.learningBridge.stop();\n this.notifyTrajectoryChanged();\n }\n\n /**\n * Records an outcome that clicks cannot show, such as a saved report or an\n * approved deal. The wire adds `value.seq`; arrays, primitives, and objects\n * already containing `seq` are preserved under `value.data`. Explicit legacy\n * sinks retain object-only events with open-Thread enrichment.\n * No-op while no Trajectory runs. Events emitted during connection recovery\n * count as dropped. Built-in names such as `click` are rejected.\n *\n * @example copilotkit.emitTrajectoryEvent(\"deal.approved\", { dealId: \"deal-1\" })\n */\n emitTrajectoryEvent(name: string, value: JsonValue = {}) {\n this.learningBridge.emit(name, value);\n }\n\n /**\n * Tells Core that a view shows this Thread, so captured interactions can link to it.\n * Framework bindings call this; call it yourself only without a CopilotKit provider.\n */\n registerOpenThread(params: { agentId: string; threadId: string }) {\n return this.learningBridge.registerOpenThread(params);\n }\n\n /**\n * Re-apply the last resolved header snapshot to a single agent (delegated\n * to AgentRegistry). Core headers are merged on top of the agent's own\n * construction-time headers rather than replacing them, so headers\n * configured directly on an `HttpAgent` (e.g. an `Authorization` for a\n * self-hosted backend) survive header updates instead of being silently\n * dropped (see #5635). On a key conflict the core-level value wins.\n *\n * The merge baseline is the agent's headers as captured the first time the\n * agent is applied (at registration), so the way to change headers\n * afterwards is `setHeaders` (which re-applies to every agent), not mutating\n * `agent.headers` directly — a direct mutation is overwritten on the next\n * re-apply.\n *\n * A `ProxiedCopilotRuntimeAgent` keeps only its own construction-time\n * headers here — core headers are added by `ɵruntimeFetch` when each\n * request is sent (see #1937), so `agent.headers` never carries a stale\n * copy of a core header the builder has since stopped returning.\n *\n * Never invokes the headers builder (unlike the run/connect path's\n * internal `prepareAgentHeadersForRun`): safe to call from a dev-only\n * registration helper or a React effect that re-runs on every render\n * without risking a synchronous throw or an unhandled async rejection from\n * a user-supplied builder.\n */\n applyHeadersToAgent(agent: AbstractAgent): void {\n this.agentRegistry.applyHeadersToAgent(agent);\n }\n\n /**\n * Resolve headers fresh and apply them to `agent` right before a run or\n * connect actually sends (#1937). Friends-only (delegated to\n * AgentRegistry) — the run handler is the sole caller, since resolving can\n * invoke a user-supplied builder that throws or rejects.\n */\n private prepareAgentHeadersForRun(\n agent: AbstractAgent,\n ): void | Promise<void> {\n return this.agentRegistry.prepareAgentHeadersForRun(agent);\n }\n\n /**\n * Context management (delegated to ContextStore).\n * Pass `agentIds` to restrict the entry to runs of specific agents;\n * omit it for context every agent should receive.\n */\n addContext(context: ScopedContext): string {\n return this.contextStore.addContext(context);\n }\n\n removeContext(id: string): void {\n this.contextStore.removeContext(id);\n }\n\n /**\n * Build the context array for a run of the given agent, dropping entries\n * scoped to other agents and stripping the scoping metadata.\n */\n getContextForAgent(agentId?: string): Context[] {\n return this.contextStore.getContextForAgent(agentId);\n }\n\n /**\n * Thread store registry (delegated to ThreadStoreRegistry)\n */\n registerThreadStore(agentId: string, store: ɵThreadStore): void {\n this.threadStoreRegistry.register(agentId, store);\n }\n\n unregisterThreadStore(agentId: string): void {\n this.threadStoreRegistry.unregister(agentId);\n }\n\n getThreadStore(agentId: string): ɵThreadStore | undefined {\n return this.threadStoreRegistry.get(agentId);\n }\n\n getThreadStores(): Readonly<Record<string, ɵThreadStore>> {\n return this.threadStoreRegistry.getAll();\n }\n\n /**\n * Returns the single core-owned, user-scoped memory store, creating and\n * starting it on first access. Unlike thread stores, memory is not scoped per\n * agent: there is exactly one store whose runtime context the core wires\n * itself (see `syncMemoryContext`), so consumers (e.g. a `useMemories`\n * binding) just read this store rather than registering one.\n */\n getMemoryStore(): ɵMemoryStore {\n return this.ensureMemoryStore();\n }\n\n /**\n * Lazily creates, starts, and context-syncs the core-owned memory store on\n * first access, then returns it. Subsequent calls return the existing store.\n * The store uses the Core Runtime fetch so REST and single-route transports\n * share the same resource behavior. Its Runtime context is synced at once.\n */\n private ensureMemoryStore(): ɵMemoryStore {\n if (!this._memoryStore) {\n this._memoryStore = ɵcreateMemoryStore({\n fetch: this.ɵruntimeFetch,\n });\n this._memoryStore.start();\n this.syncMemoryContext();\n }\n return this._memoryStore;\n }\n\n /**\n * Pushes the current runtime wiring into the memory store. When the runtime\n * is connected and both the intelligence WebSocket URL and runtime URL are\n * available, the store receives a context (runtime URL, WebSocket URL);\n * otherwise its context is cleared. No-op when the store has not been\n * created yet.\n *\n * Headers are deliberately NOT part of this context: the store's `fetch` is\n * `ɵruntimeFetch` (see `ensureMemoryStore`), which already resolves and\n * overlays the current core headers at send time (#1937) — a header\n * snapshot copied here would go stale between context syncs.\n */\n private syncMemoryContext(): void {\n if (!this._memoryStore) return;\n if (\n this.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected &&\n this.intelligence?.wsUrl &&\n this.runtimeUrl\n ) {\n this._memoryStore.setContext({\n runtimeUrl: this.runtimeUrl,\n wsUrl: this.intelligence.wsUrl,\n });\n } else {\n this._memoryStore.setContext(null);\n }\n }\n\n /**\n * Suggestions management (delegated to SuggestionEngine)\n */\n addSuggestionsConfig(config: SuggestionsConfig): string {\n return this.suggestionEngine.addSuggestionsConfig(config);\n }\n\n removeSuggestionsConfig(id: string): void {\n this.suggestionEngine.removeSuggestionsConfig(id);\n }\n\n reloadSuggestions(agentId: string): void {\n this.suggestionEngine.reloadSuggestions(agentId);\n }\n\n clearSuggestions(agentId: string): void {\n this.suggestionEngine.clearSuggestions(agentId);\n }\n\n getSuggestions(agentId: string): CopilotKitCoreGetSuggestionsResult {\n return this.suggestionEngine.getSuggestions(agentId);\n }\n\n /**\n * Tool management (delegated to RunHandler)\n */\n addTool<T extends Record<string, unknown> = Record<string, unknown>>(\n tool: FrontendTool<T>,\n ): void {\n this.runHandler.addTool(tool);\n }\n\n removeTool(id: string, agentId?: string): void {\n this.runHandler.removeTool(id, agentId);\n }\n\n getTool(params: CopilotKitCoreGetToolParams): FrontendTool<any> | undefined {\n return this.runHandler.getTool(params);\n }\n\n setTools(tools: FrontendTool<any>[]): void {\n this.runHandler.setTools(tools);\n }\n\n /**\n * Enable/disable a registered frontend tool at runtime without unregistering\n * it (Inspector \"Capabilities\" tool). A disabled tool is omitted from the\n * tool list sent to the agent on the next run. The override is keyed by name\n * (+ optional agentId) and survives the tool being re-registered.\n */\n setToolEnabled(name: string, enabled: boolean, agentId?: string): void {\n this.runHandler.setToolEnabled(name, enabled, agentId);\n }\n\n /** Whether a registered tool is currently enabled (defaults true). */\n isToolEnabled(name: string, agentId?: string): boolean {\n return this.runHandler.isToolEnabled(name, agentId);\n }\n\n /**\n * A2UI catalog component management (delegated to RunHandler).\n * Registers the full component list and controls per-component enablement.\n */\n setCatalogComponents(components: CopilotKitCoreCatalogComponent[]): void {\n this.runHandler.setCatalogComponents(components);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onCatalogComponentsChanged?.({\n copilotkit: this,\n catalogComponents: this.runHandler.catalogComponents,\n }),\n \"Subscriber onCatalogComponentsChanged error:\",\n );\n }\n\n setCatalogComponentEnabled(name: string, enabled: boolean): void {\n this.runHandler.setCatalogComponentEnabled(name, enabled);\n void this.notifySubscribers(\n (subscriber) =>\n subscriber.onCatalogComponentsChanged?.({\n copilotkit: this,\n catalogComponents: this.runHandler.catalogComponents,\n }),\n \"Subscriber onCatalogComponentsChanged error:\",\n );\n }\n\n isCatalogComponentEnabled(name: string): boolean {\n return this.runHandler.isCatalogComponentEnabled(name);\n }\n\n /**\n * Subscription lifecycle\n */\n subscribe(subscriber: CopilotKitCoreSubscriber): CopilotKitCoreSubscription {\n this.subscribers.add(subscriber);\n\n // Return subscription with unsubscribe method\n return {\n unsubscribe: () => {\n this.subscribers.delete(subscriber);\n },\n };\n }\n\n /**\n * Subscribe to an agent's notification and lifecycle events with\n * optional configuration (e.g. throttling).\n *\n * Wraps every callback with error protection (`safeCall`) and applies\n * the options before delegating to `agent.subscribe()`.\n *\n * See {@link SubscribeToAgentSubscriber} for the accepted callback subset\n * and the rationale for excluding AG-UI event handlers.\n */\n subscribeToAgentWithOptions(\n agent: AbstractAgent,\n subscriber: SubscribeToAgentSubscriber,\n options?: SubscribeToAgentOptions,\n ): CopilotKitCoreSubscription {\n const resolved = options?.throttleMs ?? this._defaultThrottleMs ?? 0;\n\n let effectiveMs = 0;\n if (!Number.isFinite(resolved) || resolved < 0) {\n const source =\n options?.throttleMs !== undefined ? \"throttleMs\" : \"defaultThrottleMs\";\n this.logAndEmitError(\n `CopilotKitCore.subscribeToAgentWithOptions: ${source} must be a non-negative finite number, ` +\n `got ${resolved}. Falling back to unthrottled.`,\n {\n error: new Error(\n `subscribeToAgentWithOptions: invalid ${source} (${resolved}), falling back to unthrottled`,\n ),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { agentId: agent.agentId, source, value: resolved },\n },\n );\n } else {\n effectiveMs = resolved;\n }\n\n const agentLabel = agent.agentId || \"(unknown agent)\";\n\n // Wraps a callback so that synchronous throws and async rejections are\n // caught, logged, and emitted — preventing one failing callback from\n // corrupting the agent's notification loop.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const safeCall = <F extends (...args: any[]) => any>(\n label: string,\n fn: F,\n ...args: Parameters<F>\n ): any => {\n const reportError = (err: unknown, verb: string) => {\n this.logAndEmitError(\n `CopilotKitCore.subscribeToAgentWithOptions[${agentLabel}]: ${label} callback ${verb}:`,\n {\n error: err instanceof Error ? err : new Error(String(err)),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { agentId: agent.agentId, callback: label },\n },\n );\n };\n try {\n const result = fn(...args);\n if (result instanceof Promise) {\n return result.catch((err: unknown) => {\n reportError(err, \"rejected\");\n });\n }\n return result;\n } catch (err) {\n reportError(err, \"threw\");\n }\n };\n\n const guardAll = (\n sub: SubscribeToAgentSubscriber,\n ): SubscribeToAgentSubscriber => {\n const guarded: SubscribeToAgentSubscriber = {};\n if (sub.onMessagesChanged) {\n const fn = sub.onMessagesChanged;\n guarded.onMessagesChanged = (params) =>\n safeCall(\"onMessagesChanged\", fn, params);\n }\n if (sub.onStateChanged) {\n const fn = sub.onStateChanged;\n guarded.onStateChanged = (params) =>\n safeCall(\"onStateChanged\", fn, params);\n }\n if (sub.onRunInitialized) {\n const fn = sub.onRunInitialized;\n guarded.onRunInitialized = (params) =>\n safeCall(\"onRunInitialized\", fn, params);\n }\n if (sub.onRunStartedEvent) {\n const fn = sub.onRunStartedEvent;\n guarded.onRunStartedEvent = (params) =>\n safeCall(\"onRunStartedEvent\", fn, params);\n }\n if (sub.onRunFinalized) {\n const fn = sub.onRunFinalized;\n guarded.onRunFinalized = (params) =>\n safeCall(\"onRunFinalized\", fn, params);\n }\n if (sub.onRunFailed) {\n const fn = sub.onRunFailed;\n guarded.onRunFailed = (params) => safeCall(\"onRunFailed\", fn, params);\n }\n if (sub.onRunErrorEvent) {\n const fn = sub.onRunErrorEvent;\n guarded.onRunErrorEvent = (params) =>\n safeCall(\"onRunErrorEvent\", fn, params);\n }\n return guarded;\n };\n\n // Warn about unsupported keys so JS / `as any` consumers get diagnostics.\n for (const key of Object.keys(subscriber)) {\n if (\n typeof (subscriber as Record<string, unknown>)[key] === \"function\" &&\n !(ALLOWED_KEYS as ReadonlySet<string>).has(key)\n ) {\n const message =\n `CopilotKitCore.subscribeToAgentWithOptions[${agentLabel}]: callback \"${key}\" is not supported ` +\n `and was dropped. Supported callbacks: ${Array.from(ALLOWED_KEYS).join(\", \")}. ` +\n `Use agent.subscribe() directly for event handlers and per-item notifications.`;\n this.logAndEmitError(\n message,\n {\n error: new Error(message),\n code: CopilotKitCoreErrorCode.SUBSCRIBER_CALLBACK_FAILED,\n context: { agentId: agent.agentId, droppedCallback: key },\n },\n \"warn\",\n );\n }\n }\n\n // No throttle — guard callbacks and subscribe directly.\n if (effectiveMs <= 0) {\n const subscription = agent.subscribe(guardAll(subscriber));\n return { unsubscribe: () => subscription.unsubscribe() };\n }\n\n // Throttled path: lifecycle callbacks fire immediately; onMessagesChanged\n // and onStateChanged share a single Throttler that flushes the latest\n // params for both channels.\n let active = true;\n let latestMessagesParams:\n | Parameters<\n NonNullable<SubscribeToAgentSubscriber[\"onMessagesChanged\"]>\n >[0]\n | null = null;\n let latestStateParams:\n | Parameters<NonNullable<SubscribeToAgentSubscriber[\"onStateChanged\"]>>[0]\n | null = null;\n\n const flushPending = () => {\n if (active && subscriber.onMessagesChanged && latestMessagesParams) {\n const params = latestMessagesParams;\n latestMessagesParams = null;\n safeCall(\"onMessagesChanged\", subscriber.onMessagesChanged, params);\n }\n if (active && subscriber.onStateChanged && latestStateParams) {\n const params = latestStateParams;\n latestStateParams = null;\n safeCall(\"onStateChanged\", subscriber.onStateChanged, params);\n }\n };\n\n const throttler = new Throttler(flushPending, {\n wait: effectiveMs,\n leading: true,\n trailing: true,\n });\n\n // Lifecycle callbacks are guarded but never throttled.\n const lifecycleOnly: SubscribeToAgentSubscriber = {};\n if (subscriber.onRunInitialized)\n lifecycleOnly.onRunInitialized = subscriber.onRunInitialized;\n if (subscriber.onRunStartedEvent)\n lifecycleOnly.onRunStartedEvent = subscriber.onRunStartedEvent;\n if (subscriber.onRunFinalized)\n lifecycleOnly.onRunFinalized = subscriber.onRunFinalized;\n if (subscriber.onRunFailed)\n lifecycleOnly.onRunFailed = subscriber.onRunFailed;\n if (subscriber.onRunErrorEvent)\n lifecycleOnly.onRunErrorEvent = subscriber.onRunErrorEvent;\n\n const wrappedSubscriber: SubscribeToAgentSubscriber =\n guardAll(lifecycleOnly);\n\n if (subscriber.onMessagesChanged) {\n wrappedSubscriber.onMessagesChanged = (params) => {\n latestMessagesParams = params;\n throttler.maybeExecute();\n };\n }\n\n if (subscriber.onStateChanged) {\n wrappedSubscriber.onStateChanged = (params) => {\n latestStateParams = params;\n throttler.maybeExecute();\n };\n }\n\n const subscription = agent.subscribe(wrappedSubscriber);\n\n return {\n unsubscribe: () => {\n active = false;\n throttler.cancel();\n subscription.unsubscribe();\n },\n };\n }\n\n /**\n * Agent connectivity (delegated to RunHandler)\n */\n async connectAgent(\n params: CopilotKitCoreConnectAgentParams,\n ): Promise<import(\"@ag-ui/client\").RunAgentResult> {\n return this.runHandler.connectAgent(params);\n }\n\n stopAgent(params: CopilotKitCoreStopAgentParams): void {\n this.runHandler.abortCurrentRun(params.agent);\n params.agent.abortRun();\n }\n\n async runAgent(\n params: CopilotKitCoreRunAgentParams,\n ): Promise<import(\"@ag-ui/client\").RunAgentResult> {\n return this.runHandler.runAgent(params);\n }\n\n /**\n * Programmatically execute a registered frontend tool without going through an LLM turn.\n * The handler runs, render components show up in the UI, and both the tool call and\n * result messages are added to `agent.messages`.\n */\n async runTool(\n params: CopilotKitCoreRunToolParams,\n ): Promise<CopilotKitCoreRunToolResult> {\n return this.runHandler.runTool(params);\n }\n\n /**\n * State management (delegated to StateManager)\n */\n getStateByRun(\n agentId: string,\n threadId: string,\n runId: string,\n ): State | undefined {\n return this.stateManager.getStateByRun(agentId, threadId, runId);\n }\n\n getRunIdForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): string | undefined {\n return this.stateManager.getRunIdForMessage(agentId, threadId, messageId);\n }\n\n getRawEventForMessage(\n agentId: string,\n threadId: string,\n messageId: string,\n ): unknown {\n return this.stateManager.getRawEventForMessage(\n agentId,\n threadId,\n messageId,\n );\n }\n\n getRunIdsForThread(agentId: string, threadId: string): string[] {\n return this.stateManager.getRunIdsForThread(agentId, threadId);\n }\n\n /**\n * Internal method used by RunHandler to build frontend tools\n */\n private buildFrontendTools(agentId?: string): import(\"@ag-ui/client\").Tool[] {\n return this.runHandler.buildFrontendTools(agentId);\n }\n\n /**\n * Called before each follow-up agent run (after tool execution).\n *\n * When a frontend tool handler calls framework state setters (e.g. React's\n * setState), those updates are batched and deferred — they do not take effect\n * until the framework's scheduler runs (React uses MessageChannel).\n * useAgentContext registers context via useLayoutEffect, which runs\n * synchronously after React commits that deferred batch.\n *\n * Without yielding here, the follow-up runAgent reads the context store\n * synchronously while the deferred updates are still pending, producing stale\n * context for the next agent turn.\n *\n * Override in framework-specific subclasses to yield to the framework\n * scheduler before the follow-up run. The base implementation is a no-op\n * because non-React environments have no deferred state to flush.\n */\n async waitForPendingFrameworkUpdates(): Promise<void> {}\n}\n","import type { AbstractAgent, ToolCall } from \"@ag-ui/client\";\nimport type {\n InspectorMetadataV1,\n IntelligenceRuntimeInfo,\n RuntimeMode,\n RuntimeLicenseStatus,\n ThreadEndpointRuntimeInfo,\n} from \"@copilotkit/shared\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\n\n/**\n * Status of a tool call execution\n */\nexport enum ToolCallStatus {\n InProgress = \"inProgress\",\n Executing = \"executing\",\n Complete = \"complete\",\n}\n\nexport type CopilotRuntimeTransport = \"rest\" | \"single\" | \"auto\";\nexport type {\n InspectorMetadataV1,\n RuntimeMode,\n IntelligenceRuntimeInfo,\n RuntimeLicenseStatus,\n ThreadEndpointRuntimeInfo,\n};\n\n/**\n * Context passed to a frontend tool handler\n */\nexport type FrontendToolHandlerContext = {\n toolCall: ToolCall;\n /**\n * The agent that invoked the tool. Absent when the tool is invoked through\n * the WebMCP browser API (`document.modelContext`), which has no agent.\n */\n agent?: AbstractAgent;\n /** Aborted when `stopAgent()` is called. Handlers can check `signal.aborted`\n * or pass the signal to fetch/setTimeout to cooperatively cancel. */\n signal?: AbortSignal;\n /**\n * True when CopilotKit runs this call while restoring a thread's history on\n * connect, for a call that a previous page or client left without a result.\n * Absent for a call made by a live run. See `reconnectBehavior`.\n */\n isReplay?: boolean;\n};\n\n/**\n * What a frontend tool does with its own calls that are still unanswered when\n * a thread's history is restored (a reload, a remount, or a thread switch).\n * Only calls after the latest user message are eligible; older unanswered\n * calls remain historical and never resume work on reconnect.\n *\n * - `\"passive\"` (default) — show the call, but do not run the handler. Nothing\n * the handler did runs twice.\n * - `\"resume-pending\"` — run the handler for each call that has no result,\n * with `isReplay: true` in its context, then continue the run as usual\n * (follow-up included, unless `followUp` is false).\n *\n * Use `\"resume-pending\"` only for a handler that is safe to run more than\n * once. A call does not start twice at the same time in one CopilotKit\n * instance, but it can run again after a stop or a thread switch if its result\n * never reached the agent, and two tabs or devices that restore the same\n * thread can each run it.\n *\n * If one assistant message also calls a tool that stays passive, the follow-up\n * run sends that call without a result, which some model providers reject.\n * Opt in every tool the agent calls together, or set `followUp: false`.\n */\nexport type FrontendToolReconnectBehavior = \"passive\" | \"resume-pending\";\n\n/**\n * Annotations for a WebMCP tool, passed through to\n * `document.modelContext.registerTool`. Mirrors the WebMCP spec's tool\n * annotations. These are hints for browser agents only — they do not enforce\n * any policy on their own.\n */\nexport type WebMCPToolAnnotations = {\n /**\n * Hint that the tool does not modify state. Defaults to false.\n * Set it for read-only tools (search, status lookup, ...).\n */\n readOnlyHint?: boolean;\n /**\n * Hint that the tool's output may contain untrusted content\n * (e.g. user-generated or external content). Defaults to false.\n */\n untrustedContentHint?: boolean;\n};\n\n/**\n * WebMCP registration options for a frontend tool.\n */\nexport type WebMCPToolConfig = {\n /** Hints that tell browser agents how the tool behaves. */\n annotations?: WebMCPToolAnnotations;\n};\n\nexport type FrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n> = {\n /**\n * @internal Classifies local execution. Omitted means an ordinary frontend\n * tool. Pending calls in the latest user turn are eligible for restoration.\n * Human-in-the-loop handlers are restored from history replay;\n * other handlers only with `reconnectBehavior: \"resume-pending\"`. Tools\n * without a handler restore missing empty completion results automatically.\n * This field is not sent to the agent as part of the tool schema.\n */\n type?: \"frontend\" | \"human-in-the-loop\";\n name: string;\n description?: string;\n parameters?: StandardSchemaV1<any, T>;\n handler?: (args: T, context: FrontendToolHandlerContext) => Promise<unknown>;\n followUp?: boolean;\n /**\n * Whether to run the handler again for a call that is still unanswered when\n * the thread's history is restored. Defaults to `\"passive\"`. See\n * {@link FrontendToolReconnectBehavior}.\n */\n reconnectBehavior?: FrontendToolReconnectBehavior;\n /**\n * Optional agent ID to constrain this tool to a specific agent.\n * If specified, this tool will only be available to the specified agent.\n */\n agentId?: string;\n /**\n * Whether this tool is available to the agent.\n * Set to false to hide the tool from the agent without unregistering it.\n * Defaults to true when not specified.\n */\n available?: boolean;\n /**\n * Also expose this tool to browser agents through the WebMCP API\n * (`document.modelContext`) while keeping the normal agent registration.\n *\n * - `true` — register with default annotations.\n * - `{ annotations }` — register with the given WebMCP annotations.\n * - `false` / `undefined` — do not register.\n *\n * The tool's `handler` runs when a browser agent calls the tool; the handler\n * context then has no `agent`. No-op in environments without WebMCP support\n * (e.g. React Native, or browsers without the API enabled).\n */\n webmcp?: boolean | WebMCPToolConfig;\n};\n\nexport type Suggestion = {\n title: string;\n message: string;\n /** Indicates whether this suggestion is still being generated. */\n isLoading: boolean;\n /** Optional CSS class name applied to the suggestion pill. */\n className?: string;\n};\n\nexport type SuggestionAvailability =\n | \"before-first-message\"\n | \"after-first-message\"\n | \"always\"\n | \"disabled\";\n\nexport type DynamicSuggestionsConfig = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * When the suggestions are available. Defaults to \"after-first-message\".\n */\n available?: SuggestionAvailability;\n\n /**\n * The agent ID of the provider of the suggestions. Defaults to `\"default\"`.\n */\n providerAgentId?: string;\n\n /**\n * The agent ID of the consumer of the suggestions. Defaults to `\"*\"` (all agents).\n */\n consumerAgentId?: string;\n};\n\nexport type StaticSuggestionsConfig = {\n /**\n * The suggestions to display.\n */\n suggestions: Omit<Suggestion, \"isLoading\">[];\n\n /**\n * When the suggestions are available. Defaults to \"before-first-message\".\n */\n available?: SuggestionAvailability;\n\n /**\n * The agent ID of the consumer of the suggestions. Defaults to `\"*\"` (all agents).\n */\n consumerAgentId?: string;\n};\n\nexport type SuggestionsConfig =\n | DynamicSuggestionsConfig\n | StaticSuggestionsConfig;\n","export function completePartialMarkdown(input: string): string {\n let s = input;\n\n // Handle code fences first - use FIRST unmatched fence for proper nesting\n const fenceMatches = Array.from(s.matchAll(/^(\\s*)(`{3,}|~{3,})/gm));\n if (fenceMatches.length % 2 === 1) {\n const [, indent, fence] = fenceMatches[0]!;\n s += `\\n${indent}${fence}`;\n }\n\n // Identify incomplete links at the end and close them\n const incompleteLinkMatch = s.match(/\\[([^\\]]*)\\]\\(([^)]*)$/);\n if (incompleteLinkMatch) {\n s += \")\";\n }\n\n // State-based parsing\n interface OpenElement {\n type: string;\n marker: string;\n position: number;\n }\n\n const openElements: OpenElement[] = [];\n const chars = Array.from(s);\n\n // First pass: identify code block boundaries and inline code to avoid processing their content\n const codeBlockRanges: Array<{ start: number; end: number }> = [];\n const inlineCodeRanges: Array<{ start: number; end: number }> = [];\n\n // Find code block ranges\n let tempCodeFenceCount = 0;\n let currentCodeBlockStart = -1;\n\n for (let i = 0; i < chars.length; i++) {\n if (i === 0 || chars[i - 1] === \"\\n\") {\n const lineMatch = s.substring(i).match(/^(\\s*)(`{3,}|~{3,})/);\n if (lineMatch) {\n tempCodeFenceCount++;\n if (tempCodeFenceCount % 2 === 1) {\n currentCodeBlockStart = i;\n } else if (currentCodeBlockStart !== -1) {\n codeBlockRanges.push({\n start: currentCodeBlockStart,\n end: i + lineMatch[0].length,\n });\n currentCodeBlockStart = -1;\n }\n i += lineMatch[0].length - 1;\n }\n }\n }\n\n // Find inline code ranges\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\") {\n // Check if escaped\n let backslashCount = 0;\n for (let j = i - 1; j >= 0 && chars[j] === \"\\\\\"; j--) {\n backslashCount++;\n }\n if (backslashCount % 2 === 0) {\n // Not escaped - find the closing backtick\n for (let j = i + 1; j < chars.length; j++) {\n if (chars[j] === \"`\") {\n let closingBackslashCount = 0;\n for (let k = j - 1; k >= 0 && chars[k] === \"\\\\\"; k--) {\n closingBackslashCount++;\n }\n if (closingBackslashCount % 2 === 0) {\n inlineCodeRanges.push({ start: i, end: j + 1 });\n i = j;\n break;\n }\n }\n }\n }\n }\n }\n\n // Helper function to check if position is in code\n const isInCode = (pos: number): boolean => {\n return (\n codeBlockRanges.some((range) => pos >= range.start && pos < range.end) ||\n inlineCodeRanges.some((range) => pos >= range.start && pos < range.end)\n );\n };\n\n // Second pass: process markdown elements, skipping code regions\n for (let i = 0; i < chars.length; i++) {\n const char = chars[i];\n const nextChar = chars[i + 1];\n const prevChar = chars[i - 1];\n\n if (isInCode(i)) {\n continue;\n }\n\n // Handle brackets (but not if they're part of already-complete links)\n if (char === \"[\") {\n // Check if this is part of a complete link [text](url)\n let isCompleteLink = false;\n let bracketDepth = 1;\n let j = i + 1;\n\n // Find the matching ]\n while (j < chars.length && bracketDepth > 0) {\n if (chars[j] === \"[\" && !isInCode(j)) bracketDepth++;\n if (chars[j] === \"]\" && !isInCode(j)) bracketDepth--;\n j++;\n }\n\n // Check if followed by (\n if (bracketDepth === 0 && chars[j] === \"(\") {\n // Find the closing )\n let parenDepth = 1;\n j++;\n while (j < chars.length && parenDepth > 0) {\n if (chars[j] === \"(\" && !isInCode(j)) parenDepth++;\n if (chars[j] === \")\" && !isInCode(j)) parenDepth--;\n j++;\n }\n if (parenDepth === 0) {\n isCompleteLink = true;\n i = j - 1;\n continue;\n }\n }\n\n // This is a standalone bracket, treat as markdown\n if (!isCompleteLink) {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bracket\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bracket\", marker: \"[\", position: i });\n }\n }\n }\n\n // Handle double emphasis first (**, __, ~~) - these take precedence\n else if (char === \"*\" && nextChar === \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_star\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"bold_star\", marker: \"**\", position: i });\n }\n i++; // Skip next character\n } else if (char === \"_\" && nextChar === \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"bold_underscore\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"bold_underscore\",\n marker: \"__\",\n position: i,\n });\n }\n i++; // Skip next character\n } else if (char === \"~\" && nextChar === \"~\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"strike\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"strike\", marker: \"~~\", position: i });\n }\n i++; // Skip next character\n }\n\n // Handle single emphasis (*, _) - only if not part of double\n else if (char === \"*\" && prevChar !== \"*\" && nextChar !== \"*\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_star\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({ type: \"italic_star\", marker: \"*\", position: i });\n }\n } else if (char === \"_\" && prevChar !== \"_\" && nextChar !== \"_\") {\n const existingIndex = openElements.findIndex(\n (el) => el.type === \"italic_underscore\",\n );\n if (existingIndex !== -1) {\n openElements.splice(existingIndex, 1);\n } else {\n openElements.push({\n type: \"italic_underscore\",\n marker: \"_\",\n position: i,\n });\n }\n }\n }\n\n // Handle remaining unmatched backticks (outside of inline code ranges)\n let backtickCount = 0;\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] === \"`\" && !isInCode(i)) {\n backtickCount++;\n }\n }\n if (backtickCount % 2 === 1) {\n s += \"`\";\n }\n\n // Close remaining open elements in reverse order (LIFO stack semantics)\n openElements.sort((a, b) => b.position - a.position);\n\n const closers = openElements.map((el) => {\n switch (el.type) {\n case \"bracket\":\n return \"]\";\n case \"bold_star\":\n return \"**\";\n case \"bold_underscore\":\n return \"__\";\n case \"strike\":\n return \"~~\";\n case \"italic_star\":\n return \"*\";\n case \"italic_underscore\":\n return \"_\";\n default:\n return \"\";\n }\n });\n\n let result = s + closers.join(\"\");\n\n // Handle parentheses ONLY if not inside code\n const finalFenceMatches = Array.from(\n result.matchAll(/^(\\s*)(`{3,}|~{3,})/gm),\n );\n const hasUnclosedBacktick = (result.match(/`/g) || []).length % 2 === 1;\n const hasUnclosedCodeFence = finalFenceMatches.length % 2 === 1;\n\n let shouldCloseParens = !hasUnclosedBacktick && !hasUnclosedCodeFence;\n\n if (shouldCloseParens) {\n const lastOpenParen = result.lastIndexOf(\"(\");\n if (lastOpenParen !== -1) {\n // Check if this paren is inside a backtick pair\n const beforeParen = result.substring(0, lastOpenParen);\n const backticksBeforeParen = (beforeParen.match(/`/g) || []).length;\n if (backticksBeforeParen % 2 === 1) {\n shouldCloseParens = false;\n }\n }\n }\n\n if (shouldCloseParens) {\n const openParens = (result.match(/\\(/g) || []).length;\n const closeParens = (result.match(/\\)/g) || []).length;\n if (openParens > closeParens) {\n result += \")\".repeat(openParens - closeParens);\n }\n }\n\n return result;\n}\n","import { phoenixExponentialBackoff } from \"@copilotkit/shared\";\nimport type { Subscription } from \"rxjs\";\nimport { defer, firstValueFrom, merge, Observable, of } from \"rxjs\";\nimport {\n catchError,\n filter,\n map,\n mergeMap,\n share,\n shareReplay,\n switchMap,\n take,\n takeUntil,\n tap,\n withLatestFrom,\n} from \"rxjs/operators\";\nimport {\n createActionGroup,\n createEffect,\n createReducer,\n createSelector,\n createStore,\n empty,\n ofType,\n on,\n props,\n} from \"./utils/micro-redux\";\nimport type { Reducer, Store } from \"./utils/micro-redux\";\nimport type {\n RuntimeRequestInit,\n RuntimeRequestMeta,\n} from \"./utils/runtime-request\";\nimport {\n ɵphoenixChannel$,\n ɵphoenixSocket$,\n ɵobservePhoenixEvent$,\n ɵobservePhoenixJoinOutcome$,\n ɵobservePhoenixSocketHealth$,\n ɵobservePhoenixSocketSignals$,\n} from \"./utils/phoenix-observable\";\nimport type { ɵPhoenixChannelSession } from \"./utils/phoenix-observable\";\n\nconst THREADS_CHANNEL_EVENT = \"thread_metadata\";\nconst THREAD_RUN_ACTIVITY_CHANNEL_EVENT = \"thread_run_activity\";\nconst THREAD_SUBSCRIBE_PATH = \"/threads/subscribe\";\nconst MAX_SOCKET_RETRIES = 5;\nconst REQUEST_TIMEOUT_MS = 15_000;\n\ninterface ThreadRecord {\n id: string;\n organizationId: string;\n agentId: string;\n createdById: string;\n name: string | null;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n lastRunAt?: string;\n}\n\ninterface ThreadRuntimeContext {\n runtimeUrl: string;\n /**\n * Optional: `environment.fetch` is expected to be `ɵruntimeFetch`, which\n * already resolves and overlays the current core headers at send time\n * (#1937). Set explicitly only when the store's `fetch` does NOT already\n * carry headers.\n */\n headers?: Record<string, string>;\n wsUrl?: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n}\n\ntype ThreadMetadataEvent =\n | {\n operation: \"created\" | \"renamed\" | \"archived\" | \"unarchived\" | \"updated\";\n threadId: string;\n userId: string;\n organizationId: string;\n occurredAt: string;\n thread: ThreadRecord;\n }\n | {\n operation: \"deleted\";\n threadId: string;\n userId: string;\n organizationId: string;\n occurredAt: string;\n deleted: {\n id: string;\n };\n };\n\n/**\n * Internal notification emitted when Intelligence observes new run activity\n * for a thread without changing that thread's metadata row.\n */\nexport type ThreadRunActivityNotification = {\n type: \"thread_run_activity\";\n threadId: string;\n agentId?: string;\n runId?: string;\n eventType: string;\n latestEventId?: string;\n};\n\ntype ThreadRunActivityGatewayPayload = {\n threadId?: unknown;\n thread_id?: unknown;\n agentId?: unknown;\n agent_id?: unknown;\n runId?: unknown;\n run_id?: unknown;\n eventType?: unknown;\n event_type?: unknown;\n latestEventId?: unknown;\n latest_event_id?: unknown;\n};\n\ninterface ThreadListResponse {\n threads: ThreadRecord[];\n joinCode?: string | null;\n nextCursor?: string | null;\n}\n\ninterface ThreadMetadataCredentialsResponse {\n joinToken: string;\n}\n\ninterface MutationRequest {\n requestId: string;\n /** Session the mutation was dispatched in; stale results are dropped. */\n sessionId: number;\n path: string;\n method: \"PATCH\" | \"POST\" | \"DELETE\";\n body: Record<string, unknown>;\n}\n\ntype MutationOutcome =\n | { requestId: string; sessionId: number; ok: true }\n | { requestId: string; sessionId: number; ok: false; error: Error };\n\ninterface ThreadEnvironment {\n fetch: typeof fetch;\n /**\n * Optional callback invoked whenever a thread mutation (rename, archive,\n * unarchive, delete) is rejected by the server. Lets framework wrappers\n * surface a transient error toast without subscribing to the error\n * selector. The error is also recorded in `state.error` regardless.\n *\n * Fired after any rollback (delete) has been applied to local state.\n */\n onError?: (error: Error) => void;\n}\n\ninterface ThreadState {\n threads: ThreadRecord[];\n isLoading: boolean;\n isFetchingNextPage: boolean;\n error: Error | null;\n /**\n * Error from the most recent failed next-page (`fetchMore`) load, or `null`.\n * Tracked SEPARATELY from `error` so a paginated-load failure surfaces an\n * inline \"couldn't load more\" affordance without replacing the already-loaded\n * list with a full-panel error. Cleared when a fetch-more is retried or when\n * one succeeds; reset on context change / stop.\n */\n fetchMoreError: Error | null;\n context: ThreadRuntimeContext | null;\n sessionId: number;\n metadataCredentialsRequested: boolean;\n metadataJoinCode: string | null;\n nextCursor: string | null;\n /** Number of thread mutations currently awaiting a server response. */\n inFlightMutationCount: number;\n /**\n * Rows optimistically removed by an in-flight `delete`, keyed by the\n * originating request id. DELETE is the one mutation that rolls back on\n * rejection, so the removed row is parked here and restored if the server\n * rejects. Rename/archive/unarchive are optimistic no-rollback and do not\n * populate this map.\n */\n pendingDeletes: Record<string, ThreadRecord>;\n}\n\nconst initialThreadState: ThreadState = {\n threads: [],\n isLoading: false,\n isFetchingNextPage: false,\n error: null,\n fetchMoreError: null,\n context: null,\n sessionId: 0,\n metadataCredentialsRequested: false,\n metadataJoinCode: null,\n nextCursor: null,\n inFlightMutationCount: 0,\n pendingDeletes: {},\n};\n\nconst threadAdapterEvents = createActionGroup(\"Thread Adapter\", {\n started: empty(),\n stopped: empty(),\n contextChanged: props<{ context: ThreadRuntimeContext | null }>(),\n fetchNextPageRequested: empty(),\n renameRequested: props<{\n requestId: string;\n threadId: string;\n name: string;\n }>(),\n archiveRequested: props<{ requestId: string; threadId: string }>(),\n unarchiveRequested: props<{ requestId: string; threadId: string }>(),\n deleteRequested: props<{ requestId: string; threadId: string }>(),\n newThreadStarted: empty(),\n});\n\nconst threadRestEvents = createActionGroup(\"Thread REST\", {\n listRequested: props<{ sessionId: number }>(),\n listSucceeded: props<{\n sessionId: number;\n threads: ThreadRecord[];\n joinCode: string | null;\n nextCursor: string | null;\n }>(),\n listFailed: props<{ sessionId: number; error: Error }>(),\n nextPageSucceeded: props<{\n sessionId: number;\n threads: ThreadRecord[];\n nextCursor: string | null;\n }>(),\n nextPageFailed: props<{ sessionId: number; error: Error }>(),\n metadataCredentialsRequested: props<{ sessionId: number }>(),\n metadataCredentialsSucceeded: props<{\n sessionId: number;\n joinToken: string;\n }>(),\n metadataCredentialsFailed: props<{ sessionId: number; error: Error }>(),\n mutationFinished: props<{ outcome: MutationOutcome }>(),\n});\n\nconst threadSocketEvents = createActionGroup(\"Thread Socket\", {\n opened: props<{ sessionId: number }>(),\n errored: props<{ sessionId: number }>(),\n joinFailed: props<{ sessionId: number }>(),\n joinTimedOut: props<{ sessionId: number }>(),\n metadataReceived: props<{\n sessionId: number;\n payload: ThreadMetadataEvent;\n }>(),\n runActivityReceived: props<{\n sessionId: number;\n notification: ThreadRunActivityNotification;\n }>(),\n});\n\nconst threadDomainEvents = createActionGroup(\"Thread Domain\", {\n threadUpserted: props<{ sessionId: number; thread: ThreadRecord }>(),\n threadDeleted: props<{ sessionId: number; threadId: string }>(),\n});\n\nfunction sortThreadsByRecency(threads: ThreadRecord[]): ThreadRecord[] {\n // Prefer lastRunAt so the order reflects actual agent activity and stays\n // stable when a user performs metadata-only actions like archive or rename.\n // Fall back to updatedAt (and then createdAt) for threads that have never run.\n return [...threads].sort((left, right) => {\n const leftKey = left.lastRunAt ?? left.updatedAt ?? left.createdAt;\n const rightKey = right.lastRunAt ?? right.updatedAt ?? right.createdAt;\n return rightKey.localeCompare(leftKey);\n });\n}\n\nfunction upsertThread(\n threads: ThreadRecord[],\n thread: ThreadRecord,\n): ThreadRecord[] {\n const existingIndex = threads.findIndex((item) => item.id === thread.id);\n if (existingIndex === -1) {\n return sortThreadsByRecency([...threads, thread]);\n }\n\n const next = [...threads];\n next[existingIndex] = thread;\n return sortThreadsByRecency(next);\n}\n\n/**\n * Returns a non-empty string payload field or undefined for absent fields.\n */\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\n/**\n * REST `/threads` is agent-scoped. The Phoenix `user_meta` channel is not.\n * Drop live upserts that belong to a different agent, or one Inspector\n * `all-agents` flatten shows the same thread twice until a hard refresh.\n */\nfunction threadMetadataTargetsAgent(\n payload: ThreadMetadataEvent,\n agentId: string | undefined,\n): boolean {\n if (!agentId || payload.operation === \"deleted\") {\n return true;\n }\n\n const threadAgentId = optionalString(payload.thread.agentId);\n return !threadAgentId || threadAgentId === agentId;\n}\n\n/**\n * Converts gateway run-activity payloads into the internal TypeScript shape.\n */\nfunction normalizeThreadRunActivityNotification(\n payload: ThreadRunActivityGatewayPayload,\n): ThreadRunActivityNotification | null {\n const threadId = optionalString(payload.threadId ?? payload.thread_id);\n const eventType = optionalString(payload.eventType ?? payload.event_type);\n\n if (!threadId || !eventType) {\n return null;\n }\n\n return {\n type: \"thread_run_activity\",\n threadId,\n agentId: optionalString(payload.agentId ?? payload.agent_id),\n runId: optionalString(payload.runId ?? payload.run_id),\n eventType,\n latestEventId: optionalString(\n payload.latestEventId ?? payload.latest_event_id,\n ),\n };\n}\n\nconst threadReducer = createReducer(\n initialThreadState,\n on(threadAdapterEvents.contextChanged, (state: ThreadState, { context }) => ({\n ...state,\n context,\n sessionId: state.sessionId + 1,\n threads: [],\n isLoading: Boolean(context),\n isFetchingNextPage: false,\n error: null,\n fetchMoreError: null,\n metadataCredentialsRequested: false,\n metadataJoinCode: null,\n nextCursor: null,\n inFlightMutationCount: 0,\n pendingDeletes: {},\n })),\n on(threadAdapterEvents.stopped, (state: ThreadState) => ({\n ...state,\n threads: [],\n isLoading: false,\n isFetchingNextPage: false,\n error: null,\n fetchMoreError: null,\n metadataCredentialsRequested: false,\n metadataJoinCode: null,\n nextCursor: null,\n inFlightMutationCount: 0,\n pendingDeletes: {},\n })),\n on(threadRestEvents.listRequested, (state: ThreadState, { sessionId }) => {\n if (sessionId !== state.sessionId || !state.context) {\n return state;\n }\n\n return {\n ...state,\n isLoading: true,\n error: null,\n // A full-list refetch supersedes any prior fetch-more failure: the whole\n // list is being reloaded, so the stale inline \"couldn't load more\" banner\n // must not survive onto the fresh list.\n fetchMoreError: null,\n };\n }),\n on(\n threadRestEvents.listSucceeded,\n (state: ThreadState, { sessionId, threads, joinCode, nextCursor }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n const joinCodeChanged = joinCode !== state.metadataJoinCode;\n\n return {\n ...state,\n threads: sortThreadsByRecency(threads),\n isLoading: false,\n error: null,\n // The fresh full list also clears any lingering fetch-more error, in\n // case the list arrived without passing through `listRequested`.\n fetchMoreError: null,\n metadataJoinCode: joinCode,\n metadataCredentialsRequested: joinCodeChanged\n ? false\n : state.metadataCredentialsRequested,\n nextCursor,\n };\n },\n ),\n on(\n threadRestEvents.listFailed,\n (state: ThreadState, { sessionId, error }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n isLoading: false,\n error,\n };\n },\n ),\n on(\n threadRestEvents.nextPageSucceeded,\n (state: ThreadState, { sessionId, threads, nextCursor }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n let merged = state.threads;\n for (const thread of threads) {\n merged = upsertThread(merged, thread);\n }\n\n return {\n ...state,\n threads: merged,\n isFetchingNextPage: false,\n // A successful next page clears any prior fetch-more error.\n fetchMoreError: null,\n nextCursor,\n };\n },\n ),\n on(\n threadRestEvents.nextPageFailed,\n (state: ThreadState, { sessionId, error }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n // A failed next-page load records the error on the DEDICATED fetch-more\n // channel — NOT `state.error` — so the already-loaded list is preserved\n // and the drawer renders an inline \"couldn't load more — retry\" panel\n // rather than replacing the whole list with a full-panel error.\n return {\n ...state,\n isFetchingNextPage: false,\n fetchMoreError: error,\n };\n },\n ),\n on(\n threadRestEvents.metadataCredentialsFailed,\n (state: ThreadState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n // Non-fatal: the metadata-credentials (realtime join-token) fetch runs\n // AFTER the thread list has already loaded and only powers the realtime\n // channel. A failure means realtime won't connect, but the fetched list\n // is still valid — so we do NOT write `state.error` (which would replace\n // the whole list with a \"couldn't load\" panel). The failure is surfaced\n // as a diagnostic warning instead (socketDiagnosticsEffect), mirroring the\n // stay-stale handling of a realtime channel join failure. Clear the\n // request latch so a later list refresh can retry realtime setup.\n return {\n ...state,\n metadataCredentialsRequested: false,\n };\n },\n ),\n on(\n threadRestEvents.metadataCredentialsRequested,\n (state: ThreadState, { sessionId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n metadataCredentialsRequested: true,\n };\n },\n ),\n on(threadAdapterEvents.fetchNextPageRequested, (state: ThreadState) => {\n if (!state.nextCursor || state.isFetchingNextPage) {\n return state;\n }\n\n return {\n ...state,\n isFetchingNextPage: true,\n // Clear any prior fetch-more error so a retry dismisses the inline panel\n // immediately while the next-page request is in flight.\n fetchMoreError: null,\n };\n }),\n on(\n threadAdapterEvents.renameRequested,\n (state: ThreadState, { threadId, name }) => {\n // Optimistic, no-rollback: reflect the new name immediately. A failure\n // surfaces via `error`/`onError` but the local row is left as-is; a\n // realtime metadata event or refetch reconciles the true server state.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, { ...existing, name }),\n inFlightMutationCount,\n };\n },\n ),\n on(\n threadAdapterEvents.archiveRequested,\n (state: ThreadState, { threadId }) => {\n // Optimistic, no-rollback. When archived threads are hidden, drop the\n // row; otherwise flip the flag in place. Note: archiving the active\n // thread is non-destructive — the wrapper keeps viewing it.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n if (!state.context?.includeArchived) {\n return {\n ...state,\n threads: state.threads.filter((thread) => thread.id !== threadId),\n inFlightMutationCount,\n };\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, { ...existing, archived: true }),\n inFlightMutationCount,\n };\n },\n ),\n on(\n threadAdapterEvents.unarchiveRequested,\n (state: ThreadState, { threadId }) => {\n // Optimistic, no-rollback.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, { ...existing, archived: false }),\n inFlightMutationCount,\n };\n },\n ),\n on(\n threadAdapterEvents.deleteRequested,\n (state: ThreadState, { requestId, threadId }) => {\n // Optimistic WITH rollback: remove the row now, but park it under the\n // request id so it can be restored if the server rejects the delete.\n const existing = state.threads.find((thread) => thread.id === threadId);\n const inFlightMutationCount = state.inFlightMutationCount + 1;\n if (!existing) {\n return { ...state, inFlightMutationCount };\n }\n\n return {\n ...state,\n threads: state.threads.filter((thread) => thread.id !== threadId),\n pendingDeletes: { ...state.pendingDeletes, [requestId]: existing },\n inFlightMutationCount,\n };\n },\n ),\n on(threadAdapterEvents.newThreadStarted, (state: ThreadState) => ({\n // Lazy creation: a fresh client-side thread does NOT add a phantom row —\n // it only materializes once its first run persists server-side. The\n // store-side concern is purely to clear any stale error so the welcome\n // screen renders cleanly; the wrapper owns the active/explicit threadId.\n ...state,\n error: null,\n })),\n on(threadRestEvents.mutationFinished, (state: ThreadState, { outcome }) => {\n // Drop results from a superseded session. `contextChanged`/`stopped` already\n // reset `threads`, `pendingDeletes`, and `inFlightMutationCount`, so a\n // mutation that resolves after the context switched must not write an error,\n // fire onError (guarded in subscribeErrors), or roll a stale row back into\n // the new list. Mirrors every other session-scoped handler.\n if (outcome.sessionId !== state.sessionId) {\n return state;\n }\n\n const inFlightMutationCount = Math.max(0, state.inFlightMutationCount - 1);\n\n if (outcome.ok) {\n // Success: drop any parked delete-rollback snapshot for this request.\n if (state.pendingDeletes[outcome.requestId] === undefined) {\n return { ...state, inFlightMutationCount };\n }\n\n const { [outcome.requestId]: _settled, ...rest } = state.pendingDeletes;\n return { ...state, inFlightMutationCount, pendingDeletes: rest };\n }\n\n // Failure: surface the error. For a rejected delete, restore the row that\n // was optimistically removed (rollback). Other mutations are no-rollback.\n const rolledBack = state.pendingDeletes[outcome.requestId];\n if (rolledBack === undefined) {\n return { ...state, inFlightMutationCount, error: outcome.error };\n }\n\n const { [outcome.requestId]: _restored, ...rest } = state.pendingDeletes;\n return {\n ...state,\n threads: upsertThread(state.threads, rolledBack),\n pendingDeletes: rest,\n inFlightMutationCount,\n error: outcome.error,\n };\n }),\n on(\n threadDomainEvents.threadUpserted,\n (state: ThreadState, { sessionId, thread }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n threads: upsertThread(state.threads, thread),\n };\n },\n ),\n on(\n threadDomainEvents.threadDeleted,\n (state: ThreadState, { sessionId, threadId }) => {\n if (sessionId !== state.sessionId) {\n return state;\n }\n\n return {\n ...state,\n threads: state.threads.filter((thread) => thread.id !== threadId),\n };\n },\n ),\n) as Reducer<ThreadState>;\n\n/**\n * The set of memoized thread selectors bound to a single store instance.\n *\n * @see createThreadSelectors\n */\ninterface ThreadSelectors {\n threads: (state: ThreadState) => ThreadRecord[];\n isLoading: (state: ThreadState) => boolean;\n error: (state: ThreadState) => Error | null;\n fetchMoreError: (state: ThreadState) => Error | null;\n hasNextPage: (state: ThreadState) => boolean;\n isFetchingNextPage: (state: ThreadState) => boolean;\n isMutating: (state: ThreadState) => boolean;\n}\n\n/**\n * Builds a fresh set of memoized thread selectors.\n *\n * Each `createSelector` closure owns a private one-entry cache. Sharing a\n * single module-level selector instance across multiple concurrent stores\n * (e.g. a `<CopilotThreadsDrawer>` plus an independent `useThreads`) makes every\n * cross-store emission a cache miss, defeating memoization and risking\n * emission instability for any future selector that allocates a new\n * object/array. Creating a per-store instance keeps each store's cache\n * isolated so concurrent stores never thrash one another.\n */\nfunction createThreadSelectors(): ThreadSelectors {\n return {\n threads: createSelector((state: ThreadState) => state.threads),\n isLoading: createSelector((state: ThreadState) => state.isLoading),\n error: createSelector((state: ThreadState) => state.error),\n fetchMoreError: createSelector(\n (state: ThreadState) => state.fetchMoreError,\n ),\n hasNextPage: createSelector(\n (state: ThreadState) => state.nextCursor != null,\n ),\n isFetchingNextPage: createSelector(\n (state: ThreadState) => state.isFetchingNextPage,\n ),\n isMutating: createSelector(\n (state: ThreadState) => state.inFlightMutationCount > 0,\n ),\n };\n}\n\n// Standalone selector instances retained for callers that read a one-off\n// snapshot (e.g. `selectThreads(store.getState())`) where cross-store memo\n// isolation is irrelevant. Subscriptions through `store.select(...)` should\n// prefer the per-store `ThreadStore.selectors` bundle below.\nconst standaloneSelectors = createThreadSelectors();\nconst selectThreads = standaloneSelectors.threads;\nconst selectThreadsIsLoading = standaloneSelectors.isLoading;\nconst selectThreadsError = standaloneSelectors.error;\nconst selectFetchMoreError = standaloneSelectors.fetchMoreError;\nconst selectHasNextPage = standaloneSelectors.hasNextPage;\nconst selectIsFetchingNextPage = standaloneSelectors.isFetchingNextPage;\nconst selectIsMutating = standaloneSelectors.isMutating;\n\ninterface ThreadStore {\n start(): void;\n stop(): void;\n setContext(context: ThreadRuntimeContext | null): void;\n /** Re-fetches the thread list without resetting the current list to empty. */\n refresh(): void;\n /**\n * Re-fetches the thread list without resetting the current list to empty.\n *\n * Public, design-named alias of {@link refresh} used by the drawer's\n * error-state Retry affordance and the Active/All filter-change refetch.\n */\n refetchThreads(): void;\n /**\n * Resets to a fresh, client-side thread so the welcome screen can show.\n *\n * Lazy creation: no phantom row is added to the list — the new thread only\n * materializes once its first run persists server-side. This is distinct\n * from selecting an existing thread (which the wrapper marks *explicit*,\n * suppressing the welcome screen): the thread produced here is NOT explicit.\n */\n startNewThread(): void;\n fetchNextPage(): void;\n renameThread(threadId: string, name: string): Promise<void>;\n archiveThread(threadId: string): Promise<void>;\n unarchiveThread(threadId: string): Promise<void>;\n deleteThread(threadId: string): Promise<void>;\n /**\n * Subscribes to synthetic run-activity notifications without changing the\n * thread metadata list.\n */\n subscribeToRunActivity?(\n callback: (notification: ThreadRunActivityNotification) => void,\n ): Subscription;\n getState(): ThreadState;\n /**\n * Returns a stable initial snapshot for server-side rendering.\n *\n * `useSyncExternalStore` requires a `getServerSnapshot` during SSR/prerender\n * (e.g. Next.js); without one React throws \"Missing getServerSnapshot\". The\n * returned reference is stable across calls so React does not loop. There is\n * no client-side thread data during prerender, so this is the empty initial\n * state.\n */\n getServerState(): ThreadState;\n select: Store<ThreadState>[\"select\"];\n /**\n * Memoized selectors bound to THIS store instance.\n *\n * Subscriptions should pass these to {@link select} (e.g.\n * `store.select(store.selectors.threads)`) so each store keeps its own\n * one-entry memo cache. Sharing the module-level singletons across\n * concurrent stores defeats memoization and risks emission instability.\n */\n selectors: ThreadSelectors;\n}\n\nlet threadRequestId = 0;\n\nfunction createThreadRequestId(): string {\n threadRequestId += 1;\n return `thread-request-${threadRequestId}`;\n}\n\nfunction threadFromFetch<T>(\n input: string,\n init: RequestInit & {\n selector: (response: Response) => Promise<T>;\n fetch: typeof fetch;\n timeoutMs?: number;\n nonCritical?: boolean;\n },\n): Observable<T> {\n return new Observable<T>((subscriber) => {\n const {\n fetch: fetchImpl,\n selector,\n signal,\n timeoutMs,\n nonCritical,\n ...requestInit\n } = init;\n const controller = new AbortController();\n const runtimeRequest: RuntimeRequestMeta = {\n ...(nonCritical ? { nonCritical: true } : {}),\n ...(timeoutMs === undefined ? {} : { selfBounded: true }),\n };\n let timedOut = false;\n const abortRequest = () => controller.abort();\n\n if (signal?.aborted) {\n abortRequest();\n } else {\n signal?.addEventListener(\"abort\", abortRequest, { once: true });\n }\n\n const timeoutId =\n timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n timedOut = true;\n runtimeRequest.timedOut = true;\n abortRequest();\n }, timeoutMs);\n\n const requestInitWithMeta: RuntimeRequestInit = {\n ...requestInit,\n signal: controller.signal,\n ɵruntimeRequest: runtimeRequest,\n };\n\n fetchImpl(input, requestInitWithMeta)\n .then((response) => selector(response))\n .then((value) => {\n if (subscriber.closed) return;\n subscriber.next(value);\n subscriber.complete();\n })\n .catch((error: unknown) => {\n if (!subscriber.closed) {\n subscriber.error(\n timedOut ? new Error(\"Request timed out\") : (error as Error),\n );\n }\n });\n\n return () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n signal?.removeEventListener(\"abort\", abortRequest);\n abortRequest();\n };\n });\n}\n\nfunction createThreadFetchObservable(\n environment: ThreadEnvironment,\n context: ThreadRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof threadRestEvents.listSucceeded>\n | ReturnType<typeof threadRestEvents.listFailed>\n> {\n return defer(() => {\n const params: Record<string, string> = {\n agentId: context.agentId,\n };\n if (context.includeArchived) params.includeArchived = \"true\";\n if (context.limit != null) params.limit = String(context.limit);\n\n const qs = new URLSearchParams(params);\n return threadFromFetch(`${context.runtimeUrl}/threads?${qs.toString()}`, {\n selector: (response) => {\n if (!response.ok) {\n throw new Error(`Failed to fetch threads: ${response.status}`);\n }\n\n return response.json() as Promise<ThreadListResponse>;\n },\n fetch: environment.fetch,\n timeoutMs: REQUEST_TIMEOUT_MS,\n method: \"GET\",\n headers: { ...context.headers },\n }).pipe(\n map((data) =>\n threadRestEvents.listSucceeded({\n sessionId,\n threads: data.threads,\n joinCode:\n typeof data.joinCode === \"string\" && data.joinCode.length > 0\n ? data.joinCode\n : null,\n nextCursor: data.nextCursor ?? null,\n }),\n ),\n catchError((error) => {\n return of(\n threadRestEvents.listFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n );\n });\n}\n\nfunction createThreadMetadataCredentialsObservable(\n environment: ThreadEnvironment,\n context: ThreadRuntimeContext,\n sessionId: number,\n): Observable<\n | ReturnType<typeof threadRestEvents.metadataCredentialsSucceeded>\n | ReturnType<typeof threadRestEvents.metadataCredentialsFailed>\n> {\n return defer(() => {\n return threadFromFetch(`${context.runtimeUrl}${THREAD_SUBSCRIBE_PATH}`, {\n selector: async (response) => {\n if (!response.ok) {\n throw new Error(\n `Failed to fetch thread metadata credentials: ${response.status}`,\n );\n }\n\n return response.json() as Promise<ThreadMetadataCredentialsResponse>;\n },\n fetch: environment.fetch,\n timeoutMs: REQUEST_TIMEOUT_MS,\n nonCritical: true,\n method: \"POST\",\n headers: {\n ...context.headers,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({}),\n }).pipe(\n map((data) => {\n if (typeof data.joinToken !== \"string\" || data.joinToken.length === 0) {\n throw new Error(\"missing joinToken\");\n }\n\n return threadRestEvents.metadataCredentialsSucceeded({\n sessionId,\n joinToken: data.joinToken,\n });\n }),\n catchError((error) => {\n return of(\n threadRestEvents.metadataCredentialsFailed({\n sessionId,\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n );\n }),\n );\n });\n}\n\nfunction createThreadMutationObservable(\n environment: ThreadEnvironment,\n context: ThreadRuntimeContext,\n request: MutationRequest,\n): Observable<ReturnType<typeof threadRestEvents.mutationFinished>> {\n return defer(() => {\n return threadFromFetch(`${context.runtimeUrl}${request.path}`, {\n selector: async (response) => {\n if (!response.ok) {\n throw new Error(`Request failed: ${response.status}`);\n }\n\n return null;\n },\n fetch: environment.fetch,\n method: request.method,\n headers: {\n ...context.headers,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(request.body),\n }).pipe(\n map(() =>\n threadRestEvents.mutationFinished({\n outcome: {\n requestId: request.requestId,\n sessionId: request.sessionId,\n ok: true,\n },\n }),\n ),\n catchError((error) => {\n return of(\n threadRestEvents.mutationFinished({\n outcome: {\n requestId: request.requestId,\n sessionId: request.sessionId,\n ok: false,\n error: error instanceof Error ? error : new Error(String(error)),\n },\n }),\n );\n }),\n );\n });\n}\n\nfunction createThreadStore(environment: ThreadEnvironment): ThreadStore {\n // Per-store selector instances keep this store's memo cache isolated from\n // any other concurrent store (see createThreadSelectors).\n const selectors = createThreadSelectors();\n\n const bootstrapEffect = createEffect(\n (\n actions$,\n state$: Observable<ThreadState>,\n ): Observable<ReturnType<typeof threadRestEvents.listRequested>> =>\n actions$.pipe(\n ofType(threadAdapterEvents.contextChanged),\n withLatestFrom(state$),\n filter(([, state]) => Boolean(state.context)),\n map(([, state]) =>\n threadRestEvents.listRequested({ sessionId: state.sessionId }),\n ),\n ),\n );\n\n const fetchEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.listRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is ThreadRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createThreadFetchObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const metadataCredentialsEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.listSucceeded),\n withLatestFrom(state$),\n filter(([action, state]) => {\n return (\n action.sessionId === state.sessionId &&\n !state.metadataCredentialsRequested &&\n Boolean(state.context?.wsUrl) &&\n Boolean(state.metadataJoinCode)\n );\n }),\n map(([action]) =>\n threadRestEvents.metadataCredentialsRequested({\n sessionId: action.sessionId,\n }),\n ),\n ),\n );\n\n const metadataCredentialsFetchEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.metadataCredentialsRequested),\n switchMap((action) =>\n state$.pipe(\n map((state) => state.context),\n filter((context): context is ThreadRuntimeContext =>\n Boolean(context),\n ),\n take(1),\n map((context) => ({ action, context })),\n takeUntil(\n actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n ),\n ),\n switchMap(({ action: currentAction, context }) =>\n createThreadMetadataCredentialsObservable(\n environment,\n context,\n currentAction.sessionId,\n ),\n ),\n ),\n ),\n ),\n );\n\n const socketEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadRestEvents.metadataCredentialsSucceeded),\n withLatestFrom(state$),\n filter(([action, state]) => {\n return (\n action.sessionId === state.sessionId &&\n Boolean(state.context?.wsUrl)\n );\n }),\n switchMap(([action, state]) => {\n const context = state.context as ThreadRuntimeContext;\n const joinToken = action.joinToken as string;\n const joinCode = state.metadataJoinCode as string;\n const shutdown$ = actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n );\n\n return defer(() => {\n const socket$ = ɵphoenixSocket$({\n url: context.wsUrl!,\n options: {\n params: { join_token: joinToken },\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n },\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const channel$ = ɵphoenixChannel$({\n socket$,\n topic: `user_meta:${joinCode}`,\n }).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n const socketSignals$ =\n ɵobservePhoenixSocketSignals$(socket$).pipe(share());\n const fatalSocketShutdown$ = ɵobservePhoenixSocketHealth$(\n socketSignals$,\n MAX_SOCKET_RETRIES,\n ).pipe(\n catchError(() => {\n console.warn(\n `[threads] WebSocket failed after ${MAX_SOCKET_RETRIES} attempts, giving up`,\n );\n return of(undefined);\n }),\n share(),\n );\n const socketLifecycle$ = socketSignals$.pipe(\n map((signal) =>\n signal.type === \"open\"\n ? threadSocketEvents.opened({ sessionId: action.sessionId })\n : threadSocketEvents.errored({ sessionId: action.sessionId }),\n ),\n );\n const metadata$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<ThreadMetadataEvent>(\n channel,\n THREADS_CHANNEL_EVENT,\n ),\n ),\n map((payload) =>\n threadSocketEvents.metadataReceived({\n sessionId: action.sessionId,\n payload,\n }),\n ),\n );\n const runActivity$ = channel$.pipe(\n switchMap(({ channel }: ɵPhoenixChannelSession) =>\n ɵobservePhoenixEvent$<ThreadRunActivityGatewayPayload>(\n channel,\n THREAD_RUN_ACTIVITY_CHANNEL_EVENT,\n ),\n ),\n map((payload) => normalizeThreadRunActivityNotification(payload)),\n filter(\n (notification): notification is ThreadRunActivityNotification =>\n notification !== null,\n ),\n map((notification) =>\n threadSocketEvents.runActivityReceived({\n sessionId: action.sessionId,\n notification,\n }),\n ),\n );\n const joinOutcome$ = ɵobservePhoenixJoinOutcome$(channel$).pipe(\n filter((outcome) => outcome.type !== \"joined\"),\n map((outcome) =>\n outcome.type === \"timeout\"\n ? threadSocketEvents.joinTimedOut({\n sessionId: action.sessionId,\n })\n : threadSocketEvents.joinFailed({\n sessionId: action.sessionId,\n }),\n ),\n );\n\n return merge(\n socketLifecycle$,\n metadata$,\n runActivity$,\n joinOutcome$,\n ).pipe(takeUntil(merge(shutdown$, fatalSocketShutdown$)));\n });\n }),\n ),\n );\n\n const realtimeMappingEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadSocketEvents.metadataReceived),\n withLatestFrom(state$),\n filter(\n ([action, state]) =>\n action.sessionId === state.sessionId &&\n threadMetadataTargetsAgent(action.payload, state.context?.agentId),\n ),\n map(([action, state]) => {\n if (action.payload.operation === \"deleted\") {\n return threadDomainEvents.threadDeleted({\n sessionId: action.sessionId,\n threadId: action.payload.deleted.id,\n });\n }\n\n // When includeArchived is false, an \"archived\" event should remove\n // the thread from the local list rather than upserting it.\n if (\n action.payload.operation === \"archived\" &&\n !state.context?.includeArchived\n ) {\n return threadDomainEvents.threadDeleted({\n sessionId: action.sessionId,\n threadId: action.payload.threadId,\n });\n }\n\n return threadDomainEvents.threadUpserted({\n sessionId: action.sessionId,\n thread: action.payload.thread,\n });\n }),\n ),\n );\n\n // Observability-only effect for realtime-join health. The socket effect\n // dispatches `joinFailed`/`joinTimedOut`/`errored` but the reducer has no\n // handler for them by design: a transient WS drop while the (already\n // fetched) list is present must NOT become a hard list error — the user\n // keeps the stale list. Previously these actions were silently swallowed,\n // leaving a realtime-join failure with zero signal. This effect emits a\n // non-fatal warning (mirroring the MAX_SOCKET_RETRIES warn) so the failure\n // is diagnosable. Session-guarded so a superseded session stays quiet.\n const socketDiagnosticsEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(\n threadSocketEvents.joinFailed,\n threadSocketEvents.joinTimedOut,\n threadSocketEvents.errored,\n threadRestEvents.metadataCredentialsFailed,\n ),\n withLatestFrom(state$),\n filter(([action, state]) => action.sessionId === state.sessionId),\n tap(([action]) => {\n const reason = threadSocketEvents.joinTimedOut.match(action)\n ? \"channel join timed out\"\n : threadSocketEvents.joinFailed.match(action)\n ? \"channel join was rejected\"\n : threadRestEvents.metadataCredentialsFailed.match(action)\n ? \"metadata credentials fetch failed\"\n : \"socket errored\";\n console.warn(\n `[threads] realtime ${reason}; the thread list may be stale until reconnect`,\n );\n }),\n ),\n { dispatch: false },\n );\n\n const fetchNextPageEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(threadAdapterEvents.fetchNextPageRequested),\n withLatestFrom(state$),\n filter(\n ([, state]) => Boolean(state.context) && Boolean(state.nextCursor),\n ),\n switchMap(([, state]) => {\n const context = state.context as ThreadRuntimeContext;\n const params: Record<string, string> = {\n agentId: context.agentId,\n cursor: state.nextCursor!,\n };\n if (context.includeArchived) params.includeArchived = \"true\";\n if (context.limit != null) params.limit = String(context.limit);\n\n return threadFromFetch(\n `${context.runtimeUrl}/threads?${new URLSearchParams(params).toString()}`,\n {\n selector: (response) => {\n if (!response.ok) {\n throw new Error(\n `Failed to fetch next page: ${response.status}`,\n );\n }\n\n return response.json() as Promise<ThreadListResponse>;\n },\n fetch: environment.fetch,\n timeoutMs: REQUEST_TIMEOUT_MS,\n method: \"GET\",\n headers: { ...context.headers },\n },\n ).pipe(\n map((data) =>\n threadRestEvents.nextPageSucceeded({\n sessionId: state.sessionId,\n threads: data.threads,\n nextCursor: data.nextCursor ?? null,\n }),\n ),\n catchError((error) =>\n of(\n threadRestEvents.nextPageFailed({\n sessionId: state.sessionId,\n error:\n error instanceof Error ? error : new Error(String(error)),\n }),\n ),\n ),\n takeUntil(\n actions$.pipe(\n ofType(\n threadAdapterEvents.contextChanged,\n threadAdapterEvents.stopped,\n ),\n ),\n ),\n );\n }),\n ),\n );\n\n const mutationEffect = createEffect(\n (actions$, state$: Observable<ThreadState>) =>\n actions$.pipe(\n ofType(\n threadAdapterEvents.renameRequested,\n threadAdapterEvents.archiveRequested,\n threadAdapterEvents.unarchiveRequested,\n threadAdapterEvents.deleteRequested,\n ),\n withLatestFrom(state$),\n mergeMap(([action, state]) => {\n // Capture the dispatching session so a result that resolves after a\n // `contextChanged` is dropped by the reducer instead of leaking an\n // error/onError/rollback into the new session. The mergeMap is not\n // cancelled on context change, so the session tag is the guard.\n const sessionId = state.sessionId;\n const context = state.context;\n if (!context?.runtimeUrl) {\n const requestId = action.requestId;\n return of(\n threadRestEvents.mutationFinished({\n outcome: {\n requestId,\n sessionId,\n ok: false,\n error: new Error(\"Runtime URL is not configured\"),\n },\n }),\n );\n }\n\n const commonBody = {\n agentId: context.agentId,\n };\n\n if (threadAdapterEvents.renameRequested.match(action)) {\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"PATCH\",\n path: `/threads/${encodeURIComponent(action.threadId)}`,\n body: {\n ...commonBody,\n name: action.name,\n },\n });\n }\n\n if (threadAdapterEvents.archiveRequested.match(action)) {\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"POST\",\n path: `/threads/${encodeURIComponent(action.threadId)}/archive`,\n body: commonBody,\n });\n }\n\n if (threadAdapterEvents.unarchiveRequested.match(action)) {\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"PATCH\",\n path: `/threads/${encodeURIComponent(action.threadId)}`,\n body: {\n ...commonBody,\n archived: false,\n },\n });\n }\n\n return createThreadMutationObservable(environment, context, {\n requestId: action.requestId,\n sessionId,\n method: \"DELETE\",\n path: `/threads/${encodeURIComponent(action.threadId)}`,\n body: commonBody,\n });\n }),\n ),\n );\n\n const store = createStore<ThreadState>({\n reducer: threadReducer,\n effects: [\n bootstrapEffect,\n fetchEffect,\n metadataCredentialsEffect,\n metadataCredentialsFetchEffect,\n socketEffect,\n realtimeMappingEffect,\n socketDiagnosticsEffect,\n fetchNextPageEffect,\n mutationEffect,\n ],\n });\n\n function trackMutation(\n dispatchAction:\n | ReturnType<typeof threadAdapterEvents.renameRequested>\n | ReturnType<typeof threadAdapterEvents.archiveRequested>\n | ReturnType<typeof threadAdapterEvents.unarchiveRequested>\n | ReturnType<typeof threadAdapterEvents.deleteRequested>,\n ): Promise<void> {\n const completion$ = merge(\n store.actions$.pipe(\n ofType(threadRestEvents.mutationFinished),\n filter(\n (action) => action.outcome.requestId === dispatchAction.requestId,\n ),\n map((action) => action.outcome),\n ),\n store.actions$.pipe(\n ofType(threadAdapterEvents.stopped),\n map(\n () =>\n ({\n requestId: dispatchAction.requestId,\n sessionId: store.getState().sessionId,\n ok: false,\n error: new Error(\n \"Thread store stopped before mutation completed\",\n ),\n }) satisfies MutationOutcome,\n ),\n ),\n ).pipe(take(1));\n\n const resultPromise = firstValueFrom(completion$).then((outcome) => {\n if (outcome.ok) {\n return;\n }\n\n throw outcome.error;\n });\n\n store.dispatch(dispatchAction);\n return resultPromise;\n }\n\n // Surface mutation rejections to the optional environment callback. The\n // reducer has already applied any delete rollback by the time this fires\n // (the store reduces state before re-emitting the action), so consumers see\n // a consistent list when they react to the error.\n let errorSubscription: Subscription | null = null;\n const subscribeErrors = (): void => {\n if (!environment.onError || errorSubscription) {\n return;\n }\n\n errorSubscription = store.actions$\n .pipe(\n ofType(threadRestEvents.mutationFinished),\n // Drop stale-session failures: a mutation that rejects after a\n // `contextChanged` belongs to a context the user already left, so\n // surfacing it would fire onError for the wrong session. The reducer\n // applies the same guard before writing `state.error`.\n filter(\n (action) =>\n !action.outcome.ok &&\n action.outcome.sessionId === store.getState().sessionId,\n ),\n )\n .subscribe((action) => {\n if (!action.outcome.ok) {\n environment.onError?.(action.outcome.error);\n }\n });\n };\n\n return {\n start(): void {\n store.init();\n subscribeErrors();\n store.dispatch(threadAdapterEvents.started());\n },\n stop(): void {\n store.dispatch(threadAdapterEvents.stopped());\n errorSubscription?.unsubscribe();\n errorSubscription = null;\n store.stop();\n },\n setContext(context: ThreadRuntimeContext | null): void {\n store.dispatch(threadAdapterEvents.contextChanged({ context }));\n },\n refresh(): void {\n const { sessionId, context } = store.getState();\n if (!context) return;\n store.dispatch(threadRestEvents.listRequested({ sessionId }));\n },\n refetchThreads(): void {\n const { sessionId, context } = store.getState();\n if (!context) return;\n store.dispatch(threadRestEvents.listRequested({ sessionId }));\n },\n startNewThread(): void {\n store.dispatch(threadAdapterEvents.newThreadStarted());\n },\n fetchNextPage(): void {\n store.dispatch(threadAdapterEvents.fetchNextPageRequested());\n },\n renameThread(threadId: string, name: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.renameRequested({\n requestId: createThreadRequestId(),\n threadId,\n name,\n }),\n );\n },\n archiveThread(threadId: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.archiveRequested({\n requestId: createThreadRequestId(),\n threadId,\n }),\n );\n },\n unarchiveThread(threadId: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.unarchiveRequested({\n requestId: createThreadRequestId(),\n threadId,\n }),\n );\n },\n deleteThread(threadId: string): Promise<void> {\n return trackMutation(\n threadAdapterEvents.deleteRequested({\n requestId: createThreadRequestId(),\n threadId,\n }),\n );\n },\n subscribeToRunActivity(\n callback: (notification: ThreadRunActivityNotification) => void,\n ): Subscription {\n return store.actions$\n .pipe(\n ofType(threadSocketEvents.runActivityReceived),\n filter((action) => action.sessionId === store.getState().sessionId),\n map((action) => action.notification),\n )\n .subscribe(callback);\n },\n getState(): ThreadState {\n return store.getState();\n },\n getServerState(): ThreadState {\n return initialThreadState;\n },\n select: store.select.bind(store),\n selectors,\n };\n}\n\nexport type ɵThread = ThreadRecord;\nexport type ɵThreadRuntimeContext = ThreadRuntimeContext;\nexport type ɵThreadMetadataEvent = ThreadMetadataEvent;\nexport type ɵThreadEnvironment = ThreadEnvironment;\nexport type ɵThreadStore = ThreadStore;\nexport type ɵThreadSelectors = ThreadSelectors;\nexport const ɵthreadAdapterEvents = threadAdapterEvents;\nexport const ɵcreateThreadSelectors = createThreadSelectors;\nexport const ɵselectThreads = selectThreads;\nexport const ɵselectThreadsIsLoading = selectThreadsIsLoading;\nexport const ɵselectThreadsError = selectThreadsError;\nexport const ɵselectFetchMoreError = selectFetchMoreError;\nexport const ɵselectHasNextPage = selectHasNextPage;\nexport const ɵselectIsFetchingNextPage = selectIsFetchingNextPage;\nexport const ɵselectIsMutating = selectIsMutating;\nexport { createThreadStore as ɵcreateThreadStore };\n/**\n * Number of consecutive WebSocket connection failures after which the\n * threads channel tears itself down rather than retrying indefinitely.\n * Exposed for tests so they can assert teardown semantics without\n * hardcoding the threshold separately from production.\n */\nexport const ɵMAX_SOCKET_RETRIES = MAX_SOCKET_RETRIES;\n/**\n * How long a thread REST request is given before the store gives up on it.\n * Exposed for tests for the same reason as {@link ɵMAX_SOCKET_RETRIES}: a\n * separately hardcoded copy silently drifts away from this one.\n */\nexport const ɵTHREAD_REQUEST_TIMEOUT_MS = REQUEST_TIMEOUT_MS;\n","/**\n * Central registry of CopilotKit feature names.\n *\n * Feature names are the strings passed to a license context's `checkFeature`\n * (see `@copilotkit/shared`'s `LicenseContextValue`). Historically the only\n * features referenced by literal were the chat surfaces (`chat`, `sidebar`,\n * `popup`); this module makes the set explicit and typed so new surfaces —\n * such as the threads drawer — register a real, discoverable feature name\n * rather than an ad-hoc string scattered across components.\n *\n * `checkFeature` itself still accepts any `string` for backward compatibility;\n * this registry simply documents and types the names CopilotKit recognises.\n */\n\n/**\n * The set of feature names CopilotKit recognises.\n *\n * Frozen so the array cannot be mutated at runtime. Add new surfaces here when\n * they begin gating behaviour on `checkFeature`.\n */\nexport const ɵCOPILOTKIT_FEATURES = Object.freeze([\n \"chat\",\n \"sidebar\",\n \"popup\",\n \"threads\",\n] as const);\n\n/**\n * Union of recognised CopilotKit feature names.\n */\nexport type ɵCopilotKitFeature = (typeof ɵCOPILOTKIT_FEATURES)[number];\n\nconst FEATURE_SET: ReadonlySet<string> = new Set(ɵCOPILOTKIT_FEATURES);\n\n/**\n * Type guard: returns `true` when `name` is a recognised CopilotKit feature.\n *\n * @param name - Candidate feature name.\n * @returns Whether `name` is a registered feature.\n *\n * @example\n * ```ts\n * if (ɵisCopilotKitFeature(\"threads\")) {\n * // narrowed to ɵCopilotKitFeature\n * }\n * ```\n */\nexport function ɵisCopilotKitFeature(name: string): name is ɵCopilotKitFeature {\n return FEATURE_SET.has(name);\n}\n","export const INSPECTOR_THREAD_BRIDGE_PLUGIN_ID =\n \"cpk-inspector-thread\" as const;\n\nconst EVENT_PREFIX = `copilotkit:${INSPECTOR_THREAD_BRIDGE_PLUGIN_ID}`;\n\ntype InspectorBridgeGlobal = typeof globalThis & {\n __COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__?: EventTarget;\n};\n\nexport type InspectorViewThreadPayload = {\n requestId: string;\n threadId: string;\n agentId: string;\n};\n\nexport type InspectorStopViewingPayload = {\n requestId: string;\n agentId: string;\n};\n\nexport type InspectorActiveThreadPayload = {\n requestId: string;\n threadId: string;\n agentId: string;\n source: \"app\" | \"override\";\n};\n\nexport type InspectorViewThreadResultPayload =\n | {\n requestId: string;\n threadId: string;\n agentId: string;\n ok: true;\n }\n | {\n requestId: string;\n threadId: string;\n agentId: string;\n ok: false;\n reason: \"connect-failed\";\n };\n\ntype InspectorThreadBridgeEvents = {\n \"stop-viewing\": InspectorStopViewingPayload;\n \"active-thread\": InspectorActiveThreadPayload;\n \"view-thread-result\": InspectorViewThreadResultPayload;\n};\n\ntype ClaimableViewThreadEvent = {\n payload: InspectorViewThreadPayload;\n claimed: boolean;\n};\n\nfunction eventName(suffix: string): string {\n return `${EVENT_PREFIX}:${suffix}`;\n}\n\nfunction getEventTarget(): EventTarget | null {\n if (\n typeof window !== \"undefined\" &&\n typeof window.addEventListener === \"function\"\n ) {\n return window;\n }\n if (typeof EventTarget === \"undefined\") return null;\n // Shared by duplicate @copilotkit/core copies in non-browser test realms.\n // Browser copies use window itself as the shared event target.\n const sharedGlobal = globalThis as InspectorBridgeGlobal;\n sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__ ??=\n new EventTarget();\n return sharedGlobal.__COPILOTKIT_INSPECTOR_THREAD_EVENT_TARGET__;\n}\n\nfunction createDetailEvent<T>(name: string, detail: T): Event {\n if (typeof CustomEvent !== \"undefined\") {\n return new CustomEvent(name, { detail });\n }\n const event = new Event(name);\n Object.defineProperty(event, \"detail\", { value: detail });\n return event;\n}\n\nfunction detailFromEvent<T>(event: Event): T {\n return (event as Event & { detail: T }).detail;\n}\n\n/** The Inspector thread bridge is development-only. */\nexport function isInspectorThreadBridgeEnabled(): boolean {\n return process.env.NODE_ENV !== \"production\";\n}\n\nexport function createInspectorThreadRequestId(): string {\n if (typeof crypto !== \"undefined\" && \"randomUUID\" in crypto) {\n return crypto.randomUUID();\n }\n return `inspector-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n\nfunction dispatch<K extends keyof InspectorThreadBridgeEvents>(\n suffix: K,\n payload: InspectorThreadBridgeEvents[K],\n): void {\n if (!isInspectorThreadBridgeEnabled()) return;\n const target = getEventTarget();\n if (!target) return;\n target.dispatchEvent(createDetailEvent(eventName(suffix), payload));\n}\n\nfunction on<K extends keyof InspectorThreadBridgeEvents>(\n suffix: K,\n handler: (payload: InspectorThreadBridgeEvents[K]) => void,\n): () => void {\n if (!isInspectorThreadBridgeEnabled()) return () => undefined;\n const target = getEventTarget();\n if (!target) return () => undefined;\n const listener = (event: Event) => {\n handler(detailFromEvent<InspectorThreadBridgeEvents[K]>(event));\n };\n const name = eventName(suffix);\n target.addEventListener(name, listener);\n return () => target.removeEventListener(name, listener);\n}\n\n/**\n * Ask the first mounted official chat for the matching agent to load a thread.\n * Returns false when no chat claims the request synchronously.\n */\nexport function emitInspectorViewThread(\n payload: InspectorViewThreadPayload,\n): boolean {\n if (!isInspectorThreadBridgeEnabled()) return false;\n const target = getEventTarget();\n if (!target) return false;\n const detail: ClaimableViewThreadEvent = { payload, claimed: false };\n target.dispatchEvent(createDetailEvent(eventName(\"view-thread\"), detail));\n return detail.claimed;\n}\n\nexport function emitInspectorStopViewing(\n payload: InspectorStopViewingPayload,\n): void {\n dispatch(\"stop-viewing\", payload);\n}\n\nexport function emitInspectorActiveThread(\n payload: InspectorActiveThreadPayload,\n): void {\n dispatch(\"active-thread\", payload);\n}\n\nexport function emitInspectorViewThreadResult(\n payload: InspectorViewThreadResultPayload,\n): void {\n dispatch(\"view-thread-result\", payload);\n}\n\nexport function onInspectorViewThread(\n handler: (payload: InspectorViewThreadPayload) => boolean,\n): () => void {\n if (!isInspectorThreadBridgeEnabled()) return () => undefined;\n const target = getEventTarget();\n if (!target) return () => undefined;\n const listener = (event: Event) => {\n const detail = detailFromEvent<ClaimableViewThreadEvent>(event);\n if (detail.claimed) return;\n detail.claimed = handler(detail.payload);\n };\n const name = eventName(\"view-thread\");\n target.addEventListener(name, listener);\n return () => target.removeEventListener(name, listener);\n}\n\nexport function onInspectorStopViewing(\n handler: (payload: InspectorStopViewingPayload) => void,\n): () => void {\n return on(\"stop-viewing\", handler);\n}\n\nexport function onInspectorActiveThread(\n handler: (payload: InspectorActiveThreadPayload) => void,\n): () => void {\n return on(\"active-thread\", handler);\n}\n\nexport function onInspectorViewThreadResult(\n handler: (payload: InspectorViewThreadResultPayload) => void,\n): () => void {\n return on(\"view-thread-result\", handler);\n}\n","/** Language of a fenced code block that carries A2UI operations. */\nexport const A2UI_FENCE_LANGUAGE = \"a2ui\";\n\n/**\n * One part of an assistant message, in source order: prose markdown, or the\n * body of a top-level ```a2ui fence. `target` is the id from a\n * `target=<id>` token in the fence info string. With no target, the surface\n * goes to the chat.\n */\nexport type MarkdownSegment =\n | { type: \"markdown\"; text: string }\n | {\n type: \"a2ui\";\n index: number;\n text: string;\n closed: boolean;\n target?: string;\n };\n\ntype A2UISegment = Extract<MarkdownSegment, { type: \"a2ui\" }>;\n\n/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */\nconst FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;\n\n/** Info-string token that names the placement target of an a2ui fence. */\nconst TARGET_TOKEN = /^target=(.+)$/;\n\ninterface OpenFence {\n /** Fence character (` or ~). */\n char: string;\n /** Length of the opening marker; the closer must be at least this long. */\n length: number;\n /** Offset in the source where the fence body starts. */\n bodyStart: number;\n /** a2ui fence index, or -1 for fences of other languages. */\n index: number;\n /** Target id from the info string of an a2ui fence. */\n target: string | undefined;\n}\n\nfunction isCloser(line: string, fence: OpenFence) {\n const trimmed = line.trim();\n if (trimmed.length < fence.length) return false;\n for (const ch of trimmed) {\n if (ch !== fence.char) return false;\n }\n return true;\n}\n\n/** The id of the first `target=<id>` token. Other tokens are ignored. */\nfunction readTarget(tokens: string[]) {\n for (const token of tokens) {\n const match = TARGET_TOKEN.exec(token);\n if (match) return match[1];\n }\n return undefined;\n}\n\nfunction a2uiSegment(fence: OpenFence, text: string, closed: boolean) {\n const segment: A2UISegment = {\n type: \"a2ui\",\n index: fence.index,\n text,\n closed,\n };\n if (fence.target !== undefined) segment.target = fence.target;\n return segment;\n}\n\n/**\n * Split a (possibly still streaming) markdown string into prose segments and\n * top-level ```a2ui fences. Fences of other languages stay inside prose\n * segments byte-for-byte, and a2ui markers inside them are ignored. Only\n * column-0 fences are recognised, so a fence indented inside a list item is\n * left to the markdown renderer.\n *\n * The first info-string token must be exactly `a2ui`. A later\n * `target=<id>` token sets `target` on the segment (for example\n * ```` ```a2ui target=recommendations ````). Other tokens are ignored.\n *\n * An a2ui segment's `text` is the fence body. For a closed fence it ends with\n * \"\\n\" when non-empty. For an open (still streaming or aborted) fence it is\n * everything after the opener line, minus a half-streamed closing marker.\n *\n * @param markdown - The assistant message text, complete or still streaming.\n * @returns The segments in source order.\n *\n * @example\n * ```ts\n * for (const segment of splitA2UIMarkdown(message.content)) {\n * if (segment.type === \"a2ui\") renderSurface(segment.text, segment.target);\n * else renderMarkdown(segment.text);\n * }\n * ```\n */\nexport function splitA2UIMarkdown(markdown: string) {\n const segments: MarkdownSegment[] = [];\n let proseStart = 0;\n let fence: OpenFence | null = null;\n let a2uiIndex = 0;\n\n const pushProse = (end: number) => {\n if (end > proseStart) {\n segments.push({\n type: \"markdown\",\n text: markdown.slice(proseStart, end),\n });\n }\n };\n\n let lineStart = 0;\n while (lineStart <= markdown.length) {\n const newline = markdown.indexOf(\"\\n\", lineStart);\n const lineEnd = newline < 0 ? markdown.length : newline;\n // A CRLF line keeps its \"\\r\" in the source slices (prose stays\n // byte-identical) but is matched without it, since \".\" does not match \"\\r\".\n const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === \"\\r\";\n const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);\n\n if (fence) {\n if (isCloser(line, fence)) {\n if (fence.index >= 0) {\n const body = markdown.slice(\n fence.bodyStart,\n Math.max(fence.bodyStart, lineStart),\n );\n segments.push(a2uiSegment(fence, body, true));\n proseStart = hasCR ? lineEnd - 1 : lineEnd;\n }\n fence = null;\n }\n } else {\n const open = FENCE_OPEN.exec(line);\n if (open) {\n const marker = open[1] ?? \"\";\n const info = open[2] ?? \"\";\n const char = marker.charAt(0);\n // Backtick fences cannot have backticks in their info string (CommonMark).\n const isValidOpener = !(char === \"`\" && info.includes(\"`\"));\n if (isValidOpener) {\n const [lang = \"\", ...tokens] = info.trim().split(/\\s+/);\n const isA2UI = lang === A2UI_FENCE_LANGUAGE;\n if (isA2UI) pushProse(lineStart);\n fence = {\n char,\n length: marker.length,\n bodyStart: newline < 0 ? markdown.length : lineEnd + 1,\n index: isA2UI ? a2uiIndex++ : -1,\n target: isA2UI ? readTarget(tokens) : undefined,\n };\n }\n }\n }\n\n if (newline < 0) break;\n lineStart = newline + 1;\n }\n\n if (fence && fence.index >= 0) {\n const { char } = fence;\n let body = markdown.slice(fence.bodyStart);\n // Drop a closing marker that is still streaming in (e.g. \"``\").\n const lastNewline = body.lastIndexOf(\"\\n\");\n const lastLine = body.slice(lastNewline + 1).replace(/\\r$/, \"\");\n const isHalfCloser =\n lastLine.length > 0 && [...lastLine].every((ch) => ch === char);\n if (isHalfCloser) {\n body = body.slice(0, lastNewline + 1);\n }\n segments.push(a2uiSegment(fence, body, false));\n } else {\n pushProse(markdown.length);\n }\n\n return segments;\n}\n","import { jsonrepair } from \"jsonrepair\";\nimport { A2UI_VERSION, GENERATIVE_UI_ROOT_ID } from \"@copilotkit/shared\";\n\n/**\n * An A2UI v1.0 message as the model wrote it in an a2ui fence: an object that\n * carries one of createSurface, updateComponents, updateDataModel,\n * deleteSurface or callRendererFunction. The shape is not checked yet.\n * Validate it (for example with `validateOperation` from `@copilotkit/shared`)\n * before it reaches a surface or runs a function.\n *\n * It is named `A2UIMarkdownOperation` because `@copilotkit/shared` already\n * exports the strict `A2UIOperation` type.\n */\nexport type A2UIMarkdownOperation = Record<string, unknown>;\n\n/** The operation keys that change a surface. */\nconst SURFACE_OP_KEYS = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n] as const;\n\n/** The operation key of an agent-called function. It has no surface. */\nconst FUNCTION_CALL_KEY = \"callRendererFunction\";\n\nconst OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isWhitespace(ch: string | undefined) {\n return ch === \" \" || ch === \"\\n\" || ch === \"\\r\" || ch === \"\\t\";\n}\n\nfunction skipWhitespace(s: string, i: number) {\n while (i < s.length && isWhitespace(s[i])) i++;\n return i;\n}\n\n/** Index of the closing quote of the JSON string opening at `start`, or -1. */\nfunction findStringEnd(s: string, start: number) {\n for (let i = start + 1; i < s.length; i++) {\n if (s[i] === \"\\\\\") {\n i++;\n continue;\n }\n if (s[i] === '\"') return i;\n }\n return -1;\n}\n\n/**\n * Find the first `\"key\":` whose value starts with `opener` and return the index\n * of that opener, or -1.\n */\nfunction findKeyValue(s: string, key: string, opener: string) {\n const needle = `\"${key}\"`;\n let from = 0;\n while (true) {\n const k = s.indexOf(needle, from);\n if (k < 0) return -1;\n let i = skipWhitespace(s, k + needle.length);\n if (s[i] === \":\") {\n i = skipWhitespace(s, i + 1);\n if (s[i] === opener) return i;\n }\n from = k + 1;\n }\n}\n\n/**\n * Read `\"key\":\"value\"` from partial JSON. The first match anywhere in the\n * text wins, at any depth.\n *\n * @param partialJson - JSON text that can still be streaming.\n * @param key - The field name.\n * @returns The string value, or null until its closing quote has arrived.\n *\n * @example\n * ```ts\n * extractStringField('{\"createSurface\":{\"surfaceId\":\"plan\",\"cat', \"surfaceId\"); // \"plan\"\n * ```\n */\nexport function extractStringField(partialJson: string, key: string) {\n const start = findKeyValue(partialJson, key, '\"');\n if (start < 0) return null;\n const end = findStringEnd(partialJson, start);\n if (end < 0) return null;\n try {\n const value: unknown = JSON.parse(partialJson.slice(start, end + 1));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n}\n\nfunction pushItem(raw: string, items: unknown[]) {\n const trimmed = raw.trim();\n if (!trimmed) return;\n try {\n items.push(JSON.parse(trimmed));\n } catch {\n // Incomplete primitive; ignore until it completes.\n }\n}\n\n/**\n * Find `\"key\":[` in partial JSON and return every complete item of that array\n * so far, plus whether the array has closed. Items of a `components` array get\n * structural-key depth repair: a component that lost closing braces is fixed\n * when its `id`, `component`, `child` or `children` key shows where it ends.\n *\n * @param partialJson - JSON text that can still be streaming.\n * @param key - The name of the array field.\n * @returns `{ items, closed }`, or null when the key (with an array value)\n * has not appeared yet.\n *\n * @example\n * ```ts\n * const result = extractCompleteArrayItems(streamedText, \"components\");\n * if (result) render(result.items);\n * ```\n */\nexport function extractCompleteArrayItems(partialJson: string, key: string) {\n const open = findKeyValue(partialJson, key, \"[\");\n if (open < 0) return null;\n return completeArrayItemsAt(partialJson, open, {\n repairComponents: key === \"components\",\n });\n}\n\n/** Index of the last non-whitespace character before `i`, or -1. */\nfunction prevNonWhitespace(s: string, i: number) {\n let j = i - 1;\n while (j >= 0 && isWhitespace(s[j])) j--;\n return j;\n}\n\n/**\n * Keys that only ever belong at a component's top level. Seen nested inside\n * the component's objects, they mean the model forgot closing braces.\n */\nconst STRUCTURAL_KEYS = new Set([\"id\", \"component\", \"child\", \"children\"]);\n\n/** Whether a value starting with `ch` has the shape `key` takes on a component. */\nfunction structuralValueFits(key: string, ch: string | undefined) {\n if (key === \"children\") return ch === \"[\" || ch === \"{\";\n return ch === '\"';\n}\n\n/** `{\"id\":` — a new component object starting at `i`. */\nconst COMPONENT_START = /^\\{\\s*\"id\"\\s*:/;\n\n/**\n * Structural-key depth repair for one component item. While scanning, a\n * structural key (`id`, `component`, `child`, `children`) found as an object\n * key below the item's top level, with only objects (no arrays) between it\n * and the item root, a value of the expected shape, and not already present\n * at the top level, means closing braces were dropped: the missing `}` are\n * synthesized right before it so it lands at the top level. Containers still\n * open at the end are closed. Returns null when a string never terminates.\n */\nfunction repairComponentItem(item: string) {\n const stack: string[] = [];\n const topKeys = new Set<string>();\n let out = \"\";\n let copied = 0;\n for (let i = 0; i < item.length; i++) {\n const c = item[i];\n if (c === '\"') {\n const end = findStringEnd(item, i);\n if (end < 0) return null;\n const prev = prevNonWhitespace(item, i);\n const prevCh = item[prev];\n const colon = skipWhitespace(item, end + 1);\n const isKey =\n stack[stack.length - 1] === \"{\" &&\n (prevCh === \",\" || prevCh === \"{\") &&\n item[colon] === \":\";\n if (isKey) {\n let key: unknown;\n try {\n key = JSON.parse(item.slice(i, end + 1));\n } catch {\n return null;\n }\n if (typeof key === \"string\") {\n if (stack.length === 1) {\n topKeys.add(key);\n } else if (\n STRUCTURAL_KEYS.has(key) &&\n !topKeys.has(key) &&\n stack.every((x) => x === \"{\") &&\n structuralValueFits(key, item[skipWhitespace(item, colon + 1)])\n ) {\n const closers = \"}\".repeat(stack.length - 1);\n if (prevCh === \",\") {\n out += item.slice(copied, prev) + closers;\n copied = prev;\n } else {\n // `\"x\":{\"children\":…` — close the empty object, then a comma.\n out += item.slice(copied, i) + closers + \",\";\n copied = i;\n }\n stack.length = 1;\n topKeys.add(key);\n }\n }\n }\n i = end;\n continue;\n }\n if (c === \"{\" || c === \"[\") {\n stack.push(c);\n } else if (c === \"}\" || c === \"]\") {\n stack.pop();\n if (stack.length === 0) return out + item.slice(copied, i + 1);\n }\n }\n // Close the open brackets, innermost first.\n const closers = stack.reduceRight(\n (text, opener) => text + (opener === \"{\" ? \"}\" : \"]\"),\n \"\",\n );\n return out + item.slice(copied) + closers;\n}\n\nfunction parseRecord(text: string | null) {\n if (text === null) return undefined;\n try {\n const value: unknown = JSON.parse(text);\n return isRecord(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Complete items of the (possibly unterminated) array whose \"[\" is at `open`.\n * With `repairComponents`, an item that balanced but does not parse is retried\n * with structural-key repair, and a `,{\"id\":` where an item expects a key\n * ends that (unbalanced) item there, so one malformed component cannot\n * swallow the rest of the array; the cut item is kept only if repair makes\n * it parse.\n */\nfunction completeArrayItemsAt(\n partialJson: string,\n open: number,\n options: { repairComponents: boolean },\n) {\n const { repairComponents } = options;\n const s = partialJson;\n const items: unknown[] = [];\n const stack: string[] = [];\n let inString = false;\n let itemStart = -1;\n\n const finishItem = (end: number, balanced: boolean) => {\n const raw = s.slice(itemStart, end);\n if (!repairComponents) {\n pushItem(raw, items);\n return;\n }\n if (balanced) {\n try {\n items.push(JSON.parse(raw));\n return;\n } catch {\n // Fall through to repair.\n }\n }\n const repaired = parseRecord(repairComponentItem(raw.trim()));\n if (repaired !== undefined) items.push(repaired);\n };\n\n for (let i = open + 1; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n continue;\n }\n if (c === '\"') {\n inString = true;\n if (stack.length === 0 && itemStart < 0) itemStart = i;\n continue;\n }\n if (c === \"{\" || c === \"[\") {\n if (\n repairComponents &&\n c === \"{\" &&\n stack[stack.length - 1] === \"{\" &&\n COMPONENT_START.test(s.slice(i, i + 24))\n ) {\n const prev = prevNonWhitespace(s, i);\n if (s[prev] === \",\") {\n // A new component where a key was expected: the current item\n // is missing closers. End it before the comma and start anew.\n finishItem(prev, false);\n stack.length = 0;\n itemStart = i;\n stack.push(c);\n continue;\n }\n }\n if (stack.length === 0) itemStart = i;\n stack.push(c);\n continue;\n }\n if (c === \"}\" || c === \"]\") {\n if (stack.length === 0) {\n // Closing bracket of the items array itself (or malformed input).\n if (c === \"]\") {\n if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);\n return { items, closed: true };\n }\n return { items, closed: false };\n }\n stack.pop();\n if (stack.length === 0) {\n finishItem(i + 1, true);\n itemStart = -1;\n }\n continue;\n }\n if (stack.length === 0) {\n if (c === \",\") {\n if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);\n itemStart = -1;\n } else if (itemStart < 0 && !isWhitespace(c)) {\n itemStart = i; // start of a primitive item\n }\n }\n }\n return { items, closed: false };\n}\n\n/** The first operation key whose value is an object, with that value. */\nfunction getOperationEntry(op: A2UIMarkdownOperation) {\n for (const key of OP_KEYS) {\n const inner = op[key];\n if (isRecord(inner)) return { key, inner };\n }\n return null;\n}\n\n/**\n * The surfaceId an operation targets: the one nested under its operation key,\n * else a top-level `surfaceId`. A `callRendererFunction` operation targets no\n * surface, so it gets undefined.\n *\n * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`\n * already exports a strict `getOperationSurfaceId`. This one also reads a\n * top-level `surfaceId`, which models sometimes write.\n *\n * @param op - An operation from an a2ui fence.\n * @returns The surfaceId, or undefined when the operation names none or is a\n * function call.\n *\n * @example\n * ```ts\n * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: \"plan\" } }); // \"plan\"\n * ```\n */\nexport function getMarkdownOperationSurfaceId(op: A2UIMarkdownOperation) {\n if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return undefined;\n for (const key of SURFACE_OP_KEYS) {\n const inner = op[key];\n if (isRecord(inner) && typeof inner.surfaceId === \"string\") {\n return inner.surfaceId;\n }\n }\n return typeof op.surfaceId === \"string\" ? op.surfaceId : undefined;\n}\n\n/**\n * Index just past the JSON value starting at `start`, or -1 when the value is\n * still incomplete. A primitive at the very end of the input counts as\n * incomplete, since more digits or letters may still stream in.\n */\nfunction findValueEnd(s: string, start: number) {\n const c = s[start];\n if (c === '\"') {\n const end = findStringEnd(s, start);\n return end < 0 ? -1 : end + 1;\n }\n if (c === \"{\" || c === \"[\") {\n let depth = 0;\n for (let i = start; i < s.length; i++) {\n const ch = s[i];\n if (ch === '\"') {\n const end = findStringEnd(s, i);\n if (end < 0) return -1;\n i = end;\n } else if (ch === \"{\" || ch === \"[\") {\n depth++;\n } else if (ch === \"}\" || ch === \"]\") {\n depth--;\n if (depth === 0) return i + 1;\n }\n }\n return -1;\n }\n let i = start;\n while (i < s.length && !isWhitespace(s[i]) && !\",}]\".includes(s[i]!)) i++;\n return i >= s.length ? -1 : i;\n}\n\n/**\n * Walk the direct entries of the (possibly unterminated) JSON object whose \"{\"\n * is at `objStart`, calling `visit` with each key and the index where its value\n * starts. Nested objects and arrays are skipped whole, so keys inside them are\n * never visited. Stops when `visit` returns true, at the object's end, or where\n * the input runs out.\n */\nfunction visitDirectEntries(\n s: string,\n objStart: number,\n visit: (key: string, valueStart: number) => boolean,\n) {\n let i = objStart + 1;\n while (i < s.length) {\n i = skipWhitespace(s, i);\n const c = s[i];\n if (c === \",\") {\n i++;\n continue;\n }\n if (c !== '\"') return; // \"}\" (object closed), end of input, or malformed\n const keyEnd = findStringEnd(s, i);\n if (keyEnd < 0) return;\n let key: unknown;\n try {\n key = JSON.parse(s.slice(i, keyEnd + 1));\n } catch {\n return;\n }\n i = skipWhitespace(s, keyEnd + 1);\n if (s[i] !== \":\") return;\n i = skipWhitespace(s, i + 1);\n if (i >= s.length) return;\n if (typeof key === \"string\" && visit(key, i)) return;\n const valueEnd = findValueEnd(s, i);\n if (valueEnd < 0) return;\n i = valueEnd;\n }\n}\n\n/**\n * Value start of a direct `key` of the object at `objStart` whose value begins\n * with `opener` (any value when omitted), or -1.\n */\nfunction findDirectKeyValue(\n s: string,\n objStart: number,\n key: string,\n opener?: string,\n) {\n let found = -1;\n visitDirectEntries(s, objStart, (k, valueStart) => {\n if (k !== key) return false;\n if (opener === undefined || s[valueStart] === opener) found = valueStart;\n return true;\n });\n return found;\n}\n\n/** A direct string field of the object at `objStart`, once its closing quote has arrived. */\nfunction readDirectString(s: string, objStart: number, key: string) {\n if (objStart < 0) return null;\n const start = findDirectKeyValue(s, objStart, key, '\"');\n if (start < 0) return null;\n const end = findValueEnd(s, start);\n if (end < 0) return null;\n try {\n const value: unknown = JSON.parse(s.slice(start, end));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n}\n\n/** A direct object field of the object at `objStart`, once the whole object has arrived. */\nfunction readDirectRecord(s: string, objStart: number, key: string) {\n const start = findDirectKeyValue(s, objStart, key, \"{\");\n if (start < 0) return undefined;\n const end = findValueEnd(s, start);\n if (end < 0) return undefined;\n return parseRecord(s.slice(start, end));\n}\n\n/**\n * The complete part of a (possibly unterminated) JSON value: the parsed value\n * when it is complete; for an open object, its complete entries plus the\n * complete items of any streaming array entry; otherwise undefined.\n */\nfunction completePartOfValue(s: string, start: number) {\n const end = findValueEnd(s, start);\n if (end >= 0) {\n try {\n const value: unknown = JSON.parse(s.slice(start, end));\n return value;\n } catch {\n return undefined;\n }\n }\n if (s[start] !== \"{\") return undefined;\n const out: Record<string, unknown> = {};\n visitDirectEntries(s, start, (key, valueStart) => {\n const valueEnd = findValueEnd(s, valueStart);\n if (valueEnd >= 0) {\n try {\n out[key] = JSON.parse(s.slice(valueStart, valueEnd));\n } catch {\n // Malformed entry; leave it out.\n }\n } else if (s[valueStart] === \"[\") {\n const { items } = completeArrayItemsAt(s, valueStart, {\n repairComponents: false,\n });\n if (items.length > 0) out[key] = items;\n }\n return false;\n });\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Best-effort operation from an unfinished or malformed top-level object.\n * Fields are read only from the operation's own keys (`version` at the top\n * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside\n * the operation object), never from component props or data-model values that\n * happen to share a name.\n *\n * A `createSurface` keeps its complete components and a `dataModel` that has\n * fully arrived, so a surface created in one line renders while it streams.\n * A `callRendererFunction` gives nothing: a function must not run with half\n * of its args.\n */\nfunction partialOperation(line: string) {\n const root = skipWhitespace(line, 0);\n if (line[root] !== \"{\") return null;\n const version = readDirectString(line, root, \"version\") ?? A2UI_VERSION;\n\n const components = findDirectKeyValue(line, root, \"updateComponents\", \"{\");\n if (components >= 0) {\n const arrayStart = findDirectKeyValue(line, components, \"components\", \"[\");\n if (arrayStart < 0) return null;\n const { items } = completeArrayItemsAt(line, arrayStart, {\n repairComponents: true,\n });\n if (items.length === 0) return null;\n const surfaceId = readDirectString(line, components, \"surfaceId\");\n return {\n version,\n updateComponents: {\n ...(surfaceId ? { surfaceId } : {}),\n components: items,\n },\n };\n }\n\n const data = findDirectKeyValue(line, root, \"updateDataModel\", \"{\");\n if (data >= 0) {\n const valueStart = findDirectKeyValue(line, data, \"value\");\n if (valueStart < 0) return null;\n const value = completePartOfValue(line, valueStart);\n if (value === undefined) return null;\n const surfaceId = readDirectString(line, data, \"surfaceId\");\n const path = readDirectString(line, data, \"path\");\n return {\n version,\n updateDataModel: {\n ...(surfaceId ? { surfaceId } : {}),\n ...(path ? { path } : {}),\n value,\n },\n };\n }\n\n const create = findDirectKeyValue(line, root, \"createSurface\", \"{\");\n if (create >= 0) {\n const surfaceId = readDirectString(line, create, \"surfaceId\");\n if (!surfaceId) return null;\n const catalogId = readDirectString(line, create, \"catalogId\");\n const dataModel = readDirectRecord(line, create, \"dataModel\");\n const componentsStart = findDirectKeyValue(line, create, \"components\", \"[\");\n const components =\n componentsStart < 0\n ? []\n : completeArrayItemsAt(line, componentsStart, {\n repairComponents: true,\n }).items;\n return {\n version,\n createSurface: {\n surfaceId,\n ...(catalogId ? { catalogId } : {}),\n ...(dataModel ? { dataModel } : {}),\n ...(components.length > 0 ? { components } : {}),\n },\n };\n }\n return null;\n}\n\n/**\n * A line that opens a new top-level operation: `{\"version\":\"1…` or\n * `{\"<operation>\":{`. Seen at the start of a line while an earlier object is\n * still unbalanced, it means that object is malformed and has ended.\n */\nconst OPERATION_START = new RegExp(\n `^\\\\{\\\\s*\"(?:version\"\\\\s*:\\\\s*\"\\\\d|(?:${OP_KEYS.join(\"|\")})\"\\\\s*:\\\\s*\\\\{)`,\n);\n\n/**\n * Scan the top-level object whose \"{\" is at `start`. Returns the index just\n * past it and whether it balanced. An unbalanced object ends early (at the\n * start of the line) when a line opens a new operation; otherwise it runs to\n * the end of the input. JSON strings cannot contain raw newlines, so a newline\n * inside a string ends it: a stray quote then breaks one line, not the rest of\n * the fence.\n */\nfunction scanTopLevelObject(s: string, start: number) {\n let depth = 0;\n let inString = false;\n for (let i = start; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (c === \"\\\\\" && s[i + 1] !== \"\\n\") i++;\n else if (c === '\"' || c === \"\\n\") inString = false;\n if (c !== \"\\n\") continue;\n }\n if (c === \"\\n\") {\n const next = skipWhitespace(s, i + 1);\n if (OPERATION_START.test(s.slice(next, next + 40))) {\n return { end: i + 1, balanced: false };\n }\n continue;\n }\n if (c === '\"') inString = true;\n else if (c === \"{\" || c === \"[\") depth++;\n else if (c === \"}\" || c === \"]\") {\n depth--;\n if (depth === 0) return { end: i + 1, balanced: true };\n }\n }\n return { end: s.length, balanced: false };\n}\n\nconst OPERATION_NAMES = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n \"callRendererFunction\",\n];\n\n/** Whether a value is shaped like one A2UI operation, with named components. */\nfunction isOperationShape(value: unknown): boolean {\n if (!isRecord(value) || value.version !== A2UI_VERSION) return false;\n const names = OPERATION_NAMES.filter((name) => name in value);\n if (names.length !== 1 || Object.keys(value).length !== 2) return false;\n const body = value[names[0]!];\n if (!isRecord(body)) return false;\n if (names[0] === \"callRendererFunction\") return true;\n if (typeof body.surfaceId !== \"string\") return false;\n const components = body.components;\n return (\n components === undefined ||\n (Array.isArray(components) &&\n components.every(\n (c) =>\n isRecord(c) &&\n typeof c.id === \"string\" &&\n typeof c.component === \"string\",\n ))\n );\n}\n\n/** Openers minus closers ({ and [ against } and ]) outside strings. */\nfunction closerImbalance(line: string) {\n let depth = 0;\n let inString = false;\n for (let i = 0; i < line.length; i++) {\n const c = line[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n } else if (c === '\"') inString = true;\n else if (c === \"{\" || c === \"[\") depth++;\n else if (c === \"}\" || c === \"]\") depth--;\n }\n return depth;\n}\n\n/** The text with closers and whitespace removed, to compare a repair. */\nfunction withoutClosers(text: string) {\n return text.replace(/[\\]}\\s]/g, \"\");\n}\n\n/**\n * Whether a component of the operation holds a structural key (`id`,\n * `component`, `child`, `children`) in a nested object: a closer added at\n * the end instead of where it was dropped. The scan below repairs those.\n */\nfunction nestsStructuralKey(value: unknown) {\n const nests = (v: unknown): boolean =>\n isRecord(v) &&\n Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));\n const body = isRecord(value)\n ? Object.values(value).find(isRecord)\n : undefined;\n const components = body?.components;\n return (\n Array.isArray(components) &&\n components.some(\n (c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)),\n )\n );\n}\n\n/**\n * Repairs the complete lines of a fence that are not valid JSON (a missing\n * or extra brace) with jsonrepair, when the repair only adds or removes\n * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.\n */\nfunction repairFenceLines(fenceText: string) {\n const repaired: string[] = [];\n const lines = fenceText.split(\"\\n\");\n // A top-level array spreads its closers over lines: nothing to repair.\n if (fenceText.trimStart().startsWith(\"[\"))\n return { text: fenceText, repaired };\n for (let n = 0; n < lines.length - 1; n++) {\n const line = lines[n]!;\n if (!line.trim().startsWith(\"{\")) continue;\n try {\n JSON.parse(line);\n continue;\n } catch {\n // Not valid JSON: try a repair.\n }\n // Only a slip of one closer: the first line of a pretty-printed\n // operation is off by more and must stay for the scan below.\n const imbalance = closerImbalance(line);\n if (Math.abs(imbalance) !== 1) continue;\n // A line that misses a closer and is followed by more than a new\n // operation is the start of an object over several lines.\n const next = lines.slice(n + 1).find((l) => l.trim() !== \"\");\n if (imbalance > 0 && next !== undefined && !next.trim().startsWith(\"{\")) {\n continue;\n }\n try {\n const fixed = jsonrepair(line);\n const value: unknown = JSON.parse(fixed);\n if (\n withoutClosers(fixed) === withoutClosers(line) &&\n isOperationShape(value) &&\n !nestsStructuralKey(value) &&\n // A call must not run with args that a closer moved.\n !(isRecord(value) && \"callRendererFunction\" in value)\n ) {\n repaired.push(line.trim());\n lines[n] = JSON.stringify(value);\n }\n } catch {\n // Leave it: the scan below drops or salvages it as before.\n }\n }\n return { text: lines.join(\"\\n\"), repaired };\n}\n\n/**\n * Parse the body of an a2ui fence as a stream of top-level JSON values, so\n * operations may be one per line (the documented format), several per line,\n * pretty-printed over many lines, or wrapped in a top-level array (which is\n * flattened). Whitespace and commas between objects are ignored.\n *\n * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),\n * its raw text goes to `invalidLines` and whatever `partialOperation` can\n * salvage (complete components, data-model entries, createSurface fields)\n * is kept.\n * - An unbalanced object followed by a line that opens a new operation is\n * treated the same way.\n * - The trailing unbalanced object (still streaming, or never closed) is\n * `partialObject` and yields a partial operation when it has usable data.\n * - Other text between objects is skipped and reported in `recovered` (and in\n * `invalidLines`, which predates it).\n *\n * `partialLine` is a deprecated alias of `partialObject`.\n *\n * @param fenceText - The body of an a2ui fence (`text` of an a2ui\n * `MarkdownSegment`), complete or still streaming.\n * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.\n *\n * @example\n * ```ts\n * const { operations } = extractFenceOperations(segment.text);\n * ```\n */\nexport function extractFenceOperations(fenceText: string) {\n const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);\n const operations: A2UIMarkdownOperation[] = [];\n const invalidLines: string[] = [];\n const recovered: string[] = [];\n let partialObject: string | null = null;\n\n const salvage = (raw: string) => {\n invalidLines.push(raw.trim());\n const partial = partialOperation(raw);\n if (partial) operations.push(partial);\n };\n\n let junkStart = -1;\n const flushJunk = (end: number) => {\n if (junkStart < 0) return;\n const junk = s.slice(junkStart, end).trim();\n junkStart = -1;\n if (!junk) return;\n recovered.push(junk);\n invalidLines.push(junk);\n };\n\n let i = 0;\n while (i < s.length) {\n const c = s[i]!;\n if (c === \"{\") {\n flushJunk(i);\n const { end, balanced } = scanTopLevelObject(s, i);\n const raw = s.slice(i, end);\n if (balanced) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n parsed = undefined;\n }\n if (isRecord(parsed)) operations.push(parsed);\n else salvage(raw);\n } else if (end < s.length) {\n salvage(raw);\n } else {\n partialObject = raw;\n const partial = partialOperation(raw);\n if (partial) operations.push(partial);\n }\n i = end;\n continue;\n }\n if (c === \"\\n\" || c === \"[\" || c === \"]\") {\n // A top-level array of operations is flattened by skipping its brackets.\n flushJunk(i);\n } else if (junkStart < 0 && !isWhitespace(c) && c !== \",\") {\n junkStart = i;\n }\n i++;\n }\n flushJunk(s.length);\n\n return {\n operations,\n partialObject,\n partialLine: partialObject,\n invalidLines,\n recovered,\n /** Complete lines that were off by one closing brace and were repaired. */\n repairedLines,\n };\n}\n\n/**\n * Normalise a fence's operations for the renderer: drop unknown messages, fill\n * in `version` and missing `surfaceId`s, keep only the first `createSurface`,\n * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize\n * `createSurface` when the model omitted it, and report the\n * surfaceId (the first one found, else `fallbackSurfaceId`).\n *\n * `callRendererFunction` operations target no surface. They get no surfaceId,\n * do not cause a synthesized `createSurface`, and come back in\n * `functionCalls` (in fence order), never in `operations`.\n *\n * @param input.operations - Operations from `extractFenceOperations`.\n * @param input.fallbackSurfaceId - The surfaceId to use when no operation\n * names one.\n * @param input.catalogId - The client catalog. It replaces a catalogId of the\n * model that `catalogIds` does not list.\n * @param input.catalogIds - The catalogs that the model can name. Left out,\n * only `catalogId`.\n * @returns `{ surfaceId, operations, functionCalls }`.\n *\n * @example\n * ```ts\n * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({\n * operations: extractFenceOperations(segment.text).operations,\n * fallbackSurfaceId: `${messageId}-${segment.index}`,\n * catalogId,\n * });\n * ```\n */\nexport function prepareSurfaceOperations(input: {\n operations: A2UIMarkdownOperation[];\n fallbackSurfaceId: string;\n catalogId: string;\n catalogIds?: readonly string[];\n}) {\n const { operations, fallbackSurfaceId, catalogId } = input;\n const catalogIds = input.catalogIds ?? [catalogId];\n const surfaceId =\n operations\n .map(getMarkdownOperationSurfaceId)\n .find((id): id is string => !!id) ?? fallbackSurfaceId;\n\n const out: A2UIMarkdownOperation[] = [];\n const functionCalls: A2UIMarkdownOperation[] = [];\n let hasCreate = false;\n for (const op of operations) {\n const entry = getOperationEntry(op);\n if (!entry) continue;\n const { key } = entry;\n const inner = { ...entry.inner };\n const version = typeof op.version === \"string\" ? op.version : A2UI_VERSION;\n if (key === FUNCTION_CALL_KEY) {\n functionCalls.push({ version, [key]: inner });\n continue;\n }\n if (typeof inner.surfaceId !== \"string\") inner.surfaceId = surfaceId;\n if (key === \"createSurface\") {\n // A surface is created once; a repeated createSurface (e.g. a later\n // reply that rebuilds a page target) would throw \"Surface already\n // exists\". Its data model and components become updates instead, so\n // the new UI is not lost.\n if (hasCreate) {\n const { surfaceId: id, dataModel, components } = inner;\n if (dataModel !== undefined) {\n out.push({\n version,\n updateDataModel: { surfaceId: id, path: \"/\", value: dataModel },\n });\n }\n if (Array.isArray(components) && components.length > 0) {\n out.push({\n version,\n updateComponents: { surfaceId: id, components },\n });\n }\n continue;\n }\n hasCreate = true;\n // The catalog is client-owned: a catalog that the client does not\n // list is replaced.\n if (!catalogIds.includes(inner.catalogId as string)) {\n inner.catalogId = catalogId;\n }\n }\n out.push({ version, [key]: inner });\n }\n\n if (!hasCreate && out.length > 0) {\n out.unshift({\n version: A2UI_VERSION,\n createSurface: { surfaceId, catalogId },\n });\n }\n return { surfaceId, operations: out, functionCalls };\n}\n\n/**\n * Components a user operates. A Card containing one of these is an\n * interactive panel and keeps its box; every other Card is informational.\n */\nconst INTERACTIVE_COMPONENTS = new Set([\n \"Button\",\n \"Pressable\",\n \"Form\",\n \"TextField\",\n \"TextArea\",\n \"Select\",\n \"CheckBox\",\n \"Radio\",\n \"RadioGroup\",\n \"Slider\",\n \"SegmentedControl\",\n \"ChoicePicker\",\n \"DateTimeInput\",\n]);\n\n/** A component id referenced by a `child`/`children` entry or a table cell. */\nfunction referencedId(value: unknown) {\n if (typeof value === \"string\") return value;\n if (isRecord(value)) {\n if (typeof value.componentId === \"string\") return value.componentId;\n if (typeof value.id === \"string\") return value.id;\n }\n return undefined;\n}\n\n/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */\nfunction cellComponentId(value: unknown) {\n return isRecord(value) ? referencedId(value) : undefined;\n}\n\n/**\n * More ids a component renders, beyond `child`, `children` and the table\n * cells: the typed child references of its catalog, which can sit at any\n * depth of its props (the `child` of each entry of `tabs`). The catalog\n * knows them; the operations alone do not.\n */\nexport type ChildIdsOf = (\n component: Record<string, unknown>,\n) => string[] | \"unknown\";\n\n/** The options of the walks that follow child ids. */\nexport interface ChildWalkOptions {\n childIds?: ChildIdsOf;\n}\n\n/**\n * Ids a component renders directly: `child`, `children` (string ids, an\n * array, or a `{componentId}` template), component cells of a Table's\n * `rows`/`columns`, and the ids that `extra` finds in its typed references.\n */\nfunction directChildIds(\n component: Record<string, unknown>,\n extra?: ChildIdsOf,\n) {\n const ids: string[] = [];\n const add = (id: string | undefined) => {\n if (id) ids.push(id);\n };\n const extraIds = extra?.(component);\n if (Array.isArray(extraIds)) extraIds.forEach(add);\n add(referencedId(component.child));\n const children = component.children;\n if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));\n else add(referencedId(children));\n if (Array.isArray(component.columns)) {\n component.columns.forEach((c) => add(cellComponentId(c)));\n }\n if (Array.isArray(component.rows)) {\n for (const row of component.rows) {\n if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));\n }\n }\n return ids;\n}\n\n/** Components of every updateComponents operation, by id (last definition wins). */\nfunction componentsById(operations: A2UIMarkdownOperation[]) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const op of operations) {\n const update = op.updateComponents;\n const list = isRecord(update) ? update.components : undefined;\n if (!Array.isArray(list)) continue;\n for (const c of list) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n }\n return byId;\n}\n\nfunction descendantIds(\n rootId: string,\n byId: Map<string, Record<string, unknown>>,\n extra?: ChildIdsOf,\n) {\n const seen = new Set<string>();\n const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];\n while (stack.length > 0) {\n const id = stack.pop()!;\n if (seen.has(id) || id === rootId) continue;\n seen.add(id);\n const c = byId.get(id);\n if (c) stack.push(...directChildIds(c, extra));\n }\n return seen;\n}\n\n/**\n * Ids of the `Card` components that are interactive panels: at least one\n * descendant (via `child`, `children` or table component cells) is a control\n * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,\n * RadioGroup, Slider, SegmentedControl, DateTimeInput).\n *\n * @param components - The components of one surface.\n * @returns The ids of the interactive cards.\n *\n * @example\n * ```ts\n * const interactive = classifySurfaceCards(components);\n * const keepsBox = interactive.has(\"quote-form\");\n * ```\n */\nexport function classifySurfaceCards(\n components: Record<string, unknown>[],\n options: ChildWalkOptions = {},\n) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const c of components) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n const interactive = new Set<string>();\n for (const [id, c] of byId) {\n if (c.component !== \"Card\") continue;\n for (const d of descendantIds(id, byId, options.childIds)) {\n const type = byId.get(d)?.component;\n if (typeof type === \"string\" && INTERACTIVE_COMPONENTS.has(type)) {\n interactive.add(id);\n break;\n }\n }\n }\n return interactive;\n}\n\n/**\n * Markdown mode: only interactive panels keep a box. Every `Card` that is not\n * an interactive panel (see `classifySurfaceCards`), sets no `variant` or\n * `border` of its own and is not nested inside an interactive panel becomes\n * `variant: \"section\"` (a heading plus content without a box). Operations\n * other than updateComponents pass through unchanged.\n *\n * @param operations - The operations of one surface.\n * @returns The operations with informational cards set to `variant: \"section\"`.\n * When no card changes, it returns the same array.\n *\n * @example\n * ```ts\n * const operations = flattenInformationalCards(prepared.operations);\n * ```\n */\nexport function flattenInformationalCards(\n operations: A2UIMarkdownOperation[],\n options: ChildWalkOptions = {},\n) {\n const byId = componentsById(operations);\n if (![...byId.values()].some((c) => c.component === \"Card\")) {\n return operations;\n }\n const interactive = classifySurfaceCards([...byId.values()], options);\n const insideInteractive = new Set<string>();\n for (const id of interactive) {\n for (const d of descendantIds(id, byId, options.childIds)) {\n insideInteractive.add(d);\n }\n }\n const flatten = (c: Record<string, unknown>) =>\n c.component === \"Card\" &&\n typeof c.id === \"string\" &&\n !interactive.has(c.id) &&\n !insideInteractive.has(c.id) &&\n c.variant == null &&\n c.border == null;\n\n const flattened: A2UIMarkdownOperation[] = operations.map((op) => {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) return op;\n if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;\n return {\n ...op,\n updateComponents: {\n ...update,\n components: update.components.map((c) =>\n isRecord(c) && flatten(c) ? { ...c, variant: \"section\" } : c,\n ),\n },\n };\n });\n return flattened;\n}\n\n/** Text-bearing components that belong in the chat's markdown, not a surface. */\nconst PROSE_TEXT_COMPONENTS = new Set([\"Title\", \"Text\", \"Caption\", \"Markdown\"]);\n\n/** A component that converts to markdown: text-bearing prose, or a separator next to it. */\ntype ProseItem =\n | { kind: \"text\"; markdown: string }\n | { kind: \"divider\" | \"spacer\" };\n\n/** One line of text: list items and headings cannot span lines in markdown. */\nfunction oneLine(text: string) {\n return text.trim().replace(/\\s*\\n\\s*/g, \" \");\n}\n\n/**\n * A literal List entry as list-item markdown: a non-empty string, or\n * `{ label, description? }` with literal strings only. Anything carrying\n * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.\n */\nfunction listEntryMarkdown(entry: unknown) {\n if (typeof entry === \"string\") return entry.trim() ? oneLine(entry) : null;\n if (!isRecord(entry)) return null;\n for (const key of Object.keys(entry)) {\n if (key !== \"label\" && key !== \"description\") return null;\n }\n if (typeof entry.label !== \"string\" || !entry.label.trim()) return null;\n const label = oneLine(entry.label);\n if (entry.description === undefined) return label;\n if (typeof entry.description !== \"string\") return null;\n return entry.description.trim()\n ? `**${label}** — ${oneLine(entry.description)}`\n : label;\n}\n\n/**\n * A List of literal text items as a markdown list (`marker: \"number\"` →\n * `1. …`, otherwise `- …`), or null when it binds its items, renders\n * `children`, or any item is not plain text.\n */\nfunction listToMarkdown(c: Record<string, unknown>) {\n const children = c.children;\n if (children != null && !(Array.isArray(children) && children.length === 0)) {\n return null;\n }\n if (!Array.isArray(c.items) || c.items.length === 0) return null;\n const lines: string[] = [];\n for (const entry of c.items) {\n const line = listEntryMarkdown(entry);\n if (line === null) return null;\n lines.push(line);\n }\n if (c.marker === \"number\") {\n const start =\n typeof c.start === \"number\" && Number.isInteger(c.start) ? c.start : 1;\n return lines.map((line, i) => `${start + i}. ${line}`).join(\"\\n\");\n }\n return lines.map((line) => `- ${line}`).join(\"\\n\");\n}\n\n/** The prose item a component converts to, or null when it is not prose. */\nfunction toProseItem(c: Record<string, unknown> | undefined) {\n if (!c) return null;\n // A component with an accessibility envelope stays a component: markdown\n // has no place for its label, its live region or its hidden state.\n if (c.accessibility !== undefined) return null;\n if (c.component === \"Divider\") return { kind: \"divider\" as const };\n if (c.component === \"Spacer\") return { kind: \"spacer\" as const };\n if (c.component === \"List\") {\n // A horizontal list is a layout, not a text list; a bound direction\n // may be horizontal at render time.\n if (c.direction !== undefined && c.direction !== \"vertical\") return null;\n const markdown = listToMarkdown(c);\n return markdown === null ? null : { kind: \"text\" as const, markdown };\n }\n if (typeof c.component !== \"string\") return null;\n if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;\n // Only literal strings are prose; `{path}`-bound text is data.\n if (typeof c.text !== \"string\" || c.text.trim() === \"\") return null;\n const text = c.text.trim();\n switch (c.component) {\n case \"Title\": {\n const size = typeof c.size === \"string\" ? c.size : \"md\";\n const level =\n size === \"sm\" ? \"####\" : size === \"md\" || size === \"lg\" ? \"###\" : \"##\";\n return { kind: \"text\" as const, markdown: `${level} ${text}` };\n }\n case \"Text\":\n // Inline children (e.g. a Badge) have no markdown form.\n if (directChildIds(c).length > 0) return null;\n return {\n kind: \"text\" as const,\n markdown: c.strong === true ? `**${text}**` : text,\n };\n default:\n return { kind: \"text\" as const, markdown: text };\n }\n}\n\n/** Prose items as markdown: separators only survive between two text items. */\nfunction proseItemsToMarkdown(items: (ProseItem | null)[]) {\n const blocks: string[] = [];\n let pendingDivider = false;\n for (const item of items) {\n if (item?.kind === \"text\") {\n if (pendingDivider && blocks.length > 0) blocks.push(\"---\");\n pendingDivider = false;\n blocks.push(item.markdown);\n } else if (item?.kind === \"divider\") {\n pendingDivider = true;\n }\n }\n return blocks.join(\"\\n\\n\");\n}\n\n/** Column, column-direction Box, or an informational Card (section/unset variant). */\nfunction isVerticalStack(\n c: Record<string, unknown>,\n interactiveCards: Set<string>,\n) {\n // A container with an accessibility envelope keeps its children: lifted\n // text would lose its hidden state or its live region.\n if (c.accessibility !== undefined) return false;\n if (c.component === \"Column\") return true;\n if (c.component === \"Box\") {\n return c.direction == null || c.direction === \"col\";\n }\n if (c.component === \"Card\") {\n return (\n (c.variant == null || c.variant === \"section\") &&\n typeof c.id === \"string\" &&\n !interactiveCards.has(c.id)\n );\n }\n return false;\n}\n\n/** The child-id list of a stack (`children`, or a lone `child`), else null. */\n/**\n * The children of a stack in render order: `child` first (a Card renders\n * its `child` before its `children`), then `children`.\n */\nfunction stackChildren(c: Record<string, unknown>) {\n const first = typeof c.child === \"string\" ? [c.child] : [];\n if (Array.isArray(c.children)) return [...first, ...c.children];\n if (first.length > 0 && c.children === undefined) return first;\n return null;\n}\n\n/** A contiguous slice `[start, end)` of the stack's children. */\ntype ChildRun = { prose: boolean; start: number; end: number };\n\n/**\n * Partitions the stack's children into alternating prose and surface runs.\n * A run of consecutive prose items is prose only when it holds text: a run of\n * separators alone (Divider/Spacer between two UI components, or at the very\n * start/end of the stack) stays with the surface it sits in.\n */\nfunction partitionChildren(items: (ProseItem | null)[]) {\n const runs: ChildRun[] = [];\n let i = 0;\n while (i < items.length) {\n const candidate = items[i] !== null;\n let hasText = false;\n let j = i;\n while (j < items.length && (items[j] !== null) === candidate) {\n if (items[j]?.kind === \"text\") hasText = true;\n j++;\n }\n const prose = candidate && hasText;\n const last = runs[runs.length - 1];\n if (!prose && last && !last.prose) last.end = j;\n else runs.push({ prose, start: i, end: j });\n i = j;\n }\n return runs;\n}\n\n/** One block of a segmented surface, in render order. */\nexport type SurfaceSegment =\n | { kind: \"markdown\"; markdown: string }\n | { kind: \"surface\"; components: Record<string, unknown>[] };\n\n/**\n * Markdown mode: split a surface into markdown and surface segments so that\n * only real UI renders as A2UI and everything else is the chat's markdown.\n *\n * From `root`, descend through single-child vertical containers (Column,\n * column Box, informational Card) to the first one with several children:\n * the stack. Its children are partitioned, in order, into runs of prose and\n * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal\n * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:\n * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →\n * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →\n * `- …` (or `1. …` for `marker: \"number\"`, `**label** — description` for\n * described items), and a `Divider` between two prose blocks → `---`.\n *\n * Not prose: `{path}`-bound text or items, a Text with inline children, a\n * List with `children`/icons/actions, a template entry, a component with an\n * `accessibility` envelope, and a child whose component has not streamed\n * yet. Separators with no text beside them stay in\n * the surface. An interactive Card (see `classifySurfaceCards`) is never\n * entered.\n *\n * Each prose run becomes a markdown segment; each UI run becomes a surface\n * segment whose `root` is a copy of the stack (its other props kept, `child`\n * dropped) with only that run's `children`, followed by every component\n * reachable from them. When nothing is prose the input comes back as the one\n * surface segment (same array); when everything is (or `root` itself is),\n * there are only markdown segments.\n *\n * Pure and linear in the number of components, so it runs on every stream\n * update.\n *\n * @param components - The components of one surface, root included.\n * @returns The segments in render order.\n *\n * @example\n * ```ts\n * for (const segment of segmentSurfaceProse(components)) {\n * if (segment.kind === \"markdown\") renderMarkdown(segment.markdown);\n * else renderSurface(segment.components);\n * }\n * ```\n */\nexport function segmentSurfaceProse(\n components: Record<string, unknown>[],\n options: ChildWalkOptions = {},\n) {\n const unchanged: SurfaceSegment[] = [{ kind: \"surface\", components }];\n const byId = new Map<string, Record<string, unknown>>();\n for (const c of components) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n const root = byId.get(GENERATIVE_UI_ROOT_ID);\n if (!root) return unchanged;\n // A component whose children are known only at render time (a bound\n // list of tabs) could reference any component. The lift cannot tell\n // which ones to keep, so it keeps the surface whole.\n const hasUnknownChildren = components.some(\n (c) => isRecord(c) && options.childIds?.(c) === \"unknown\",\n );\n if (hasUnknownChildren) return unchanged;\n\n const rootItem = toProseItem(root);\n if (rootItem?.kind === \"text\") {\n const whole: SurfaceSegment[] = [\n { kind: \"markdown\", markdown: rootItem.markdown },\n ];\n return whole;\n }\n\n const interactiveCards = classifySurfaceCards(components, options);\n let stack = root;\n let stackId: string = GENERATIVE_UI_ROOT_ID;\n let children: unknown[];\n const visited = new Set<string>();\n while (true) {\n if (!isVerticalStack(stack, interactiveCards)) return unchanged;\n visited.add(stackId);\n const list = stackChildren(stack);\n if (!list) return unchanged;\n children = list;\n const nextId = list.length === 1 ? list[0] : undefined;\n if (typeof nextId !== \"string\") break;\n const next = byId.get(nextId);\n if (!next || visited.has(nextId) || toProseItem(next)) break;\n stack = next;\n stackId = nextId;\n }\n\n const stackChildIds = children;\n const items = stackChildIds.map((id) =>\n typeof id === \"string\" ? toProseItem(byId.get(id)) : null,\n );\n const runs = partitionChildren(items);\n if (!runs.some((run) => run.prose)) return unchanged;\n\n // Which surface segments each component belongs to (shared ones go to all).\n const surfaceRuns = runs.filter((run) => !run.prose);\n const owners = new Map<string, number[]>();\n surfaceRuns.forEach((run, index) => {\n const pending = stackChildIds\n .slice(run.start, run.end)\n .map(referencedId)\n .filter((id): id is string => id !== undefined);\n const seen = new Set<string>();\n while (pending.length > 0) {\n const id = pending.pop()!;\n // `root` is replaced by the stack copy; the stack never nests in itself.\n const isSkipped = id === GENERATIVE_UI_ROOT_ID || id === stackId;\n if (isSkipped || seen.has(id)) continue;\n seen.add(id);\n const list = owners.get(id);\n if (list) list.push(index);\n else owners.set(id, [index]);\n const c = byId.get(id);\n if (c) pending.push(...directChildIds(c, options.childIds));\n }\n });\n const surfaceComponents = surfaceRuns.map((run) => {\n // `child` is folded into `children` by stackChildren, so the copy must\n // not render it a second time.\n const { child: _child, ...stackRest } = stack;\n const nextRoot: Record<string, unknown> = {\n ...stackRest,\n id: GENERATIVE_UI_ROOT_ID,\n children: stackChildIds.slice(run.start, run.end),\n };\n delete nextRoot.child;\n return [nextRoot];\n });\n for (const c of components) {\n if (!isRecord(c) || typeof c.id !== \"string\" || byId.get(c.id) !== c) {\n continue;\n }\n const ownerIndexes = owners.get(c.id) ?? [];\n for (const index of ownerIndexes) {\n surfaceComponents[index]!.push(c);\n }\n }\n\n let surfaceIndex = 0;\n const segments: SurfaceSegment[] = runs.map((run) => {\n if (run.prose) {\n return {\n kind: \"markdown\",\n markdown: proseItemsToMarkdown(items.slice(run.start, run.end)),\n };\n }\n return { kind: \"surface\", components: surfaceComponents[surfaceIndex++]! };\n });\n return segments;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAUA,SAAgB,aAAa,OAAoC;AAC/D,KAAI,iBAAiB,UAAW,QAAO;AACvC,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAY;AAClB,QACE,OAAO,UAAU,QAAQ,YACzB,OAAO,UAAU,YAAY,YAC7B,UAAU,YAAY,QACtB,UAAU,2BAA2B,mBACrC,OAAO,UAAU,aAAa;;;;;ACclC,MAAM,wCAAwB,IAAI,SAAuC;;;;;;AAOzE,SAAgB,yBAAyB,OAAiC;AACxE,QAAO,sBAAsB,IAAI,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6C7C,eAAsB,iCACpB,OACA,YACA,YACA,SAIyB;CAOzB,MAAM,OAAO;CACb,IAAI,oBAAoB;AACtB,QAAM,YAAY;;AAG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