@copilotkit/runtime 1.76.0 → 1.77.1

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 (110) hide show
  1. package/dist/_virtual/_rolldown/runtime.mjs +1 -25
  2. package/dist/lib/runtime/copilot-runtime.cjs +1 -0
  3. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  4. package/dist/lib/runtime/copilot-runtime.d.cts +1 -0
  5. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  6. package/dist/lib/runtime/copilot-runtime.d.mts +1 -0
  7. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  8. package/dist/lib/runtime/copilot-runtime.mjs +1 -0
  9. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  10. package/dist/lib/telemetry-client.cjs +1 -1
  11. package/dist/lib/telemetry-client.mjs +1 -1
  12. package/dist/package.cjs +6 -6
  13. package/dist/package.mjs +6 -6
  14. package/dist/v2/runtime/core/channel-manager.cjs +15 -15
  15. package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
  16. package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
  17. package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
  18. package/dist/v2/runtime/core/channel-manager.mjs +15 -15
  19. package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
  20. package/dist/v2/runtime/core/fetch-handler.cjs +16 -1
  21. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  22. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  23. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  24. package/dist/v2/runtime/core/fetch-handler.mjs +16 -1
  25. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  26. package/dist/v2/runtime/core/fetch-router.cjs +8 -0
  27. package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
  28. package/dist/v2/runtime/core/fetch-router.mjs +8 -0
  29. package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
  30. package/dist/v2/runtime/core/hooks.cjs.map +1 -1
  31. package/dist/v2/runtime/core/hooks.d.cts +3 -0
  32. package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
  33. package/dist/v2/runtime/core/hooks.d.mts +3 -0
  34. package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
  35. package/dist/v2/runtime/core/hooks.mjs.map +1 -1
  36. package/dist/v2/runtime/core/package-info.cjs +10 -0
  37. package/dist/v2/runtime/core/package-info.cjs.map +1 -0
  38. package/dist/v2/runtime/core/package-info.mjs +8 -0
  39. package/dist/v2/runtime/core/package-info.mjs.map +1 -0
  40. package/dist/v2/runtime/core/runtime.cjs +4 -4
  41. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  42. package/dist/v2/runtime/core/runtime.d.cts +7 -1
  43. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  44. package/dist/v2/runtime/core/runtime.d.mts +7 -1
  45. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  46. package/dist/v2/runtime/core/runtime.mjs +4 -5
  47. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  48. package/dist/v2/runtime/endpoints/single-route-helpers.cjs +1 -0
  49. package/dist/v2/runtime/endpoints/single-route-helpers.cjs.map +1 -1
  50. package/dist/v2/runtime/endpoints/single-route-helpers.mjs +1 -0
  51. package/dist/v2/runtime/endpoints/single-route-helpers.mjs.map +1 -1
  52. package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs +41 -0
  53. package/dist/v2/runtime/handlers/handle-trajectory-connect.cjs.map +1 -0
  54. package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs +40 -0
  55. package/dist/v2/runtime/handlers/handle-trajectory-connect.mjs.map +1 -0
  56. package/dist/v2/runtime/handlers/intelligence/memories.cjs +5 -17
  57. package/dist/v2/runtime/handlers/intelligence/memories.cjs.map +1 -1
  58. package/dist/v2/runtime/handlers/intelligence/memories.mjs +5 -17
  59. package/dist/v2/runtime/handlers/intelligence/memories.mjs.map +1 -1
  60. package/dist/v2/runtime/handlers/intelligence/run.cjs +43 -16
  61. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
  62. package/dist/v2/runtime/handlers/intelligence/run.mjs +43 -16
  63. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
  64. package/dist/v2/runtime/handlers/intelligence/threads.cjs +4 -3
  65. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  66. package/dist/v2/runtime/handlers/intelligence/threads.mjs +4 -3
  67. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  68. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.cjs +1 -2
  69. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.cjs.map +1 -1
  70. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.mjs +1 -2
  71. package/dist/v2/runtime/handlers/shared/mcp-apps-servers.mjs.map +1 -1
  72. package/dist/v2/runtime/handlers/shared/platform-error.cjs +40 -0
  73. package/dist/v2/runtime/handlers/shared/platform-error.cjs.map +1 -0
  74. package/dist/v2/runtime/handlers/shared/platform-error.mjs +40 -0
  75. package/dist/v2/runtime/handlers/shared/platform-error.mjs.map +1 -0
  76. package/dist/v2/runtime/intelligence-platform/client.cjs +43 -4
  77. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  78. package/dist/v2/runtime/intelligence-platform/client.d.cts +31 -0
  79. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  80. package/dist/v2/runtime/intelligence-platform/client.d.mts +31 -0
  81. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  82. package/dist/v2/runtime/intelligence-platform/client.mjs +43 -4
  83. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  84. package/dist/v2/runtime/intelligence-platform/thread-lock-heartbeat.cjs +143 -0
  85. package/dist/v2/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -0
  86. package/dist/v2/runtime/intelligence-platform/thread-lock-heartbeat.mjs +142 -0
  87. package/dist/v2/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -0
  88. package/dist/v2/runtime/intelligence-platform/trajectories.cjs +80 -0
  89. package/dist/v2/runtime/intelligence-platform/trajectories.cjs.map +1 -0
  90. package/dist/v2/runtime/intelligence-platform/trajectories.d.cts +12 -0
  91. package/dist/v2/runtime/intelligence-platform/trajectories.d.cts.map +1 -0
  92. package/dist/v2/runtime/intelligence-platform/trajectories.d.mts +12 -0
  93. package/dist/v2/runtime/intelligence-platform/trajectories.d.mts.map +1 -0
  94. package/dist/v2/runtime/intelligence-platform/trajectories.mjs +76 -0
  95. package/dist/v2/runtime/intelligence-platform/trajectories.mjs.map +1 -0
  96. package/dist/v2/runtime/runner/intelligence.cjs +8 -1
  97. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
  98. package/dist/v2/runtime/runner/intelligence.d.cts +12 -0
  99. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
  100. package/dist/v2/runtime/runner/intelligence.d.mts +12 -0
  101. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
  102. package/dist/v2/runtime/runner/intelligence.mjs +8 -1
  103. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
  104. package/dist/v2/runtime/telemetry/telemetry-client.cjs +3 -4
  105. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -1
  106. package/dist/v2/runtime/telemetry/telemetry-client.d.cts.map +1 -1
  107. package/dist/v2/runtime/telemetry/telemetry-client.d.mts.map +1 -1
  108. package/dist/v2/runtime/telemetry/telemetry-client.mjs +3 -5
  109. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -1
  110. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/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} 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 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 pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../v1-deprecated/lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../v1-deprecated/lib/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} from \"./learning\";\n\nexport const VERSION = pkg.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 is unsupported at its pinned 0.0.3 release. */\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\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 * 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\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 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 /** 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 intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: 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 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 licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n public readonly telemetry: TelemetryCapture;\n public readonly forwardHeadersPolicy: ResolvedForwardHeadersPolicy;\n public readonly sseKeepAliveIntervalSeconds: number;\n public readonly exposeMemoryRoutes: boolean;\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 licenseChecker) 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 constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\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.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 process.env.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 process.env.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 = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\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();\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 }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\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 super(options, options.runner ?? new InMemoryAgentRunner());\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\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 (\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 }),\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 // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken ?? \"\");\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\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 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 isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\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 get licenseChecker() {\n return this.delegate.licenseChecker;\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 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":";;;;;;;;;;;;;;;;;;;AAkEA,MAAa,UAAUA,uBAAI;;;;;;AA4E3B,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;;AAiPT,IAAe,qBAAf,MAAgE;CA8B9D,YAAY,SAAoC,QAAqB;AACnE,iCAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;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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,SAAS,eACd;;CAGN,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,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,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/v2/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} 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 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 { createLogger } from \"../../../v1-deprecated/lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../v1-deprecated/lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../v1-deprecated/lib/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} 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\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 * 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\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 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 intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: 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 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 licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n public readonly telemetry: TelemetryCapture;\n public readonly forwardHeadersPolicy: ResolvedForwardHeadersPolicy;\n public readonly sseKeepAliveIntervalSeconds: number;\n public readonly exposeMemoryRoutes: boolean;\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 licenseChecker) 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 constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\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.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 process.env.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 process.env.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 = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\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();\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 }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\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 super(options, options.runner ?? new InMemoryAgentRunner());\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\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 (\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 }),\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 // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken ?? \"\");\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\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 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 isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\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 get licenseChecker() {\n return this.delegate.licenseChecker;\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 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":";;;;;;;;;;;;;;;;;AAkEA,MAAa,UAAU;;;;;;AA4EvB,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;;AAuPT,IAAe,qBAAf,MAAgE;CA8B9D,YAAY,SAAoC,QAAqB;AACnE,iCAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;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,SAAS;AAKd,OAA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,KAAK,SAAS,eACd;;CAGN,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,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,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"}
