@copilotkit/runtime 1.64.2-canary.1785441273 → 1.64.2-canary.1785477663

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 (65) hide show
  1. package/dist/package.cjs +1 -1
  2. package/dist/runtime/package.mjs +1 -1
  3. package/dist/v2/runtime/core/channel-manager.cjs +17 -3
  4. package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
  5. package/dist/v2/runtime/core/channel-manager.mjs +17 -3
  6. package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
  7. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  8. package/dist/v2/runtime/core/fetch-handler.d.cts +5 -0
  9. package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
  10. package/dist/v2/runtime/core/fetch-handler.d.mts +5 -0
  11. package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
  12. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  13. package/dist/v2/runtime/endpoints/auto-start-channels.cjs +47 -0
  14. package/dist/v2/runtime/endpoints/auto-start-channels.cjs.map +1 -0
  15. package/dist/v2/runtime/endpoints/auto-start-channels.mjs +46 -0
  16. package/dist/v2/runtime/endpoints/auto-start-channels.mjs.map +1 -0
  17. package/dist/v2/runtime/endpoints/express.cjs +2 -0
  18. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  19. package/dist/v2/runtime/endpoints/express.d.cts +9 -8
  20. package/dist/v2/runtime/endpoints/express.d.cts.map +1 -1
  21. package/dist/v2/runtime/endpoints/express.d.mts +9 -8
  22. package/dist/v2/runtime/endpoints/express.d.mts.map +1 -1
  23. package/dist/v2/runtime/endpoints/express.mjs +2 -0
  24. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  25. package/dist/v2/runtime/endpoints/hono.cjs.map +1 -1
  26. package/dist/v2/runtime/endpoints/hono.d.cts +14 -5
  27. package/dist/v2/runtime/endpoints/hono.d.cts.map +1 -1
  28. package/dist/v2/runtime/endpoints/hono.d.mts +14 -5
  29. package/dist/v2/runtime/endpoints/hono.d.mts.map +1 -1
  30. package/dist/v2/runtime/endpoints/hono.mjs.map +1 -1
  31. package/dist/v2/runtime/endpoints/node.cjs +2 -0
  32. package/dist/v2/runtime/endpoints/node.cjs.map +1 -1
  33. package/dist/v2/runtime/endpoints/node.d.cts +23 -13
  34. package/dist/v2/runtime/endpoints/node.d.cts.map +1 -1
  35. package/dist/v2/runtime/endpoints/node.d.mts +23 -13
  36. package/dist/v2/runtime/endpoints/node.d.mts.map +1 -1
  37. package/dist/v2/runtime/endpoints/node.mjs +2 -0
  38. package/dist/v2/runtime/endpoints/node.mjs.map +1 -1
  39. package/dist/v2/runtime/intelligence-platform/client.cjs +2 -2
  40. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  41. package/dist/v2/runtime/intelligence-platform/client.d.cts +4 -1
  42. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
  43. package/dist/v2/runtime/intelligence-platform/client.d.mts +4 -1
  44. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
  45. package/dist/v2/runtime/intelligence-platform/client.mjs +2 -2
  46. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  47. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
  48. package/dist/v2/runtime/runner/agent-runner.d.cts +2 -0
  49. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
  50. package/dist/v2/runtime/runner/agent-runner.d.mts +2 -0
  51. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
  52. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
  53. package/dist/v2/runtime/runner/in-memory.cjs +1 -0
  54. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  55. package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
  56. package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
  57. package/dist/v2/runtime/runner/in-memory.mjs +1 -0
  58. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  59. package/dist/v2/runtime/runner/intelligence.cjs +2 -0
  60. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
  61. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
  62. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
  63. package/dist/v2/runtime/runner/intelligence.mjs +2 -0
  64. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
  65. package/package.json +5 -5
