@copilotkit/runtime 1.64.2-canary.1785346263 → 1.64.2-canary.rc-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 (39) hide show
  1. package/dist/package.cjs +1 -1
  2. package/dist/runtime/package.mjs +1 -1
  3. package/dist/v2/runtime/core/fetch-handler.cjs +12 -0
  4. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  5. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  6. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  7. package/dist/v2/runtime/core/fetch-handler.mjs +13 -1
  8. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  9. package/dist/v2/runtime/core/fetch-router.cjs +1 -0
  10. package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
  11. package/dist/v2/runtime/core/fetch-router.mjs +1 -0
  12. package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
  13. package/dist/v2/runtime/core/hooks.cjs.map +1 -1
  14. package/dist/v2/runtime/core/hooks.d.cts +2 -0
  15. package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
  16. package/dist/v2/runtime/core/hooks.d.mts +2 -0
  17. package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
  18. package/dist/v2/runtime/core/hooks.mjs.map +1 -1
  19. package/dist/v2/runtime/core/runtime.cjs +4 -0
  20. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  21. package/dist/v2/runtime/core/runtime.d.cts +24 -0
  22. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  23. package/dist/v2/runtime/core/runtime.d.mts +24 -0
  24. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  25. package/dist/v2/runtime/core/runtime.mjs +4 -0
  26. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  27. package/dist/v2/runtime/handlers/intelligence/memories.cjs +63 -1
  28. package/dist/v2/runtime/handlers/intelligence/memories.cjs.map +1 -1
  29. package/dist/v2/runtime/handlers/intelligence/memories.mjs +63 -2
  30. package/dist/v2/runtime/handlers/intelligence/memories.mjs.map +1 -1
  31. package/dist/v2/runtime/intelligence-platform/client.cjs +17 -1
  32. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  33. package/dist/v2/runtime/intelligence-platform/client.d.cts +31 -1
  34. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  35. package/dist/v2/runtime/intelligence-platform/client.d.mts +31 -1
  36. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  37. package/dist/v2/runtime/intelligence-platform/client.mjs +17 -1
  38. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  39. package/package.json +5 -5
package/dist/package.cjs CHANGED
@@ -5,7 +5,7 @@ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
5
5
  var require_package = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
