@copilotkit/runtime 2.0.0-rc.42 → 2.0.0-rc.43

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.
Files changed (63) hide show
  1. package/dist/agent/converters/aisdk.cjs +1 -1
  2. package/dist/agent/converters/aisdk.mjs +1 -1
  3. package/dist/agent/converters/tanstack.cjs +1 -1
  4. package/dist/agent/converters/tanstack.mjs +1 -1
  5. package/dist/index.cjs +2 -1
  6. package/dist/index.d.cts +3 -2
  7. package/dist/index.d.mts +3 -2
  8. package/dist/index.mjs +3 -2
  9. package/dist/runtime/core/package-info.cjs +1 -1
  10. package/dist/runtime/core/package-info.mjs +1 -1
  11. package/dist/runtime/core/runtime.cjs +1 -19
  12. package/dist/runtime/core/runtime.cjs.map +1 -1
  13. package/dist/runtime/core/runtime.d.cts +77 -29
  14. package/dist/runtime/core/runtime.d.cts.map +1 -1
  15. package/dist/runtime/core/runtime.d.mts +77 -29
  16. package/dist/runtime/core/runtime.d.mts.map +1 -1
  17. package/dist/runtime/core/runtime.mjs +2 -19
  18. package/dist/runtime/core/runtime.mjs.map +1 -1
  19. package/dist/runtime/event-transforms/recorded-events.cjs +4 -0
  20. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -1
  21. package/dist/runtime/event-transforms/recorded-events.d.cts +5 -1
  22. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -1
  23. package/dist/runtime/event-transforms/recorded-events.d.mts +5 -1
  24. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -1
  25. package/dist/runtime/event-transforms/recorded-events.mjs +4 -0
  26. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -1
  27. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs +106 -0
  28. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs.map +1 -0
  29. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs +106 -0
  30. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs.map +1 -0
  31. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs +422 -0
  32. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs.map +1 -0
  33. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs +422 -0
  34. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs.map +1 -0
  35. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs +84 -0
  36. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -0
  37. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts +41 -0
  38. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts.map +1 -0
  39. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts +41 -0
  40. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts.map +1 -0
  41. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs +83 -0
  42. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -0
  43. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs +620 -0
  44. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs.map +1 -0
  45. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs +620 -0
  46. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs.map +1 -0
  47. package/dist/runtime/generative-ui/index.d.cts +1 -0
  48. package/dist/runtime/generative-ui/index.d.mts +1 -0
  49. package/dist/runtime/handlers/get-runtime-info.cjs +19 -5
  50. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  51. package/dist/runtime/handlers/get-runtime-info.mjs +20 -6
  52. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  53. package/dist/runtime/handlers/handle-run.cjs +0 -2
  54. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  55. package/dist/runtime/handlers/handle-run.mjs +0 -2
  56. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  57. package/dist/runtime/handlers/shared/agent-utils.cjs +17 -14
  58. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  59. package/dist/runtime/handlers/shared/agent-utils.mjs +18 -15
  60. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  61. package/dist/runtime/index.d.cts +2 -1
  62. package/dist/runtime/index.d.mts +2 -1
  63. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../src/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n processEnv,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport { resolveForwardHeadersPolicy } from \"../handlers/header-utils\";\nimport { resolveSseKeepAliveIntervalSeconds } from \"../handlers/shared/sse-keep-alive\";\nimport {\n resolveThreadAccessMode,\n warnIfThreadListRefused,\n warnIfThreadOwnershipUnenforced,\n} from \"../handlers/shared/thread-access\";\nimport type {\n ThreadAccessMode,\n ThreadsConfig,\n} from \"../handlers/shared/thread-access\";\nexport type {\n ThreadAccessMode,\n ThreadsConfig,\n} from \"../handlers/shared/thread-access\";\nimport type {\n ForwardHeadersConfig,\n ResolvedForwardHeadersPolicy,\n} from \"../handlers/header-utils\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { RUNTIME_PACKAGE_VERSION } from \"./package-info\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createDebugLogger, getRuntimeLogger } from \"./logger\";\nimport type { CopilotRuntimeLogger } from \"./logger\";\nexport type { CopilotRuntimeLogger } from \"./logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry/disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus, isDebugEventFeedEnabled } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\n// Type-only: @copilotkit/channels-core is the pure-ESM type source, so a value import would break this\n// package's CJS output. The channels are validated + activated (wired to delivery\n// transports) by `startChannels` from @copilotkit/channels-intelligence, called\n// by the Channel-listener bootstrap — not here.\nimport type { Channel } from \"@copilotkit/channels-core\";\nimport telemetry from \"../telemetry/telemetry-client\";\nimport type { TelemetryCapture } from \"../telemetry/telemetry-client\";\n\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../telemetry/telemetry-identity\";\nimport {\n attachRuntimeErrorReporter,\n getRuntimeErrorReporterFromOptions,\n} from \"./runtime-error-reporter\";\nimport type {\n CopilotRuntimeLearningConfig,\n CopilotRuntimeUser,\n} from \"./learning\";\nimport { assertStableLearningContainerId } from \"./learning\";\n\nexport type {\n CopilotRuntimeUser,\n CopilotRuntimeLearningConfig,\n CopilotRuntimeLearningContext,\n GetLearningContainerId,\n LearningContainerSelectorInput,\n GetTrajectoryLearningContainerIds,\n TrajectoryLearningContainerSelectorInput,\n} from \"./learning\";\n\nexport const VERSION = RUNTIME_PACKAGE_VERSION;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\n/** Per-server tool policy belongs to the external middleware, and the release the runtime depends on does not support it. */\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Intelligence-only HTTP/SSE credentials from trusted server config, never iframe input. */\n headers?: Record<string, string>;\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n /**\n * Experimental: CopilotKit generative UI surfaces (`render_ui`).\n *\n * - Omitted: applied to a run when the React provider sends a\n * tool-transport envelope (`forwardedProps.copilotkit.ui`).\n * - `true`: applied to every run.\n * - `{ agents }`: applied to every run of the named agents.\n * - `false`: never applied.\n *\n * A run with a markdown-transport envelope never gets it: the model writes\n * the UI in a2ui code fences, and the client renders them.\n */\n generativeUI?: boolean | BaseCopilotRuntimeMiddlewareOptions;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Properties added to every telemetry event this runtime sends.\n *\n * For what is true of the whole process rather than of one event. A product\n * built on this runtime can name itself here and then be told apart in the\n * events that already go, rather than sending events of its own.\n *\n * No effect when telemetry is off: nothing is sent, so nothing carries this.\n */\n telemetryProperties?: Record<string, unknown>;\n /**\n * A capture scope to emit this runtime's telemetry through, instead of one\n * built from the identity options above.\n *\n * @internal Set by the deprecated v1 entrypoint, which delegates every\n * request to this runtime. Handing its own scope down is what collapses\n * the duplicate: the v1 entrypoint no longer emits the same events itself,\n * and the events this runtime sends still reach Segment and still report\n * the v1 surface. There is no reason for an application to pass this.\n */\n ɵtelemetry?: TelemetryCapture;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n /**\n * Where the runtime writes its logs. Pass pino, `console`, or any object\n * with pino-style `debug`, `info`, `warn` and `error` methods\n * (`(message)` or `(fields, message)`). When `debug` is on, debug output\n * goes to `logger.child({ component: \"copilotkit-debug\" })`, or to the\n * logger itself when it has no `child`.\n *\n * Without it, the runtime writes to the console, and debug output is JSON\n * lines on stdout.\n */\n logger?: CopilotRuntimeLogger;\n /**\n * Policy controlling which inbound HTTP headers are forwarded onto the\n * outgoing agent call. By default a built-in denylist strips known\n * infrastructure/proxy/platform headers (`x-forwarded-*`, `x-real-ip`,\n * `x-vercel-*`, `x-copilotcloud-*`, etc.) while `authorization` and custom\n * `x-*` application headers continue to forward (#5712). Set\n * `{ useDefaultDenylist: false }` to restore the previous wide-open behavior.\n */\n forwardHeaders?: ForwardHeadersConfig;\n /**\n * Seconds of silence on an SSE response before the runtime writes a\n * `: keep-alive` comment, so proxies and browsers with idle timeouts keep\n * the connection open through long reasoning or tool phases. Comments are\n * transport frames and never become AG-UI events. `0` disables it.\n * @default 15\n */\n sseKeepAliveIntervalSeconds?: number;\n /**\n * Opt-in flag exposing the client-facing memory proxy routes\n * (`/memories`, `/memories/recall`, `/memories/subscribe`, `/memories/:id`).\n *\n * Defaults to `false` — a **secure default**. When off, every `/memories/*`\n * request 404s as if the route did not exist, so an un-opted-in deployment\n * reveals nothing about memory even when Intelligence is configured. This does\n * NOT affect the agent's own server-side memory tooling (`recall_memory` runs\n * via the Intelligence MCP path, separate from this client REST proxy).\n *\n * Flip to `true` to power a client memory inspector (e.g. the dev console's\n * Memory tab). Existing Intelligence deployments relying on the previously\n * always-on Learning tab must set this to restore it.\n *\n * @deprecated Configure `memory.access` on an Intelligence Runtime. That one\n * policy enables and limits both agent and browser Memory.\n */\n exposeMemoryRoutes?: boolean;\n /**\n * How local Threads are shared among callers that `identifyUser` does not\n * identify, when no Intelligence is configured. Has no effect on an\n * Intelligence runtime, where the platform scopes Threads per user.\n *\n * With `identifyUser`, every Thread operation (list, read, connect, run,\n * stop, clear) reaches only the caller's own Threads, whatever this says.\n * Without it, by default (`access: \"owner\"`), a Thread id works as a\n * capability: whoever holds it may read, connect to, continue and stop that\n * Thread, but listing and clearing Threads are refused with HTTP 403.\n * `access: \"open\"` also lets every caller list and clear the Threads created\n * without identity, as in earlier releases. That is insecure for any\n * deployment that more than one person can reach. A Thread created by an\n * identified user is never reachable without that identity.\n */\n threads?: ThreadsConfig;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport type MemoryAccess = \"none\" | \"read\" | \"read-write\";\n\nexport interface MemoryGrant {\n readonly user: MemoryAccess;\n readonly project: MemoryAccess;\n}\n\nexport type MemoryConsumer = \"agent\" | \"client\";\n\nexport interface CopilotRuntimeMemoryConfig {\n /** Resolves immutable Memory access for one authenticated web request. */\n access(input: {\n readonly request: Request;\n readonly user: CopilotRuntimeUser;\n readonly consumer: MemoryConsumer;\n }): MaybePromise<MemoryGrant | null>;\n}\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n /**\n * Resolves the authenticated user for a request. When set, each Thread\n * belongs to the user whose request created it, and only that user can list,\n * read, replay, clear, continue or stop it. The runner must enforce owners\n * (InMemoryAgentRunner and SqliteAgentRunner do); with a runner that does\n * not, those requests are refused. See `threads`.\n *\n * Threads that SqliteAgentRunner stored before it recorded owners belong to\n * nobody: as before the upgrade, whoever holds such a Thread's id can reach\n * it, and continuing it does not claim it. The runner logs how many it holds\n * when it opens the database. Every new Thread is owned. InMemoryAgentRunner\n * keeps no Threads across a restart, so it holds no such Threads.\n */\n identifyUser?: IdentifyUserCallback;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n /** Intelligence Channels require the Intelligence runtime; not available in SSE mode. */\n channels?: undefined;\n}\n\ninterface CopilotIntelligenceRuntimeBaseOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /**\n * Chooses one stable Learning Container ID for each web or Channel run.\n * @deprecated Configure `getLearningContainerId` on `CopilotKitIntelligence`.\n */\n ɵlearning?: CopilotRuntimeLearningConfig;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /**\n * Interval (ms) between Phoenix heartbeats on the runner WebSocket. Keep it\n * below the idle timeout of any proxy between the runtime and Intelligence.\n * @default 15_000\n */\n heartbeatIntervalMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n /**\n * Intelligence Channels declared by this runtime. Each is a\n * `createChannel({ name })` instance. Only available on the Intelligence runtime\n * path. Names are validated (required, lowercase kebab-case, unique) and wired\n * to delivery/egress transports when activated via `startChannels` from\n * `@copilotkit/channels-intelligence` — not at construction.\n */\n}\n\ntype NonEmptyChannels = readonly [Channel, ...Channel[]];\n\n/** Intelligence runtime options with web identity, Channels, or both. */\nexport type CopilotIntelligenceRuntimeOptions =\n CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n /** Resolves the authenticated user for web requests. */\n identifyUser: IdentifyUserCallback;\n /** Enables agent and browser Memory under one request policy. */\n memory?: CopilotRuntimeMemoryConfig;\n channels?: readonly Channel[];\n }\n | {\n /** Channels-only runtimes expose no functional web surface. */\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n );\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n generativeUI?: CopilotRuntimeOptions[\"generativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n /**\n * Resolve the license checker, verifying the token on the first call.\n * Optional so external implementations of this published interface remain\n * source-compatible; absent or resolving to `undefined` means no license\n * gating.\n */\n getLicenseChecker?(): Promise<LicenseChecker | undefined>;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n /**\n * The logger the runtime writes to. Optional so external implementations of\n * this published interface remain source-compatible; a missing value means\n * the console.\n */\n logger?: CopilotRuntimeLogger;\n /**\n * Runtime-bound telemetry capture. Optional so external implementations of\n * this published interface remain source-compatible.\n */\n telemetry?: TelemetryCapture;\n /**\n * Resolved inbound-header forwarding policy read by the /run and /connect call\n * sites. Optional on the published interface so an external `CopilotRuntimeLike`\n * implementor predating this field stays source-compatible (non-breaking minor\n * release). Concrete runtimes (`BaseCopilotRuntime`) always resolve and set it;\n * the call sites coalesce a missing value to the default resolved policy\n * (`resolveForwardHeadersPolicy(undefined)` — default-on denylist).\n */\n forwardHeadersPolicy?: ResolvedForwardHeadersPolicy;\n /**\n * Resolved SSE keep-alive interval in seconds; `0` disables it. Optional on\n * the published interface for the same source-compatibility reason as\n * `forwardHeadersPolicy`; the SSE call sites fall back to the default.\n */\n sseKeepAliveIntervalSeconds?: number;\n /**\n * Resolved opt-in flag for the client-facing memory proxy routes. Optional on\n * the published interface so an external `CopilotRuntimeLike` implementor\n * predating this field stays source-compatible; the dispatcher coalesces a\n * missing value to `false` (secure default — routes hidden). Concrete runtimes\n * (`BaseCopilotRuntime`) always resolve and set it.\n */\n exposeMemoryRoutes?: boolean;\n /**\n * Resolved local Thread access mode. Optional on the published interface so\n * an external implementor stays source-compatible; a missing value means\n * the default (`DEFAULT_THREAD_ACCESS`).\n */\n threadAccess?: ThreadAccessMode;\n memory?: CopilotRuntimeMemoryConfig;\n learning?: CopilotRuntimeLearningConfig;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: typeof RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n channels: Channel[];\n learning?: CopilotRuntimeLearningConfig;\n mode: typeof RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public generativeUI: CopilotRuntimeOptions[\"generativeUI\"];\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n public readonly logger: CopilotRuntimeLogger;\n public readonly telemetry: TelemetryCapture;\n public readonly forwardHeadersPolicy: ResolvedForwardHeadersPolicy;\n public readonly sseKeepAliveIntervalSeconds: number;\n public readonly exposeMemoryRoutes: boolean;\n public readonly threadAccess: ThreadAccessMode;\n public readonly memory?: CopilotRuntimeMemoryConfig;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's getLicenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n /** Runtimes without Intelligence do no license gating. */\n getLicenseChecker(): Promise<LicenseChecker | undefined> {\n return Promise.resolve(undefined);\n }\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n this.logger = getRuntimeLogger(options);\n logRuntimeTelemetryDisclosure(this.logger);\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n generativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.generativeUI = generativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken = firstNonBlankLicenseToken(\n options.licenseToken,\n processEnv().COPILOTKIT_LICENSE_TOKEN,\n );\n\n // Snapshot identity and sampling authority for this runtime. Capture\n // scopes share process-level telemetry settings but cannot be rewritten by\n // another runtime's construction.\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n options.telemetryId,\n processEnv().CPK_TELEMETRY_ID,\n );\n this.telemetry =\n options.ɵtelemetry ??\n telemetry.createScope(\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : this.resolvedLicenseToken !== undefined\n ? { licenseToken: this.resolvedLicenseToken }\n : {},\n );\n\n // Set here rather than per event, beside the license token and for the same\n // reason: it describes the caller, not the call, and every event should\n // carry it whichever handler fired.\n if (options.telemetryProperties) {\n telemetry.setGlobalProperties(options.telemetryProperties);\n }\n\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createDebugLogger(options.logger);\n }\n // The debug feed carries every thread's events to any subscriber, so the\n // bus only exists where the feed is allowed to be served. Resolving\n // `debug` first keeps the bus and the route gate reading one value.\n if (isDebugEventFeedEnabled(this.debug)) {\n this.debugEventBus = new DebugEventBus(this.logger);\n }\n // Resolve the inbound-header forwarding policy once (mirroring the\n // `debug` → `ResolvedDebugConfig` resolve-once above) so both the /run and\n // /connect call sites read the exact same resolved policy off the runtime\n // and can never diverge.\n this.forwardHeadersPolicy = resolveForwardHeadersPolicy(\n options.forwardHeaders,\n );\n this.sseKeepAliveIntervalSeconds = resolveSseKeepAliveIntervalSeconds(\n options.sseKeepAliveIntervalSeconds,\n );\n // Secure default: the client-facing memory proxy routes stay hidden (404)\n // unless a deployment explicitly opts in.\n this.memory = (options as { memory?: CopilotRuntimeMemoryConfig }).memory;\n this.exposeMemoryRoutes =\n this.memory !== undefined || (options.exposeMemoryRoutes ?? false);\n this.threadAccess = resolveThreadAccessMode(options.threads);\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n readonly identifyUser?: IdentifyUserCallback;\n\n constructor(options: CopilotSseRuntimeOptions) {\n // Runtime guard mirroring the discriminated-union type: the SSE runtime has\n // no Intelligence delivery path, so `channels` cannot be honored here. The\n // type forbids it, but a JS / `as any` caller passing `{ agents, channels }`\n // would otherwise land here and have `channels` silently dropped — fail\n // loud instead.\n const channels = (options as { channels?: unknown[] }).channels;\n if (Array.isArray(channels) && channels.length > 0) {\n throw new Error(\n \"`channels` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Intelligence Channels are not available in SSE mode.\",\n );\n }\n if ((options as { ɵlearning?: unknown }).ɵlearning !== undefined) {\n throw new Error(\n \"`ɵlearning` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Learning Containers are not available in SSE mode.\",\n );\n }\n if (\n options.identifyUser !== undefined &&\n typeof options.identifyUser !== \"function\"\n ) {\n throw new Error(\"`identifyUser` must be a callback\");\n }\n super(options, options.runner ?? new InMemoryAgentRunner());\n this.identifyUser = options.identifyUser;\n warnIfThreadOwnershipUnenforced(this);\n warnIfThreadListRefused(this);\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser?: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly channels: Channel[];\n readonly learning?: CopilotRuntimeLearningConfig;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n private licenseCheckerPromise?: Promise<LicenseChecker>;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n const rawOptions = options as CopilotIntelligenceRuntimeBaseOptions & {\n identifyUser?: unknown;\n channels?: unknown;\n memory?: unknown;\n runner?: unknown;\n ɵlearning?: unknown;\n };\n // Runtime guard mirroring the `channels` guard in `CopilotSseRuntime`: this\n // constructor hardcodes `IntelligenceAgentRunner` into its `super()` call,\n // so a caller-supplied `runner` can never be honored. The type forbids it\n // (`runner` is declared only on `CopilotSseRuntimeOptions`), but that is an\n // excess-property check — a JS / `as any` / non-literal caller passing\n // `{ intelligence, runner }` would otherwise land here and have `runner`\n // silently dropped in favor of the auto-wired one. Fail loud instead.\n if (rawOptions.runner !== undefined) {\n throw new Error(\n \"Intelligence Runtime auto-wires its own `runner`; passing `runner` \" +\n \"alongside `intelligence` is not supported. Durability is managed by \" +\n \"the Intelligence service, so `InMemoryAgentRunner` / a SQLite runner \" +\n \"is unnecessary here — drop `runner`, or drop `intelligence` to run \" +\n \"in SSE mode with a runner you control.\",\n );\n }\n if (\n rawOptions.identifyUser !== undefined &&\n typeof rawOptions.identifyUser !== \"function\"\n ) {\n throw new Error(\"Intelligence Runtime `identifyUser` must be a callback\");\n }\n if (rawOptions.threads !== undefined) {\n getRuntimeLogger(options).warn(\n \"[CopilotKit] `threads` has no effect on an Intelligence runtime: the \" +\n \"platform scopes threads per user. Remove the option.\",\n );\n }\n if (\n rawOptions.channels !== undefined &&\n !Array.isArray(rawOptions.channels)\n ) {\n throw new Error(\"Intelligence Runtime `channels` must be an array\");\n }\n const hasWebIdentity = typeof rawOptions.identifyUser === \"function\";\n const hasChannels =\n Array.isArray(rawOptions.channels) && rawOptions.channels.length > 0;\n if (!hasWebIdentity && !hasChannels) {\n throw new Error(\n \"Intelligence Runtime requires web `identifyUser`, at least one Channel, or both surfaces\",\n );\n }\n if (\n rawOptions.memory !== undefined &&\n (typeof rawOptions.memory !== \"object\" ||\n rawOptions.memory === null ||\n typeof (rawOptions.memory as { access?: unknown }).access !==\n \"function\")\n ) {\n throw new Error(\n \"Intelligence Runtime `memory.access` must be a callback\",\n );\n }\n if (rawOptions.memory !== undefined && !hasWebIdentity) {\n throw new Error(\n \"Intelligence Runtime web `memory` requires `identifyUser`\",\n );\n }\n if (\n rawOptions.ɵlearning !== undefined &&\n (typeof rawOptions.ɵlearning !== \"object\" ||\n rawOptions.ɵlearning === null ||\n !(\n typeof (rawOptions.ɵlearning as { containerId?: unknown })\n .containerId === \"string\" ||\n typeof (rawOptions.ɵlearning as { containerId?: unknown })\n .containerId === \"function\"\n ))\n ) {\n throw new Error(\n \"Intelligence Runtime `ɵlearning.containerId` must be a stable ID or callback\",\n );\n }\n if (\n rawOptions.ɵlearning !== undefined &&\n options.intelligence.ɵgetLearningContainerId?.() !== undefined\n ) {\n throw new Error(\n \"Configure Learning Containers with `getLearningContainerId` on `CopilotKitIntelligence`; do not also pass deprecated `ɵlearning` to `CopilotRuntime`\",\n );\n }\n if (\n typeof (rawOptions.ɵlearning as { containerId?: unknown } | undefined)\n ?.containerId === \"string\"\n ) {\n assertStableLearningContainerId(\n (rawOptions.ɵlearning as { containerId: string }).containerId,\n );\n }\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n heartbeatIntervalMs: options.heartbeatIntervalMs,\n logger: getRuntimeLogger(options),\n }),\n );\n this.intelligence = options.intelligence;\n this.learning = options.ɵlearning;\n this.identifyUser = hasWebIdentity\n ? (rawOptions.identifyUser as IdentifyUserCallback)\n : undefined;\n this.generateThreadNames = options.generateThreadNames ?? true;\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n // Declared Intelligence Channels. Lowercase kebab-case name-shape validation\n // (`assertValidChannelNames`) lives in the channels-intelligence launcher —\n // it can't run here because it's a value import from the pure-ESM\n // `@copilotkit/channels-intelligence`, which this CJS package must not pull in.\n // Name UNIQUENESS across declared Channels is enforced by\n // `ChannelManager.activate()`, not the launcher: the managed path activates\n // one Channel per launcher call, so the launcher never sees the full set.\n // Fail fast on the most common misconfiguration (a missing name) right here\n // at construction, though, rather than only at activation.\n this.channels = [\n ...((rawOptions.channels as readonly Channel[] | undefined) ?? []),\n ];\n for (const c of this.channels) {\n if (!c || typeof c !== \"object\" || !c.name) {\n throw new Error(\n \"Intelligence Channel is missing a `name` — pass createChannel({ name }) for each Channel in `channels`\",\n );\n }\n }\n }\n\n /**\n * Verify the license token on first use, then reuse the result. Not done in\n * the constructor: edge-safe (Web Crypto) verification is async, and\n * Cloudflare Workers forbid crypto work in global scope, where runtimes are\n * usually constructed. Reuses the base-resolved token so feature gating and\n * telemetry attribution can never disagree.\n */\n override getLicenseChecker(): Promise<LicenseChecker> {\n this.licenseCheckerPromise ??= Promise.resolve().then(() =>\n createLicenseChecker(this.resolvedLicenseToken ?? \"\"),\n );\n return this.licenseCheckerPromise;\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compile-time phantom brand marking a {@link CopilotRuntime} that was\n * constructed with at least one declared Intelligence Channel. It has no runtime\n * representation — the shim never sets this property; it exists purely so\n * `createCopilotRuntimeHandler` can tell, at the type level, that the resulting\n * handler will carry a non-optional `.channels` control surface.\n */\nexport interface RuntimeWithDeclaredChannels {\n /**\n * @internal Phantom brand key. Never present at runtime; do not read or set.\n */\n readonly __copilotkitChannelsDeclared: true;\n}\n\n/**\n * Instance shape of the {@link CopilotRuntime} compatibility shim. Extends\n * {@link CopilotRuntimeLike} with the Intelligence-only accessors the shim\n * surfaces (all `undefined` in SSE mode). Declared explicitly so the exported\n * `CopilotRuntime` name resolves as a type as well as a value.\n */\nexport interface CopilotRuntime extends CopilotRuntimeLike {\n /** Telemetry capture bound to this runtime's construction-time identity. */\n telemetry: TelemetryCapture;\n /** Auto-generate short thread names; `undefined` in SSE mode. */\n generateThreadNames?: boolean;\n /** Thread lock TTL in seconds; `undefined` in SSE mode. */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock; `undefined` in SSE mode. */\n lockKeyPrefix?: string;\n /** Thread lock heartbeat interval in seconds; `undefined` in SSE mode. */\n lockHeartbeatIntervalSeconds?: number;\n /** Declared Intelligence Channels; `undefined` in SSE mode. */\n channels?: Channel[];\n /** Learning Container selector; `undefined` in SSE mode. */\n learning?: CopilotRuntimeLearningConfig;\n}\n\n/**\n * Constructor type for the {@link CopilotRuntime} compatibility shim.\n *\n * The first overload fires when the caller passes `intelligence` together with a\n * non-empty `channels` tuple: it returns a {@link RuntimeWithDeclaredChannels}-\n * branded runtime, which `createCopilotRuntimeHandler` maps to a handler whose\n * `.channels` is non-optional. Every other configuration (SSE, or Intelligence\n * without channels, or an empty `channels: []`) falls through to the second\n * overload and stays unbranded, so its handler keeps `.channels` optional.\n *\n * A class constructor cannot vary its return type across overloads (it is pinned\n * to the instance type), so the branding lives on this construct-signature\n * interface instead of on the class itself.\n */\nexport interface CopilotRuntimeConstructor {\n new (\n options: CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n identifyUser: IdentifyUserCallback;\n memory?: CopilotRuntimeMemoryConfig;\n channels: NonEmptyChannels;\n }\n | {\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n ),\n ): CopilotRuntime & RuntimeWithDeclaredChannels;\n new (options: CopilotRuntimeOptions): CopilotRuntime;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n *\n * Exported to consumers as the {@link CopilotRuntime} value (typed as\n * {@link CopilotRuntimeConstructor}) rather than as a class, so that the\n * channel-presence brand can flow from construction into the handler type.\n */\nclass CopilotRuntimeShim implements CopilotRuntime {\n private delegate: CopilotSseRuntime | CopilotIntelligenceRuntime;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n\n const reporter = getRuntimeErrorReporterFromOptions(options);\n if (reporter) {\n attachRuntimeErrorReporter(this, reporter);\n }\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get generativeUI(): CopilotRuntimeOptions[\"generativeUI\"] {\n return this.delegate.generativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return this.delegate.identifyUser;\n }\n\n get threadAccess(): ThreadAccessMode {\n return this.delegate.threadAccess;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get channels(): Channel[] | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.channels\n : undefined;\n }\n\n get learning(): CopilotRuntimeLearningConfig | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.learning\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n getLicenseChecker(): Promise<LicenseChecker | undefined> {\n return this.delegate.getLicenseChecker();\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n\n get logger(): CopilotRuntimeLogger {\n return this.delegate.logger;\n }\n\n get telemetry(): TelemetryCapture {\n return this.delegate.telemetry;\n }\n\n get forwardHeadersPolicy(): ResolvedForwardHeadersPolicy {\n return this.delegate.forwardHeadersPolicy;\n }\n\n get sseKeepAliveIntervalSeconds(): number {\n return this.delegate.sseKeepAliveIntervalSeconds;\n }\n\n get exposeMemoryRoutes(): boolean | undefined {\n return this.delegate.exposeMemoryRoutes;\n }\n\n get memory(): CopilotRuntimeMemoryConfig | undefined {\n return this.delegate.memory;\n }\n}\n\n/**\n * The public `CopilotRuntime` constructor. Backed by {@link CopilotRuntimeShim}\n * but typed as {@link CopilotRuntimeConstructor} so that constructing with a\n * non-empty `channels` array yields a {@link RuntimeWithDeclaredChannels}-branded\n * runtime type.\n *\n * The `as unknown as` cast is required (not dishonest widening): the brand is a\n * phantom, compile-time-only marker with no runtime representation, so the shim\n * instances legitimately do not carry the brand property. Behavior is identical\n * to the former `class CopilotRuntime` — this only refines the static type.\n */\nexport const CopilotRuntime: CopilotRuntimeConstructor =\n CopilotRuntimeShim as unknown as CopilotRuntimeConstructor;\n"],"mappings":";;;;;;;;;;;;;;;;;AAmFA,MAAa,UAAU;;;;;;AAyFvB,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAmTT,IAAe,qBAAf,MAAgE;;CAiC9D,oBAAyD;AACvD,SAAO,QAAQ,QAAQ,OAAU;;CAGnC,YAAY,SAAoC,QAAqB;AACnE,OAAK,SAAS,iBAAiB,QAAQ;AACvC,gCAA8B,KAAK,OAAO;EAE1C,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,kBACA,iBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,eAAe;AACpB,OAAK,SAAS;AAKd,OAAK,uBAAuB,0BAC1B,QAAQ,cACR,YAAY,CAAC,yBACd;EAKD,MAAM,sBAAsB,yBAC1B,QAAQ,aACR,YAAY,CAAC,iBACd;AACD,OAAK,YACH,QAAQ,cACR,UAAU,YACR,wBAAwB,SACpB,EAAE,aAAa,qBAAqB,GACpC,KAAK,yBAAyB,SAC5B,EAAE,cAAc,KAAK,sBAAsB,GAC3C,EAAE,CACT;AAKH,MAAI,QAAQ,oBACV,WAAU,oBAAoB,QAAQ,oBAAoB;A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AAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAiC;AACnC,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,WAAkC;AACpC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,WACd;;CAGN,IAAI,WAAqD;AACvD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,WACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,oBAAyD;AACvD,SAAO,KAAK,SAAS,mBAAmB;;CAG1C,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAA+B;AACjC,SAAO,KAAK,SAAS;;CAGvB,IAAI,YAA8B;AAChC,SAAO,KAAK,SAAS;;CAGvB,IAAI,uBAAqD;AACvD,SAAO,KAAK,SAAS;;CAGvB,IAAI,8BAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,qBAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAiD;AACnD,SAAO,KAAK,SAAS;;;;;;;;;;;;;;AAezB,MAAa,iBACX"}