@@ -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 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 runner: runtime.runner,\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\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,Q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AE,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;AAEH,OAAI,WAAW,OAAQ,QAAO;AAC9B,UAAO,aAAa,EAAE,OAAO,sBAAsB,EAAE,KAAK,EACxD,OAAO,QACR,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 / a Bun or Deno server),\n * call `await handler.channels.ready()` ONCE at startup to open the listener;\n * 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 * This laziness is a property of THIS handler, because it is the one entry point\n * that must stay serverless-safe. The process-owning wrappers do not inherit it:\n * `createCopilotNodeListener` and `createCopilotExpressHandler` START activation\n * at creation (OSS-641), so `ready()` there is optional and await-and-observe.\n * `createCopilotHonoHandler` keeps this handler's lazy behavior — a Hono app is\n * multi-runtime and is our Next.js/edge surface in practice.\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 * The process-owning wrappers (`createCopilotNodeListener`,\n * `createCopilotExpressHandler`) also START activation when this is left on,\n * so `false` is the opt-out that keeps a mounted listener socket-free in a test\n * or a short-lived script.\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 runner: runtime.runner,\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsNA,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,QAAQ,QAAQ;EAChB,gBAAgB,QAAQ;EACxB,8BAA8B,QAAQ;EACtC,GAAI,QAAQ,kBAAkB,SAC1B,EAAE,eAAe,QAAQ,eAAe,GACxC,EAAE;EACN,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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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"}
@@ -0,0 +1,47 @@
1
+ require("reflect-metadata");
2
+ const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
+ let _copilotkit_shared = require("@copilotkit/shared");
4
+
5
+ //#region src/v2/runtime/endpoints/auto-start-channels.ts
6
+ /**
7
+ * Begin activation of a runtime's declared managed Channels on behalf of a
8
+ * LONG-RUNNING host (OSS-641).
9
+ *
10
+ * The generic Fetch handler deliberately defers activation to the first
11
+ * `channels.ready()`: it is the serverless/edge entry point, where an isolate
12
+ * freezes and recycles per request and separate cold starts would mint
13
+ * competing listeners for the same Channel. That constraint does not apply to a
14
+ * host that owns its own lifetime — a Node server or an Express app — so those
15
+ * wrappers start activation as soon as they are created and leave `ready()` as
16
+ * a pure await-and-observe call.
17
+ *
18
+ * Fire-and-forget by necessity: a factory is synchronous, so the activation
19
+ * outcome cannot be returned. That is a deliberate trade against the failure
20
+ * mode it replaces — a process that serves HTTP, looks healthy, and is silently
21
+ * disconnected because nothing ever called `ready()`. Here the worst case is an
22
+ * activation error in the logs. `ready()` is idempotent and one-shot, so a host
23
+ * that DOES await it afterwards observes THIS activation's outcome (including
24
+ * its rejection reason) rather than triggering a second one.
25
+ *
26
+ * The rejection is logged at `error`, not swallowed: an up-front
27
+ * misconfiguration (duplicate or missing Channel names) rejects `ready()`
28
+ * synchronously-ish from `activate()` and would otherwise be invisible to a
29
+ * host that never awaits `ready()` — the exact silence this change exists to
30
+ * remove. Per-Channel activation failures ALSO emit their own `warn`
31
+ * breadcrumbs through the manager's log bridge (see `fetch-handler.ts`), so the
32
+ * `error` here is the set-level summary, not the only signal.
33
+ *
34
+ * @param channels - The handler's control surface, or `undefined` when the
35
+ * runtime declares no Channels or opted out via `activateChannels: false`
36
+ * (both no-op, so the opt-out stays a genuine "open no socket").
37
+ */
38
+ function autoStartChannels(channels) {
39
+ if (!channels) return;
40
+ channels.ready().catch((err) => {
41
+ _copilotkit_shared.logger.error({ err }, "CopilotKit managed Channels failed to activate. The runtime is serving requests but one or more declared Channels are not connected.");
42
+ });
43
+ }
44
+
45
+ //#endregion
46
+ exports.autoStartChannels = autoStartChannels;
47
+ //# sourceMappingURL=auto-start-channels.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-start-channels.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/auto-start-channels.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type { ChannelsControl } from \"../core/channel-manager\";\n\n/**\n * Begin activation of a runtime's declared managed Channels on behalf of a\n * LONG-RUNNING host (OSS-641).\n *\n * The generic Fetch handler deliberately defers activation to the first\n * `channels.ready()`: it is the serverless/edge entry point, where an isolate\n * freezes and recycles per request and separate cold starts would mint\n * competing listeners for the same Channel. That constraint does not apply to a\n * host that owns its own lifetime — a Node server or an Express app — so those\n * wrappers start activation as soon as they are created and leave `ready()` as\n * a pure await-and-observe call.\n *\n * Fire-and-forget by necessity: a factory is synchronous, so the activation\n * outcome cannot be returned. That is a deliberate trade against the failure\n * mode it replaces — a process that serves HTTP, looks healthy, and is silently\n * disconnected because nothing ever called `ready()`. Here the worst case is an\n * activation error in the logs. `ready()` is idempotent and one-shot, so a host\n * that DOES await it afterwards observes THIS activation's outcome (including\n * its rejection reason) rather than triggering a second one.\n *\n * The rejection is logged at `error`, not swallowed: an up-front\n * misconfiguration (duplicate or missing Channel names) rejects `ready()`\n * synchronously-ish from `activate()` and would otherwise be invisible to a\n * host that never awaits `ready()` — the exact silence this change exists to\n * remove. Per-Channel activation failures ALSO emit their own `warn`\n * breadcrumbs through the manager's log bridge (see `fetch-handler.ts`), so the\n * `error` here is the set-level summary, not the only signal.\n *\n * @param channels - The handler's control surface, or `undefined` when the\n * runtime declares no Channels or opted out via `activateChannels: false`\n * (both no-op, so the opt-out stays a genuine \"open no socket\").\n */\nexport function autoStartChannels(channels: ChannelsControl | undefined): void {\n if (!channels) {\n return;\n }\n channels.ready().catch((err) => {\n logger.error(\n { err },\n \"CopilotKit managed Channels failed to activate. The runtime is serving \" +\n \"requests but one or more declared Channels are not connected.\",\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,kBAAkB,UAA6C;AAC7E,KAAI,CAAC,SACH;AAEF,UAAS,OAAO,CAAC,OAAO,QAAQ;AAC9B,4BAAO,MACL,EAAE,KAAK,EACP,uIAED;GACD"}
@@ -0,0 +1,46 @@
1
+ import "reflect-metadata";
2
+ import { logger } from "@copilotkit/shared";
3
+
4
+ //#region src/v2/runtime/endpoints/auto-start-channels.ts
5
+ /**
6
+ * Begin activation of a runtime's declared managed Channels on behalf of a
7
+ * LONG-RUNNING host (OSS-641).
8
+ *
9
+ * The generic Fetch handler deliberately defers activation to the first
10
+ * `channels.ready()`: it is the serverless/edge entry point, where an isolate
11
+ * freezes and recycles per request and separate cold starts would mint
12
+ * competing listeners for the same Channel. That constraint does not apply to a
13
+ * host that owns its own lifetime — a Node server or an Express app — so those
14
+ * wrappers start activation as soon as they are created and leave `ready()` as
15
+ * a pure await-and-observe call.
16
+ *
17
+ * Fire-and-forget by necessity: a factory is synchronous, so the activation
18
+ * outcome cannot be returned. That is a deliberate trade against the failure
19
+ * mode it replaces — a process that serves HTTP, looks healthy, and is silently
20
+ * disconnected because nothing ever called `ready()`. Here the worst case is an
21
+ * activation error in the logs. `ready()` is idempotent and one-shot, so a host
22
+ * that DOES await it afterwards observes THIS activation's outcome (including
23
+ * its rejection reason) rather than triggering a second one.
24
+ *
25
+ * The rejection is logged at `error`, not swallowed: an up-front
26
+ * misconfiguration (duplicate or missing Channel names) rejects `ready()`
27
+ * synchronously-ish from `activate()` and would otherwise be invisible to a
28
+ * host that never awaits `ready()` — the exact silence this change exists to
29
+ * remove. Per-Channel activation failures ALSO emit their own `warn`
30
+ * breadcrumbs through the manager's log bridge (see `fetch-handler.ts`), so the
31
+ * `error` here is the set-level summary, not the only signal.
32
+ *
33
+ * @param channels - The handler's control surface, or `undefined` when the
34
+ * runtime declares no Channels or opted out via `activateChannels: false`
35
+ * (both no-op, so the opt-out stays a genuine "open no socket").
36
+ */
37
+ function autoStartChannels(channels) {
38
+ if (!channels) return;
39
+ channels.ready().catch((err) => {
40
+ logger.error({ err }, "CopilotKit managed Channels failed to activate. The runtime is serving requests but one or more declared Channels are not connected.");
41
+ });
42
+ }
43
+
44
+ //#endregion
45
+ export { autoStartChannels };
46
+ //# sourceMappingURL=auto-start-channels.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auto-start-channels.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/auto-start-channels.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type { ChannelsControl } from \"../core/channel-manager\";\n\n/**\n * Begin activation of a runtime's declared managed Channels on behalf of a\n * LONG-RUNNING host (OSS-641).\n *\n * The generic Fetch handler deliberately defers activation to the first\n * `channels.ready()`: it is the serverless/edge entry point, where an isolate\n * freezes and recycles per request and separate cold starts would mint\n * competing listeners for the same Channel. That constraint does not apply to a\n * host that owns its own lifetime — a Node server or an Express app — so those\n * wrappers start activation as soon as they are created and leave `ready()` as\n * a pure await-and-observe call.\n *\n * Fire-and-forget by necessity: a factory is synchronous, so the activation\n * outcome cannot be returned. That is a deliberate trade against the failure\n * mode it replaces — a process that serves HTTP, looks healthy, and is silently\n * disconnected because nothing ever called `ready()`. Here the worst case is an\n * activation error in the logs. `ready()` is idempotent and one-shot, so a host\n * that DOES await it afterwards observes THIS activation's outcome (including\n * its rejection reason) rather than triggering a second one.\n *\n * The rejection is logged at `error`, not swallowed: an up-front\n * misconfiguration (duplicate or missing Channel names) rejects `ready()`\n * synchronously-ish from `activate()` and would otherwise be invisible to a\n * host that never awaits `ready()` — the exact silence this change exists to\n * remove. Per-Channel activation failures ALSO emit their own `warn`\n * breadcrumbs through the manager's log bridge (see `fetch-handler.ts`), so the\n * `error` here is the set-level summary, not the only signal.\n *\n * @param channels - The handler's control surface, or `undefined` when the\n * runtime declares no Channels or opted out via `activateChannels: false`\n * (both no-op, so the opt-out stays a genuine \"open no socket\").\n */\nexport function autoStartChannels(channels: ChannelsControl | undefined): void {\n if (!channels) {\n return;\n }\n channels.ready().catch((err) => {\n logger.error(\n { err },\n \"CopilotKit managed Channels failed to activate. The runtime is serving \" +\n \"requests but one or more declared Channels are not connected.\",\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,kBAAkB,UAA6C;AAC7E,KAAI,CAAC,SACH;AAEF,UAAS,OAAO,CAAC,OAAO,QAAQ;AAC9B,SAAO,MACL,EAAE,KAAK,EACP,uIAED;GACD"}
@@ -2,6 +2,7 @@ require("reflect-metadata");
2
2
  const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_fetch_handler = require('../core/fetch-handler.cjs');
4
4
  const require_express_fetch_bridge = require('./express-fetch-bridge.cjs');
5
+ const require_auto_start_channels = require('./auto-start-channels.cjs');
5
6
  let express = require("express");
6
7
  express = require_runtime.__toESM(express);
7
8
  let cors = require("cors");