6
6
  module.exports = {
7
7
  "name": "@copilotkit/runtime",
8
- "version": "1.64.2-canary.1785346263",
8
+ "version": "1.64.2-canary.rc-1",
9
9
  "private": false,
10
10
  "keywords": [
11
11
  "ai",
@@ -5,7 +5,7 @@ import { __commonJSMin } from "../_virtual/_rolldown/runtime.mjs";
5
5
  var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6
6
  module.exports = {
7
7
  "name": "@copilotkit/runtime",
8
- "version": "1.64.2-canary.1785346263",
8
+ "version": "1.64.2-canary.rc-1",
9
9
  "private": false,
10
10
  "keywords": [
11
11
  "ai",
@@ -117,6 +117,10 @@ function createCopilotRuntimeHandler(options) {
117
117
  } else {
118
118
  const matched = require_fetch_router.matchRoute(path, basePath);
119
119
  if (!matched) throw jsonResponse({ error: "Not found" }, 404);
120
+ if (matched.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) {
121
+ route = matched;
122
+ throw jsonResponse({ error: "Not found" }, 404);
123
+ }
120
124
  const methodError = validateHttpMethod(request.method, matched);
121
125
  if (methodError) {
122
126
  route = matched;
@@ -188,6 +192,7 @@ function createCopilotRuntimeHandler(options) {
188
192
  return handler;
189
193
  }
190
194
  function dispatchRoute(runtime, request, route, options) {
195
+ if (route.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) throw jsonResponse({ error: "Not found" }, 404);
191
196
  switch (route.method) {
192
197
  case "agent/run": return require_handle_run.handleRunAgent({
193
198
  runtime,
@@ -234,6 +239,10 @@ function dispatchRoute(runtime, request, route, options) {
234
239
  runtime,
235
240
  request
236
241
  });
242
+ case "memories/recall": return require_memories.handleRecallMemories({
243
+ runtime,
244
+ request
245
+ });
237
246
  case "memories/subscribe": return require_memories.handleSubscribeToMemories({
238
247
  runtime,
239
248
  request
@@ -366,6 +375,9 @@ function validateHttpMethod(httpMethod, route) {
366
375
  case "memories/mutate":
367
376
  if (method === "PATCH" || method === "DELETE") return null;
368
377
  return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
378
+ case "memories/recall":
379
+ if (method === "POST") return null;
380
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "POST" });
369
381
  case "threads/update":
370
382
  if (method === "PATCH" || method === "DELETE") return null;
371
383
  return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.cjs","names":["ChannelManager","logger","handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","runOnResponse","runOnError","isIntelligenceRuntime","handleRunAgent","handleSuggestAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","handleClearThreads","handleListThreads","handleCreateMemory","handleListMemories","handleSubscribeToMemories","handleRemoveMemory","handleUpdateMemory","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","handleGetThreadEvents","handleGetThreadState","handleAnnotate","handleDebugEvents","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAIA,uCAAe;EACjC,cAAc,QAAQ;EACtB,UAAU,QAAQ;EAYlB,MAAM,KAAK,SAC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CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAOC,kCAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
1
+ {"version":3,"file":"fetch-handler.cjs","names":["ChannelManager","logger","handleCors","runOnRequest","callBeforeRequestMiddleware","runOnBeforeHandler","createJsonRequest","matchRoute","runOnResponse","runOnError","isIntelligenceRuntime","handleRunAgent","handleSuggestAgent","handleConnectAgent","handleStopAgent","handleGetRuntimeInfo","handleTranscribe","handleClearThreads","handleListThreads","handleCreateMemory","handleListMemories","handleRecallMemories","handleSubscribeToMemories","handleRemoveMemory","handleUpdateMemory","handleSubscribeToThreads","handleDeleteThread","handleUpdateThread","handleArchiveThread","handleGetThreadMessages","handleGetThreadEvents","handleGetThreadState","handleAnnotate","handleDebugEvents","parseMethodCall","expectString","addCorsHeaders"],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\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,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UAiHiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EA4EE;;;;;AA+Eb;;;;EAhJE,QAAA;EAqJC;;;;;EA9ID,IAAA;EA4IE;;;;;EArIF,IAAA,aAAiB,iBAAA;EA4IwB;;;EAvIzC,KAAA,GAAQ,mBAAA;EAwIR;;;;;;;;;EA7HA,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBA6EI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
1
+ {"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UAkHiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EA4EE;;;;;AA+Eb;;;;EAhJE,QAAA;EAqJC;;;;;EA9ID,IAAA;EA4IE;;;;;EArIF,IAAA,aAAiB,iBAAA;EA4IwB;;;EAvIzC,KAAA,GAAQ,mBAAA;EAwIR;;;;;;;;;EA7HA,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBA6EI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
@@ -13,7 +13,7 @@ import { handleGetRuntimeInfo } from "../handlers/get-runtime-info.mjs";
13
13
  import { handleTranscribe } from "../handlers/handle-transcribe.mjs";
14
14
  import { handleDebugEvents } from "../handlers/handle-debug-events.mjs";
15
15
  import { handleArchiveThread, handleClearThreads, handleDeleteThread, handleGetThreadEvents, handleGetThreadMessages, handleGetThreadState, handleListThreads, handleSubscribeToThreads, handleUpdateThread } from "../handlers/intelligence/threads.mjs";
16
- import { handleCreateMemory, handleListMemories, handleRemoveMemory, handleSubscribeToMemories, handleUpdateMemory } from "../handlers/intelligence/memories.mjs";
16
+ import { handleCreateMemory, handleListMemories, handleRecallMemories, handleRemoveMemory, handleSubscribeToMemories, handleUpdateMemory } from "../handlers/intelligence/memories.mjs";
17
17
  import { handleAnnotate } from "../handlers/intelligence/annotate.mjs";
18
18
  import { createJsonRequest, expectString, parseMethodCall } from "../endpoints/single-route-helpers.mjs";
19
19
  import { fireInstanceCreatedTelemetry } from "../telemetry/instance-created.mjs";
@@ -116,6 +116,10 @@ function createCopilotRuntimeHandler(options) {
116
116
  } else {
117
117
  const matched = matchRoute(path, basePath);
118
118
  if (!matched) throw jsonResponse({ error: "Not found" }, 404);
119
+ if (matched.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) {
120
+ route = matched;
121
+ throw jsonResponse({ error: "Not found" }, 404);
122
+ }
119
123
  const methodError = validateHttpMethod(request.method, matched);
120
124
  if (methodError) {
121
125
  route = matched;
@@ -187,6 +191,7 @@ function createCopilotRuntimeHandler(options) {
187
191
  return handler;
188
192
  }
189
193
  function dispatchRoute(runtime, request, route, options) {
194
+ if (route.method.startsWith("memories/") && runtime.exposeMemoryRoutes !== true) throw jsonResponse({ error: "Not found" }, 404);
190
195
  switch (route.method) {
191
196
  case "agent/run": return handleRunAgent({
192
197
  runtime,
@@ -233,6 +238,10 @@ function dispatchRoute(runtime, request, route, options) {
233
238
  runtime,
234
239
  request
235
240
  });
241
+ case "memories/recall": return handleRecallMemories({
242
+ runtime,
243
+ request
244
+ });
236
245
  case "memories/subscribe": return handleSubscribeToMemories({
237
246
  runtime,
238
247
  request
@@ -365,6 +374,9 @@ function validateHttpMethod(httpMethod, route) {
365
374
  case "memories/mutate":
366
375
  if (method === "PATCH" || method === "DELETE") return null;
367
376
  return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
377
+ case "memories/recall":
378
+ if (method === "POST") return null;
379
+ return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "POST" });
368
380
  case "threads/update":
369
381
  if (method === "PATCH" || method === "DELETE") return null;
370
382
  return jsonResponse({ error: "Method not allowed" }, 405, { Allow: "PATCH, DELETE" });
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAI,eAAe;EACjC,cAAc,QAAQ;EACtB,UAAU,QAAQ;EAYlB,MAAM,KAAK,SACT,OAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;AAEjE,8BAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,kBAAkB,KAAK;CAE1C,MAAM,UAAsC,OAC1C,YACsB;EAEtB,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,SAAS;EAGnD,MAAM,UAAuB;GAAE;GAAS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E,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;AACH,OAAI,WAAW,MAAO,QAAO;AAC7B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,OACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,SAAS,WAAW,OAAQ,QAAO;AAClD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,aACR,CAAC;EAEJ,KAAK;AAEH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ,KAAK;AACH,OAAI,WAAW,WAAW,WAAW,SAAU,QAAO;AACtD,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,iBACR,CAAC;EAEJ;AACE,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,CAAC;;;AAQR,SAAS,kBACP,MAC0B;AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAO,eAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
1
+ {"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / the node/express/hono\n * endpoint wrappers), call `await handler.channels.ready()` ONCE at startup to\n * open the listener; the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n channels: runtime.channels,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAI,eAAe;EACjC,cAAc,QAAQ;EACtB,UAAU,QAAQ;EAYlB,MAAM,KAAK,SACT,OAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;AAEjE,8BAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,kBAAkB,KAAK;CAE1C,MAAM,UAAsC,OAC1C,YACsB;EAEtB,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,SAAS;EAGnD,MAAM,UAAuB;GAAE;GAAS;GAAM;GAAS;EAEvD,IAAI;AAEJ,MAAI;AAEF,OAAI,YAAY;IACd,MAAM,YAAY,WAAW,SAAS,WAAW;AACjD,QAAI,UAAW,QAAO;;AAIxB,aAAU,MAAM,aAA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ACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
@@ -112,6 +112,7 @@ function matchSegments(path) {
112
112
  };
113
113
  }
114
114
  if (len >= 1 && segments[len - 1] === "threads") return { method: "threads/list" };
115
+ if (len >= 2 && segments[len - 2] === "memories" && segments[len - 1] === "recall") return { method: "memories/recall" };
115
116
  if (len >= 2 && segments[len - 2] === "memories" && segments[len - 1] === "subscribe") return { method: "memories/subscribe" };
116
117
  if (len >= 2 && segments[len - 2] === "memories" && segments[len - 1] !== "subscribe") {
117
118
  const memoryId = safeDecodeURIComponent(segments[len - 1]);
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-router.cjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/suggest (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"suggest\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/suggest\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n // /memories/subscribe (2 segments) — mint memory-realtime join credentials.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"memories/subscribe\" };\n }\n\n // /memories/:id (2 segments) — supersede (PATCH) or retire (DELETE).\n // Disambiguated by HTTP method in the handler.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] !== \"subscribe\"\n ) {\n const memoryId = safeDecodeURIComponent(segments[len - 1]!);\n if (!memoryId) return null;\n return { method: \"memories/mutate\", memoryId };\n }\n\n // /memories (1 segment) — GET lists; POST creates.\n if (len >= 1 && segments[len - 1] === \"memories\") {\n return { method: \"memories/list\" };\n }\n\n // /annotate (1 segment) — annotate a thread event\n if (len >= 1 && segments[len - 1] === \"annotate\") {\n return { method: \"annotate\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO;;;AAIX,SAAS,cAAc,MAAgC;CACrD,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;CAChD,MAAM,MAAM,SAAS;AAKrB,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,OACpC,QAAO,EA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QAAQ;GAAmB;GAAU;;AAIhD,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,YAAY;AAG/B,QAAO"}
1
+ {"version":3,"file":"fetch-router.cjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/suggest (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"suggest\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/suggest\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n // /memories/recall (2 segments) — semantic recall (POST). Must precede the\n // /memories/:id mutate rule below, which would otherwise capture \"recall\".\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"recall\"\n ) {\n return { method: \"memories/recall\" };\n }\n\n // /memories/subscribe (2 segments) — mint memory-realtime join credentials.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"memories/subscribe\" };\n }\n\n // /memories/:id (2 segments) — supersede (PATCH) or retire (DELETE).\n // Disambiguated by HTTP method in the handler.\n if (\n len >= 2 &&\n segments[len - 2] === \"memories\" &&\n segments[len - 1] !== \"subscribe\"\n ) {\n const memoryId = safeDecodeURIComponent(segments[len - 1]!);\n if (!memoryId) return null;\n return { method: \"memories/mutate\", memoryId };\n }\n\n // /memories (1 segment) — GET lists; POST creates.\n if (len >= 1 && segments[len - 1] === \"memories\") {\n return { method: \"memories/list\" };\n }\n\n // /annotate (1 segment) — annotate a thread event\n if (len >= 1 && segments[len - 1] === \"annotate\") {\n return { method: \"annotate\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO;;;AAIX,SAAS,cAAc,MAAgC;CACrD,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;CAChD,MAAM,MAAM,SAAS;AAKrB,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,OACpC,QAAO,EAAE,QAAQ,QAAQ;AAI3B,KAAI,OAAO,KAAK,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,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAmB;GAAU;;AAIhD,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,YAAY;AAG/B,QAAO"}
@@ -111,6 +111,7 @@ function matchSegments(path) {
111
111
  };
112
112
  }
113
113
  if (len >= 1 && segments[len - 1] === "threads") return { method: "threads/list" };
114
+ if (len >= 2 && segments[len - 2] === "memories" && segments[len - 1] === "recall") return { method: "memories/recall" };
114
115
  if (len >= 2 && segments[len - 2] === "memories" && segments[len - 1] === "subscribe") return { method: "memories/subscribe" };
115
116
  if (len >= 2 && segments[len - 2] === "memories" && segments[len - 1] !== "subscribe") {
116
117
  const memoryId = safeDecodeURIComponent(segments[len - 1]);