1
+ {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../src/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n processEnv,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport { resolveForwardHeadersPolicy } from \"../handlers/header-utils\";\nimport { resolveSseKeepAliveIntervalSeconds } from \"../handlers/shared/sse-keep-alive\";\nimport {\n resolveThreadAccessMode,\n warnIfThreadListRefused,\n warnIfThreadOwnershipUnenforced,\n} from \"../handlers/shared/thread-access\";\nimport type {\n ThreadAccessMode,\n ThreadsConfig,\n} from \"../handlers/shared/thread-access\";\nexport type {\n ThreadAccessMode,\n ThreadsConfig,\n} from \"../handlers/shared/thread-access\";\nimport type {\n ForwardHeadersConfig,\n ResolvedForwardHeadersPolicy,\n} from \"../handlers/header-utils\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { RUNTIME_PACKAGE_VERSION } from \"./package-info\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createDebugLogger, getRuntimeLogger } from \"./logger\";\nimport type { CopilotRuntimeLogger } from \"./logger\";\nexport type { CopilotRuntimeLogger } from \"./logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../telemetry/disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus, isDebugEventFeedEnabled } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\n// Type-only: @copilotkit/channels-core is the pure-ESM type source, so a value import would break this\n// package's CJS output. The channels are validated + activated (wired to delivery\n// transports) by `startChannels` from @copilotkit/channels-intelligence, called\n// by the Channel-listener bootstrap — not here.\nimport type { Channel } from \"@copilotkit/channels-core\";\nimport telemetry from \"../telemetry/telemetry-client\";\nimport type { TelemetryCapture } from \"../telemetry/telemetry-client\";\n\nimport {\n firstNonBlankLicenseToken,\n firstNonBlankTelemetryId,\n} from \"../telemetry/telemetry-identity\";\nimport {\n attachRuntimeErrorReporter,\n getRuntimeErrorReporterFromOptions,\n} from \"./runtime-error-reporter\";\nimport type {\n CopilotRuntimeLearningConfig,\n CopilotRuntimeUser,\n} from \"./learning\";\nimport { assertStableLearningContainerId } from \"./learning\";\n\nexport type {\n CopilotRuntimeUser,\n CopilotRuntimeLearningConfig,\n CopilotRuntimeLearningContext,\n GetLearningContainerId,\n LearningContainerSelectorInput,\n GetTrajectoryLearningContainerIds,\n TrajectoryLearningContainerSelectorInput,\n} from \"./learning\";\n\nexport const VERSION = RUNTIME_PACKAGE_VERSION;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\n/** Per-server tool policy belongs to the external middleware, and the release the runtime depends on does not support it. */\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Intelligence-only HTTP/SSE credentials from trusted server config, never iframe input. */\n headers?: Record<string, string>;\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\n/** An A2UI protocol version that an agent speaks. */\nexport type A2UIVersion = \"0.9\" | \"1.0\";\n\n/**\n * Options of {@link CopilotRuntimeMiddlewares.generativeUI}.\n *\n * The client renders A2UI 1.0 only. An agent that speaks A2UI v0.9 is set\n * to `\"0.9\"` with `a2uiVersion`: the runtime then gives it the v0.9 tool and\n * catalog, and converts its surfaces to 1.0 for the client and the clicks\n * on them back to v0.9 for the agent.\n *\n * @example\n * ```ts\n * new CopilotRuntime({\n * agents: { legacy: legacyAgent, current: currentAgent },\n * generativeUI: { a2uiVersion: { legacy: \"0.9\" } },\n * });\n * ```\n */\nexport interface GenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {\n /**\n * The A2UI version that the agents speak. Default: `\"1.0\"`.\n *\n * - `\"1.0\"`: the agent gets the `render_ui` tool and the generative UI\n * guide.\n * - `\"0.9\"`: the agent gets the `render_a2ui` tool of\n * `@ag-ui/a2ui-middleware`, its guide, and the v0.9 component schema of\n * the client's catalog. It does not get `render_ui`.\n * - A record of agent id to version: one version for each agent. An agent\n * that is not in the record speaks `\"1.0\"`.\n *\n * For both versions, the runtime converts the v0.9 surfaces that a run\n * emits (for example, from a tool result) to 1.0, and turns a click on a\n * converted surface back into a v0.9 action.\n */\n a2uiVersion?: A2UIVersion | Record<string, A2UIVersion>;\n /**\n * v0.9 agents only. The component schema for `A2UIMiddleware` to add to\n * the agent's context. It replaces the schema that the runtime makes from\n * the client's catalog.\n */\n schema?: A2UIMiddlewareConfig[\"schema\"];\n /**\n * v0.9 agents only. The generation lifecycle options of `A2UIMiddleware`:\n * `debugExposure`, `showProgressTokens` and `maxAttempts`.\n */\n recovery?: A2UIMiddlewareConfig[\"recovery\"];\n /**\n * v0.9 agents only. Adds the A2UI render tool to the agent's tools: `true`\n * adds `render_a2ui`, a string adds it with that name, and `false` adds no\n * tool. Default: `true` when the client sends a generative UI catalog\n * with the \"tool\" transport.\n */\n injectA2UITool?: A2UIMiddlewareConfig[\"injectA2UITool\"];\n /**\n * v0.9 agents only. The tool names that `A2UIMiddleware` streams into\n * surfaces. Default: `[\"render_a2ui\"]`.\n */\n a2uiToolNames?: A2UIMiddlewareConfig[\"a2uiToolNames\"];\n /**\n * v0.9 agents only. The tool names that `A2UIMiddleware` treats as\n * generation wrappers: a render call inside one of them belongs to it.\n * Left out, every tool can wrap a render call. Use `[]` when there are no\n * generation wrappers.\n */\n a2uiGenerationToolNames?: A2UIMiddlewareConfig[\"a2uiGenerationToolNames\"];\n /**\n * v0.9 agents only. The catalog id of the surfaces that `A2UIMiddleware`\n * creates from a streamed render tool call. Default: the catalog id of the\n * component schema in the agent's context.\n */\n defaultCatalogId?: A2UIMiddlewareConfig[\"defaultCatalogId\"];\n}\n\ninterface CopilotRuntimeMiddlewares {\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n /**\n * CopilotKit generative UI surfaces (A2UI 1.0).\n *\n * - Omitted: applied to a run when the React provider sends a\n * tool-transport envelope (`forwardedProps.copilotkit.ui`).\n * - `true`: applied to every run.\n * - An object: applied to every run of `agents` (all agents when\n * omitted). See {@link GenerativeUIOptions}, which also sets the A2UI\n * version of each agent with `a2uiVersion`.\n * - `false`: never applied.\n *\n * A run with a markdown-transport envelope never gets it: the model writes\n * the UI in a2ui code fences, and the client renders them.\n */\n generativeUI?: boolean | GenerativeUIOptions;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Standalone telemetry identity. Falls back to CPK_TELEMETRY_ID before legacy license identity. */\n telemetryId?: string;\n /**\n * Properties added to every telemetry event this runtime sends.\n *\n * For what is true of the whole process rather than of one event. A product\n * built on this runtime can name itself here and then be told apart in the\n * events that already go, rather than sending events of its own.\n *\n * No effect when telemetry is off: nothing is sent, so nothing carries this.\n */\n telemetryProperties?: Record<string, unknown>;\n /**\n * A capture scope to emit this runtime's telemetry through, instead of one\n * built from the identity options above.\n *\n * @internal Set by the deprecated v1 entrypoint, which delegates every\n * request to this runtime. Handing its own scope down is what collapses\n * the duplicate: the v1 entrypoint no longer emits the same events itself,\n * and the events this runtime sends still reach Segment and still report\n * the v1 surface. There is no reason for an application to pass this.\n */\n ɵtelemetry?: TelemetryCapture;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n /**\n * Where the runtime writes its logs. Pass pino, `console`, or any object\n * with pino-style `debug`, `info`, `warn` and `error` methods\n * (`(message)` or `(fields, message)`). When `debug` is on, debug output\n * goes to `logger.child({ component: \"copilotkit-debug\" })`, or to the\n * logger itself when it has no `child`.\n *\n * Without it, the runtime writes to the console, and debug output is JSON\n * lines on stdout.\n */\n logger?: CopilotRuntimeLogger;\n /**\n * Policy controlling which inbound HTTP headers are forwarded onto the\n * outgoing agent call. By default a built-in denylist strips known\n * infrastructure/proxy/platform headers (`x-forwarded-*`, `x-real-ip`,\n * `x-vercel-*`, `x-copilotcloud-*`, etc.) while `authorization` and custom\n * `x-*` application headers continue to forward (#5712). Set\n * `{ useDefaultDenylist: false }` to restore the previous wide-open behavior.\n */\n forwardHeaders?: ForwardHeadersConfig;\n /**\n * Seconds of silence on an SSE response before the runtime writes a\n * `: keep-alive` comment, so proxies and browsers with idle timeouts keep\n * the connection open through long reasoning or tool phases. Comments are\n * transport frames and never become AG-UI events. `0` disables it.\n * @default 15\n */\n sseKeepAliveIntervalSeconds?: number;\n /**\n * Opt-in flag exposing the client-facing memory proxy routes\n * (`/memories`, `/memories/recall`, `/memories/subscribe`, `/memories/:id`).\n *\n * Defaults to `false` — a **secure default**. When off, every `/memories/*`\n * request 404s as if the route did not exist, so an un-opted-in deployment\n * reveals nothing about memory even when Intelligence is configured. This does\n * NOT affect the agent's own server-side memory tooling (`recall_memory` runs\n * via the Intelligence MCP path, separate from this client REST proxy).\n *\n * Flip to `true` to power a client memory inspector (e.g. the dev console's\n * Memory tab). Existing Intelligence deployments relying on the previously\n * always-on Learning tab must set this to restore it.\n *\n * @deprecated Configure `memory.access` on an Intelligence Runtime. That one\n * policy enables and limits both agent and browser Memory.\n */\n exposeMemoryRoutes?: boolean;\n /**\n * How local Threads are shared among callers that `identifyUser` does not\n * identify, when no Intelligence is configured. Has no effect on an\n * Intelligence runtime, where the platform scopes Threads per user.\n *\n * With `identifyUser`, every Thread operation (list, read, connect, run,\n * stop, clear) reaches only the caller's own Threads, whatever this says.\n * Without it, by default (`access: \"owner\"`), a Thread id works as a\n * capability: whoever holds it may read, connect to, continue and stop that\n * Thread, but listing and clearing Threads are refused with HTTP 403.\n * `access: \"open\"` also lets every caller list and clear the Threads created\n * without identity, as in earlier releases. That is insecure for any\n * deployment that more than one person can reach. A Thread created by an\n * identified user is never reachable without that identity.\n */\n threads?: ThreadsConfig;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport type MemoryAccess = \"none\" | \"read\" | \"read-write\";\n\nexport interface MemoryGrant {\n readonly user: MemoryAccess;\n readonly project: MemoryAccess;\n}\n\nexport type MemoryConsumer = \"agent\" | \"client\";\n\nexport interface CopilotRuntimeMemoryConfig {\n /** Resolves immutable Memory access for one authenticated web request. */\n access(input: {\n readonly request: Request;\n readonly user: CopilotRuntimeUser;\n readonly consumer: MemoryConsumer;\n }): MaybePromise<MemoryGrant | null>;\n}\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n /**\n * Resolves the authenticated user for a request. When set, each Thread\n * belongs to the user whose request created it, and only that user can list,\n * read, replay, clear, continue or stop it. The runner must enforce owners\n * (InMemoryAgentRunner and SqliteAgentRunner do); with a runner that does\n * not, those requests are refused. See `threads`.\n *\n * Threads that SqliteAgentRunner stored before it recorded owners belong to\n * nobody: as before the upgrade, whoever holds such a Thread's id can reach\n * it, and continuing it does not claim it. The runner logs how many it holds\n * when it opens the database. Every new Thread is owned. InMemoryAgentRunner\n * keeps no Threads across a restart, so it holds no such Threads.\n */\n identifyUser?: IdentifyUserCallback;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n /** Intelligence Channels require the Intelligence runtime; not available in SSE mode. */\n channels?: undefined;\n}\n\ninterface CopilotIntelligenceRuntimeBaseOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /**\n * Chooses one stable Learning Container ID for each web or Channel run.\n * @deprecated Configure `getLearningContainerId` on `CopilotKitIntelligence`.\n */\n ɵlearning?: CopilotRuntimeLearningConfig;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /**\n * Interval (ms) between Phoenix heartbeats on the runner WebSocket. Keep it\n * below the idle timeout of any proxy between the runtime and Intelligence.\n * @default 15_000\n */\n heartbeatIntervalMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n /**\n * Intelligence Channels declared by this runtime. Each is a\n * `createChannel({ name })` instance. Only available on the Intelligence runtime\n * path. Names are validated (required, lowercase kebab-case, unique) and wired\n * to delivery/egress transports when activated via `startChannels` from\n * `@copilotkit/channels-intelligence` — not at construction.\n */\n}\n\ntype NonEmptyChannels = readonly [Channel, ...Channel[]];\n\n/** Intelligence runtime options with web identity, Channels, or both. */\nexport type CopilotIntelligenceRuntimeOptions =\n CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n /** Resolves the authenticated user for web requests. */\n identifyUser: IdentifyUserCallback;\n /** Enables agent and browser Memory under one request policy. */\n memory?: CopilotRuntimeMemoryConfig;\n channels?: readonly Channel[];\n }\n | {\n /** Channels-only runtimes expose no functional web surface. */\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n );\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n generativeUI?: CopilotRuntimeOptions[\"generativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n /**\n * Resolve the license checker, verifying the token on the first call.\n * Optional so external implementations of this published interface remain\n * source-compatible; absent or resolving to `undefined` means no license\n * gating.\n */\n getLicenseChecker?(): Promise<LicenseChecker | undefined>;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n /**\n * The logger the runtime writes to. Optional so external implementations of\n * this published interface remain source-compatible; a missing value means\n * the console.\n */\n logger?: CopilotRuntimeLogger;\n /**\n * Runtime-bound telemetry capture. Optional so external implementations of\n * this published interface remain source-compatible.\n */\n telemetry?: TelemetryCapture;\n /**\n * Resolved inbound-header forwarding policy read by the /run and /connect call\n * sites. Optional on the published interface so an external `CopilotRuntimeLike`\n * implementor predating this field stays source-compatible (non-breaking minor\n * release). Concrete runtimes (`BaseCopilotRuntime`) always resolve and set it;\n * the call sites coalesce a missing value to the default resolved policy\n * (`resolveForwardHeadersPolicy(undefined)` — default-on denylist).\n */\n forwardHeadersPolicy?: ResolvedForwardHeadersPolicy;\n /**\n * Resolved SSE keep-alive interval in seconds; `0` disables it. Optional on\n * the published interface for the same source-compatibility reason as\n * `forwardHeadersPolicy`; the SSE call sites fall back to the default.\n */\n sseKeepAliveIntervalSeconds?: number;\n /**\n * Resolved opt-in flag for the client-facing memory proxy routes. Optional on\n * the published interface so an external `CopilotRuntimeLike` implementor\n * predating this field stays source-compatible; the dispatcher coalesces a\n * missing value to `false` (secure default — routes hidden). Concrete runtimes\n * (`BaseCopilotRuntime`) always resolve and set it.\n */\n exposeMemoryRoutes?: boolean;\n /**\n * Resolved local Thread access mode. Optional on the published interface so\n * an external implementor stays source-compatible; a missing value means\n * the default (`DEFAULT_THREAD_ACCESS`).\n */\n threadAccess?: ThreadAccessMode;\n memory?: CopilotRuntimeMemoryConfig;\n learning?: CopilotRuntimeLearningConfig;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: typeof RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n channels: Channel[];\n learning?: CopilotRuntimeLearningConfig;\n mode: typeof RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public generativeUI: CopilotRuntimeOptions[\"generativeUI\"];\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n public readonly logger: CopilotRuntimeLogger;\n public readonly telemetry: TelemetryCapture;\n public readonly forwardHeadersPolicy: ResolvedForwardHeadersPolicy;\n public readonly sseKeepAliveIntervalSeconds: number;\n public readonly exposeMemoryRoutes: boolean;\n public readonly threadAccess: ThreadAccessMode;\n public readonly memory?: CopilotRuntimeMemoryConfig;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's getLicenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n /** Runtimes without Intelligence do no license gating. */\n getLicenseChecker(): Promise<LicenseChecker | undefined> {\n return Promise.resolve(undefined);\n }\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n this.logger = getRuntimeLogger(options);\n logRuntimeTelemetryDisclosure(this.logger);\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n mcpApps,\n openGenerativeUI,\n generativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.generativeUI = generativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken = firstNonBlankLicenseToken(\n options.licenseToken,\n processEnv().COPILOTKIT_LICENSE_TOKEN,\n );\n\n // Snapshot identity and sampling authority for this runtime. Capture\n // scopes share process-level telemetry settings but cannot be rewritten by\n // another runtime's construction.\n const resolvedTelemetryId = firstNonBlankTelemetryId(\n options.telemetryId,\n processEnv().CPK_TELEMETRY_ID,\n );\n this.telemetry =\n options.ɵtelemetry ??\n telemetry.createScope(\n resolvedTelemetryId !== undefined\n ? { telemetryId: resolvedTelemetryId }\n : this.resolvedLicenseToken !== undefined\n ? { licenseToken: this.resolvedLicenseToken }\n : {},\n );\n\n // Set here rather than per event, beside the license token and for the same\n // reason: it describes the caller, not the call, and every event should\n // carry it whichever handler fired.\n if (options.telemetryProperties) {\n telemetry.setGlobalProperties(options.telemetryProperties);\n }\n\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createDebugLogger(options.logger);\n }\n // The debug feed carries every thread's events to any subscriber, so the\n // bus only exists where the feed is allowed to be served. Resolving\n // `debug` first keeps the bus and the route gate reading one value.\n if (isDebugEventFeedEnabled(this.debug)) {\n this.debugEventBus = new DebugEventBus(this.logger);\n }\n // Resolve the inbound-header forwarding policy once (mirroring the\n // `debug` → `ResolvedDebugConfig` resolve-once above) so both the /run and\n // /connect call sites read the exact same resolved policy off the runtime\n // and can never diverge.\n this.forwardHeadersPolicy = resolveForwardHeadersPolicy(\n options.forwardHeaders,\n );\n this.sseKeepAliveIntervalSeconds = resolveSseKeepAliveIntervalSeconds(\n options.sseKeepAliveIntervalSeconds,\n );\n // Secure default: the client-facing memory proxy routes stay hidden (404)\n // unless a deployment explicitly opts in.\n this.memory = (options as { memory?: CopilotRuntimeMemoryConfig }).memory;\n this.exposeMemoryRoutes =\n this.memory !== undefined || (options.exposeMemoryRoutes ?? false);\n this.threadAccess = resolveThreadAccessMode(options.threads);\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n readonly identifyUser?: IdentifyUserCallback;\n\n constructor(options: CopilotSseRuntimeOptions) {\n // Runtime guard mirroring the discriminated-union type: the SSE runtime has\n // no Intelligence delivery path, so `channels` cannot be honored here. The\n // type forbids it, but a JS / `as any` caller passing `{ agents, channels }`\n // would otherwise land here and have `channels` silently dropped — fail\n // loud instead.\n const channels = (options as { channels?: unknown[] }).channels;\n if (Array.isArray(channels) && channels.length > 0) {\n throw new Error(\n \"`channels` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Intelligence Channels are not available in SSE mode.\",\n );\n }\n if ((options as { ɵlearning?: unknown }).ɵlearning !== undefined) {\n throw new Error(\n \"`ɵlearning` requires the Intelligence runtime (pass `intelligence`); \" +\n \"Learning Containers are not available in SSE mode.\",\n );\n }\n if (\n options.identifyUser !== undefined &&\n typeof options.identifyUser !== \"function\"\n ) {\n throw new Error(\"`identifyUser` must be a callback\");\n }\n super(options, options.runner ?? new InMemoryAgentRunner());\n this.identifyUser = options.identifyUser;\n warnIfThreadOwnershipUnenforced(this);\n warnIfThreadListRefused(this);\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser?: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly channels: Channel[];\n readonly learning?: CopilotRuntimeLearningConfig;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n private licenseCheckerPromise?: Promise<LicenseChecker>;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n const rawOptions = options as CopilotIntelligenceRuntimeBaseOptions & {\n identifyUser?: unknown;\n channels?: unknown;\n memory?: unknown;\n runner?: unknown;\n ɵlearning?: unknown;\n };\n // Runtime guard mirroring the `channels` guard in `CopilotSseRuntime`: this\n // constructor hardcodes `IntelligenceAgentRunner` into its `super()` call,\n // so a caller-supplied `runner` can never be honored. The type forbids it\n // (`runner` is declared only on `CopilotSseRuntimeOptions`), but that is an\n // excess-property check — a JS / `as any` / non-literal caller passing\n // `{ intelligence, runner }` would otherwise land here and have `runner`\n // silently dropped in favor of the auto-wired one. Fail loud instead.\n if (rawOptions.runner !== undefined) {\n throw new Error(\n \"Intelligence Runtime auto-wires its own `runner`; passing `runner` \" +\n \"alongside `intelligence` is not supported. Durability is managed by \" +\n \"the Intelligence service, so `InMemoryAgentRunner` / a SQLite runner \" +\n \"is unnecessary here — drop `runner`, or drop `intelligence` to run \" +\n \"in SSE mode with a runner you control.\",\n );\n }\n if (\n rawOptions.identifyUser !== undefined &&\n typeof rawOptions.identifyUser !== \"function\"\n ) {\n throw new Error(\"Intelligence Runtime `identifyUser` must be a callback\");\n }\n if (rawOptions.threads !== undefined) {\n getRuntimeLogger(options).warn(\n \"[CopilotKit] `threads` has no effect on an Intelligence runtime: the \" +\n \"platform scopes threads per user. Remove the option.\",\n );\n }\n if (\n rawOptions.channels !== undefined &&\n !Array.isArray(rawOptions.channels)\n ) {\n throw new Error(\"Intelligence Runtime `channels` must be an array\");\n }\n const hasWebIdentity = typeof rawOptions.identifyUser === \"function\";\n const hasChannels =\n Array.isArray(rawOptions.channels) && rawOptions.channels.length > 0;\n if (!hasWebIdentity && !hasChannels) {\n throw new Error(\n \"Intelligence Runtime requires web `identifyUser`, at least one Channel, or both surfaces\",\n );\n }\n if (\n rawOptions.memory !== undefined &&\n (typeof rawOptions.memory !== \"object\" ||\n rawOptions.memory === null ||\n typeof (rawOptions.memory as { access?: unknown }).access !==\n \"function\")\n ) {\n throw new Error(\n \"Intelligence Runtime `memory.access` must be a callback\",\n );\n }\n if (rawOptions.memory !== undefined && !hasWebIdentity) {\n throw new Error(\n \"Intelligence Runtime web `memory` requires `identifyUser`\",\n );\n }\n if (\n rawOptions.ɵlearning !== undefined &&\n (typeof rawOptions.ɵlearning !== \"object\" ||\n rawOptions.ɵlearning === null ||\n !(\n typeof (rawOptions.ɵlearning as { containerId?: unknown })\n .containerId === \"string\" ||\n typeof (rawOptions.ɵlearning as { containerId?: unknown })\n .containerId === \"function\"\n ))\n ) {\n throw new Error(\n \"Intelligence Runtime `ɵlearning.containerId` must be a stable ID or callback\",\n );\n }\n if (\n rawOptions.ɵlearning !== undefined &&\n options.intelligence.ɵgetLearningContainerId?.() !== undefined\n ) {\n throw new Error(\n \"Configure Learning Containers with `getLearningContainerId` on `CopilotKitIntelligence`; do not also pass deprecated `ɵlearning` to `CopilotRuntime`\",\n );\n }\n if (\n typeof (rawOptions.ɵlearning as { containerId?: unknown } | undefined)\n ?.containerId === \"string\"\n ) {\n assertStableLearningContainerId(\n (rawOptions.ɵlearning as { containerId: string }).containerId,\n );\n }\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n heartbeatIntervalMs: options.heartbeatIntervalMs,\n logger: getRuntimeLogger(options),\n }),\n );\n this.intelligence = options.intelligence;\n this.learning = options.ɵlearning;\n this.identifyUser = hasWebIdentity\n ? (rawOptions.identifyUser as IdentifyUserCallback)\n : undefined;\n this.generateThreadNames = options.generateThreadNames ?? true;\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n // Declared Intelligence Channels. Lowercase kebab-case name-shape validation\n // (`assertValidChannelNames`) lives in the channels-intelligence launcher —\n // it can't run here because it's a value import from the pure-ESM\n // `@copilotkit/channels-intelligence`, which this CJS package must not pull in.\n // Name UNIQUENESS across declared Channels is enforced by\n // `ChannelManager.activate()`, not the launcher: the managed path activates\n // one Channel per launcher call, so the launcher never sees the full set.\n // Fail fast on the most common misconfiguration (a missing name) right here\n // at construction, though, rather than only at activation.\n this.channels = [\n ...((rawOptions.channels as readonly Channel[] | undefined) ?? []),\n ];\n for (const c of this.channels) {\n if (!c || typeof c !== \"object\" || !c.name) {\n throw new Error(\n \"Intelligence Channel is missing a `name` — pass createChannel({ name }) for each Channel in `channels`\",\n );\n }\n }\n }\n\n /**\n * Verify the license token on first use, then reuse the result. Not done in\n * the constructor: edge-safe (Web Crypto) verification is async, and\n * Cloudflare Workers forbid crypto work in global scope, where runtimes are\n * usually constructed. Reuses the base-resolved token so feature gating and\n * telemetry attribution can never disagree.\n */\n override getLicenseChecker(): Promise<LicenseChecker> {\n this.licenseCheckerPromise ??= Promise.resolve().then(() =>\n createLicenseChecker(this.resolvedLicenseToken ?? \"\"),\n );\n return this.licenseCheckerPromise;\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Compile-time phantom brand marking a {@link CopilotRuntime} that was\n * constructed with at least one declared Intelligence Channel. It has no runtime\n * representation — the shim never sets this property; it exists purely so\n * `createCopilotRuntimeHandler` can tell, at the type level, that the resulting\n * handler will carry a non-optional `.channels` control surface.\n */\nexport interface RuntimeWithDeclaredChannels {\n /**\n * @internal Phantom brand key. Never present at runtime; do not read or set.\n */\n readonly __copilotkitChannelsDeclared: true;\n}\n\n/**\n * Instance shape of the {@link CopilotRuntime} compatibility shim. Extends\n * {@link CopilotRuntimeLike} with the Intelligence-only accessors the shim\n * surfaces (all `undefined` in SSE mode). Declared explicitly so the exported\n * `CopilotRuntime` name resolves as a type as well as a value.\n */\nexport interface CopilotRuntime extends CopilotRuntimeLike {\n /** Telemetry capture bound to this runtime's construction-time identity. */\n telemetry: TelemetryCapture;\n /** Auto-generate short thread names; `undefined` in SSE mode. */\n generateThreadNames?: boolean;\n /** Thread lock TTL in seconds; `undefined` in SSE mode. */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock; `undefined` in SSE mode. */\n lockKeyPrefix?: string;\n /** Thread lock heartbeat interval in seconds; `undefined` in SSE mode. */\n lockHeartbeatIntervalSeconds?: number;\n /** Declared Intelligence Channels; `undefined` in SSE mode. */\n channels?: Channel[];\n /** Learning Container selector; `undefined` in SSE mode. */\n learning?: CopilotRuntimeLearningConfig;\n}\n\n/**\n * Constructor type for the {@link CopilotRuntime} compatibility shim.\n *\n * The first overload fires when the caller passes `intelligence` together with a\n * non-empty `channels` tuple: it returns a {@link RuntimeWithDeclaredChannels}-\n * branded runtime, which `createCopilotRuntimeHandler` maps to a handler whose\n * `.channels` is non-optional. Every other configuration (SSE, or Intelligence\n * without channels, or an empty `channels: []`) falls through to the second\n * overload and stays unbranded, so its handler keeps `.channels` optional.\n *\n * A class constructor cannot vary its return type across overloads (it is pinned\n * to the instance type), so the branding lives on this construct-signature\n * interface instead of on the class itself.\n */\nexport interface CopilotRuntimeConstructor {\n new (\n options: CopilotIntelligenceRuntimeBaseOptions &\n (\n | {\n identifyUser: IdentifyUserCallback;\n memory?: CopilotRuntimeMemoryConfig;\n channels: NonEmptyChannels;\n }\n | {\n identifyUser?: undefined;\n memory?: undefined;\n channels: NonEmptyChannels;\n }\n ),\n ): CopilotRuntime & RuntimeWithDeclaredChannels;\n new (options: CopilotRuntimeOptions): CopilotRuntime;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n *\n * Exported to consumers as the {@link CopilotRuntime} value (typed as\n * {@link CopilotRuntimeConstructor}) rather than as a class, so that the\n * channel-presence brand can flow from construction into the handler type.\n */\nclass CopilotRuntimeShim implements CopilotRuntime {\n private delegate: CopilotSseRuntime | CopilotIntelligenceRuntime;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n\n const reporter = getRuntimeErrorReporterFromOptions(options);\n if (reporter) {\n attachRuntimeErrorReporter(this, reporter);\n }\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get generativeUI(): CopilotRuntimeOptions[\"generativeUI\"] {\n return this.delegate.generativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return this.delegate.identifyUser;\n }\n\n get threadAccess(): ThreadAccessMode {\n return this.delegate.threadAccess;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get channels(): Channel[] | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.channels\n : undefined;\n }\n\n get learning(): CopilotRuntimeLearningConfig | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.learning\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n getLicenseChecker(): Promise<LicenseChecker | undefined> {\n return this.delegate.getLicenseChecker();\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n\n get logger(): CopilotRuntimeLogger {\n return this.delegate.logger;\n }\n\n get telemetry(): TelemetryCapture {\n return this.delegate.telemetry;\n }\n\n get forwardHeadersPolicy(): ResolvedForwardHeadersPolicy {\n return this.delegate.forwardHeadersPolicy;\n }\n\n get sseKeepAliveIntervalSeconds(): number {\n return this.delegate.sseKeepAliveIntervalSeconds;\n }\n\n get exposeMemoryRoutes(): boolean | undefined {\n return this.delegate.exposeMemoryRoutes;\n }\n\n get memory(): CopilotRuntimeMemoryConfig | undefined {\n return this.delegate.memory;\n }\n}\n\n/**\n * The public `CopilotRuntime` constructor. Backed by {@link CopilotRuntimeShim}\n * but typed as {@link CopilotRuntimeConstructor} so that constructing with a\n * non-empty `channels` array yields a {@link RuntimeWithDeclaredChannels}-branded\n * runtime type.\n *\n * The `as unknown as` cast is required (not dishonest widening): the brand is a\n * phantom, compile-time-only marker with no runtime representation, so the shim\n * instances legitimately do not carry the brand property. Behavior is identical\n * to the former `class CopilotRuntime` — this only refines the static type.\n */\nexport const CopilotRuntime: CopilotRuntimeConstructor =\n CopilotRuntimeShim as unknown as CopilotRuntimeConstructor;\n"],"mappings":";;;;;;;;;;;;;;;;;AAmFA,MAAa,UAAU;;;;;;AAuJvB,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAkTT,IAAe,qBAAf,MAAgE;;CAgC9D,oBAAyD;AACvD,SAAO,QAAQ,QAAQ,OAAU;;CAGnC,YAAY,SAAoC,QAAqB;AACnE,OAAK,SAAS,iBAAiB,QAAQ;AACvC,gCAA8B,KAAK,OAAO;EAE1C,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,SAAS;;CAGvB,IAAI,uBAAqD;AACvD,SAAO,KAAK,SAAS;;CAGvB,IAAI,8BAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,qBAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAiD;AACnD,SAAO,KAAK,SAAS;;;;;;;;;;;;;;AAezB,MAAa,iBACX"}
@@ -1,3 +1,4 @@
1
+ const require_a2ui_v09_middleware = require('../generative-ui/a2ui-v09-middleware.cjs');
1
2
  const require_open_generative_ui_middleware = require('./open-generative-ui-middleware.cjs');