@@ -5,6 +5,7 @@ const METHOD_NAMES = [
5
5
  "agent/run",
6
6
  "agent/suggest",
7
7
  "agent/connect",
8
+ "trajectory/connect",
8
9
  "agent/stop",
9
10
  "info",
10
11
  "inspector/metadata",
@@ -1 +1 @@
1
- {"version":3,"file":"single-route-helpers.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,SAAO;;AAGT,KAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;CAE9D,MAAM,SAAU,SAA0B;AAC1C,KAAI,OAAO,WAAW,SAAU,QAAO;AACvC,KAAI,CAAE,aAAmC,SAAS,OAAO,CAAE,QAAO;AAElE,QAAO;;AAGT,eAAsB,gBAAgB,SAAuC;AAG3E,KAAI,EAFgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAE1C,SAAS,mBAAmB,CAC3C,OAAM,oBACJ,+CACA,IACD;CAGH,IAAI;AACJ,KAAI;AACF,iBAAgB,MAAM,QAAQ,OAAO,CAAC,MAAM;SACtC;AACN,QAAM,oBAAoB,wBAAwB,IAAI;;AAKxD,QAAO;EACL,QAHa,eAAe,aAAa,OAAO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C;;AAGJ,SAAgB,oBAAoB,SAAiB,QAA0B;AAC7E,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP;EACD,CAAC,EACF;EACE;EACA,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;AAGH,SAAS,eAAe,QAA4C;AAClE,KAAI,CAAC,OACH,OAAM,oBAAoB,wBAAwB,IAAI;AAGxD,KAAK,aAAmC,SAAS,OAAO,CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
1
+ {"version":3,"file":"single-route-helpers.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"trajectory/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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AAO,KAAK,UAAU,KAAK"}
@@ -4,6 +4,7 @@ const METHOD_NAMES = [
4
4
  "agent/run",
5
5
  "agent/suggest",
6
6
  "agent/connect",
7
+ "trajectory/connect",
7
8
  "agent/stop",
8
9
  "info",
9
10
  "inspector/metadata",
@@ -1 +1 @@
1
- {"version":3,"file":"single-route-helpers.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,SAAO;;AAGT,KAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;CAE9D,MAAM,SAAU,SAA0B;AAC1C,KAAI,OAAO,WAAW,SAAU,QA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U,SAAS,QAAQ,OAAO,GAAG,GAAG,YAAY;AAC5E,WAAU,SAAS,YAAY;CAE/B,MAAM,SAAS,WAAW,aAAa;CACvC,MAAM,UAAU,IAAI,QAAQ,KAAK,QAAQ;AACzC,SAAQ,OAAO,iBAAiB;CAChC,MAAM,UAAU,WAAW,SAAS,WAAW,UAAU,QAAQ;AAEjE,QAAO,IAAI,QAAQ,WAAW;EAC5B;EACA;EACA,GAAI,UAAU,EAAE,MAAM,kBAAkB,KAAK,EAAE,GAAG,EAAE;EACpD,QAAQ,KAAK;EACd,CAAC;;AAGJ,SAAgB,oBAAoB,SAAiB,QAA0B;AAC7E,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP;EACD,CAAC,EACF;EACE;EACA,SAAS,EACP,gBAAgB,oBACjB;EACF,CACF;;AAGH,SAAS,eAAe,QAA4C;AAClE,KAAI,CAAC,OACH,OAAM,oBAAoB,wBAAwB,IAAI;AAGxD,KAAK,aAAmC,SAAS,OAAO,CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
1
+ {"version":3,"file":"single-route-helpers.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/suggest\",\n \"agent/connect\",\n \"trajectory/connect\",\n \"agent/stop\",\n \"info\",\n \"inspector/metadata\",\n \"inspector/learning\",\n \"transcribe\",\n \"resource/request\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\n/**\n * Detect a single-route JSON envelope on a request the multi-route router\n * could not match.\n *\n * A single-endpoint client (`useSingleEndpoint` on the frontend provider)\n * POSTs `{ method, params, body }` at the base path. A multi-route runtime\n * matches no route for that path and would otherwise answer a bare 404, giving\n * the developer nothing to go on. Recognising the envelope here lets the\n * handler name the actual cause instead.\n *\n * Deliberately conservative: it reports a method only for a POST carrying a\n * JSON body whose `method` is one the single-route endpoint actually accepts.\n * Anything else is a genuine 404 and must stay one.\n *\n * @returns The envelope's method name, or `null` if this is not an envelope.\n */\nexport async function detectSingleRouteEnvelope(\n request: Request,\n): Promise<EndpointMethod | null> {\n if (request.method !== \"POST\") return null;\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/json\")) return null;\n\n let envelope: unknown;\n try {\n envelope = await request.clone().json();\n } catch {\n return null;\n }\n\n if (typeof envelope !== \"object\" || envelope === null) return null;\n\n const method = (envelope as JsonEnvelope).method;\n if (typeof method !== \"string\") return null;\n if (!(METHOD_NAMES as readonly string[]).includes(method)) return null;\n\n return method as EndpointMethod;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\n/**\n * Rebuild a resource request carried inside the single-route JSON envelope.\n *\n * The resource path must stay relative to the mounted Runtime. This prevents\n * the envelope from becoming an open HTTP proxy while preserving the method,\n * query string, headers, and cancellation signal used by the REST handler.\n */\nexport function createResourceRequest(\n base: Request,\n path: string,\n httpMethod: string,\n body: unknown,\n): Request {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const resourceUrl = new URL(path, \"http://copilotkit.resource\");\n if (resourceUrl.origin !== \"http://copilotkit.resource\") {\n throw createResponseError(\"Resource path must be Runtime-relative\", 400);\n }\n\n const targetUrl = new URL(base.url);\n targetUrl.pathname = `${targetUrl.pathname.replace(/\\/$/, \"\")}${resourceUrl.pathname}`;\n targetUrl.search = resourceUrl.search;\n\n const method = httpMethod.toUpperCase();\n const headers = new Headers(base.headers);\n headers.delete(\"content-length\");\n const hasBody = method !== \"GET\" && method !== \"HEAD\" && body != null;\n\n return new Request(targetUrl, {\n method,\n headers,\n ...(hasBody ? { body: serializeJsonBody(body) } : {}),\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;AAgCD,eAAsB,0BACpB,SACgC;AAChC,KAAI,QAAQ,WAAW,OAAQ,QAAO;AAGtC,KAAI,EADgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAC1C,SAAS,mBAAmB,CAAE,QAAO;CAEtD,IAAI;AACJ,KAAI;AACF,aAAW,MAAM,QAAQ,OAAO,CAAC,MAAM;SACjC;AACN,SAAO;;AAGT,KAAI,OAAO,aAAa,YAAY,aAAa,KAAM,QAAO;CAE9D,MAAM,SAAU,SAA0B;AAC1C,KAAI,OAAO,WAAW,SAAU,QAAO;AACvC,KAAI,CAAE,aAAmC,SAAS,OAAO,CAAE,QAAO;AAElE,QAAO;;AAGT,eAAsB,gBAAgB,SAAuC;AAG3E,KAAI,EAFgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAE1C,SAAS,mBAAmB,CAC3C,OAAM,oBACJ,+CACA,IACD;CAGH,IAAI;AACJ,KAAI;AACF,iBAAgB,MAAM,QAAQ,OAAO,CAAC,MAAM;SACtC;AACN,QAAM,oBAAoB,wBAAwB,IAAI;;AAKxD,QAAO;EACL,QAHa,eAAe,aAAa,OAAO;EAIhD,QAAQ,aAAa;EACrB,MAAM,aAAa;EACpB;;AAGH,SAAgB,aACd,QACA,KACQ;CACR,MAAM,QAAQ,SAAS;AACvB,KAAI,OAAO,UAAU,YAAY,MAAM,MAAM,CAAC,SAAS,EACr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GH,SAAS,eAAe,QAA4C;AAClE,KAAI,CAAC,OACH,OAAM,oBAAoB,wBAAwB,IAAI;AAGxD,KAAK,aAAmC,SAAS,OAAO,CACtD,QAAO;AAGT,OAAM,oBAAoB,uBAAuB,OAAO,IAAI,IAAI;;AAGlE,SAAS,kBAAkB,MAAyB;AAClD,KAAI,OAAO,SAAS,SAClB,QAAO;AAGT,KACE,gBAAgB,QAChB,gBAAgB,eAChB,gBAAgB,WAIhB,QAAO;AAGT,KAAI,gBAAgB,YAAY,gBAAgB,gBAC9C,QAAO;AAGT,QAAO,KAAK,UAAU,KAAK"}
@@ -0,0 +1,41 @@
1
+ require("reflect-metadata");
2
+ const require_runtime = require('../core/runtime.cjs');
3
+ const require_trajectories = require('../intelligence-platform/trajectories.cjs');
4
+ const require_resolve_intelligence_user = require('./shared/resolve-intelligence-user.cjs');
5
+
6
+ //#region src/v2/runtime/handlers/handle-trajectory-connect.ts
7
+ function trajectoryErrorResponse(code, message, status) {
8
+ return Response.json({
9
+ code,
10
+ message
11
+ }, {
12
+ status,
13
+ headers: { "Cache-Control": "no-store" }
14
+ });
15
+ }
16
+ async function handleTrajectoryConnect({ runtime, request, trajectoryId }) {
17
+ if (!require_trajectories.isValidTrajectoryId(trajectoryId)) return trajectoryErrorResponse("INVALID_REQUEST", "A valid trajectoryId is required", 400);
18
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return trajectoryErrorResponse("CONNECTION_FAILED", "Trajectory capture requires an Intelligence runtime", 503);
19
+ if (!runtime.identifyUser) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
20
+ const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
21
+ runtime,
22
+ request
23
+ });
24
+ if (user instanceof Response) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
25
+ try {
26
+ const grant = await runtime.intelligence.ɵconnectTrajectory({
27
+ trajectoryId,
28
+ user,
29
+ signal: request.signal
30
+ });
31
+ return Response.json(grant, { headers: { "Cache-Control": "no-store" } });
32
+ } catch (error) {
33
+ if (error instanceof require_trajectories.TrajectoryConnectionError) return trajectoryErrorResponse(error.code, error.message, error.status);
34
+ return trajectoryErrorResponse("CONNECTION_FAILED", "Could not connect to Intelligence", 502);
35
+ }
36
+ }
37
+
38
+ //#endregion
39
+ exports.handleTrajectoryConnect = handleTrajectoryConnect;
40
+ exports.trajectoryErrorResponse = trajectoryErrorResponse;
41
+ //# sourceMappingURL=handle-trajectory-connect.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-trajectory-connect.cjs","names":["isValidTrajectoryId","isIntelligenceRuntime","resolveIntelligenceUser","TrajectoryConnectionError"],"sources":["../../../../src/v2/runtime/handlers/handle-trajectory-connect.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport {\n isValidTrajectoryId,\n TrajectoryConnectionError,\n} from \"../intelligence-platform/trajectories\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nexport function trajectoryErrorResponse(\n code: string,\n message: string,\n status: number,\n): Response {\n return Response.json(\n { code, message },\n { status, headers: { \"Cache-Control\": \"no-store\" } },\n );\n}\n\nexport async function handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId,\n}: {\n runtime: CopilotRuntimeLike;\n request: Request;\n trajectoryId: string;\n}): Promise<Response> {\n if (!isValidTrajectoryId(trajectoryId)) {\n return trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n if (!isIntelligenceRuntime(runtime)) {\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Trajectory capture requires an Intelligence runtime\",\n 503,\n );\n }\n if (!runtime.identifyUser) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n\n try {\n const grant = await runtime.intelligence.ɵconnectTrajectory({\n trajectoryId,\n user,\n signal: request.signal,\n });\n return Response.json(grant, {\n headers: { \"Cache-Control\": \"no-store\" },\n });\n } catch (error) {\n if (error instanceof TrajectoryConnectionError) {\n return trajectoryErrorResponse(error.code, error.message, error.status);\n }\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n}\n"],"mappings":";;;;;;AAQA,SAAgB,wBACd,MACA,SACA,QACU;AACV,QAAO,SAAS,KACd;EAAE;EAAM;EAAS,EACjB;EAAE;EAAQ,SAAS,EAAE,iBAAiB,YAAY;EAAE,CACrD;;AAGH,eAAsB,wBAAwB,EAC5C,SACA,SACA,gBAKoB;AACpB,KAAI,CAACA,yCAAoB,aAAa,CACpC,QAAO,wBACL,mBACA,oCACA,IACD;AAEH,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAO,wBACL,qBACA,uDACA,IACD;AAEH,KAAI,CAAC,QAAQ,aACX,QAAO,wBACL,qBACA,kDACA,IACD;CAEH,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAClB,QAAO,wBACL,qBACA,kDACA,IACD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,aAAa,mBAAmB;GAC1D;GACA;GACA,QAAQ,QAAQ;GACjB,CAAC;AACF,SAAO,SAAS,KAAK,OAAO,EAC1B,SAAS,EAAE,iBAAiB,YAAY,EACzC,CAAC;UACK,OAAO;AACd,MAAI,iBAAiBC,+CACnB,QAAO,wBAAwB,MAAM,MAAM,MAAM,SAAS,MAAM,OAAO;AAEzE,SAAO,wBACL,qBACA,qCACA,IACD"}
@@ -0,0 +1,40 @@
1
+ import "reflect-metadata";
2
+ import { isIntelligenceRuntime } from "../core/runtime.mjs";
3
+ import { TrajectoryConnectionError, isValidTrajectoryId } from "../intelligence-platform/trajectories.mjs";
4
+ import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs";
5
+
6
+ //#region src/v2/runtime/handlers/handle-trajectory-connect.ts
7
+ function trajectoryErrorResponse(code, message, status) {
8
+ return Response.json({
9
+ code,
10
+ message
11
+ }, {
12
+ status,
13
+ headers: { "Cache-Control": "no-store" }
14
+ });
15
+ }
16
+ async function handleTrajectoryConnect({ runtime, request, trajectoryId }) {
17
+ if (!isValidTrajectoryId(trajectoryId)) return trajectoryErrorResponse("INVALID_REQUEST", "A valid trajectoryId is required", 400);
18
+ if (!isIntelligenceRuntime(runtime)) return trajectoryErrorResponse("CONNECTION_FAILED", "Trajectory capture requires an Intelligence runtime", 503);
19
+ if (!runtime.identifyUser) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
20
+ const user = await resolveIntelligenceUser({
21
+ runtime,
22
+ request
23
+ });
24
+ if (user instanceof Response) return trajectoryErrorResponse("IDENTITY_REQUIRED", "Trajectory capture requires an identified user", 401);
25
+ try {
26
+ const grant = await runtime.intelligence.ɵconnectTrajectory({
27
+ trajectoryId,
28
+ user,
29
+ signal: request.signal
30
+ });
31
+ return Response.json(grant, { headers: { "Cache-Control": "no-store" } });
32
+ } catch (error) {
33
+ if (error instanceof TrajectoryConnectionError) return trajectoryErrorResponse(error.code, error.message, error.status);
34
+ return trajectoryErrorResponse("CONNECTION_FAILED", "Could not connect to Intelligence", 502);
35
+ }
36
+ }
37
+
38
+ //#endregion
39
+ export { handleTrajectoryConnect, trajectoryErrorResponse };
40
+ //# sourceMappingURL=handle-trajectory-connect.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handle-trajectory-connect.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-trajectory-connect.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime } from \"../core/runtime\";\nimport {\n isValidTrajectoryId,\n TrajectoryConnectionError,\n} from \"../intelligence-platform/trajectories\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\n\nexport function trajectoryErrorResponse(\n code: string,\n message: string,\n status: number,\n): Response {\n return Response.json(\n { code, message },\n { status, headers: { \"Cache-Control\": \"no-store\" } },\n );\n}\n\nexport async function handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId,\n}: {\n runtime: CopilotRuntimeLike;\n request: Request;\n trajectoryId: string;\n}): Promise<Response> {\n if (!isValidTrajectoryId(trajectoryId)) {\n return trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n if (!isIntelligenceRuntime(runtime)) {\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Trajectory capture requires an Intelligence runtime\",\n 503,\n );\n }\n if (!runtime.identifyUser) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n if (user instanceof Response) {\n return trajectoryErrorResponse(\n \"IDENTITY_REQUIRED\",\n \"Trajectory capture requires an identified user\",\n 401,\n );\n }\n\n try {\n const grant = await runtime.intelligence.ɵconnectTrajectory({\n trajectoryId,\n user,\n signal: request.signal,\n });\n return Response.json(grant, {\n headers: { \"Cache-Control\": \"no-store\" },\n });\n } catch (error) {\n if (error instanceof TrajectoryConnectionError) {\n return trajectoryErrorResponse(error.code, error.message, error.status);\n }\n return trajectoryErrorResponse(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n}\n"],"mappings":";;;;;;AAQA,SAAgB,wBACd,MACA,SACA,QACU;AACV,QAAO,SAAS,KACd;EAAE;EAAM;EAAS,EACjB;EAAE;EAAQ,SAAS,EAAE,iBAAiB,YAAY;EAAE,CACrD;;AAGH,eAAsB,wBAAwB,EAC5C,SACA,SACA,gBAKoB;AACpB,KAAI,CAAC,oBAAoB,aAAa,CACpC,QAAO,wBACL,mBACA,oCACA,IACD;AAEH,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,wBACL,qBACA,uDACA,IACD;AAEH,KAAI,CAAC,QAAQ,aACX,QAAO,wBACL,qBACA,kDACA,IACD;CAEH,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,gBAAgB,SAClB,QAAO,wBACL,qBACA,kDACA,IACD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,aAAa,mBAAmB;GAC1D;GACA;GACA,QAAQ,QAAQ;GACjB,CAAC;AACF,SAAO,SAAS,KAAK,OAAO,EAC1B,SAAS,EAAE,iBAAiB,YAAY,EACzC,CAAC;UACK,OAAO;AACd,MAAI,iBAAiB,0BACnB,QAAO,wBAAwB,MAAM,MAAM,MAAM,SAAS,MAAM,OAAO;AAEzE,SAAO,wBACL,qBACA,qCACA,IACD"}
@@ -1,10 +1,10 @@
1
1
  require("reflect-metadata");
2
2
  const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_runtime$1 = require('../../core/runtime.cjs');
4
- const require_client = require('../../intelligence-platform/client.cjs');
5
4
  const require_json_response = require('../shared/json-response.cjs');
6
5
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
7
6
  const require_memory_policy = require('../shared/memory-policy.cjs');
7
+ const require_platform_error = require('../shared/platform-error.cjs');
8
8
  let _copilotkit_shared = require("@copilotkit/shared");
9
9
 
10
10
  //#region src/v2/runtime/handlers/intelligence/memories.ts
@@ -31,23 +31,11 @@ const MEMORY_SCOPES = new Set(["user", "project"]);
31
31
  /**
32
32
  * Maps a thrown error to a `Response`.
33
33
  *
34
- * For a {@link PlatformRequestError}, forward only client-actionable **4xx**
35
- * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422
36
- * unprocessable) so a `useMemories` consumer can branch on them — a flat 500
37
- * would erase that distinction. A platform **5xx** (or any non-4xx / malformed
38
- * status) means the runtime is healthy but its dependency failed, so it surfaces
39
- * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime
40
- * itself broke — and this also avoids a `new Response(..., { status })`
41
- * `RangeError` on an out-of-range status. Non-platform throws stay 500.
34
+ * The reasoning now lives with the implementation in
35
+ * `../shared/platform-error`, which the thread handlers share. This alias is
36
+ * kept so the many call sites below read the same as they always did.
42
37
  */
43
- function memoryErrorResponse(error, message) {
44
- if (error instanceof require_client.PlatformRequestError) {
45
- const { status } = error;
46
- if (Number.isInteger(status) && status >= 400 && status <= 499) return require_json_response.errorResponse(message, status);
47
- return require_json_response.errorResponse(message, 502);
48
- }
49
- return require_json_response.errorResponse(message, 500);
50
- }
38
+ const memoryErrorResponse = require_platform_error.platformErrorResponse;
51
39
  async function parseJsonBody(request) {
52
40
  try {
53
41
  return await request.json();
@@ -1 +1 @@
1
- {"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","grantAllowsMemory","errorResponse","PlatformRequestError","isIntelligenceRuntime"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const access = await resolveWebMemory(runtime, request, user, \"client\");\n if (isHandlerResponse(access)) return access;\n // Unlike an agent run — which proceeds without Memory tools when the policy\n // grants nothing — these routes exist ONLY to serve memories. A caller who\n // asked for them and may not have them gets 403; an empty list would imply\n // there are none, which is a different and false claim.\n if (runtime.memory && !grantAllowsMemory(access.grant)) {\n return errorResponse(\"Memory access denied\", 403);\n }\n return access;\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via CopilotKit Intelligence.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;CACpC,MAAM,SAAS,MAAMC,uCAAiB,SAAS,SAAS,MAAM,SAAS;AACvE,KAAID,wCAAkB,OAAO,CAAE,QAAO;AAKtC,KAAI,QAAQ,UAAU,CAACE,wCAAkB,OAAO,MAAM,CACpD,QAAOC,oCAAc,wBAAwB,IAAI;AAEnD,QAAO;;AAGT,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiBC,qCAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,OAAO,UAAU,OAAO,IAAI,UAAU,OAAO,UAAU,IACzD,QAAOD,oCAAc,SAAS,OAAO;AAEvC,SAAOA,oCAAc,SAAS,IAAI;;AAEpC,QAAOA,oCAAc,SAAS,IAAI;;AAGpC,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wCAAwC;AACrE,SAAOA,oCAAc,wBAAwB,IAAI;;;;;;;AAQrD,SAAS,gBAAgB,MAOZ;CACX,MAAM,EAAE,SAAS,MAAM,OAAO,oBAAoB;AAClD,KAAI,OAAO,YAAY,YAAY,OAAO,SAAS,SACjD,QAAOA,o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AAsB,QAAQ,CACjC,QAAOF,oCAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAIH,wCAAkB,OAAO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
1
+ {"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","grantAllowsMemory","errorResponse","platformErrorResponse","isIntelligenceRuntime"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"../shared/memory-policy\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const access = await resolveWebMemory(runtime, request, user, \"client\");\n if (isHandlerResponse(access)) return access;\n // Unlike an agent run — which proceeds without Memory tools when the policy\n // grants nothing — these routes exist ONLY to serve memories. A caller who\n // asked for them and may not have them gets 403; an empty list would imply\n // there are none, which is a different and false claim.\n if (runtime.memory && !grantAllowsMemory(access.grant)) {\n return errorResponse(\"Memory access denied\", 403);\n }\n return access;\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * The reasoning now lives with the implementation in\n * `../shared/platform-error`, which the thread handlers share. This alias is\n * kept so the many call sites below read the same as they always did.\n */\nconst memoryErrorResponse = platformErrorResponse;\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via CopilotKit Intelligence.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;CACpC,MAAM,SAAS,MAAMC,uCAAiB,SAAS,SAAS,MAAM,SAAS;AACvE,KAAID,wCAAkB,OAAO,CAAE,QAAO;AAKtC,KAAI,QAAQ,UAAU,CA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