@@ -51,6 +52,7 @@ function createCopilotExpressHandler({ runtime, basePath, mode = "multi-route",
51
52
  else router.all(new RegExp(`^${escapeRegExp(normalizedBase)}(\\/.*)?$`), expressHandler);
52
53
  const exposedRouter = router;
53
54
  exposedRouter.channels = handler.channels;
55
+ require_auto_start_channels.autoStartChannels(exposedRouter.channels);
54
56
  return exposedRouter;
55
57
  }
56
58
  function escapeRegExp(s) {
@@ -1 +1 @@
1
- {"version":3,"file":"express.cjs","names":["createCopilotRuntimeHandler","createExpressNodeHandler"],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\nimport type { CorsOptions } from \"cors\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { createCopilotRuntimeHandler } from \"../core/fetch-handler\";\nimport type {\n ActivateChannelEngine,\n ChannelsControl,\n} from \"../core/channel-manager\";\nimport { createExpressNodeHandler } from \"./express-fetch-bridge\";\nimport type { CopilotRuntimeHooks } from \"../core/hooks\";\n\n/**\n * An Express {@link Router} that may also carry an optional\n * {@link ChannelsControl} surface. Express's Router is a request-scoped\n * middleware object, not a long-running process owner — Node\n * (`createCopilotNodeListener`) is the lifecycle-owning surface for\n * `.channels`. It is attached here too, best-effort, for callers that mount\n * the router directly and want to start (`ready()`), observe, or stop managed\n * Channel activation without also standing up a Node listener.\n */\nexport type CopilotExpressRouter = Router & { channels?: ChannelsControl };\n\nexport interface CopilotExpressEndpointParams {\n runtime: CopilotRuntimeLike;\n basePath: string;\n\n /**\n * Endpoint mode.\n * - `\"multi-route\"` (default): separate routes for each operation\n * - `\"single-route\"`: single POST endpoint with JSON envelope dispatch\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * CORS configuration for the Express router.\n * - `true` (default): permissive CORS (`origin: \"*\"`, all methods, all headers).\n * - `false`: no CORS middleware is applied — handle it yourself.\n * - object: passed directly to the Express `cors()` middleware.\n */\n cors?: boolean | CorsOptions;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the underlying handler builds the control surface for the runtime's\n * declared managed Channels. Defaults to `true`. Building it opens no\n * connection activation is deferred to the first `channels.ready()`. See\n * `CopilotRuntimeHandlerOptions.activateChannels`.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine. Forwarded\n * to `createCopilotRuntimeHandler`. Not part of the public API.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * Creates an Express router that serves the CopilotKit runtime.\n *\n * In **multi-route** mode (default) the router exposes:\n * - `GET {basePath}/info` — runtime info\n * - `POST {basePath}/agent/:agentId/run` — start an agent run\n * - `POST {basePath}/agent/:agentId/connect` — connect to an agent run\n * - `POST {basePath}/agent/:agentId/stop/:threadId` — stop an agent run\n * - `POST {basePath}/transcribe` — transcribe audio\n *\n * In **single-route** mode a single `POST {basePath}` endpoint accepts a JSON\n * envelope `{ method, params, body }` and dispatches to the appropriate handler.\n *\n * @example\n * ```typescript\n * import express from \"express\";\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n * import { createCopilotExpressHandler } from \"@copilotkit/runtime/v2/express\";\n *\n * const runtime = new CopilotRuntime({\n * agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o-mini\" }) },\n * });\n *\n * const app = express();\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * }));\n * app.listen(4000);\n * ```\n *\n * @example Single-route mode with lifecycle hooks\n * ```typescript\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * mode: \"single-route\",\n * hooks: {\n * onRequest: ({ request }) => {\n * if (!request.headers.get(\"authorization\")) {\n * throw new Response(\"Unauthorized\", { status: 401 });\n * }\n * },\n * },\n * }));\n * ```\n */\n/** @deprecated Use `createCopilotExpressHandler` instead. */\nexport { createCopilotExpressHandler as createCopilotEndpointExpress };\n\nexport function createCopilotExpressHandler({\n runtime,\n basePath,\n mode = \"multi-route\",\n cors: corsOption = true,\n hooks,\n activateChannels,\n __channelEngine,\n}: CopilotExpressEndpointParams): CopilotExpressRouter {\n const normalizedBase = normalizeBasePath(basePath);\n\n const handler = createCopilotRuntimeHandler({\n runtime,\n basePath: normalizedBase,\n mode,\n cors: false, // CORS is handled at the Express middleware layer\n hooks,\n activateChannels,\n __channelEngine,\n });\n\n const nodeHandler = createExpressNodeHandler(handler);\n\n const expressHandler = async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n try {\n await nodeHandler(req, res);\n } catch (err) {\n next(err);\n }\n };\n\n const router = express.Router();\n\n // CORS middleware\n if (corsOption) {\n const corsConfig: CorsOptions =\n corsOption === true\n ? {\n origin: \"*\",\n methods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowedHeaders: [\"*\"],\n }\n : corsOption;\n router.use(cors(corsConfig));\n }\n\n // Route mounting\n if (mode === \"single-route\") {\n router.post(normalizedBase, expressHandler);\n router.options(normalizedBase, expressHandler);\n } else if (normalizedBase === \"/\") {\n router.all(/.*/, expressHandler);\n } else {\n router.all(\n new RegExp(`^${escapeRegExp(normalizedBase)}(\\\\/.*)?$`),\n expressHandler,\n );\n }\n\n const exposedRouter: CopilotExpressRouter = router;\n exposedRouter.channels = handler.channels;\n return exposedRouter;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction normalizeBasePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for Express endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;AAuHA,SAAgB,4BAA4B,EAC1C,SACA,UACA,OAAO,eACP,MAAM,aAAa,MACnB,OACA,kBACA,mBACqD;CACrD,MAAM,iBAAiB,kBAAkB,SAAS;CAElD,MAAM,UAAUA,kDAA4B;EAC1C;EACA,UAAU;EACV;EACA,MAAM;EACN;EACA;EACA;EACD,CAAC;CAEF,MAAM,cAAcC,sDAAyB,QAAQ;CAErD,MAAM,iBAAiB,OACrB,KACA,KACA,SACG;AACH,MAAI;AACF,SAAM,YAAY,KAAK,IAAI;WACpB,KAAK;AACZ,QAAK,IAAI;;;CAIb,MAAM,SAAS,gBAAQ,QAAQ;AAG/B,KAAI,YAAY;EACd,MAAM,aACJ,eAAe,OACX;GACE,QAAQ;GACR,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACD;GACD,gBAAgB,CAAC,IAAI;GACtB,GACD;AACN,SAAO,sBAAS,WAAW,CAAC;;AAI9B,KAAI,SAAS,gBAAgB;AAC3B,SAAO,KAAK,gBAAgB,eAAe;AAC3C,SAAO,QAAQ,gBAAgB,eAAe;YACrC,mBAAmB,IAC5B,QAAO,IAAI,MAAM,eAAe;KAEhC,QAAO,IACL,IAAI,OAAO,IAAI,aAAa,eAAe,CAAC,WAAW,EACvD,eACD;CAGH,MAAM,gBAAsC;AAC5C,eAAc,WAAW,QAAQ;AACjC,QAAO;;AAGT,SAAS,aAAa,GAAmB;AACvC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AAGjD,SAAS,kBAAkB,MAAsB;AAC/C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
1
+ {"version":3,"file":"express.cjs","names":["createCopilotRuntimeHandler","createExpressNodeHandler"],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\nimport type { CorsOptions } from \"cors\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { createCopilotRuntimeHandler } from \"../core/fetch-handler\";\nimport type {\n ActivateChannelEngine,\n ChannelsControl,\n} from \"../core/channel-manager\";\nimport { createExpressNodeHandler } from \"./express-fetch-bridge\";\nimport { autoStartChannels } from \"./auto-start-channels\";\nimport type { CopilotRuntimeHooks } from \"../core/hooks\";\n\n/**\n * An Express {@link Router} that may also carry an optional\n * {@link ChannelsControl} surface. The Router object itself is request-scoped\n * middleware, but an Express app can only run inside a long-running\n * `http.Server` — so this wrapper is a lifecycle-owning host like\n * `createCopilotNodeListener`: it STARTS activation of the runtime's declared\n * managed Channels at creation, and `.channels` is here to observe (`ready()`)\n * or tear down (`stop()`) that activation.\n */\nexport type CopilotExpressRouter = Router & { channels?: ChannelsControl };\n\nexport interface CopilotExpressEndpointParams {\n runtime: CopilotRuntimeLike;\n basePath: string;\n\n /**\n * Endpoint mode.\n * - `\"multi-route\"` (default): separate routes for each operation\n * - `\"single-route\"`: single POST endpoint with JSON envelope dispatch\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * CORS configuration for the Express router.\n * - `true` (default): permissive CORS (`origin: \"*\"`, all methods, all headers).\n * - `false`: no CORS middleware is applied — handle it yourself.\n * - object: passed directly to the Express `cors()` middleware.\n */\n cors?: boolean | CorsOptions;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the underlying handler builds the control surface for the runtime's\n * declared managed Channels — and, because Express is a long-running host,\n * starts their activation at creation. Defaults to `true`. Set `false` to\n * build no surface and open no socket (tests, short-lived scripts). See\n * `CopilotRuntimeHandlerOptions.activateChannels`.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine. Forwarded\n * to `createCopilotRuntimeHandler`. Not part of the public API.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * Creates an Express router that serves the CopilotKit runtime.\n *\n * In **multi-route** mode (default) the router exposes:\n * - `GET {basePath}/info` — runtime info\n * - `POST {basePath}/agent/:agentId/run` — start an agent run\n * - `POST {basePath}/agent/:agentId/connect` — connect to an agent run\n * - `POST {basePath}/agent/:agentId/stop/:threadId` — stop an agent run\n * - `POST {basePath}/transcribe` — transcribe audio\n *\n * In **single-route** mode a single `POST {basePath}` endpoint accepts a JSON\n * envelope `{ method, params, body }` and dispatches to the appropriate handler.\n *\n * @example\n * ```typescript\n * import express from \"express\";\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n * import { createCopilotExpressHandler } from \"@copilotkit/runtime/v2/express\";\n *\n * const runtime = new CopilotRuntime({\n * agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o-mini\" }) },\n * });\n *\n * const app = express();\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * }));\n * app.listen(4000);\n * ```\n *\n * @example Single-route mode with lifecycle hooks\n * ```typescript\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * mode: \"single-route\",\n * hooks: {\n * onRequest: ({ request }) => {\n * if (!request.headers.get(\"authorization\")) {\n * throw new Response(\"Unauthorized\", { status: 401 });\n * }\n * },\n * },\n * }));\n * ```\n */\n/** @deprecated Use `createCopilotExpressHandler` instead. */\nexport { createCopilotExpressHandler as createCopilotEndpointExpress };\n\nexport function createCopilotExpressHandler({\n runtime,\n basePath,\n mode = \"multi-route\",\n cors: corsOption = true,\n hooks,\n activateChannels,\n __channelEngine,\n}: CopilotExpressEndpointParams): CopilotExpressRouter {\n const normalizedBase = normalizeBasePath(basePath);\n\n const handler = createCopilotRuntimeHandler({\n runtime,\n basePath: normalizedBase,\n mode,\n cors: false, // CORS is handled at the Express middleware layer\n hooks,\n activateChannels,\n __channelEngine,\n });\n\n const nodeHandler = createExpressNodeHandler(handler);\n\n const expressHandler = async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n try {\n await nodeHandler(req, res);\n } catch (err) {\n next(err);\n }\n };\n\n const router = express.Router();\n\n // CORS middleware\n if (corsOption) {\n const corsConfig: CorsOptions =\n corsOption === true\n ? {\n origin: \"*\",\n methods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowedHeaders: [\"*\"],\n }\n : corsOption;\n router.use(cors(corsConfig));\n }\n\n // Route mounting\n if (mode === \"single-route\") {\n router.post(normalizedBase, expressHandler);\n router.options(normalizedBase, expressHandler);\n } else if (normalizedBase === \"/\") {\n router.all(/.*/, expressHandler);\n } else {\n router.all(\n new RegExp(`^${escapeRegExp(normalizedBase)}(\\\\/.*)?$`),\n expressHandler,\n );\n }\n\n const exposedRouter: CopilotExpressRouter = router;\n exposedRouter.channels = handler.channels;\n autoStartChannels(exposedRouter.channels);\n return exposedRouter;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction normalizeBasePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for Express endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;;;;AAyHA,SAAgB,4BAA4B,EAC1C,SACA,UACA,OAAO,eACP,MAAM,aAAa,MACnB,OACA,kBACA,mBACqD;CACrD,MAAM,iBAAiB,kBAAkB,SAAS;CAElD,MAAM,UAAUA,kDAA4B;EAC1C;EACA,UAAU;EACV;EACA,MAAM;EACN;EACA;EACA;EACD,CAAC;CAEF,MAAM,cAAcC,sDAAyB,QAAQ;CAErD,MAAM,iBAAiB,OACrB,KACA,KACA,SACG;AACH,MAAI;AACF,SAAM,YAAY,KAAK,IAAI;WACpB,KAAK;AACZ,QAAK,IAAI;;;CAIb,MAAM,SAAS,gBAAQ,QAAQ;AAG/B,KAAI,YAAY;EACd,MAAM,aACJ,eAAe,OACX;GACE,QAAQ;GACR,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACD;GACD,gBAAgB,CAAC,IAAI;GACtB,GACD;AACN,SAAO,sBAAS,WAAW,CAAC;;AAI9B,KAAI,SAAS,gBAAgB;AAC3B,SAAO,KAAK,gBAAgB,eAAe;AAC3C,SAAO,QAAQ,gBAAgB,eAAe;YACrC,mBAAmB,IAC5B,QAAO,IAAI,MAAM,eAAe;KAEhC,QAAO,IACL,IAAI,OAAO,IAAI,aAAa,eAAe,CAAC,WAAW,EACvD,eACD;CAGH,MAAM,gBAAsC;AAC5C,eAAc,WAAW,QAAQ;AACjC,+CAAkB,cAAc,SAAS;AACzC,QAAO;;AAGT,SAAS,aAAa,GAAmB;AACvC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AAGjD,SAAS,kBAAkB,MAAsB;AAC/C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
@@ -8,12 +8,12 @@ import { CorsOptions } from "cors";
8
8
  //#region src/v2/runtime/endpoints/express.d.ts
9
9
  /**
10
10
  * An Express {@link Router} that may also carry an optional
11
- * {@link ChannelsControl} surface. Express's Router is a request-scoped
12
- * middleware object, not a long-running process owner — Node
13
- * (`createCopilotNodeListener`) is the lifecycle-owning surface for
14
- * `.channels`. It is attached here too, best-effort, for callers that mount
15
- * the router directly and want to start (`ready()`), observe, or stop managed
16
- * Channel activation without also standing up a Node listener.
11
+ * {@link ChannelsControl} surface. The Router object itself is request-scoped
12
+ * middleware, but an Express app can only run inside a long-running
13
+ * `http.Server` — so this wrapper is a lifecycle-owning host like
14
+ * `createCopilotNodeListener`: it STARTS activation of the runtime's declared
15
+ * managed Channels at creation, and `.channels` is here to observe (`ready()`)
16
+ * or tear down (`stop()`) that activation.
17
17
  */
18
18
  type CopilotExpressRouter = Router & {
19
19
  channels?: ChannelsControl;
@@ -40,8 +40,9 @@ interface CopilotExpressEndpointParams {
40
40
  hooks?: CopilotRuntimeHooks;
41
41
  /**
42
42
  * Whether the underlying handler builds the control surface for the runtime's
43
- * declared managed Channels. Defaults to `true`. Building it opens no
44
- * connection activation is deferred to the first `channels.ready()`. See
43
+ * declared managed Channels and, because Express is a long-running host,
44
+ * starts their activation at creation. Defaults to `true`. Set `false` to
45
+ * build no surface and open no socket (tests, short-lived scripts). See
45
46
  * `CopilotRuntimeHandlerOptions.activateChannels`.
46
47
  */
47
48
  activateChannels?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"express.d.cts","names":[],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"mappings":";;;;;;;;;;AA2BA;;;;;;;KAAY,oBAAA,GAAuB,MAAA;EAAW,QAAA,GAAW,eAAA;AAAA;AAAA,UAExC,4BAAA;EACf,OAAA,EAAS,kBAAA;EACT,QAAA;EAeiB;;;;;EARjB,IAAA;EARS;;;;;;EAgBT,IAAA,aAAiB,WAAA;EAajB;;;EARA,KAAA,GAAQ,mBAAA;EAc+B;AAsDzC;;;;;EA5DE,gBAAA;EAgEM;;;;EA1DN,eAAA,GAAkB,qBAAA;AAAA;AAAA,iBAsDJ,2BAAA,CAAA;EACd,OAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,gBAAA;EACA;AAAA,GACC,4BAAA,GAA+B,oBAAA"}
1
+ {"version":3,"file":"express.d.cts","names":[],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"mappings":";;;;;;;;;;AA4BA;;;;;;;KAAY,oBAAA,GAAuB,MAAA;EAAW,QAAA,GAAW,eAAA;AAAA;AAAA,UAExC,4BAAA;EACf,OAAA,EAAS,kBAAA;EACT,QAAA;EAeiB;;;;;EARjB,IAAA;EARS;;;;;;EAgBT,IAAA,aAAiB,WAAA;EAcjB;;;EATA,KAAA,GAAQ,mBAAA;EAe+B;AAsDzC;;;;;;EA5DE,gBAAA;EAiEA;;;;EA3DA,eAAA,GAAkB,qBAAA;AAAA;AAAA,iBAsDJ,2BAAA,CAAA;EACd,OAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,gBAAA;EACA;AAAA,GACC,4BAAA,GAA+B,oBAAA"}
@@ -8,12 +8,12 @@ import { CorsOptions } from "cors";
8
8
  //#region src/v2/runtime/endpoints/express.d.ts
9
9
  /**
10
10
  * An Express {@link Router} that may also carry an optional
11
- * {@link ChannelsControl} surface. Express's Router is a request-scoped
12
- * middleware object, not a long-running process owner — Node
13
- * (`createCopilotNodeListener`) is the lifecycle-owning surface for
14
- * `.channels`. It is attached here too, best-effort, for callers that mount
15
- * the router directly and want to start (`ready()`), observe, or stop managed
16
- * Channel activation without also standing up a Node listener.
11
+ * {@link ChannelsControl} surface. The Router object itself is request-scoped
12
+ * middleware, but an Express app can only run inside a long-running
13
+ * `http.Server` — so this wrapper is a lifecycle-owning host like
14
+ * `createCopilotNodeListener`: it STARTS activation of the runtime's declared
15
+ * managed Channels at creation, and `.channels` is here to observe (`ready()`)
16
+ * or tear down (`stop()`) that activation.
17
17
  */
18
18
  type CopilotExpressRouter = Router & {
19
19
  channels?: ChannelsControl;
@@ -40,8 +40,9 @@ interface CopilotExpressEndpointParams {
40
40
  hooks?: CopilotRuntimeHooks;
41
41
  /**
42
42
  * Whether the underlying handler builds the control surface for the runtime's
43
- * declared managed Channels. Defaults to `true`. Building it opens no
44
- * connection activation is deferred to the first `channels.ready()`. See
43
+ * declared managed Channels and, because Express is a long-running host,
44
+ * starts their activation at creation. Defaults to `true`. Set `false` to
45
+ * build no surface and open no socket (tests, short-lived scripts). See
45
46
  * `CopilotRuntimeHandlerOptions.activateChannels`.
46
47
  */
47
48
  activateChannels?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"express.d.mts","names":[],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"mappings":";;;;;;;;;;AA2BA;;;;;;;KAAY,oBAAA,GAAuB,MAAA;EAAW,QAAA,GAAW,eAAA;AAAA;AAAA,UAExC,4BAAA;EACf,OAAA,EAAS,kBAAA;EACT,QAAA;EAeiB;;;;;EARjB,IAAA;EARS;;;;;;EAgBT,IAAA,aAAiB,WAAA;EAajB;;;EARA,KAAA,GAAQ,mBAAA;EAc+B;AAsDzC;;;;;EA5DE,gBAAA;EAgEM;;;;EA1DN,eAAA,GAAkB,qBAAA;AAAA;AAAA,iBAsDJ,2BAAA,CAAA;EACd,OAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,gBAAA;EACA;AAAA,GACC,4BAAA,GAA+B,oBAAA"}
1
+ {"version":3,"file":"express.d.mts","names":[],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"mappings":";;;;;;;;;;AA4BA;;;;;;;KAAY,oBAAA,GAAuB,MAAA;EAAW,QAAA,GAAW,eAAA;AAAA;AAAA,UAExC,4BAAA;EACf,OAAA,EAAS,kBAAA;EACT,QAAA;EAeiB;;;;;EARjB,IAAA;EARS;;;;;;EAgBT,IAAA,aAAiB,WAAA;EAcjB;;;EATA,KAAA,GAAQ,mBAAA;EAe+B;AAsDzC;;;;;;EA5DE,gBAAA;EAiEA;;;;EA3DA,eAAA,GAAkB,qBAAA;AAAA;AAAA,iBAsDJ,2BAAA,CAAA;EACd,OAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,gBAAA;EACA;AAAA,GACC,4BAAA,GAA+B,oBAAA"}
@@ -1,6 +1,7 @@
1
1
  import "reflect-metadata";
2
2
  import { createCopilotRuntimeHandler } from "../core/fetch-handler.mjs";
3
3
  import { createExpressNodeHandler } from "./express-fetch-bridge.mjs";
4
+ import { autoStartChannels } from "./auto-start-channels.mjs";
4
5
  import express from "express";
5
6
  import cors from "cors";
6
7
 
@@ -48,6 +49,7 @@ function createCopilotExpressHandler({ runtime, basePath, mode = "multi-route",
48
49
  else router.all(new RegExp(`^${escapeRegExp(normalizedBase)}(\\/.*)?$`), expressHandler);
49
50
  const exposedRouter = router;
50
51
  exposedRouter.channels = handler.channels;
52
+ autoStartChannels(exposedRouter.channels);
51
53
  return exposedRouter;
52
54
  }
53
55
  function escapeRegExp(s) {
@@ -1 +1 @@
1
- {"version":3,"file":"express.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\nimport type { CorsOptions } from \"cors\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { createCopilotRuntimeHandler } from \"../core/fetch-handler\";\nimport type {\n ActivateChannelEngine,\n ChannelsControl,\n} from \"../core/channel-manager\";\nimport { createExpressNodeHandler } from \"./express-fetch-bridge\";\nimport type { CopilotRuntimeHooks } from \"../core/hooks\";\n\n/**\n * An Express {@link Router} that may also carry an optional\n * {@link ChannelsControl} surface. Express's Router is a request-scoped\n * middleware object, not a long-running process owner — Node\n * (`createCopilotNodeListener`) is the lifecycle-owning surface for\n * `.channels`. It is attached here too, best-effort, for callers that mount\n * the router directly and want to start (`ready()`), observe, or stop managed\n * Channel activation without also standing up a Node listener.\n */\nexport type CopilotExpressRouter = Router & { channels?: ChannelsControl };\n\nexport interface CopilotExpressEndpointParams {\n runtime: CopilotRuntimeLike;\n basePath: string;\n\n /**\n * Endpoint mode.\n * - `\"multi-route\"` (default): separate routes for each operation\n * - `\"single-route\"`: single POST endpoint with JSON envelope dispatch\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * CORS configuration for the Express router.\n * - `true` (default): permissive CORS (`origin: \"*\"`, all methods, all headers).\n * - `false`: no CORS middleware is applied — handle it yourself.\n * - object: passed directly to the Express `cors()` middleware.\n */\n cors?: boolean | CorsOptions;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the underlying handler builds the control surface for the runtime's\n * declared managed Channels. Defaults to `true`. Building it opens no\n * connection activation is deferred to the first `channels.ready()`. See\n * `CopilotRuntimeHandlerOptions.activateChannels`.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine. Forwarded\n * to `createCopilotRuntimeHandler`. Not part of the public API.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * Creates an Express router that serves the CopilotKit runtime.\n *\n * In **multi-route** mode (default) the router exposes:\n * - `GET {basePath}/info` — runtime info\n * - `POST {basePath}/agent/:agentId/run` — start an agent run\n * - `POST {basePath}/agent/:agentId/connect` — connect to an agent run\n * - `POST {basePath}/agent/:agentId/stop/:threadId` — stop an agent run\n * - `POST {basePath}/transcribe` — transcribe audio\n *\n * In **single-route** mode a single `POST {basePath}` endpoint accepts a JSON\n * envelope `{ method, params, body }` and dispatches to the appropriate handler.\n *\n * @example\n * ```typescript\n * import express from \"express\";\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n * import { createCopilotExpressHandler } from \"@copilotkit/runtime/v2/express\";\n *\n * const runtime = new CopilotRuntime({\n * agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o-mini\" }) },\n * });\n *\n * const app = express();\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * }));\n * app.listen(4000);\n * ```\n *\n * @example Single-route mode with lifecycle hooks\n * ```typescript\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * mode: \"single-route\",\n * hooks: {\n * onRequest: ({ request }) => {\n * if (!request.headers.get(\"authorization\")) {\n * throw new Response(\"Unauthorized\", { status: 401 });\n * }\n * },\n * },\n * }));\n * ```\n */\n/** @deprecated Use `createCopilotExpressHandler` instead. */\nexport { createCopilotExpressHandler as createCopilotEndpointExpress };\n\nexport function createCopilotExpressHandler({\n runtime,\n basePath,\n mode = \"multi-route\",\n cors: corsOption = true,\n hooks,\n activateChannels,\n __channelEngine,\n}: CopilotExpressEndpointParams): CopilotExpressRouter {\n const normalizedBase = normalizeBasePath(basePath);\n\n const handler = createCopilotRuntimeHandler({\n runtime,\n basePath: normalizedBase,\n mode,\n cors: false, // CORS is handled at the Express middleware layer\n hooks,\n activateChannels,\n __channelEngine,\n });\n\n const nodeHandler = createExpressNodeHandler(handler);\n\n const expressHandler = async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n try {\n await nodeHandler(req, res);\n } catch (err) {\n next(err);\n }\n };\n\n const router = express.Router();\n\n // CORS middleware\n if (corsOption) {\n const corsConfig: CorsOptions =\n corsOption === true\n ? {\n origin: \"*\",\n methods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowedHeaders: [\"*\"],\n }\n : corsOption;\n router.use(cors(corsConfig));\n }\n\n // Route mounting\n if (mode === \"single-route\") {\n router.post(normalizedBase, expressHandler);\n router.options(normalizedBase, expressHandler);\n } else if (normalizedBase === \"/\") {\n router.all(/.*/, expressHandler);\n } else {\n router.all(\n new RegExp(`^${escapeRegExp(normalizedBase)}(\\\\/.*)?$`),\n expressHandler,\n );\n }\n\n const exposedRouter: CopilotExpressRouter = router;\n exposedRouter.channels = handler.channels;\n return exposedRouter;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction normalizeBasePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for Express endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;AAuHA,SAAgB,4BAA4B,EAC1C,SACA,UACA,OAAO,eACP,MAAM,aAAa,MACnB,OACA,kBACA,mBACqD;CACrD,MAAM,iBAAiB,kBAAkB,SAAS;CAElD,MAAM,UAAU,4BAA4B;EAC1C;EACA,UAAU;EACV;EACA,MAAM;EACN;EACA;EACA;EACD,CAAC;CAEF,MAAM,cAAc,yBAAyB,QAAQ;CAErD,MAAM,iBAAiB,OACrB,KACA,KACA,SACG;AACH,MAAI;AACF,SAAM,YAAY,KAAK,IAAI;WACpB,KAAK;AACZ,QAAK,IAAI;;;CAIb,MAAM,SAAS,QAAQ,QAAQ;AAG/B,KAAI,YAAY;EACd,MAAM,aACJ,eAAe,OACX;GACE,QAAQ;GACR,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACD;GACD,gBAAgB,CAAC,IAAI;GACtB,GACD;AACN,SAAO,IAAI,KAAK,WAAW,CAAC;;AAI9B,KAAI,SAAS,gBAAgB;AAC3B,SAAO,KAAK,gBAAgB,eAAe;AAC3C,SAAO,QAAQ,gBAAgB,eAAe;YACrC,mBAAmB,IAC5B,QAAO,IAAI,MAAM,eAAe;KAEhC,QAAO,IACL,IAAI,OAAO,IAAI,aAAa,eAAe,CAAC,WAAW,EACvD,eACD;CAGH,MAAM,gBAAsC;AAC5C,eAAc,WAAW,QAAQ;AACjC,QAAO;;AAGT,SAAS,aAAa,GAAmB;AACvC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AAGjD,SAAS,kBAAkB,MAAsB;AAC/C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
1
+ {"version":3,"file":"express.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/express.ts"],"sourcesContent":["import express from \"express\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n NextFunction,\n Router,\n} from \"express\";\nimport cors from \"cors\";\nimport type { CorsOptions } from \"cors\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { createCopilotRuntimeHandler } from \"../core/fetch-handler\";\nimport type {\n ActivateChannelEngine,\n ChannelsControl,\n} from \"../core/channel-manager\";\nimport { createExpressNodeHandler } from \"./express-fetch-bridge\";\nimport { autoStartChannels } from \"./auto-start-channels\";\nimport type { CopilotRuntimeHooks } from \"../core/hooks\";\n\n/**\n * An Express {@link Router} that may also carry an optional\n * {@link ChannelsControl} surface. The Router object itself is request-scoped\n * middleware, but an Express app can only run inside a long-running\n * `http.Server` — so this wrapper is a lifecycle-owning host like\n * `createCopilotNodeListener`: it STARTS activation of the runtime's declared\n * managed Channels at creation, and `.channels` is here to observe (`ready()`)\n * or tear down (`stop()`) that activation.\n */\nexport type CopilotExpressRouter = Router & { channels?: ChannelsControl };\n\nexport interface CopilotExpressEndpointParams {\n runtime: CopilotRuntimeLike;\n basePath: string;\n\n /**\n * Endpoint mode.\n * - `\"multi-route\"` (default): separate routes for each operation\n * - `\"single-route\"`: single POST endpoint with JSON envelope dispatch\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * CORS configuration for the Express router.\n * - `true` (default): permissive CORS (`origin: \"*\"`, all methods, all headers).\n * - `false`: no CORS middleware is applied — handle it yourself.\n * - object: passed directly to the Express `cors()` middleware.\n */\n cors?: boolean | CorsOptions;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the underlying handler builds the control surface for the runtime's\n * declared managed Channels — and, because Express is a long-running host,\n * starts their activation at creation. Defaults to `true`. Set `false` to\n * build no surface and open no socket (tests, short-lived scripts). See\n * `CopilotRuntimeHandlerOptions.activateChannels`.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine. Forwarded\n * to `createCopilotRuntimeHandler`. Not part of the public API.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * Creates an Express router that serves the CopilotKit runtime.\n *\n * In **multi-route** mode (default) the router exposes:\n * - `GET {basePath}/info` — runtime info\n * - `POST {basePath}/agent/:agentId/run` — start an agent run\n * - `POST {basePath}/agent/:agentId/connect` — connect to an agent run\n * - `POST {basePath}/agent/:agentId/stop/:threadId` — stop an agent run\n * - `POST {basePath}/transcribe` — transcribe audio\n *\n * In **single-route** mode a single `POST {basePath}` endpoint accepts a JSON\n * envelope `{ method, params, body }` and dispatches to the appropriate handler.\n *\n * @example\n * ```typescript\n * import express from \"express\";\n * import { CopilotRuntime } from \"@copilotkit/runtime/v2\";\n * import { createCopilotExpressHandler } from \"@copilotkit/runtime/v2/express\";\n *\n * const runtime = new CopilotRuntime({\n * agents: { default: new BuiltInAgent({ model: \"openai/gpt-4o-mini\" }) },\n * });\n *\n * const app = express();\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * }));\n * app.listen(4000);\n * ```\n *\n * @example Single-route mode with lifecycle hooks\n * ```typescript\n * app.use(createCopilotExpressHandler({\n * runtime,\n * basePath: \"/api/copilotkit\",\n * mode: \"single-route\",\n * hooks: {\n * onRequest: ({ request }) => {\n * if (!request.headers.get(\"authorization\")) {\n * throw new Response(\"Unauthorized\", { status: 401 });\n * }\n * },\n * },\n * }));\n * ```\n */\n/** @deprecated Use `createCopilotExpressHandler` instead. */\nexport { createCopilotExpressHandler as createCopilotEndpointExpress };\n\nexport function createCopilotExpressHandler({\n runtime,\n basePath,\n mode = \"multi-route\",\n cors: corsOption = true,\n hooks,\n activateChannels,\n __channelEngine,\n}: CopilotExpressEndpointParams): CopilotExpressRouter {\n const normalizedBase = normalizeBasePath(basePath);\n\n const handler = createCopilotRuntimeHandler({\n runtime,\n basePath: normalizedBase,\n mode,\n cors: false, // CORS is handled at the Express middleware layer\n hooks,\n activateChannels,\n __channelEngine,\n });\n\n const nodeHandler = createExpressNodeHandler(handler);\n\n const expressHandler = async (\n req: ExpressRequest,\n res: ExpressResponse,\n next: NextFunction,\n ) => {\n try {\n await nodeHandler(req, res);\n } catch (err) {\n next(err);\n }\n };\n\n const router = express.Router();\n\n // CORS middleware\n if (corsOption) {\n const corsConfig: CorsOptions =\n corsOption === true\n ? {\n origin: \"*\",\n methods: [\n \"GET\",\n \"HEAD\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n ],\n allowedHeaders: [\"*\"],\n }\n : corsOption;\n router.use(cors(corsConfig));\n }\n\n // Route mounting\n if (mode === \"single-route\") {\n router.post(normalizedBase, expressHandler);\n router.options(normalizedBase, expressHandler);\n } else if (normalizedBase === \"/\") {\n router.all(/.*/, expressHandler);\n } else {\n router.all(\n new RegExp(`^${escapeRegExp(normalizedBase)}(\\\\/.*)?$`),\n expressHandler,\n );\n }\n\n const exposedRouter: CopilotExpressRouter = router;\n exposedRouter.channels = handler.channels;\n autoStartChannels(exposedRouter.channels);\n return exposedRouter;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction normalizeBasePath(path: string): string {\n if (!path) {\n throw new Error(\"basePath must be provided for Express endpoint\");\n }\n\n if (!path.startsWith(\"/\")) {\n return `/${path}`;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) {\n return path.slice(0, -1);\n }\n\n return path;\n}\n"],"mappings":";;;;;;;;AAyHA,SAAgB,4BAA4B,EAC1C,SACA,UACA,OAAO,eACP,MAAM,aAAa,MACnB,OACA,kBACA,mBACqD;CACrD,MAAM,iBAAiB,kBAAkB,SAAS;CAElD,MAAM,UAAU,4BAA4B;EAC1C;EACA,UAAU;EACV;EACA,MAAM;EACN;EACA;EACA;EACD,CAAC;CAEF,MAAM,cAAc,yBAAyB,QAAQ;CAErD,MAAM,iBAAiB,OACrB,KACA,KACA,SACG;AACH,MAAI;AACF,SAAM,YAAY,KAAK,IAAI;WACpB,KAAK;AACZ,QAAK,IAAI;;;CAIb,MAAM,SAAS,QAAQ,QAAQ;AAG/B,KAAI,YAAY;EACd,MAAM,aACJ,eAAe,OACX;GACE,QAAQ;GACR,SAAS;IACP;IACA;IACA;IACA;IACA;IACA;IACA;IACD;GACD,gBAAgB,CAAC,IAAI;GACtB,GACD;AACN,SAAO,IAAI,KAAK,WAAW,CAAC;;AAI9B,KAAI,SAAS,gBAAgB;AAC3B,SAAO,KAAK,gBAAgB,eAAe;AAC3C,SAAO,QAAQ,gBAAgB,eAAe;YACrC,mBAAmB,IAC5B,QAAO,IAAI,MAAM,eAAe;KAEhC,QAAO,IACL,IAAI,OAAO,IAAI,aAAa,eAAe,CAAC,WAAW,EACvD,eACD;CAGH,MAAM,gBAAsC;AAC5C,eAAc,WAAW,QAAQ;AACjC,mBAAkB,cAAc,SAAS;AACzC,QAAO;;AAGT,SAAS,aAAa,GAAmB;AACvC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AAGjD,SAAS,kBAAkB,MAAsB;AAC/C,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,iDAAiD;AAGnE,KAAI,CAAC,KAAK,WAAW,IAAI,CACvB,QAAO,IAAI;AAGb,KAAI,KAAK,SAAS,KAAK,KAAK,SAAS,IAAI,CACvC,QAAO,KAAK,MAAM,GAAG,GAAG;AAG1B,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"hono.cjs","names":["createCopilotRuntimeHandler","Hono"],"sources":["../../../../src/v2/runtime/endpoints/hono.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { createCopilotRuntimeHandler } from \"../core/fetch-handler\";\nimport type { CopilotCorsConfig } from \"../core/fetch-cors\";\nimport type { CopilotRuntimeHooks } from \"../core/hooks\";\nimport type {\n ActivateChannelEngine,\n ChannelsControl,\n} from \"../core/channel-manager\";\n\n/**\n * A Hono app that may also carry an optional {@link ChannelsControl} surface.\n * Hono's app object is request-scoped routing config, not a long-running\n * process owner Node (`createCopilotNodeListener`) is the lifecycle-owning\n * surface for `.channels`. It is attached here too, best-effort, for callers\n * that mount the Hono app directly and want to start (`ready()`), observe, or\n * stop managed Channel activation without also standing up a Node listener.\n */\nexport type CopilotHonoApp = Hono & { channels?: ChannelsControl };\n\n/**\n * CORS configuration for CopilotKit endpoints.\n * When using credentials (e.g., HTTP-only cookies), you must specify an explicit origin.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s) for CORS. Can be:\n * - A string: exact origin (e.g., \"https://myapp.com\")\n * - An array: list of allowed origins\n * - A function: dynamic origin resolution\n *\n * Note: When credentials is true, origin cannot be \"*\"\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to allow credentials (cookies, HTTP authentication).\n * When true, origin must be explicitly specified (not \"*\").\n */\n credentials?: boolean;\n}\n\ninterface CopilotEndpointParams {\n runtime: CopilotRuntimeLike;\n basePath: string;\n\n /**\n * Endpoint mode.\n * - `\"multi-route\"` (default): separate routes for each operation\n * - `\"single-route\"`: single POST endpoint with JSON envelope dispatch\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the underlying handler builds the control surface for the runtime's\n * declared managed Channels. Defaults to `true`. Building it opens no\n * connection — activation is deferred to the first `channels.ready()`. See\n * `CopilotRuntimeHandlerOptions.activateChannels`.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine. Forwarded\n * to `createCopilotRuntimeHandler`. Not part of the public API.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n/** @deprecated Use `createCopilotHonoHandler` instead. */\nexport const createCopilotEndpoint = createCopilotHonoHandler;\n\nexport function createCopilotHonoHandler({\n runtime,\n basePath,\n mode = \"multi-route\",\n cors: corsConfig,\n hooks,\n activateChannels,\n __channelEngine,\n}: CopilotEndpointParams): CopilotHonoApp {\n const handler = createCopilotRuntimeHandler({\n runtime,\n basePath,\n mode,\n cors: corsConfig ? toFetchCorsConfig(corsConfig) : true,\n hooks,\n activateChannels,\n __channelEngine,\n });\n\n const app = new Hono();\n\n const scopedApp: CopilotHonoApp = app\n .basePath(basePath)\n .all(\"*\", async (c) => handler(c.req.raw));\n scopedApp.channels = handler.channels;\n return scopedApp;\n}\n\n/**\n * Convert Hono-specific CORS config to the fetch handler's CopilotCorsConfig.\n */\nexport function toFetchCorsConfig(\n config: CopilotEndpointCorsConfig,\n): CopilotCorsConfig {\n const origin = config.origin;\n return {\n origin:\n typeof origin === \"function\"\n ? (reqOrigin: string) => origin(reqOrigin, undefined) ?? null\n : origin,\n credentials: config.credentials,\n };\n}\n"],"mappings":";;;;;;;AAgFA,MAAa,wBAAwB;AAErC,SAAgB,yBAAyB,EACvC,SACA,UACA,OAAO,eACP,MAAM,YACN,OACA,kBACA,mBACwC;CACxC,MAAM,UAAUA,kDAA4B;EAC1C;EACA;EACA;EACA,MAAM,aAAa,kBAAkB,WAAW,GAAG;EACnD;EACA;EACA;EACD,CAAC;CAIF,MAAM,YAFM,IAAIC,WAAM,CAGnB,SAAS,SAAS,CAClB,IAAI,KAAK,OAAO,MAAM,QAAQ,EAAE,IAAI,IAAI,CAAC;AAC5C,WAAU,WAAW,QAAQ;AAC7B,QAAO;;;;;AAMT,SAAgB,kBACd,QACmB;CACnB,MAAM,SAAS,OAAO;AACtB,QAAO;EACL,QACE,OAAO,WAAW,cACb,cAAsB,OAAO,WAAW,OAAU,IAAI,OACvD;EACN,aAAa,OAAO;EACrB"}
1
+ {"version":3,"file":"hono.cjs","names":["createCopilotRuntimeHandler","Hono"],"sources":["../../../../src/v2/runtime/endpoints/hono.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { createCopilotRuntimeHandler } from \"../core/fetch-handler\";\nimport type { CopilotCorsConfig } from \"../core/fetch-cors\";\nimport type { CopilotRuntimeHooks } from \"../core/hooks\";\nimport type {\n ActivateChannelEngine,\n ChannelsControl,\n} from \"../core/channel-manager\";\n\n/**\n * A Hono app that may also carry an optional {@link ChannelsControl} surface.\n *\n * Unlike the Node and Express wrappers which own a process and therefore START\n * managed-Channel activation at creation (OSS-641) — this wrapper stays LAZY:\n * activation is triggered by the first `app.channels.ready()` and never before.\n * A Hono app is multi-runtime and is our edge/serverless surface in practice:\n * every Next.js App Router route handler in `examples/showcases/*` builds one at\n * module scope, and those isolates freeze and recycle per request. Auto-starting\n * there would mint a competing listener for the same Channel on every cold\n * start, which is exactly what the lazy design exists to prevent (see the\n * `createCopilotRuntimeHandler` TSDoc).\n *\n * So on a LONG-RUNNING Hono host (`@hono/node-server`, Bun, Deno) calling\n * `await app.channels.ready()` once at startup is REQUIRED to connect declared\n * Channels; on an edge/serverless host do NOT call it.\n */\nexport type CopilotHonoApp = Hono & { channels?: ChannelsControl };\n\n/**\n * CORS configuration for CopilotKit endpoints.\n * When using credentials (e.g., HTTP-only cookies), you must specify an explicit origin.\n */\nexport interface CopilotEndpointCorsConfig {\n /**\n * Allowed origin(s) for CORS. Can be:\n * - A string: exact origin (e.g., \"https://myapp.com\")\n * - An array: list of allowed origins\n * - A function: dynamic origin resolution\n *\n * Note: When credentials is true, origin cannot be \"*\"\n */\n origin:\n | string\n | string[]\n | ((origin: string, c: any) => string | undefined | null);\n /**\n * Whether to allow credentials (cookies, HTTP authentication).\n * When true, origin must be explicitly specified (not \"*\").\n */\n credentials?: boolean;\n}\n\ninterface CopilotEndpointParams {\n runtime: CopilotRuntimeLike;\n basePath: string;\n\n /**\n * Endpoint mode.\n * - `\"multi-route\"` (default): separate routes for each operation\n * - `\"single-route\"`: single POST endpoint with JSON envelope dispatch\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration. When not provided, defaults to allowing all origins without credentials.\n * To support HTTP-only cookies, provide cors config with credentials: true and explicit origin.\n */\n cors?: CopilotEndpointCorsConfig;\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the underlying handler builds the control surface for the runtime's\n * declared managed Channels. Defaults to `true`. Building it opens no\n * connection — activation is deferred to the first `channels.ready()`. See\n * `CopilotRuntimeHandlerOptions.activateChannels`.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine. Forwarded\n * to `createCopilotRuntimeHandler`. Not part of the public API.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n/** @deprecated Use `createCopilotHonoHandler` instead. */\nexport const createCopilotEndpoint = createCopilotHonoHandler;\n\nexport function createCopilotHonoHandler({\n runtime,\n basePath,\n mode = \"multi-route\",\n cors: corsConfig,\n hooks,\n activateChannels,\n __channelEngine,\n}: CopilotEndpointParams): CopilotHonoApp {\n const handler = createCopilotRuntimeHandler({\n runtime,\n basePath,\n mode,\n cors: corsConfig ? toFetchCorsConfig(corsConfig) : true,\n hooks,\n activateChannels,\n __channelEngine,\n });\n\n const app = new Hono();\n\n const scopedApp: CopilotHonoApp = app\n .basePath(basePath)\n .all(\"*\", async (c) => handler(c.req.raw));\n scopedApp.channels = handler.channels;\n return scopedApp;\n}\n\n/**\n * Convert Hono-specific CORS config to the fetch handler's CopilotCorsConfig.\n */\nexport function toFetchCorsConfig(\n config: CopilotEndpointCorsConfig,\n): CopilotCorsConfig {\n const origin = config.origin;\n return {\n origin:\n typeof origin === \"function\"\n ? (reqOrigin: string) => origin(reqOrigin, undefined) ?? null\n : origin,\n credentials: config.credentials,\n };\n}\n"],"mappings":";;;;;;;AAyFA,MAAa,wBAAwB;AAErC,SAAgB,yBAAyB,EACvC,SACA,UACA,OAAO,eACP,MAAM,YACN,OACA,kBACA,mBACwC;CACxC,MAAM,UAAUA,kDAA4B;EAC1C;EACA;EACA;EACA,MAAM,aAAa,kBAAkB,WAAW,GAAG;EACnD;EACA;EACA;EACD,CAAC;CAIF,MAAM,YAFM,IAAIC,WAAM,CAGnB,SAAS,SAAS,CAClB,IAAI,KAAK,OAAO,MAAM,QAAQ,EAAE,IAAI,IAAI,CAAC;AAC5C,WAAU,WAAW,QAAQ;AAC7B,QAAO;;;;;AAMT,SAAgB,kBACd,QACmB;CACnB,MAAM,SAAS,OAAO;AACtB,QAAO;EACL,QACE,OAAO,WAAW,cACb,cAAsB,OAAO,WAAW,OAAU,IAAI,OACvD;EACN,aAAa,OAAO;EACrB"}
@@ -8,11 +8,20 @@ import { Hono } from "hono";
8
8
  //#region src/v2/runtime/endpoints/hono.d.ts
9
9
  /**
10
10
  * A Hono app that may also carry an optional {@link ChannelsControl} surface.
11
- * Hono's app object is request-scoped routing config, not a long-running
12
- * process ownerNode (`createCopilotNodeListener`) is the lifecycle-owning
13
- * surface for `.channels`. It is attached here too, best-effort, for callers
14
- * that mount the Hono app directly and want to start (`ready()`), observe, or
15
- * stop managed Channel activation without also standing up a Node listener.
11
+ *
12
+ * Unlike the Node and Express wrappers which own a process and therefore START
13
+ * managed-Channel activation at creation (OSS-641) this wrapper stays LAZY:
14
+ * activation is triggered by the first `app.channels.ready()` and never before.
15
+ * A Hono app is multi-runtime and is our edge/serverless surface in practice:
16
+ * every Next.js App Router route handler in `examples/showcases/*` builds one at
17
+ * module scope, and those isolates freeze and recycle per request. Auto-starting
18
+ * there would mint a competing listener for the same Channel on every cold
19
+ * start, which is exactly what the lazy design exists to prevent (see the
20
+ * `createCopilotRuntimeHandler` TSDoc).
21
+ *
22
+ * So on a LONG-RUNNING Hono host (`@hono/node-server`, Bun, Deno) calling
23
+ * `await app.channels.ready()` once at startup is REQUIRED to connect declared
24
+ * Channels; on an edge/serverless host do NOT call it.
16
25
  */
17
26
  type CopilotHonoApp = Hono & {
18
27
  channels?: ChannelsControl;
@@ -1 +1 @@
1
- {"version":3,"file":"hono.d.cts","names":[],"sources":["../../../../src/v2/runtime/endpoints/hono.ts"],"mappings":";;;;;;;;;;AAkBA;;;;;;KAAY,cAAA,GAAiB,IAAA;EAAS,QAAA,GAAW,eAAA;AAAA;AAMjD;;;;AAAA,UAAiB,yBAAA;EAYT;;;;;AAMP;;;EATC,MAAA,wBAGM,MAAA,UAAgB,CAAA;EAuBf;;;;EAlBP,WAAA;AAAA;AAAA,UAGQ,qBAAA;EACR,OAAA,EAAS,kBAAA;EACT,QAAA;EAaA;;;;;EANA,IAAA;EAwBkB;;;AAGpB;EArBE,IAAA,GAAO,yBAAA;;;;EAIP,KAAA,GAAQ,mBAAA;EAmB8B;;;;;;EAXtC,gBAAA;EAiBA;;;;EAXA,eAAA,GAAkB,qBAAA;AAAA;;cAGP,qBAAA,SAAqB,wBAAA;AAAA,iBAElB,wBAAA,CAAA;EACd,OAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,gBAAA;EACA;AAAA,GACC,qBAAA,GAAwB,cAAA;;;;iBAuBX,iBAAA,CACd,MAAA,EAAQ,yBAAA,GACP,iBAAA"}
1
+ {"version":3,"file":"hono.d.cts","names":[],"sources":["../../../../src/v2/runtime/endpoints/hono.ts"],"mappings":";;;;;;;;;;AA2BA;;;;;;;;;AAMA;;;;;;KANY,cAAA,GAAiB,IAAA;EAAS,QAAA,GAAW,eAAA;AAAA;;AAwBhD;;;UAlBgB,yBAAA;EAmCR;;;;;;;;EA1BP,MAAA,wBAGM,MAAA,UAAgB,CAAA;EAuBtB;;;;EAlBA,WAAA;AAAA;AAAA,UAGQ,qBAAA;EACR,OAAA,EAAS,kBAAA;EACT,QAAA;EAkCW;;;;;EA3BX,IAAA;EA6BsC;;;;EAvBtC,IAAA,GAAO,yBAAA;EA2BD;;;EAvBN,KAAA,GAAQ,mBAAA;EA2BP;;;;;;EAnBD,gBAAA;EAaA;;;;EAPA,eAAA,GAAkB,qBAAA;AAAA;;cAGP,qBAAA,SAAqB,wBAAA;AAAA,iBAElB,wBAAA,CAAA;EACd,OAAA;EACA,QAAA;EACA,IAAA;EACA,IAAA,EAAM,UAAA;EACN,KAAA;EACA,gBAAA;EACA;AAAA,GACC,qBAAA,GAAwB,cAAA;;;;iBAuBX,iBAAA,CACd,MAAA,EAAQ,yBAAA,GACP,iBAAA"}
@@ -8,11 +8,20 @@ import { Hono } from "hono";
8
8
  //#region src/v2/runtime/endpoints/hono.d.ts
9
9
  /**
10
10
  * A Hono app that may also carry an optional {@link ChannelsControl} surface.
11
- * Hono's app object is request-scoped routing config, not a long-running
12
- * process ownerNode (`createCopilotNodeListener`) is the lifecycle-owning
13
- * surface for `.channels`. It is attached here too, best-effort, for callers
14
- * that mount the Hono app directly and want to start (`ready()`), observe, or
15
- * stop managed Channel activation without also standing up a Node listener.
11
+ *
12
+ * Unlike the Node and Express wrappers which own a process and therefore START
13
+ * managed-Channel activation at creation (OSS-641) this wrapper stays LAZY:
14
+ * activation is triggered by the first `app.channels.ready()` and never before.
15
+ * A Hono app is multi-runtime and is our edge/serverless surface in practice:
16
+ * every Next.js App Router route handler in `examples/showcases/*` builds one at
17
+ * module scope, and those isolates freeze and recycle per request. Auto-starting
18
+ * there would mint a competing listener for the same Channel on every cold
19
+ * start, which is exactly what the lazy design exists to prevent (see the
20
+ * `createCopilotRuntimeHandler` TSDoc).
21
+ *
22
+ * So on a LONG-RUNNING Hono host (`@hono/node-server`, Bun, Deno) calling
23
+ * `await app.channels.ready()` once at startup is REQUIRED to connect declared
24
+ * Channels; on an edge/serverless host do NOT call it.
16
25
  */
17
26
  type CopilotHonoApp = Hono & {
18
27
  channels?: ChannelsControl;
@@ -1 +1 @@
1
- {"version":3,"file":"hono.d.mts","names":[],"sources":["../../../../src/v2/runtime/endpoints/hono.ts"],"mappings":";;;;;;;;;;AAkBA;;;;;;KAAY,cAAA,GAAiB,IAAA;EAAS,QAAA,GAAW,eAAA;AAAA;AAMjD;;;;AAAA,UAAiB,yBAAA;EAYT;;;;;AAMP;;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