2
3
  let rxjs = require("rxjs");
3
4
  let _ag_ui_client = require("@ag-ui/client");
@@ -55,6 +56,9 @@ async function transformRecordedEvents(input, events, options) {
55
56
  const next = agent;
56
57
  const middleware = new _ag_ui_a2ui_middleware.A2UIMiddleware(options.a2ui);
57
58
  agent = new RecordedEventAgent(input, (runInput) => middleware.run(runInput, next));
59
+ const inner = agent;
60
+ const bridge = new require_a2ui_v09_middleware.A2UIV09BridgeMiddleware();
61
+ agent = new RecordedEventAgent(input, (runInput) => bridge.run(runInput, inner));
58
62
  }
59
63
  return (0, rxjs.firstValueFrom)(agent.run(input).pipe((0, rxjs.toArray)()));
60
64
  }
@@ -1 +1 @@
1
- {"version":3,"file":"recorded-events.cjs","names":["AbstractAgent","EventType","OpenGenerativeUIMiddleware","A2UIMiddleware"],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"sourcesContent":["import { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type { BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { firstValueFrom, from, toArray } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { OpenGenerativeUIMiddleware } from \"./open-generative-ui-middleware\";\n\nexport interface RecordedEventTransformOptions {\n /** Use the original runtime configuration, including its catalog when known. */\n a2ui?: A2UIMiddlewareConfig;\n openGenerativeUI?: boolean;\n}\n\n/** An inert event source: it cannot contact an agent or execute tools. */\nclass RecordedEventAgent extends AbstractAgent {\n constructor(\n private readonly input: RunAgentInput,\n private readonly stream: (input: RunAgentInput) => Observable<BaseEvent>,\n ) {\n super({\n threadId: input.threadId,\n initialMessages: input.messages,\n initialState: input.state,\n });\n }\n\n /** Emit recorded events through this layer without contacting an agent. */\n run(input: RunAgentInput): Observable<BaseEvent> {\n return this.stream(input);\n }\n\n /** Retain the current replay history and state in an independent agent. */\n clone(): AbstractAgent {\n return new RecordedEventAgent(\n { ...this.input, messages: this.messages, state: this.state },\n this.stream,\n );\n }\n}\n\n/**\n * Apply CPK's rich-UI middleware to one recorded, pre-middleware run.\n * Supply complete AG-UI run events and the original input/configuration. This\n * does not run an agent, fetch resources, or execute tools. Already transformed\n * histories must not be passed through a second time.\n *\n * Returns events in runtime order, including generated activity events and any\n * synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are\n * the caller's responsibility (A2UI can generate random result message IDs).\n */\nexport async function transformRecordedEvents(\n input: RunAgentInput,\n events: readonly BaseEvent[],\n options: RecordedEventTransformOptions,\n): Promise<BaseEvent[]> {\n // After A2UI answers a render call from this run, it continues the agent in\n // the same run. A recording has no later agent output, so every run after\n // the first only closes the run.\n const lifecycle = events.filter(\n (event) =>\n event.type === EventType.RUN_STARTED ||\n event.type === EventType.RUN_FINISHED,\n );\n let replayed = false;\n let agent: AbstractAgent = new RecordedEventAgent(input, () => {\n const replay = replayed ? lifecycle : events;\n replayed = true;\n return from(replay);\n });\n // Runtime registers A2UI before Open GenUI; the first middleware is outermost.\n if (options.openGenerativeUI) {\n const next = agent;\n const middleware = new OpenGenerativeUIMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n if (options.a2ui) {\n const next = agent;\n const middleware = new A2UIMiddleware(options.a2ui);\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n return firstValueFrom(agent.run(input).pipe(toArray()));\n}\n"],"mappings":";;;;;;;AAeA,IAAM,qBAAN,MAAM,2BAA2BA,4BAAc;CAC7C,YACE,AAAiB,OACjB,AAAiB,QACjB;AACA,QAAM;GACJ,UAAU,MAAM;GAChB,iBAAiB,MAAM;GACvB,cAAc,MAAM;GACrB,CAAC;EAPe;EACA;;;CAUnB,IAAI,OAA6C;AAC/C,SAAO,KAAK,OAAO,MAAM;;;CAI3B,QAAuB;AACrB,SAAO,IAAI,mBACT;GAAE,GAAG,KAAK;GAAO,UAAU,KAAK;GAAU,OAAO,KAAK;GAAO,EAC7D,KAAK,OACN;;;;;;;;;;;;;AAcL,eAAsB,wBACpB,OACA,QACA,SACsB;CAItB,MAAM,YAAY,OAAO,QACtB,UACC,MAAM,SAASC,wBAAU,eACzB,MAAM,SAASA,wBAAU,aAC5B;CACD,IAAI,WAAW;CACf,IAAI,QAAuB,IAAI,mBAAmB,aAAa;EAC7D,MAAM,SAAS,WAAW,YAAY;AACtC,aAAW;AACX,wBAAY,OAAO;GACnB;AAEF,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,OAAO;EACb,MAAM,aAAa,IAAIC,kEAA4B;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,KAAI,QAAQ,MAAM;EAChB,MAAM,OAAO;EACb,MAAM,aAAa,IAAIC,sCAAe,QAAQ,KAAK;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,iCAAsB,MAAM,IAAI,MAAM,CAAC,wBAAc,CAAC,CAAC"}
1
+ {"version":3,"file":"recorded-events.cjs","names":["AbstractAgent","EventType","OpenGenerativeUIMiddleware","A2UIMiddleware","A2UIV09BridgeMiddleware"],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"sourcesContent":["import { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type { BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { firstValueFrom, from, toArray } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { OpenGenerativeUIMiddleware } from \"./open-generative-ui-middleware\";\nimport { A2UIV09BridgeMiddleware } from \"../generative-ui/a2ui-v09-middleware\";\n\nexport interface RecordedEventTransformOptions {\n /**\n * Apply `A2UIMiddleware` with this configuration, including its catalog\n * when known. As in the runtime, its v0.9 surfaces are then converted to\n * A2UI 1.0 (`generative-ui-surface`).\n */\n a2ui?: A2UIMiddlewareConfig;\n openGenerativeUI?: boolean;\n}\n\n/** An inert event source: it cannot contact an agent or execute tools. */\nclass RecordedEventAgent extends AbstractAgent {\n constructor(\n private readonly input: RunAgentInput,\n private readonly stream: (input: RunAgentInput) => Observable<BaseEvent>,\n ) {\n super({\n threadId: input.threadId,\n initialMessages: input.messages,\n initialState: input.state,\n });\n }\n\n /** Emit recorded events through this layer without contacting an agent. */\n run(input: RunAgentInput): Observable<BaseEvent> {\n return this.stream(input);\n }\n\n /** Retain the current replay history and state in an independent agent. */\n clone(): AbstractAgent {\n return new RecordedEventAgent(\n { ...this.input, messages: this.messages, state: this.state },\n this.stream,\n );\n }\n}\n\n/**\n * Apply CPK's rich-UI middleware to one recorded, pre-middleware run.\n * Supply complete AG-UI run events and the original input/configuration. This\n * does not run an agent, fetch resources, or execute tools. Already transformed\n * histories must not be passed through a second time.\n *\n * Returns events in runtime order, including generated activity events and any\n * synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are\n * the caller's responsibility (A2UI can generate random result message IDs).\n */\nexport async function transformRecordedEvents(\n input: RunAgentInput,\n events: readonly BaseEvent[],\n options: RecordedEventTransformOptions,\n): Promise<BaseEvent[]> {\n // After A2UI answers a render call from this run, it continues the agent in\n // the same run. A recording has no later agent output, so every run after\n // the first only closes the run.\n const lifecycle = events.filter(\n (event) =>\n event.type === EventType.RUN_STARTED ||\n event.type === EventType.RUN_FINISHED,\n );\n let replayed = false;\n let agent: AbstractAgent = new RecordedEventAgent(input, () => {\n const replay = replayed ? lifecycle : events;\n replayed = true;\n return from(replay);\n });\n // Runtime registers the v0.9 bridge, then A2UI, then Open GenUI; the first\n // middleware is outermost.\n if (options.openGenerativeUI) {\n const next = agent;\n const middleware = new OpenGenerativeUIMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n if (options.a2ui) {\n const next = agent;\n const middleware = new A2UIMiddleware(options.a2ui);\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n const inner = agent;\n const bridge = new A2UIV09BridgeMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n bridge.run(runInput, inner),\n );\n }\n return firstValueFrom(agent.run(input).pipe(toArray()));\n}\n"],"mappings":";;;;;;;;AAoBA,IAAM,qBAAN,MAAM,2BAA2BA,4BAAc;CAC7C,YACE,AAAiB,OACjB,AAAiB,QACjB;AACA,QAAM;GACJ,UAAU,MAAM;GAChB,iBAAiB,MAAM;GACvB,cAAc,MAAM;GACrB,CAAC;EAPe;EACA;;;CAUnB,IAAI,OAA6C;AAC/C,SAAO,KAAK,OAAO,MAAM;;;CAI3B,QAAuB;AACrB,SAAO,IAAI,mBACT;GAAE,GAAG,KAAK;GAAO,UAAU,KAAK;GAAU,OAAO,KAAK;GAAO,EAC7D,KAAK,OACN;;;;;;;;;;;;;AAcL,eAAsB,wBACpB,OACA,QACA,SACsB;CAItB,MAAM,YAAY,OAAO,QACtB,UACC,MAAM,SAASC,wBAAU,eACzB,MAAM,SAASA,wBAAU,aAC5B;CACD,IAAI,WAAW;CACf,IAAI,QAAuB,IAAI,mBAAmB,aAAa;EAC7D,MAAM,SAAS,WAAW,YAAY;AACtC,aAAW;AACX,wBAAY,OAAO;GACnB;AAGF,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,OAAO;EACb,MAAM,aAAa,IAAIC,kEAA4B;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,KAAI,QAAQ,MAAM;EAChB,MAAM,OAAO;EACb,MAAM,aAAa,IAAIC,sCAAe,QAAQ,KAAK;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;EACD,MAAM,QAAQ;EACd,MAAM,SAAS,IAAIC,qDAAyB;AAC5C,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,OAAO,IAAI,UAAU,MAAM,CAC5B;;AAEH,iCAAsB,MAAM,IAAI,MAAM,CAAC,wBAAc,CAAC,CAAC"}
@@ -3,7 +3,11 @@ import { A2UIMiddlewareConfig } from "@ag-ui/a2ui-middleware";
3
3
 
4
4
  //#region src/runtime/event-transforms/recorded-events.d.ts
5
5
  interface RecordedEventTransformOptions {
6
- /** Use the original runtime configuration, including its catalog when known. */
6
+ /**
7
+ * Apply `A2UIMiddleware` with this configuration, including its catalog
8
+ * when known. As in the runtime, its v0.9 surfaces are then converted to
9
+ * A2UI 1.0 (`generative-ui-surface`).
10
+ */
7
11
  a2ui?: A2UIMiddlewareConfig;
8
12
  openGenerativeUI?: boolean;
9
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"recorded-events.d.cts","names":[],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"mappings":";;;;UAQiB,6BAAA;;EAEf,IAAA,GAAO,oBAAA;EACP,gBAAA;AAAA;;;;;;;AAwCF;;;;iBAAsB,uBAAA,CACpB,KAAA,EAAO,aAAA,EACP,MAAA,WAAiB,SAAA,IACjB,OAAA,EAAS,6BAAA,GACR,OAAA,CAAQ,SAAA"}
1
+ {"version":3,"file":"recorded-events.d.cts","names":[],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"mappings":";;;;UASiB,6BAAA;;AAAjB;;;;EAME,IAAA,GAAO,oBAAA;EACP,gBAAA;AAAA;;;AAwCF;;;;;;;;iBAAsB,uBAAA,CACpB,KAAA,EAAO,aAAA,EACP,MAAA,WAAiB,SAAA,IACjB,OAAA,EAAS,6BAAA,GACR,OAAA,CAAQ,SAAA"}
@@ -3,7 +3,11 @@ import { A2UIMiddlewareConfig } from "@ag-ui/a2ui-middleware";
3
3
 
4
4
  //#region src/runtime/event-transforms/recorded-events.d.ts
5
5
  interface RecordedEventTransformOptions {
6
- /** Use the original runtime configuration, including its catalog when known. */
6
+ /**
7
+ * Apply `A2UIMiddleware` with this configuration, including its catalog
8
+ * when known. As in the runtime, its v0.9 surfaces are then converted to
9
+ * A2UI 1.0 (`generative-ui-surface`).
10
+ */
7
11
  a2ui?: A2UIMiddlewareConfig;
8
12
  openGenerativeUI?: boolean;
9
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"recorded-events.d.mts","names":[],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"mappings":";;;;UAQiB,6BAAA;;EAEf,IAAA,GAAO,oBAAA;EACP,gBAAA;AAAA;;;;;;;AAwCF;;;;iBAAsB,uBAAA,CACpB,KAAA,EAAO,aAAA,EACP,MAAA,WAAiB,SAAA,IACjB,OAAA,EAAS,6BAAA,GACR,OAAA,CAAQ,SAAA"}
1
+ {"version":3,"file":"recorded-events.d.mts","names":[],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"mappings":";;;;UASiB,6BAAA;;AAAjB;;;;EAME,IAAA,GAAO,oBAAA;EACP,gBAAA;AAAA;;;AAwCF;;;;;;;;iBAAsB,uBAAA,CACpB,KAAA,EAAO,aAAA,EACP,MAAA,WAAiB,SAAA,IACjB,OAAA,EAAS,6BAAA,GACR,OAAA,CAAQ,SAAA"}
@@ -1,3 +1,4 @@
1
+ import { A2UIV09BridgeMiddleware } from "../generative-ui/a2ui-v09-middleware.mjs";
1
2
  import { OpenGenerativeUIMiddleware } from "./open-generative-ui-middleware.mjs";
2
3
  import { firstValueFrom, from, toArray } from "rxjs";
3
4
  import { AbstractAgent, EventType } from "@ag-ui/client";
@@ -55,6 +56,9 @@ async function transformRecordedEvents(input, events, options) {
55
56
  const next = agent;
56
57
  const middleware = new A2UIMiddleware(options.a2ui);
57
58
  agent = new RecordedEventAgent(input, (runInput) => middleware.run(runInput, next));
59
+ const inner = agent;
60
+ const bridge = new A2UIV09BridgeMiddleware();
61
+ agent = new RecordedEventAgent(input, (runInput) => bridge.run(runInput, inner));
58
62
  }
59
63
  return firstValueFrom(agent.run(input).pipe(toArray()));
60
64
  }
@@ -1 +1 @@
1
- {"version":3,"file":"recorded-events.mjs","names":[],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"sourcesContent":["import { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type { BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { firstValueFrom, from, toArray } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { OpenGenerativeUIMiddleware } from \"./open-generative-ui-middleware\";\n\nexport interface RecordedEventTransformOptions {\n /** Use the original runtime configuration, including its catalog when known. */\n a2ui?: A2UIMiddlewareConfig;\n openGenerativeUI?: boolean;\n}\n\n/** An inert event source: it cannot contact an agent or execute tools. */\nclass RecordedEventAgent extends AbstractAgent {\n constructor(\n private readonly input: RunAgentInput,\n private readonly stream: (input: RunAgentInput) => Observable<BaseEvent>,\n ) {\n super({\n threadId: input.threadId,\n initialMessages: input.messages,\n initialState: input.state,\n });\n }\n\n /** Emit recorded events through this layer without contacting an agent. */\n run(input: RunAgentInput): Observable<BaseEvent> {\n return this.stream(input);\n }\n\n /** Retain the current replay history and state in an independent agent. */\n clone(): AbstractAgent {\n return new RecordedEventAgent(\n { ...this.input, messages: this.messages, state: this.state },\n this.stream,\n );\n }\n}\n\n/**\n * Apply CPK's rich-UI middleware to one recorded, pre-middleware run.\n * Supply complete AG-UI run events and the original input/configuration. This\n * does not run an agent, fetch resources, or execute tools. Already transformed\n * histories must not be passed through a second time.\n *\n * Returns events in runtime order, including generated activity events and any\n * synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are\n * the caller's responsibility (A2UI can generate random result message IDs).\n */\nexport async function transformRecordedEvents(\n input: RunAgentInput,\n events: readonly BaseEvent[],\n options: RecordedEventTransformOptions,\n): Promise<BaseEvent[]> {\n // After A2UI answers a render call from this run, it continues the agent in\n // the same run. A recording has no later agent output, so every run after\n // the first only closes the run.\n const lifecycle = events.filter(\n (event) =>\n event.type === EventType.RUN_STARTED ||\n event.type === EventType.RUN_FINISHED,\n );\n let replayed = false;\n let agent: AbstractAgent = new RecordedEventAgent(input, () => {\n const replay = replayed ? lifecycle : events;\n replayed = true;\n return from(replay);\n });\n // Runtime registers A2UI before Open GenUI; the first middleware is outermost.\n if (options.openGenerativeUI) {\n const next = agent;\n const middleware = new OpenGenerativeUIMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n if (options.a2ui) {\n const next = agent;\n const middleware = new A2UIMiddleware(options.a2ui);\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n return firstValueFrom(agent.run(input).pipe(toArray()));\n}\n"],"mappings":";;;;;;;AAeA,IAAM,qBAAN,MAAM,2BAA2B,cAAc;CAC7C,YACE,AAAiB,OACjB,AAAiB,QACjB;AACA,QAAM;GACJ,UAAU,MAAM;GAChB,iBAAiB,MAAM;GACvB,cAAc,MAAM;GACrB,CAAC;EAPe;EACA;;;CAUnB,IAAI,OAA6C;AAC/C,SAAO,KAAK,OAAO,MAAM;;;CAI3B,QAAuB;AACrB,SAAO,IAAI,mBACT;GAAE,GAAG,KAAK;GAAO,UAAU,KAAK;GAAU,OAAO,KAAK;GAAO,EAC7D,KAAK,OACN;;;;;;;;;;;;;AAcL,eAAsB,wBACpB,OACA,QACA,SACsB;CAItB,MAAM,YAAY,OAAO,QACtB,UACC,MAAM,SAAS,UAAU,eACzB,MAAM,SAAS,UAAU,aAC5B;CACD,IAAI,WAAW;CACf,IAAI,QAAuB,IAAI,mBAAmB,aAAa;EAC7D,MAAM,SAAS,WAAW,YAAY;AACtC,aAAW;AACX,SAAO,KAAK,OAAO;GACnB;AAEF,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,OAAO;EACb,MAAM,aAAa,IAAI,4BAA4B;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,KAAI,QAAQ,MAAM;EAChB,MAAM,OAAO;EACb,MAAM,aAAa,IAAI,eAAe,QAAQ,KAAK;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,QAAO,eAAe,MAAM,IAAI,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC"}
1
+ {"version":3,"file":"recorded-events.mjs","names":[],"sources":["../../../src/runtime/event-transforms/recorded-events.ts"],"sourcesContent":["import { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type { BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport { firstValueFrom, from, toArray } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { OpenGenerativeUIMiddleware } from \"./open-generative-ui-middleware\";\nimport { A2UIV09BridgeMiddleware } from \"../generative-ui/a2ui-v09-middleware\";\n\nexport interface RecordedEventTransformOptions {\n /**\n * Apply `A2UIMiddleware` with this configuration, including its catalog\n * when known. As in the runtime, its v0.9 surfaces are then converted to\n * A2UI 1.0 (`generative-ui-surface`).\n */\n a2ui?: A2UIMiddlewareConfig;\n openGenerativeUI?: boolean;\n}\n\n/** An inert event source: it cannot contact an agent or execute tools. */\nclass RecordedEventAgent extends AbstractAgent {\n constructor(\n private readonly input: RunAgentInput,\n private readonly stream: (input: RunAgentInput) => Observable<BaseEvent>,\n ) {\n super({\n threadId: input.threadId,\n initialMessages: input.messages,\n initialState: input.state,\n });\n }\n\n /** Emit recorded events through this layer without contacting an agent. */\n run(input: RunAgentInput): Observable<BaseEvent> {\n return this.stream(input);\n }\n\n /** Retain the current replay history and state in an independent agent. */\n clone(): AbstractAgent {\n return new RecordedEventAgent(\n { ...this.input, messages: this.messages, state: this.state },\n this.stream,\n );\n }\n}\n\n/**\n * Apply CPK's rich-UI middleware to one recorded, pre-middleware run.\n * Supply complete AG-UI run events and the original input/configuration. This\n * does not run an agent, fetch resources, or execute tools. Already transformed\n * histories must not be passed through a second time.\n *\n * Returns events in runtime order, including generated activity events and any\n * synthetic A2UI tool results. Persistence IDs, timestamps, and provenance are\n * the caller's responsibility (A2UI can generate random result message IDs).\n */\nexport async function transformRecordedEvents(\n input: RunAgentInput,\n events: readonly BaseEvent[],\n options: RecordedEventTransformOptions,\n): Promise<BaseEvent[]> {\n // After A2UI answers a render call from this run, it continues the agent in\n // the same run. A recording has no later agent output, so every run after\n // the first only closes the run.\n const lifecycle = events.filter(\n (event) =>\n event.type === EventType.RUN_STARTED ||\n event.type === EventType.RUN_FINISHED,\n );\n let replayed = false;\n let agent: AbstractAgent = new RecordedEventAgent(input, () => {\n const replay = replayed ? lifecycle : events;\n replayed = true;\n return from(replay);\n });\n // Runtime registers the v0.9 bridge, then A2UI, then Open GenUI; the first\n // middleware is outermost.\n if (options.openGenerativeUI) {\n const next = agent;\n const middleware = new OpenGenerativeUIMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n }\n if (options.a2ui) {\n const next = agent;\n const middleware = new A2UIMiddleware(options.a2ui);\n agent = new RecordedEventAgent(input, (runInput) =>\n middleware.run(runInput, next),\n );\n const inner = agent;\n const bridge = new A2UIV09BridgeMiddleware();\n agent = new RecordedEventAgent(input, (runInput) =>\n bridge.run(runInput, inner),\n );\n }\n return firstValueFrom(agent.run(input).pipe(toArray()));\n}\n"],"mappings":";;;;;;;;AAoBA,IAAM,qBAAN,MAAM,2BAA2B,cAAc;CAC7C,YACE,AAAiB,OACjB,AAAiB,QACjB;AACA,QAAM;GACJ,UAAU,MAAM;GAChB,iBAAiB,MAAM;GACvB,cAAc,MAAM;GACrB,CAAC;EAPe;EACA;;;CAUnB,IAAI,OAA6C;AAC/C,SAAO,KAAK,OAAO,MAAM;;;CAI3B,QAAuB;AACrB,SAAO,IAAI,mBACT;GAAE,GAAG,KAAK;GAAO,UAAU,KAAK;GAAU,OAAO,KAAK;GAAO,EAC7D,KAAK,OACN;;;;;;;;;;;;;AAcL,eAAsB,wBACpB,OACA,QACA,SACsB;CAItB,MAAM,YAAY,OAAO,QACtB,UACC,MAAM,SAAS,UAAU,eACzB,MAAM,SAAS,UAAU,aAC5B;CACD,IAAI,WAAW;CACf,IAAI,QAAuB,IAAI,mBAAmB,aAAa;EAC7D,MAAM,SAAS,WAAW,YAAY;AACtC,aAAW;AACX,SAAO,KAAK,OAAO;GACnB;AAGF,KAAI,QAAQ,kBAAkB;EAC5B,MAAM,OAAO;EACb,MAAM,aAAa,IAAI,4BAA4B;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;;AAEH,KAAI,QAAQ,MAAM;EAChB,MAAM,OAAO;EACb,MAAM,aAAa,IAAI,eAAe,QAAQ,KAAK;AACnD,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,WAAW,IAAI,UAAU,KAAK,CAC/B;EACD,MAAM,QAAQ;EACd,MAAM,SAAS,IAAI,yBAAyB;AAC5C,UAAQ,IAAI,mBAAmB,QAAQ,aACrC,OAAO,IAAI,UAAU,MAAM,CAC5B;;AAEH,QAAO,eAAe,MAAM,IAAI,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC"}
@@ -0,0 +1,106 @@
1
+ const require_usage = require('../../agent/converters/usage.cjs');
2
+ let _copilotkit_shared = require("@copilotkit/shared");
3
+
4
+ //#region src/runtime/generative-ui/a2ui-v09-actions.ts
5
+ /** The 1.0 action of the user event that started the run, if one did. */
6
+ function readAction(envelope) {
7
+ const message = envelope?.metadata.extensions.copilotkit_action;
8
+ if (!require_usage.isRecord(message) || !require_usage.isRecord(message.action)) return void 0;
9
+ const { name, surfaceId, sourceComponentId, context, timestamp } = message.action;
10
+ if (typeof name !== "string" || typeof surfaceId !== "string") return;
11
+ return {
12
+ name,
13
+ surfaceId,
14
+ sourceComponentId: typeof sourceComponentId === "string" ? sourceComponentId : "",
15
+ context: require_usage.isRecord(context) ? context : {},
16
+ timestamp: typeof timestamp === "string" ? timestamp : (/* @__PURE__ */ new Date()).toISOString()
17
+ };
18
+ }
19
+ /**
20
+ * True when the surface was converted from A2UI v0.9. The first of these
21
+ * that knows the surface decides:
22
+ * 1. The summary of the surface in the envelope (`copilotkit_surfaces`).
23
+ * 2. The last `generative-ui-surface` activity message of the surface.
24
+ * 3. `agentVersion`.
25
+ */
26
+ function isV09Surface(surfaces, messages, surfaceId, agentVersion) {
27
+ if (Object.hasOwn(surfaces, surfaceId)) return surfaces[surfaceId].a2uiSourceVersion === "0.9";
28
+ const surface = messages.findLast((message) => message.role === "activity" && message.activityType === _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE && require_usage.isRecord(message.content) && message.content.surfaceId === surfaceId);
29
+ if (!surface) return agentVersion === "0.9";
30
+ return surface.content?.a2uiSourceVersion === "0.9";
31
+ }
32
+ /**
33
+ * Removes the visible user message that the 1.0 client added for the click.
34
+ * The client adds it just before the run, so it is the last message.
35
+ */
36
+ function withoutActionUserMessage(messages) {
37
+ const last = messages.at(-1);
38
+ if (last?.role !== "user" || typeof last.content !== "string") return messages;
39
+ return messages.slice(0, -1);
40
+ }
41
+ /**
42
+ * Turns a click on a surface that the runtime converted from A2UI v0.9 into
43
+ * the v0.9 action that the agent side expects.
44
+ *
45
+ * The 1.0 client sends a click as a visible user message plus
46
+ * `forwardedProps.copilotkit.ui.metadata.extensions.copilotkit_action`. A v0.9
47
+ * agent stack reads `forwardedProps.a2uiAction.userAction` instead. When the
48
+ * run carries a 1.0 action for a surface of v0.9 origin, this returns a new
49
+ * input with `forwardedProps.a2uiAction` set and the visible user message
50
+ * removed. Otherwise it returns `input` unchanged. It never mutates `input`.
51
+ *
52
+ * The visible user message is removed because the v0.9 consumers already
53
+ * turn `a2uiAction` into what the agent sees:
54
+ * - `@ag-ui/a2ui-middleware` appends the action as a private user message,
55
+ * `A2UI user action:` and the action JSON. The Python, Go, Ruby and .NET
56
+ * runtimes append a synthetic `log_a2ui_event` tool call and result, and
57
+ * prompt the model to answer them when they end the conversation. With
58
+ * the visible message kept, the model sees the click twice, and the
59
+ * conversation no longer ends with the action.
60
+ * - `@ag-ui/a2a` attaches `a2uiAction` as a data part to the latest user
61
+ * message, and A2A agents read the data part first.
62
+ * The v0.9 client sent no user message for a click, so with it removed the
63
+ * agent gets the same input as it did from the v0.9 client. The 1.0 client
64
+ * still shows the message in its chat.
65
+ *
66
+ * Origin: the first of these that knows the clicked surface decides.
67
+ * 1. Its summary in the envelope
68
+ * (`forwardedProps.copilotkit.ui.metadata.extensions.copilotkit_surfaces`):
69
+ * `a2uiSourceVersion === "0.9"` means v0.9 origin, left out means 1.0. The
70
+ * 1.0 client copies the tag from the surface's activity content, so this
71
+ * is what decides for runs from the 1.0 client.
72
+ * 2. The last `generative-ui-surface` activity message for the surface in
73
+ * `input.messages` (`a2uiSourceVersion === "0.9"`), for a caller that
74
+ * passes activity messages.
75
+ * 3. `options.agentVersion === "0.9"`.
76
+ *
77
+ * @param input - The run input from the 1.0 client.
78
+ * @param options - `agentVersion`: the fallback when the surface is unknown.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const agentInput = downgradeA2UIV09Action(input, { agentVersion: "0.9" });
83
+ * // agentInput.forwardedProps.a2uiAction.userAction:
84
+ * // { name, surfaceId, sourceComponentId, context, timestamp }
85
+ * ```
86
+ */
87
+ function downgradeA2UIV09Action(input, options = {}) {
88
+ const forwardedProps = input.forwardedProps;
89
+ if (!require_usage.isRecord(forwardedProps) || forwardedProps.a2uiAction !== void 0) return input;
90
+ const envelope = (0, _copilotkit_shared.readCopilotKitUIEnvelope)(forwardedProps);
91
+ const userAction = readAction(envelope);
92
+ if (!envelope || !userAction) return input;
93
+ if (!isV09Surface(envelope.metadata.extensions.copilotkit_surfaces, input.messages, userAction.surfaceId, options.agentVersion)) return input;
94
+ return {
95
+ ...input,
96
+ messages: withoutActionUserMessage(input.messages),
97
+ forwardedProps: {
98
+ ...forwardedProps,
99
+ a2uiAction: { userAction }
100
+ }
101
+ };
102
+ }
103
+
104
+ //#endregion
105
+ exports.downgradeA2UIV09Action = downgradeA2UIV09Action;
106
+ //# sourceMappingURL=a2ui-v09-actions.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"a2ui-v09-actions.cjs","names":["isRecord","GENERATIVE_UI_ACTIVITY_TYPE"],"sources":["../../../src/runtime/generative-ui/a2ui-v09-actions.ts"],"sourcesContent":["import type { Message, RunAgentInput } from \"@ag-ui/client\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n readCopilotKitUIEnvelope,\n} from \"@copilotkit/shared\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { isRecord } from \"../../agent/converters/usage\";\n\n/**\n * The A2UI v0.9 user action, as the v0.9 client sent it in\n * `forwardedProps.a2uiAction.userAction`. `@ag-ui/a2ui-middleware`,\n * `@ag-ui/a2a` and the CopilotKit runtimes in other languages read this shape.\n */\ninterface A2UIV09UserAction {\n name: string;\n surfaceId: string;\n sourceComponentId: string;\n context: Record<string, unknown>;\n timestamp: string;\n}\n\nexport interface DowngradeA2UIV09ActionOptions {\n /**\n * The A2UI version the agent speaks. Used only when neither the envelope\n * summary nor `input.messages` knows the clicked surface.\n */\n agentVersion?: \"0.9\" | \"1.0\";\n}\n\n/** The 1.0 action of the user event that started the run, if one did. */\nfunction readAction(\n envelope: CopilotKitUIEnvelope | undefined,\n): A2UIV09UserAction | undefined {\n const message: unknown = envelope?.metadata.extensions.copilotkit_action;\n if (!isRecord(message) || !isRecord(message.action)) return undefined;\n const { name, surfaceId, sourceComponentId, context, timestamp } =\n message.action;\n if (typeof name !== \"string\" || typeof surfaceId !== \"string\") {\n return undefined;\n }\n return {\n name,\n surfaceId,\n sourceComponentId:\n typeof sourceComponentId === \"string\" ? sourceComponentId : \"\",\n context: isRecord(context) ? context : {},\n timestamp:\n typeof timestamp === \"string\" ? timestamp : new Date().toISOString(),\n };\n}\n\n/**\n * True when the surface was converted from A2UI v0.9. The first of these\n * that knows the surface decides:\n * 1. The summary of the surface in the envelope (`copilotkit_surfaces`).\n * 2. The last `generative-ui-surface` activity message of the surface.\n * 3. `agentVersion`.\n */\nfunction isV09Surface(\n surfaces: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_surfaces\"],\n messages: readonly Message[],\n surfaceId: string,\n agentVersion: DowngradeA2UIV09ActionOptions[\"agentVersion\"],\n) {\n // `readCopilotKitUIEnvelope` checked the summary, so the tag is \"0.9\" or\n // left out. An own-key check: the ids come from the client.\n if (Object.hasOwn(surfaces, surfaceId)) {\n return surfaces[surfaceId].a2uiSourceVersion === \"0.9\";\n }\n const surface = messages.findLast(\n (message) =>\n message.role === \"activity\" &&\n message.activityType === GENERATIVE_UI_ACTIVITY_TYPE &&\n isRecord(message.content) &&\n message.content.surfaceId === surfaceId,\n );\n if (!surface) return agentVersion === \"0.9\";\n // `a2uiSourceVersion` is set by the runtime on surfaces it converted from\n // v0.9. Read it untyped: not every surface content has it.\n const content = (surface as { content?: { a2uiSourceVersion?: unknown } })\n .content;\n return content?.a2uiSourceVersion === \"0.9\";\n}\n\n/**\n * Removes the visible user message that the 1.0 client added for the click.\n * The client adds it just before the run, so it is the last message.\n */\nfunction withoutActionUserMessage(messages: Message[]) {\n const last = messages.at(-1);\n if (last?.role !== \"user\" || typeof last.content !== \"string\") {\n return messages;\n }\n return messages.slice(0, -1);\n}\n\n/**\n * Turns a click on a surface that the runtime converted from A2UI v0.9 into\n * the v0.9 action that the agent side expects.\n *\n * The 1.0 client sends a click as a visible user message plus\n * `forwardedProps.copilotkit.ui.metadata.extensions.copilotkit_action`. A v0.9\n * agent stack reads `forwardedProps.a2uiAction.userAction` instead. When the\n * run carries a 1.0 action for a surface of v0.9 origin, this returns a new\n * input with `forwardedProps.a2uiAction` set and the visible user message\n * removed. Otherwise it returns `input` unchanged. It never mutates `input`.\n *\n * The visible user message is removed because the v0.9 consumers already\n * turn `a2uiAction` into what the agent sees:\n * - `@ag-ui/a2ui-middleware` appends the action as a private user message,\n * `A2UI user action:` and the action JSON. The Python, Go, Ruby and .NET\n * runtimes append a synthetic `log_a2ui_event` tool call and result, and\n * prompt the model to answer them when they end the conversation. With\n * the visible message kept, the model sees the click twice, and the\n * conversation no longer ends with the action.\n * - `@ag-ui/a2a` attaches `a2uiAction` as a data part to the latest user\n * message, and A2A agents read the data part first.\n * The v0.9 client sent no user message for a click, so with it removed the\n * agent gets the same input as it did from the v0.9 client. The 1.0 client\n * still shows the message in its chat.\n *\n * Origin: the first of these that knows the clicked surface decides.\n * 1. Its summary in the envelope\n * (`forwardedProps.copilotkit.ui.metadata.extensions.copilotkit_surfaces`):\n * `a2uiSourceVersion === \"0.9\"` means v0.9 origin, left out means 1.0. The\n * 1.0 client copies the tag from the surface's activity content, so this\n * is what decides for runs from the 1.0 client.\n * 2. The last `generative-ui-surface` activity message for the surface in\n * `input.messages` (`a2uiSourceVersion === \"0.9\"`), for a caller that\n * passes activity messages.\n * 3. `options.agentVersion === \"0.9\"`.\n *\n * @param input - The run input from the 1.0 client.\n * @param options - `agentVersion`: the fallback when the surface is unknown.\n *\n * @example\n * ```ts\n * const agentInput = downgradeA2UIV09Action(input, { agentVersion: \"0.9\" });\n * // agentInput.forwardedProps.a2uiAction.userAction:\n * // { name, surfaceId, sourceComponentId, context, timestamp }\n * ```\n */\nexport function downgradeA2UIV09Action(\n input: RunAgentInput,\n options: DowngradeA2UIV09ActionOptions = {},\n): RunAgentInput {\n const forwardedProps: unknown = input.forwardedProps;\n // A run that already has a v0.9 action keeps it.\n if (!isRecord(forwardedProps) || forwardedProps.a2uiAction !== undefined) {\n return input;\n }\n const envelope = readCopilotKitUIEnvelope(forwardedProps);\n const userAction = readAction(envelope);\n if (!envelope || !userAction) return input;\n if (\n !isV09Surface(\n envelope.metadata.extensions.copilotkit_surfaces,\n input.messages,\n userAction.surfaceId,\n options.agentVersion,\n )\n ) {\n return input;\n }\n return {\n ...input,\n messages: withoutActionUserMessage(input.messages),\n forwardedProps: { ...forwardedProps, a2uiAction: { userAction } },\n };\n}\n"],"mappings":";;;;;AA8BA,SAAS,WACP,UAC+B;CAC/B,MAAM,UAAmB,UAAU,SAAS,WAAW;AACvD,KAAI,CAACA,uBAAS,QAAQ,IAAI,CAACA,uBAAS,QAAQ,OAAO,CAAE,QAAO;CAC5D,MAAM,EAAE,MAAM,WAAW,mBAAmB,SAAS,cACnD,QAAQ;AACV,KAAI,OAAO,SAAS,YAAY,OAAO,cAAc,SACnD;AAEF,QAAO;EACL;EACA;EACA,mBACE,OAAO,sBAAsB,WAAW,oBAAoB;EAC9D,SAASA,uBAAS,QAAQ,GAAG,UAAU,EAAE;EACzC,WACE,OAAO,cAAc,WAAW,6BAAY,IAAI,MAAM,EAAC,aAAa;EACvE;;;;;;;;;AAUH,SAAS,aACP,UACA,UACA,WACA,cACA;AAGA,KAAI,OAAO,OAAO,UAAU,UAAU,CACpC,QAAO,SAAS,WAAW,sBAAsB;CAEnD,MAAM,UAAU,SAAS,UACtB,YACC,QAAQ,SAAS,cACjB,QAAQ,iBAAiBC,kDACzBD,uBAAS,QAAQ,QAAQ,IACzB,QAAQ,QAAQ,cAAc,UACjC;AACD,KAAI,CAAC,QAAS,QAAO,iBAAiB;AAKtC,QAFiB,QACd,SACa,sBAAsB;;;;;;AAOxC,SAAS,yBAAyB,UAAqB;CACrD,MAAM,OAAO,SAAS,GAAG,GAAG;AAC5B,KAAI,MAAM,SAAS,UAAU,OAAO,KAAK,YAAY,SACnD,QAAO;AAET,QAAO,SAAS,MAAM,GAAG,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiD9B,SAAgB,uBACd,OACA,UAAyC,EAAE,EAC5B;CACf,MAAM,iBAA0B,MAAM;AAEtC,KAAI,CAACA,uBAAS,eAAe,IAAI,eAAe,eAAe,OAC7D,QAAO;CAET,MAAM,4DAAoC,eAAe;CACzD,MAAM,aAAa,WAAW,SAAS;AACvC,KAAI,CAAC,YAAY,CAAC,WAAY,QAAO;AACrC,KACE,CAAC,aACC,SAAS,SAAS,WAAW,qBAC7B,MAAM,UACN,WAAW,WACX,QAAQ,aACT,CAED,QAAO;AAET,QAAO;EACL,GAAG;EACH,UAAU,yBAAyB,MAAM,SAAS;EAClD,gBAAgB;GAAE,GAAG;GAAgB,YAAY,EAAE,YAAY;GAAE;EAClE"}
@@ -0,0 +1,106 @@
1
+ import { isRecord } from "../../agent/converters/usage.mjs";
2
+ import { GENERATIVE_UI_ACTIVITY_TYPE, readCopilotKitUIEnvelope } from "@copilotkit/shared";
3
+
4
+ //#region src/runtime/generative-ui/a2ui-v09-actions.ts
5
+ /** The 1.0 action of the user event that started the run, if one did. */
6
+ function readAction(envelope) {
7
+ const message = envelope?.metadata.extensions.copilotkit_action;
8
+ if (!isRecord(message) || !isRecord(message.action)) return void 0;
9
+ const { name, surfaceId, sourceComponentId, context, timestamp } = message.action;
10
+ if (typeof name !== "string" || typeof surfaceId !== "string") return;
11
+ return {
12
+ name,
13
+ surfaceId,
14
+ sourceComponentId: typeof sourceComponentId === "string" ? sourceComponentId : "",
15
+ context: isRecord(context) ? context : {},
16
+ timestamp: typeof timestamp === "string" ? timestamp : (/* @__PURE__ */ new Date()).toISOString()
17
+ };
18
+ }
19
+ /**
20
+ * True when the surface was converted from A2UI v0.9. The first of these
21
+ * that knows the surface decides:
22
+ * 1. The summary of the surface in the envelope (`copilotkit_surfaces`).
23
+ * 2. The last `generative-ui-surface` activity message of the surface.
24
+ * 3. `agentVersion`.
25
+ */
26
+ function isV09Surface(surfaces, messages, surfaceId, agentVersion) {
27
+ if (Object.hasOwn(surfaces, surfaceId)) return surfaces[surfaceId].a2uiSourceVersion === "0.9";
28
+ const surface = messages.findLast((message) => message.role === "activity" && message.activityType === GENERATIVE_UI_ACTIVITY_TYPE && isRecord(message.content) && message.content.surfaceId === surfaceId);
29
+ if (!surface) return agentVersion === "0.9";
30
+ return surface.content?.a2uiSourceVersion === "0.9";
31
+ }
32
+ /**
33
+ * Removes the visible user message that the 1.0 client added for the click.
34
+ * The client adds it just before the run, so it is the last message.
35
+ */
36
+ function withoutActionUserMessage(messages) {
37
+ const last = messages.at(-1);
38
+ if (last?.role !== "user" || typeof last.content !== "string") return messages;
39
+ return messages.slice(0, -1);
40
+ }
41
+ /**
42
+ * Turns a click on a surface that the runtime converted from A2UI v0.9 into
43
+ * the v0.9 action that the agent side expects.
44
+ *
45
+ * The 1.0 client sends a click as a visible user message plus
46
+ * `forwardedProps.copilotkit.ui.metadata.extensions.copilotkit_action`. A v0.9
47
+ * agent stack reads `forwardedProps.a2uiAction.userAction` instead. When the
48
+ * run carries a 1.0 action for a surface of v0.9 origin, this returns a new
49
+ * input with `forwardedProps.a2uiAction` set and the visible user message
50
+ * removed. Otherwise it returns `input` unchanged. It never mutates `input`.
51
+ *
52
+ * The visible user message is removed because the v0.9 consumers already
53
+ * turn `a2uiAction` into what the agent sees:
54
+ * - `@ag-ui/a2ui-middleware` appends the action as a private user message,
55
+ * `A2UI user action:` and the action JSON. The Python, Go, Ruby and .NET
56
+ * runtimes append a synthetic `log_a2ui_event` tool call and result, and
57
+ * prompt the model to answer them when they end the conversation. With
58
+ * the visible message kept, the model sees the click twice, and the
59
+ * conversation no longer ends with the action.
60
+ * - `@ag-ui/a2a` attaches `a2uiAction` as a data part to the latest user
61
+ * message, and A2A agents read the data part first.
62
+ * The v0.9 client sent no user message for a click, so with it removed the
63
+ * agent gets the same input as it did from the v0.9 client. The 1.0 client
64
+ * still shows the message in its chat.
65
+ *
66
+ * Origin: the first of these that knows the clicked surface decides.
67
+ * 1. Its summary in the envelope
68
+ * (`forwardedProps.copilotkit.ui.metadata.extensions.copilotkit_surfaces`):
69
+ * `a2uiSourceVersion === "0.9"` means v0.9 origin, left out means 1.0. The
70
+ * 1.0 client copies the tag from the surface's activity content, so this
71
+ * is what decides for runs from the 1.0 client.
72
+ * 2. The last `generative-ui-surface` activity message for the surface in
73
+ * `input.messages` (`a2uiSourceVersion === "0.9"`), for a caller that
74
+ * passes activity messages.
75
+ * 3. `options.agentVersion === "0.9"`.
76
+ *
77
+ * @param input - The run input from the 1.0 client.
78
+ * @param options - `agentVersion`: the fallback when the surface is unknown.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const agentInput = downgradeA2UIV09Action(input, { agentVersion: "0.9" });
83
+ * // agentInput.forwardedProps.a2uiAction.userAction:
84
+ * // { name, surfaceId, sourceComponentId, context, timestamp }
85
+ * ```
86
+ */
87
+ function downgradeA2UIV09Action(input, options = {}) {
88
+ const forwardedProps = input.forwardedProps;
89
+ if (!isRecord(forwardedProps) || forwardedProps.a2uiAction !== void 0) return input;
90
+ const envelope = readCopilotKitUIEnvelope(forwardedProps);
91
+ const userAction = readAction(envelope);
92
+ if (!envelope || !userAction) return input;
93
+ if (!isV09Surface(envelope.metadata.extensions.copilotkit_surfaces, input.messages, userAction.surfaceId, options.agentVersion)) return input;
94
+ return {
95
+ ...input,
96
+ messages: withoutActionUserMessage(input.messages),
97
+ forwardedProps: {
98
+ ...forwardedProps,
99
+ a2uiAction: { userAction }
100
+ }
101
+ };
102
+ }
103
+
104
+ //#endregion
105
+ export { downgradeA2UIV09Action };
106
+ //# sourceMappingURL=a2ui-v09-actions.mjs.map