@copilotkit/runtime 1.70.2 → 1.70.3
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.
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/v2/runtime/core/channel-activation-config.d.cts +1 -0
- package/dist/v2/runtime/core/channel-activation-config.d.cts.map +1 -1
- package/dist/v2/runtime/core/channel-manager.d.cts +2 -0
- package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.cjs +2 -6
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.cts +0 -7
- package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.mts +0 -7
- package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +2 -6
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/learning.cjs +5 -0
- package/dist/v2/runtime/core/learning.cjs.map +1 -1
- package/dist/v2/runtime/core/learning.d.cts +1 -0
- package/dist/v2/runtime/core/learning.d.cts.map +1 -1
- package/dist/v2/runtime/core/learning.d.mts +1 -0
- package/dist/v2/runtime/core/learning.d.mts.map +1 -1
- package/dist/v2/runtime/core/learning.mjs +5 -1
- package/dist/v2/runtime/core/learning.mjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +1 -0
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs +1 -2
- package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs.map +1 -1
- package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs +1 -2
- package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs.map +1 -1
- package/dist/v2/runtime/endpoints/express.cjs +1 -2
- package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
- package/dist/v2/runtime/endpoints/express.d.cts +0 -6
- package/dist/v2/runtime/endpoints/express.d.cts.map +1 -1
- package/dist/v2/runtime/endpoints/express.d.mts +0 -6
- package/dist/v2/runtime/endpoints/express.d.mts.map +1 -1
- package/dist/v2/runtime/endpoints/express.mjs +1 -2
- package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
- package/dist/v2/runtime/endpoints/hono.cjs +1 -2
- package/dist/v2/runtime/endpoints/hono.cjs.map +1 -1
- package/dist/v2/runtime/endpoints/hono.d.cts +0 -6
- package/dist/v2/runtime/endpoints/hono.d.cts.map +1 -1
- package/dist/v2/runtime/endpoints/hono.d.mts +0 -6
- package/dist/v2/runtime/endpoints/hono.d.mts.map +1 -1
- package/dist/v2/runtime/endpoints/hono.mjs +1 -2
- package/dist/v2/runtime/endpoints/hono.mjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.cjs +3 -2
- package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs +3 -2
- package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-inspector-learning.cjs +3 -2
- package/dist/v2/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-inspector-learning.mjs +3 -2
- package/dist/v2/runtime/handlers/handle-inspector-learning.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -0
- package/dist/v2/runtime/index.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/index.d.cts +2 -0
- package/package.json +2 -2
- package/skills/runtime/SKILL.md +1 -1
|
@@ -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 / 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 { handleInspectorMetadata } from \"../handlers/handle-inspector-metadata\";\nimport { handleInspectorLearning } from \"../handlers/handle-inspector-learning\";\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 createResourceRequest,\n expectString,\n detectSingleRouteEnvelope,\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 * Emitted when a single-route client's JSON envelope reaches a runtime mounted\n * in multi-route mode. Named so callers can branch on the cause rather than\n * string-matching the prose.\n */\nconst SINGLE_ROUTE_ENVELOPE_CODE =\n \"single_route_envelope_against_multi_route_runtime\";\n\nconst SINGLE_ROUTE_ENVELOPE_MESSAGE =\n 'Received a single-route request envelope ({ method: \"...\" }) but this ' +\n \"runtime is mounted in multi-route mode, so the request matched no route. \" +\n \"Either drop useSingleEndpoint from the frontend provider so it negotiates \" +\n 'the transport, or mount the runtime with mode: \"single-route\" to serve ' +\n \"this envelope.\";\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 * Explicitly exposes the read-only Inspector Learning capability.\n *\n * Defaults to `false`. Debug mode and the handler's normal request/auth\n * middleware remain independent, additional gates.\n */\n inspectorLearning?: boolean;\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 ...(runtime.learning !== undefined ? { learning: runtime.learning } : {}),\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n telemetry: runtime.telemetry,\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 {\n runtime,\n basePath,\n mode = \"multi-route\",\n cors,\n hooks,\n inspectorLearning = false,\n } = 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 let handlerPath = path;\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(\n request,\n basePath,\n path,\n runtime.exposeMemoryRoutes === true,\n );\n route = resolved.route;\n request = resolved.request;\n handlerPath = resolved.path;\n const { methodCall } = resolved;\n if (methodCall.method === \"resource/request\") {\n const methodError = validateHttpMethod(request.method, route);\n if (methodError) {\n throw methodError;\n }\n }\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path: handlerPath,\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 } else if (route.method === \"inspector/learning\") {\n const learningUrl = new URL(request.url);\n for (const key of [\n \"agentId\",\n \"skillsPage\",\n \"insightsPage\",\n ] as const) {\n const value = methodCall.params?.[key];\n if (typeof value === \"string\" || typeof value === \"number\") {\n learningUrl.searchParams.set(key, String(value));\n }\n }\n request = new Request(learningUrl, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: methodCall.method === \"resource/request\",\n inspectorLearningEnabled: inspectorLearning,\n singleRouteResourceOperationsEnabled: true,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n // A single-endpoint client POSTing `{ method }` at the base path\n // matches no route here. Say so, rather than leaving the developer\n // with a bare 404 and no way to tell a transport mismatch from a\n // wrong `basePath` (issue OSS-882).\n const envelopeMethod = await detectSingleRouteEnvelope(request);\n if (envelopeMethod) {\n logger.warn(\n { url: request.url, path, method: envelopeMethod },\n SINGLE_ROUTE_ENVELOPE_MESSAGE,\n );\n throw jsonResponse(\n {\n error: \"Not found\",\n code: SINGLE_ROUTE_ENVELOPE_CODE,\n message: SINGLE_ROUTE_ENVELOPE_MESSAGE,\n },\n 404,\n );\n }\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 inspectorLearningEnabled: inspectorLearning,\n singleRouteResourceOperationsEnabled: false,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path: handlerPath,\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: handlerPath,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path: handlerPath },\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: handlerPath,\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: handlerPath,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n {\n err: hookError,\n originalErr: error,\n url: request.url,\n path: handlerPath,\n },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path: handlerPath },\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: {\n threadEndpointsEnabled: boolean;\n inspectorLearningEnabled: boolean;\n singleRouteResourceOperationsEnabled: boolean;\n },\n): Promise<Response> {\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.identifyUser === undefined &&\n route.method !== \"info\"\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\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 inspectorLearningEnabled: options.inspectorLearningEnabled,\n singleRouteResourceOperationsEnabled:\n options.singleRouteResourceOperationsEnabled,\n });\n case \"inspector/metadata\":\n return handleInspectorMetadata({ runtime, request });\n case \"inspector/learning\":\n return handleInspectorLearning({\n runtime,\n request,\n enabled: options.inspectorLearningEnabled,\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 request: Request;\n path: string;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n memoryRoutesExposed: boolean,\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 \"inspector/metadata\":\n route = { method: \"inspector/metadata\" };\n break;\n case \"inspector/learning\":\n route = { method: \"inspector/learning\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n case \"resource/request\": {\n const resourceRequest = createResourceRequest(\n request,\n expectString(methodCall.params, \"path\"),\n expectString(methodCall.params, \"httpMethod\"),\n methodCall.body,\n );\n const resourceUrl = new URL(resourceRequest.url);\n const resourceRoute = matchRoute(resourceUrl.pathname, pathname);\n if (!resourceRoute || !isSingleRouteResourceRoute(resourceRoute)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n if (\n resourceRoute.method.startsWith(\"memories/\") &&\n !memoryRoutesExposed\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n return {\n route: resourceRoute,\n methodCall,\n request: resourceRequest,\n path: resourceUrl.pathname,\n };\n }\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, request, path: pathname };\n}\n\n/** Limits the generic envelope bridge to the Runtime's resource APIs. */\nfunction isSingleRouteResourceRoute(route: RouteInfo): boolean {\n switch (route.method) {\n case \"threads/list\":\n case \"threads/subscribe\":\n case \"threads/update\":\n case \"threads/archive\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"threads/clear\":\n case \"memories/list\":\n case \"memories/recall\":\n case \"memories/subscribe\":\n case \"memories/mutate\":\n case \"annotate\":\n return true;\n default:\n return false;\n }\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 \"inspector/metadata\":\n case \"inspector/learning\":\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8HA,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ACxD,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 { handleInspectorMetadata } from \"../handlers/handle-inspector-metadata\";\nimport { handleInspectorLearning } from \"../handlers/handle-inspector-learning\";\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 createResourceRequest,\n expectString,\n detectSingleRouteEnvelope,\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 * Emitted when a single-route client's JSON envelope reaches a runtime mounted\n * in multi-route mode. Named so callers can branch on the cause rather than\n * string-matching the prose.\n */\nconst SINGLE_ROUTE_ENVELOPE_CODE =\n \"single_route_envelope_against_multi_route_runtime\";\n\nconst SINGLE_ROUTE_ENVELOPE_MESSAGE =\n 'Received a single-route request envelope ({ method: \"...\" }) but this ' +\n \"runtime is mounted in multi-route mode, so the request matched no route. \" +\n \"Either drop useSingleEndpoint from the frontend provider so it negotiates \" +\n 'the transport, or mount the runtime with mode: \"single-route\" to serve ' +\n \"this envelope.\";\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 ...(runtime.learning !== undefined ? { learning: runtime.learning } : {}),\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n telemetry: runtime.telemetry,\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 let handlerPath = path;\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(\n request,\n basePath,\n path,\n runtime.exposeMemoryRoutes === true,\n );\n route = resolved.route;\n request = resolved.request;\n handlerPath = resolved.path;\n const { methodCall } = resolved;\n if (methodCall.method === \"resource/request\") {\n const methodError = validateHttpMethod(request.method, route);\n if (methodError) {\n throw methodError;\n }\n }\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path: handlerPath,\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 } else if (route.method === \"inspector/learning\") {\n const learningUrl = new URL(request.url);\n for (const key of [\n \"agentId\",\n \"skillsPage\",\n \"insightsPage\",\n ] as const) {\n const value = methodCall.params?.[key];\n if (typeof value === \"string\" || typeof value === \"number\") {\n learningUrl.searchParams.set(key, String(value));\n }\n }\n request = new Request(learningUrl, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: methodCall.method === \"resource/request\",\n singleRouteResourceOperationsEnabled: true,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n // A single-endpoint client POSTing `{ method }` at the base path\n // matches no route here. Say so, rather than leaving the developer\n // with a bare 404 and no way to tell a transport mismatch from a\n // wrong `basePath` (issue OSS-882).\n const envelopeMethod = await detectSingleRouteEnvelope(request);\n if (envelopeMethod) {\n logger.warn(\n { url: request.url, path, method: envelopeMethod },\n SINGLE_ROUTE_ENVELOPE_MESSAGE,\n );\n throw jsonResponse(\n {\n error: \"Not found\",\n code: SINGLE_ROUTE_ENVELOPE_CODE,\n message: SINGLE_ROUTE_ENVELOPE_MESSAGE,\n },\n 404,\n );\n }\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 singleRouteResourceOperationsEnabled: false,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path: handlerPath,\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: handlerPath,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path: handlerPath },\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: handlerPath,\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: handlerPath,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n {\n err: hookError,\n originalErr: error,\n url: request.url,\n path: handlerPath,\n },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path: handlerPath },\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: {\n threadEndpointsEnabled: boolean;\n singleRouteResourceOperationsEnabled: boolean;\n },\n): Promise<Response> {\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.identifyUser === undefined &&\n route.method !== \"info\"\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\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 singleRouteResourceOperationsEnabled:\n options.singleRouteResourceOperationsEnabled,\n });\n case \"inspector/metadata\":\n return handleInspectorMetadata({ runtime, request });\n case \"inspector/learning\":\n return handleInspectorLearning({\n runtime,\n request,\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 request: Request;\n path: string;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n memoryRoutesExposed: boolean,\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 \"inspector/metadata\":\n route = { method: \"inspector/metadata\" };\n break;\n case \"inspector/learning\":\n route = { method: \"inspector/learning\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n case \"resource/request\": {\n const resourceRequest = createResourceRequest(\n request,\n expectString(methodCall.params, \"path\"),\n expectString(methodCall.params, \"httpMethod\"),\n methodCall.body,\n );\n const resourceUrl = new URL(resourceRequest.url);\n const resourceRoute = matchRoute(resourceUrl.pathname, pathname);\n if (!resourceRoute || !isSingleRouteResourceRoute(resourceRoute)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n if (\n resourceRoute.method.startsWith(\"memories/\") &&\n !memoryRoutesExposed\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n return {\n route: resourceRoute,\n methodCall,\n request: resourceRequest,\n path: resourceUrl.pathname,\n };\n }\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, request, path: pathname };\n}\n\n/** Limits the generic envelope bridge to the Runtime's resource APIs. */\nfunction isSingleRouteResourceRoute(route: RouteInfo): boolean {\n switch (route.method) {\n case \"threads/list\":\n case \"threads/subscribe\":\n case \"threads/update\":\n case \"threads/archive\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"threads/clear\":\n case \"memories/list\":\n case \"memories/recall\":\n case \"memories/subscribe\":\n case \"memories/mutate\":\n case \"annotate\":\n return true;\n default:\n return false;\n }\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 \"inspector/metadata\":\n case \"inspector/learning\":\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8HA,MAAM,6BACJ;AAEF,MAAM,gCACJ;;;;;;;AAuGF,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,GAAI,QAAQ,aAAa,SAAY,EAAE,UAAU,QAAQ,UAAU,GAAG,EAAE;EACxE,gBAAgB,QAAQ;EACxB,8BAA8B,QAAQ;EACtC,GAAI,QAAQ,kBAAkB,SAC1B,EAAE,eAAe,QAAQ,eAAe,GACxC,EAAE;EACN,UAAU,QAAQ;EAClB,WAAW,QAAQ;EAYnB,MAAM,KAAK,SACT,OAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,M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,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
|
|
3
3
|
//#region src/v2/runtime/core/learning.ts
|
|
4
|
+
/** Checks configuration without invoking a selector that requires a real run. */
|
|
5
|
+
function hasLearningContainerConfiguration(runtime) {
|
|
6
|
+
return runtime.intelligence?.ɵgetLearningContainerId?.() !== void 0 || runtime.learning?.containerId !== void 0;
|
|
7
|
+
}
|
|
4
8
|
const STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
5
9
|
/** Validates and returns a stable Learning Container ID. */
|
|
6
10
|
function assertStableLearningContainerId(value) {
|
|
@@ -23,6 +27,7 @@ async function resolveLearningContainerId(config, input) {
|
|
|
23
27
|
|
|
24
28
|
//#endregion
|
|
25
29
|
exports.assertStableLearningContainerId = assertStableLearningContainerId;
|
|
30
|
+
exports.hasLearningContainerConfiguration = hasLearningContainerConfiguration;
|
|
26
31
|
exports.resolveLearningContainerId = resolveLearningContainerId;
|
|
27
32
|
exports.resolveLearningContainerSelector = resolveLearningContainerSelector;
|
|
28
33
|
//# sourceMappingURL=learning.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"learning.cjs","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\n\n/** Application user resolved by an Intelligence runtime. */\nexport interface CopilotRuntimeUser {\n readonly id: string;\n readonly name: string;\n}\n\n/** Context for choosing a Learning Container through the public Intelligence SDK. */\nexport type LearningContainerSelectorInput =\n | {\n readonly surface: \"web\";\n readonly user: CopilotRuntimeUser;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n }\n | {\n readonly surface: \"channel\";\n readonly user: CopilotRuntimeUser | null;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n };\n\n/** Chooses one developer-created Learning Container for an Intelligence run. */\nexport type GetLearningContainerId = (\n input: LearningContainerSelectorInput,\n) => MaybePromise<string | null | undefined>;\n\n/** Context for choosing one Learning Container for an Intelligence run. */\nexport type CopilotRuntimeLearningContext =\n | {\n readonly surface: \"web\";\n readonly request: Request;\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n }\n | {\n readonly surface: \"channel\";\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n readonly deliveryId: string;\n };\n\n/** Assigns each Intelligence Thread to one developer-created Learning Container. */\nexport interface CopilotRuntimeLearningConfig {\n readonly containerId:\n | string\n | ((\n input: CopilotRuntimeLearningContext,\n ) => MaybePromise<string | null | undefined>);\n}\n\nconst STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** Validates and returns a stable Learning Container ID. */\nexport function assertStableLearningContainerId(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > 64 ||\n !STABLE_CONTAINER_ID.test(value)\n ) {\n throw new Error(\n \"Learning Container must use a 1-64 character stable ID with lowercase letters, numbers, and single hyphens\",\n );\n }\n return value;\n}\n\n/** Resolves and validates a public Intelligence Learning Container selection. */\nexport async function resolveLearningContainerSelector(\n selector: GetLearningContainerId,\n input: LearningContainerSelectorInput,\n): Promise<string | undefined> {\n const value = await selector(input);\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n\n/** Resolves the configured Container once for one web or Channel run. */\nexport async function resolveLearningContainerId(\n config: CopilotRuntimeLearningConfig | undefined,\n input: CopilotRuntimeLearningContext,\n): Promise<string | undefined> {\n if (config === undefined) return undefined;\n const value =\n typeof config.containerId === \"function\"\n ? await config.containerId(input)\n : config.containerId;\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"learning.cjs","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/** Checks configuration without invoking a selector that requires a real run. */\nexport function hasLearningContainerConfiguration(\n runtime: CopilotRuntimeLike,\n): boolean {\n return (\n runtime.intelligence?.ɵgetLearningContainerId?.() !== undefined ||\n runtime.learning?.containerId !== undefined\n );\n}\n\n/** Application user resolved by an Intelligence runtime. */\nexport interface CopilotRuntimeUser {\n readonly id: string;\n readonly name: string;\n}\n\n/** Context for choosing a Learning Container through the public Intelligence SDK. */\nexport type LearningContainerSelectorInput =\n | {\n readonly surface: \"web\";\n readonly user: CopilotRuntimeUser;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n }\n | {\n readonly surface: \"channel\";\n readonly user: CopilotRuntimeUser | null;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n };\n\n/** Chooses one developer-created Learning Container for an Intelligence run. */\nexport type GetLearningContainerId = (\n input: LearningContainerSelectorInput,\n) => MaybePromise<string | null | undefined>;\n\n/** Context for choosing one Learning Container for an Intelligence run. */\nexport type CopilotRuntimeLearningContext =\n | {\n readonly surface: \"web\";\n readonly request: Request;\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n }\n | {\n readonly surface: \"channel\";\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n readonly deliveryId: string;\n };\n\n/** Assigns each Intelligence Thread to one developer-created Learning Container. */\nexport interface CopilotRuntimeLearningConfig {\n readonly containerId:\n | string\n | ((\n input: CopilotRuntimeLearningContext,\n ) => MaybePromise<string | null | undefined>);\n}\n\nconst STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** Validates and returns a stable Learning Container ID. */\nexport function assertStableLearningContainerId(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > 64 ||\n !STABLE_CONTAINER_ID.test(value)\n ) {\n throw new Error(\n \"Learning Container must use a 1-64 character stable ID with lowercase letters, numbers, and single hyphens\",\n );\n }\n return value;\n}\n\n/** Resolves and validates a public Intelligence Learning Container selection. */\nexport async function resolveLearningContainerSelector(\n selector: GetLearningContainerId,\n input: LearningContainerSelectorInput,\n): Promise<string | undefined> {\n const value = await selector(input);\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n\n/** Resolves the configured Container once for one web or Channel run. */\nexport async function resolveLearningContainerId(\n config: CopilotRuntimeLearningConfig | undefined,\n input: CopilotRuntimeLearningContext,\n): Promise<string | undefined> {\n if (config === undefined) return undefined;\n const value =\n typeof config.containerId === \"function\"\n ? await config.containerId(input)\n : config.containerId;\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n"],"mappings":";;;;AAKA,SAAgB,kCACd,SACS;AACT,QACE,QAAQ,cAAc,2BAA2B,KAAK,UACtD,QAAQ,UAAU,gBAAgB;;AA0DtC,MAAM,sBAAsB;;AAG5B,SAAgB,gCAAgC,OAAwB;AACtE,KACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,SAAS,MACf,CAAC,oBAAoB,KAAK,MAAM,CAEhC,OAAM,IAAI,MACR,6GACD;AAEH,QAAO;;;AAIT,eAAsB,iCACpB,UACA,OAC6B;CAC7B,MAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,gCAAgC,MAAM;;;AAI/C,eAAsB,2BACpB,QACA,OAC6B;AAC7B,KAAI,WAAW,OAAW,QAAO;CACjC,MAAM,QACJ,OAAO,OAAO,gBAAgB,aAC1B,MAAM,OAAO,YAAY,MAAM,GAC/B,OAAO;AACb,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,gCAAgC,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"learning.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"learning.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"mappings":";;;;;;AAeA;AAAA,UAAiB,kBAAA;EAAA,SACN,EAAA;EAAA,SACA,IAAA;AAAA;AAIX;AAAA,KAAY,8BAAA;EAAA,SAEG,OAAA;EAAA,SACA,IAAA,EAAM,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA,EAAO,QAAA,CAAS,aAAA;AAAA;EAAA,SAGhB,OAAA;EAAA,SACA,IAAA,EAAM,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA,EAAO,QAAA,CAAS,aAAA;AAAA;;KAInB,sBAAA,IACV,KAAA,EAAO,8BAAA,KACJ,YAAA;;KAGO,6BAAA;EAAA,SAEG,OAAA;EAAA,SACA,OAAA,EAAS,OAAA;EAAA,SACT,QAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;EAAA,SACA,MAAA;AAAA;EAAA,SAGA,OAAA;EAAA,SACA,QAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;EAAA,SACA,MAAA;EAAA,SACA,UAAA;AAAA;;UAIE,4BAAA;EAAA,SACN,WAAA,aAGH,KAAA,EAAO,6BAAA,KACJ,YAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"learning.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"learning.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"mappings":";;;;;;AAeA;AAAA,UAAiB,kBAAA;EAAA,SACN,EAAA;EAAA,SACA,IAAA;AAAA;AAIX;AAAA,KAAY,8BAAA;EAAA,SAEG,OAAA;EAAA,SACA,IAAA,EAAM,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA,EAAO,QAAA,CAAS,aAAA;AAAA;EAAA,SAGhB,OAAA;EAAA,SACA,IAAA,EAAM,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,KAAA,EAAO,QAAA,CAAS,aAAA;AAAA;;KAInB,sBAAA,IACV,KAAA,EAAO,8BAAA,KACJ,YAAA;;KAGO,6BAAA;EAAA,SAEG,OAAA;EAAA,SACA,OAAA,EAAS,OAAA;EAAA,SACT,QAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;EAAA,SACA,MAAA;AAAA;EAAA,SAGA,OAAA;EAAA,SACA,QAAA;EAAA,SACA,KAAA;EAAA,SACA,OAAA;EAAA,SACA,MAAA;EAAA,SACA,UAAA;AAAA;;UAIE,4BAAA;EAAA,SACN,WAAA,aAGH,KAAA,EAAO,6BAAA,KACJ,YAAA;AAAA"}
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
//#region src/v2/runtime/core/learning.ts
|
|
3
|
+
/** Checks configuration without invoking a selector that requires a real run. */
|
|
4
|
+
function hasLearningContainerConfiguration(runtime) {
|
|
5
|
+
return runtime.intelligence?.ɵgetLearningContainerId?.() !== void 0 || runtime.learning?.containerId !== void 0;
|
|
6
|
+
}
|
|
3
7
|
const STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
4
8
|
/** Validates and returns a stable Learning Container ID. */
|
|
5
9
|
function assertStableLearningContainerId(value) {
|
|
@@ -21,5 +25,5 @@ async function resolveLearningContainerId(config, input) {
|
|
|
21
25
|
}
|
|
22
26
|
|
|
23
27
|
//#endregion
|
|
24
|
-
export { assertStableLearningContainerId, resolveLearningContainerId, resolveLearningContainerSelector };
|
|
28
|
+
export { assertStableLearningContainerId, hasLearningContainerConfiguration, resolveLearningContainerId, resolveLearningContainerSelector };
|
|
25
29
|
//# sourceMappingURL=learning.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"learning.mjs","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\n\n/** Application user resolved by an Intelligence runtime. */\nexport interface CopilotRuntimeUser {\n readonly id: string;\n readonly name: string;\n}\n\n/** Context for choosing a Learning Container through the public Intelligence SDK. */\nexport type LearningContainerSelectorInput =\n | {\n readonly surface: \"web\";\n readonly user: CopilotRuntimeUser;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n }\n | {\n readonly surface: \"channel\";\n readonly user: CopilotRuntimeUser | null;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n };\n\n/** Chooses one developer-created Learning Container for an Intelligence run. */\nexport type GetLearningContainerId = (\n input: LearningContainerSelectorInput,\n) => MaybePromise<string | null | undefined>;\n\n/** Context for choosing one Learning Container for an Intelligence run. */\nexport type CopilotRuntimeLearningContext =\n | {\n readonly surface: \"web\";\n readonly request: Request;\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n }\n | {\n readonly surface: \"channel\";\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n readonly deliveryId: string;\n };\n\n/** Assigns each Intelligence Thread to one developer-created Learning Container. */\nexport interface CopilotRuntimeLearningConfig {\n readonly containerId:\n | string\n | ((\n input: CopilotRuntimeLearningContext,\n ) => MaybePromise<string | null | undefined>);\n}\n\nconst STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** Validates and returns a stable Learning Container ID. */\nexport function assertStableLearningContainerId(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > 64 ||\n !STABLE_CONTAINER_ID.test(value)\n ) {\n throw new Error(\n \"Learning Container must use a 1-64 character stable ID with lowercase letters, numbers, and single hyphens\",\n );\n }\n return value;\n}\n\n/** Resolves and validates a public Intelligence Learning Container selection. */\nexport async function resolveLearningContainerSelector(\n selector: GetLearningContainerId,\n input: LearningContainerSelectorInput,\n): Promise<string | undefined> {\n const value = await selector(input);\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n\n/** Resolves the configured Container once for one web or Channel run. */\nexport async function resolveLearningContainerId(\n config: CopilotRuntimeLearningConfig | undefined,\n input: CopilotRuntimeLearningContext,\n): Promise<string | undefined> {\n if (config === undefined) return undefined;\n const value =\n typeof config.containerId === \"function\"\n ? await config.containerId(input)\n : config.containerId;\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"learning.mjs","names":[],"sources":["../../../../src/v2/runtime/core/learning.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/** Checks configuration without invoking a selector that requires a real run. */\nexport function hasLearningContainerConfiguration(\n runtime: CopilotRuntimeLike,\n): boolean {\n return (\n runtime.intelligence?.ɵgetLearningContainerId?.() !== undefined ||\n runtime.learning?.containerId !== undefined\n );\n}\n\n/** Application user resolved by an Intelligence runtime. */\nexport interface CopilotRuntimeUser {\n readonly id: string;\n readonly name: string;\n}\n\n/** Context for choosing a Learning Container through the public Intelligence SDK. */\nexport type LearningContainerSelectorInput =\n | {\n readonly surface: \"web\";\n readonly user: CopilotRuntimeUser;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n }\n | {\n readonly surface: \"channel\";\n readonly user: CopilotRuntimeUser | null;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n };\n\n/** Chooses one developer-created Learning Container for an Intelligence run. */\nexport type GetLearningContainerId = (\n input: LearningContainerSelectorInput,\n) => MaybePromise<string | null | undefined>;\n\n/** Context for choosing one Learning Container for an Intelligence run. */\nexport type CopilotRuntimeLearningContext =\n | {\n readonly surface: \"web\";\n readonly request: Request;\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n }\n | {\n readonly surface: \"channel\";\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n readonly deliveryId: string;\n };\n\n/** Assigns each Intelligence Thread to one developer-created Learning Container. */\nexport interface CopilotRuntimeLearningConfig {\n readonly containerId:\n | string\n | ((\n input: CopilotRuntimeLearningContext,\n ) => MaybePromise<string | null | undefined>);\n}\n\nconst STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** Validates and returns a stable Learning Container ID. */\nexport function assertStableLearningContainerId(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > 64 ||\n !STABLE_CONTAINER_ID.test(value)\n ) {\n throw new Error(\n \"Learning Container must use a 1-64 character stable ID with lowercase letters, numbers, and single hyphens\",\n );\n }\n return value;\n}\n\n/** Resolves and validates a public Intelligence Learning Container selection. */\nexport async function resolveLearningContainerSelector(\n selector: GetLearningContainerId,\n input: LearningContainerSelectorInput,\n): Promise<string | undefined> {\n const value = await selector(input);\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n\n/** Resolves the configured Container once for one web or Channel run. */\nexport async function resolveLearningContainerId(\n config: CopilotRuntimeLearningConfig | undefined,\n input: CopilotRuntimeLearningContext,\n): Promise<string | undefined> {\n if (config === undefined) return undefined;\n const value =\n typeof config.containerId === \"function\"\n ? await config.containerId(input)\n : config.containerId;\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n"],"mappings":";;;AAKA,SAAgB,kCACd,SACS;AACT,QACE,QAAQ,cAAc,2BAA2B,KAAK,UACtD,QAAQ,UAAU,gBAAgB;;AA0DtC,MAAM,sBAAsB;;AAG5B,SAAgB,gCAAgC,OAAwB;AACtE,KACE,OAAO,UAAU,YACjB,MAAM,SAAS,KACf,MAAM,SAAS,MACf,CAAC,oBAAoB,KAAK,MAAM,CAEhC,OAAM,IAAI,MACR,6GACD;AAEH,QAAO;;;AAIT,eAAsB,iCACpB,UACA,OAC6B;CAC7B,MAAM,QAAQ,MAAM,SAAS,MAAM;AACnC,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,gCAAgC,MAAM;;;AAI/C,eAAsB,2BACpB,QACA,OAC6B;AAC7B,KAAI,WAAW,OAAW,QAAO;CACjC,MAAM,QACJ,OAAO,OAAO,gBAAgB,aAC1B,MAAM,OAAO,YAAY,MAAM,GAC/B,OAAO;AACb,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,gCAAgC,MAAM"}
|
|
@@ -7,6 +7,7 @@ import { DebugEventBus } from "./debug-event-bus.cjs";
|
|
|
7
7
|
import { AgentRunner } from "../runner/agent-runner.cjs";
|
|
8
8
|
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./learning.cjs";
|
|
9
9
|
import { CopilotKitIntelligence } from "../intelligence-platform/client.cjs";
|
|
10
|
+
import "../intelligence-platform/index.cjs";
|
|
10
11
|
import { TelemetryCapture as TelemetryCapture$1 } from "../telemetry/telemetry-client.cjs";
|
|
11
12
|
import { DebugConfig, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, ResolvedDebugConfig, RuntimeMode } from "@copilotkit/shared";
|
|
12
13
|
import { LicenseChecker } from "@copilotkit/license-verifier";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cAgEa,OAAA;AAAA,UAEH,mCAAA;;EAER,MAAA;AAAA;AAJiC;AAAA,KAQvB,mBAAA,GAAsB,eAAA;yFAEhC,OAAA;AAAA;AAAA,UAGe,aAAA;EALc;EAO7B,OAAA,EAAS,mBAAA;AAAA;AAAA,UAGM,uBAAA,SAAgC,mCAAA;AAAA,KAErC,sBAAA,aAAmC,uBAAA;AAAA,UAErC,yBAAA;EAPR;;AAGF;;E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AAW,4BAAA;EAAA,SACX,IAAA;EA9MT;EAAA,gBAiNgB,oBAAA;EAhNhB;EAAA,gBAkNgB,8BAAA;cAEJ,OAAA,EAAS,iCAAA;AAAA;AAAA,iBAmJP,qBAAA,CACd,OAAA,EAAS,kBAAA,GACR,OAAA,IAAW,8BAAA;;;;;;;;;;;iBAcE,aAAA,CACd,IAAA,EAAM,qBAAA,WACL,IAAA,IAAQ,WAAA,CAAY,qBAAA;;;;;;;;UAWN,2BAAA;EAxXf;;;EAAA,SA4XS,4BAAA;AAAA;;;;;;;UASM,cAAA,SAAuB,kBAAA;EA5W3B;EA8WX,SAAA,EAAW,kBAAA;EA9W4B;EAgXvC,mBAAA;EA7WqC;EA+WrC,cAAA;EA/W+D;EAiX/D,aAAA;EAhXA;EAkXA,4BAAA;EAjXa;EAmXb,QAAA,GAAW,OAAA;EAnXkB;EAqX7B,QAAA,GAAW,4BAAA;AAAA;;;;;;;;;;;;;;;UAiBI,yBAAA;EAAA,KAEb,OAAA,EAAS,qCAAA;IAGD,YAAA,EAAc,oBAAA;IACd,MAAA,GAAS,0BAAA;IACT,QAAA,EAAU,gBAAA;EAAA;IAGV,YAAA;IACA,MAAA;IACA,QAAA,EAAU,gBAAA;EAAA,KAGjB,cAAA,GAAiB,2BAAA;EAAA,KACf,OAAA,EAAS,qBAAA,GAAwB,cAAA;AAAA;AAzYvC;;;;;;;;;;;AAAA,cAgiBY,cAAA,EAAgB,yBAAA"}
|
|
@@ -65,8 +65,7 @@ function buildPreParsedRequest(req, res) {
|
|
|
65
65
|
}
|
|
66
66
|
function hasPreParsedBody(req) {
|
|
67
67
|
if (req.body === void 0 || req.body === null) return false;
|
|
68
|
-
|
|
69
|
-
return Boolean(req.readableEnded || req.complete || state?.ended || state?.endEmitted);
|
|
68
|
+
return Boolean(req.readableEnded);
|
|
70
69
|
}
|
|
71
70
|
function synthesizeBody(body) {
|
|
72
71
|
if (Buffer.isBuffer(body) || body instanceof Uint8Array) return { body };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-fetch-bridge.cjs","names":["createCopilotNodeHandler"],"sources":["../../../../src/v2/runtime/endpoints/express-fetch-bridge.ts"],"sourcesContent":["/**\n * Express-aware Node ↔ Fetch bridge.\n *\n * When Express body-parsing middleware (e.g. `express.json()`) runs before the\n * CopilotKit router, the Node request stream is already consumed and `req.body`\n * holds the parsed content. The generic `createCopilotNodeHandler` (which uses\n * `@remix-run/node-fetch-server`) would hang because it tries to read from the\n * exhausted stream.\n *\n * This module detects the pre-parsed case and re-serialises `req.body` into the\n * Fetch `Request`, falling back to the generic `createCopilotNodeHandler` when the\n * stream is still available.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { sendResponse } from \"@remix-run/node-fetch-server\";\nimport { createCopilotNodeHandler } from \"./node-fetch-handler\";\nimport type { CopilotRuntimeFetchHandler } from \"../core/fetch-handler\";\nimport { logger } from \"@copilotkit/shared\";\n\nconst METHODS_WITHOUT_BODY = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\nexport type ExpressNodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n) => Promise<void>;\n\n/**\n * Creates a Node HTTP handler from a fetch handler, with Express body-parser\n * compatibility. Use this instead of `createNodeFetchHandler` in Express adapters.\n *\n * When the body stream hasn't been consumed, delegates to the generic\n * `createCopilotNodeHandler`. Only intercepts when Express middleware has\n * pre-parsed the body.\n */\nexport function createExpressNodeHandler(\n handler: CopilotRuntimeFetchHandler,\n): ExpressNodeHandler {\n const nodeHandler = createCopilotNodeHandler(handler);\n\n return async (req: IncomingMessage, res: ServerResponse) => {\n const method = (req.method ?? \"GET\").toUpperCase();\n\n // Fast path: if no body parser consumed the stream, use the generic handler.\n if (METHODS_WITHOUT_BODY.has(method) || !hasPreParsedBody(req)) {\n return nodeHandler(req, res);\n }\n\n // Slow path: body was consumed by Express middleware — rebuild the Request.\n try {\n const fetchReq = buildPreParsedRequest(req, res);\n const fetchRes = await handler(fetchReq);\n await sendResponse(res, fetchRes);\n } catch (err: unknown) {\n logger.error({ err }, \"Error in Express fetch bridge (pre-parsed path)\");\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end(\"Internal Server Error\");\n }\n }\n };\n}\n\n/**\n * Build a Fetch Request from a Node IncomingMessage whose body stream has\n * already been consumed by an Express body parser.\n */\nfunction buildPreParsedRequest(\n req: IncomingMessage,\n res: ServerResponse,\n): Request {\n const expressReq = req as IncomingMessage & { body?: unknown };\n const method = (req.method ?? \"GET\").toUpperCase();\n\n const protocol = (req as any).protocol || \"http\";\n const host = req.headers.host ?? \"localhost\";\n const url = `${protocol}://${host}${(req as any).originalUrl ?? req.url ?? \"\"}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n\n // Wire an AbortSignal so client disconnects propagate to the fetch handler\n const controller = new AbortController();\n res.on(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers,\n signal: controller.signal,\n };\n\n const { body, contentType } = synthesizeBody(expressReq.body);\n if (contentType) {\n headers.set(\"content-type\", contentType);\n }\n headers.delete(\"content-length\");\n if (body !== undefined) {\n init.body = body;\n }\n\n return new Request(url, init);\n}\n\nfunction hasPreParsedBody(req: IncomingMessage & { body?: unknown }): boolean {\n if (req.body === undefined || req.body === null) return false;\n\n //
|
|
1
|
+
{"version":3,"file":"express-fetch-bridge.cjs","names":["createCopilotNodeHandler"],"sources":["../../../../src/v2/runtime/endpoints/express-fetch-bridge.ts"],"sourcesContent":["/**\n * Express-aware Node ↔ Fetch bridge.\n *\n * When Express body-parsing middleware (e.g. `express.json()`) runs before the\n * CopilotKit router, the Node request stream is already consumed and `req.body`\n * holds the parsed content. The generic `createCopilotNodeHandler` (which uses\n * `@remix-run/node-fetch-server`) would hang because it tries to read from the\n * exhausted stream.\n *\n * This module detects the pre-parsed case and re-serialises `req.body` into the\n * Fetch `Request`, falling back to the generic `createCopilotNodeHandler` when the\n * stream is still available.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { sendResponse } from \"@remix-run/node-fetch-server\";\nimport { createCopilotNodeHandler } from \"./node-fetch-handler\";\nimport type { CopilotRuntimeFetchHandler } from \"../core/fetch-handler\";\nimport { logger } from \"@copilotkit/shared\";\n\nconst METHODS_WITHOUT_BODY = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\nexport type ExpressNodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n) => Promise<void>;\n\n/**\n * Creates a Node HTTP handler from a fetch handler, with Express body-parser\n * compatibility. Use this instead of `createNodeFetchHandler` in Express adapters.\n *\n * When the body stream hasn't been consumed, delegates to the generic\n * `createCopilotNodeHandler`. Only intercepts when Express middleware has\n * pre-parsed the body.\n */\nexport function createExpressNodeHandler(\n handler: CopilotRuntimeFetchHandler,\n): ExpressNodeHandler {\n const nodeHandler = createCopilotNodeHandler(handler);\n\n return async (req: IncomingMessage, res: ServerResponse) => {\n const method = (req.method ?? \"GET\").toUpperCase();\n\n // Fast path: if no body parser consumed the stream, use the generic handler.\n if (METHODS_WITHOUT_BODY.has(method) || !hasPreParsedBody(req)) {\n return nodeHandler(req, res);\n }\n\n // Slow path: body was consumed by Express middleware — rebuild the Request.\n try {\n const fetchReq = buildPreParsedRequest(req, res);\n const fetchRes = await handler(fetchReq);\n await sendResponse(res, fetchRes);\n } catch (err: unknown) {\n logger.error({ err }, \"Error in Express fetch bridge (pre-parsed path)\");\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end(\"Internal Server Error\");\n }\n }\n };\n}\n\n/**\n * Build a Fetch Request from a Node IncomingMessage whose body stream has\n * already been consumed by an Express body parser.\n */\nfunction buildPreParsedRequest(\n req: IncomingMessage,\n res: ServerResponse,\n): Request {\n const expressReq = req as IncomingMessage & { body?: unknown };\n const method = (req.method ?? \"GET\").toUpperCase();\n\n const protocol = (req as any).protocol || \"http\";\n const host = req.headers.host ?? \"localhost\";\n const url = `${protocol}://${host}${(req as any).originalUrl ?? req.url ?? \"\"}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n\n // Wire an AbortSignal so client disconnects propagate to the fetch handler\n const controller = new AbortController();\n res.on(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers,\n signal: controller.signal,\n };\n\n const { body, contentType } = synthesizeBody(expressReq.body);\n if (contentType) {\n headers.set(\"content-type\", contentType);\n }\n headers.delete(\"content-length\");\n if (body !== undefined) {\n init.body = body;\n }\n\n return new Request(url, init);\n}\n\nfunction hasPreParsedBody(req: IncomingMessage & { body?: unknown }): boolean {\n if (req.body === undefined || req.body === null) return false;\n\n // Only `readableEnded` means \"a parser drained this stream to its end\".\n // `req.complete` and the private `_readableState.ended` are set by the HTTP\n // parser once the socket has all the bytes, whether or not anything read them.\n //\n // That distinction matters because `req.body` being set does not prove a parser\n // ran: body-parser 1.x (Express 4) assigns `req.body = req.body || {}` before\n // its own content-type checks, so a request it declines to parse — multipart\n // upload, text/plain — reaches us with `req.body === {}` and a full, unread\n // stream. Treating that as pre-parsed rebuilt the request from `{}` and\n // dropped the real payload.\n return Boolean(req.readableEnded);\n}\n\nfunction synthesizeBody(body: unknown): {\n body?: BodyInit;\n contentType?: string;\n} {\n if (Buffer.isBuffer(body) || body instanceof Uint8Array) {\n // Buffer/Uint8Array<ArrayBufferLike> are valid fetch bodies at runtime,\n // but the DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return { body: body as BodyInit };\n }\n if (typeof body === \"string\") {\n return { body };\n }\n if (typeof body === \"object\" && body !== null) {\n return { body: JSON.stringify(body), contentType: \"application/json\" };\n }\n return {};\n}\n"],"mappings":";;;;;;;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AAiB;AAChC,KAAI,SAAS,OACX,MAAK,OAAO;AAGd,QAAO,IAAI,QAAQ,KAAK,KAAK;;AAG/B,SAAS,iBAAiB,KAAoD;AAC5E,KAAI,IAAI,SAAS,UAAa,IAAI,SAAS,KAAM,QAAO;AAYxD,QAAO,QAAQ,IAAI,cAAc;;AAGnC,SAAS,eAAe,MAGtB;AACA,KAAI,OAAO,SAAS,KAAK,IAAI,gBAAgB,WAG3C,QAAO,EAAQ,MAAkB;AAEnC,KAAI,OAAO,SAAS,SAClB,QAAO,EAAE,MAAM;AAEjB,KAAI,OAAO,SAAS,YAAY,SAAS,KACvC,QAAO;EAAE,MAAM,KAAK,UAAU,KAAK;EAAE,aAAa;EAAoB;AAExE,QAAO,EAAE"}
|
|
@@ -64,8 +64,7 @@ function buildPreParsedRequest(req, res) {
|
|
|
64
64
|
}
|
|
65
65
|
function hasPreParsedBody(req) {
|
|
66
66
|
if (req.body === void 0 || req.body === null) return false;
|
|
67
|
-
|
|
68
|
-
return Boolean(req.readableEnded || req.complete || state?.ended || state?.endEmitted);
|
|
67
|
+
return Boolean(req.readableEnded);
|
|
69
68
|
}
|
|
70
69
|
function synthesizeBody(body) {
|
|
71
70
|
if (Buffer.isBuffer(body) || body instanceof Uint8Array) return { body };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-fetch-bridge.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/express-fetch-bridge.ts"],"sourcesContent":["/**\n * Express-aware Node ↔ Fetch bridge.\n *\n * When Express body-parsing middleware (e.g. `express.json()`) runs before the\n * CopilotKit router, the Node request stream is already consumed and `req.body`\n * holds the parsed content. The generic `createCopilotNodeHandler` (which uses\n * `@remix-run/node-fetch-server`) would hang because it tries to read from the\n * exhausted stream.\n *\n * This module detects the pre-parsed case and re-serialises `req.body` into the\n * Fetch `Request`, falling back to the generic `createCopilotNodeHandler` when the\n * stream is still available.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { sendResponse } from \"@remix-run/node-fetch-server\";\nimport { createCopilotNodeHandler } from \"./node-fetch-handler\";\nimport type { CopilotRuntimeFetchHandler } from \"../core/fetch-handler\";\nimport { logger } from \"@copilotkit/shared\";\n\nconst METHODS_WITHOUT_BODY = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\nexport type ExpressNodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n) => Promise<void>;\n\n/**\n * Creates a Node HTTP handler from a fetch handler, with Express body-parser\n * compatibility. Use this instead of `createNodeFetchHandler` in Express adapters.\n *\n * When the body stream hasn't been consumed, delegates to the generic\n * `createCopilotNodeHandler`. Only intercepts when Express middleware has\n * pre-parsed the body.\n */\nexport function createExpressNodeHandler(\n handler: CopilotRuntimeFetchHandler,\n): ExpressNodeHandler {\n const nodeHandler = createCopilotNodeHandler(handler);\n\n return async (req: IncomingMessage, res: ServerResponse) => {\n const method = (req.method ?? \"GET\").toUpperCase();\n\n // Fast path: if no body parser consumed the stream, use the generic handler.\n if (METHODS_WITHOUT_BODY.has(method) || !hasPreParsedBody(req)) {\n return nodeHandler(req, res);\n }\n\n // Slow path: body was consumed by Express middleware — rebuild the Request.\n try {\n const fetchReq = buildPreParsedRequest(req, res);\n const fetchRes = await handler(fetchReq);\n await sendResponse(res, fetchRes);\n } catch (err: unknown) {\n logger.error({ err }, \"Error in Express fetch bridge (pre-parsed path)\");\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end(\"Internal Server Error\");\n }\n }\n };\n}\n\n/**\n * Build a Fetch Request from a Node IncomingMessage whose body stream has\n * already been consumed by an Express body parser.\n */\nfunction buildPreParsedRequest(\n req: IncomingMessage,\n res: ServerResponse,\n): Request {\n const expressReq = req as IncomingMessage & { body?: unknown };\n const method = (req.method ?? \"GET\").toUpperCase();\n\n const protocol = (req as any).protocol || \"http\";\n const host = req.headers.host ?? \"localhost\";\n const url = `${protocol}://${host}${(req as any).originalUrl ?? req.url ?? \"\"}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n\n // Wire an AbortSignal so client disconnects propagate to the fetch handler\n const controller = new AbortController();\n res.on(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers,\n signal: controller.signal,\n };\n\n const { body, contentType } = synthesizeBody(expressReq.body);\n if (contentType) {\n headers.set(\"content-type\", contentType);\n }\n headers.delete(\"content-length\");\n if (body !== undefined) {\n init.body = body;\n }\n\n return new Request(url, init);\n}\n\nfunction hasPreParsedBody(req: IncomingMessage & { body?: unknown }): boolean {\n if (req.body === undefined || req.body === null) return false;\n\n //
|
|
1
|
+
{"version":3,"file":"express-fetch-bridge.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/express-fetch-bridge.ts"],"sourcesContent":["/**\n * Express-aware Node ↔ Fetch bridge.\n *\n * When Express body-parsing middleware (e.g. `express.json()`) runs before the\n * CopilotKit router, the Node request stream is already consumed and `req.body`\n * holds the parsed content. The generic `createCopilotNodeHandler` (which uses\n * `@remix-run/node-fetch-server`) would hang because it tries to read from the\n * exhausted stream.\n *\n * This module detects the pre-parsed case and re-serialises `req.body` into the\n * Fetch `Request`, falling back to the generic `createCopilotNodeHandler` when the\n * stream is still available.\n */\n\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { sendResponse } from \"@remix-run/node-fetch-server\";\nimport { createCopilotNodeHandler } from \"./node-fetch-handler\";\nimport type { CopilotRuntimeFetchHandler } from \"../core/fetch-handler\";\nimport { logger } from \"@copilotkit/shared\";\n\nconst METHODS_WITHOUT_BODY = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\nexport type ExpressNodeHandler = (\n req: IncomingMessage,\n res: ServerResponse,\n) => Promise<void>;\n\n/**\n * Creates a Node HTTP handler from a fetch handler, with Express body-parser\n * compatibility. Use this instead of `createNodeFetchHandler` in Express adapters.\n *\n * When the body stream hasn't been consumed, delegates to the generic\n * `createCopilotNodeHandler`. Only intercepts when Express middleware has\n * pre-parsed the body.\n */\nexport function createExpressNodeHandler(\n handler: CopilotRuntimeFetchHandler,\n): ExpressNodeHandler {\n const nodeHandler = createCopilotNodeHandler(handler);\n\n return async (req: IncomingMessage, res: ServerResponse) => {\n const method = (req.method ?? \"GET\").toUpperCase();\n\n // Fast path: if no body parser consumed the stream, use the generic handler.\n if (METHODS_WITHOUT_BODY.has(method) || !hasPreParsedBody(req)) {\n return nodeHandler(req, res);\n }\n\n // Slow path: body was consumed by Express middleware — rebuild the Request.\n try {\n const fetchReq = buildPreParsedRequest(req, res);\n const fetchRes = await handler(fetchReq);\n await sendResponse(res, fetchRes);\n } catch (err: unknown) {\n logger.error({ err }, \"Error in Express fetch bridge (pre-parsed path)\");\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end(\"Internal Server Error\");\n }\n }\n };\n}\n\n/**\n * Build a Fetch Request from a Node IncomingMessage whose body stream has\n * already been consumed by an Express body parser.\n */\nfunction buildPreParsedRequest(\n req: IncomingMessage,\n res: ServerResponse,\n): Request {\n const expressReq = req as IncomingMessage & { body?: unknown };\n const method = (req.method ?? \"GET\").toUpperCase();\n\n const protocol = (req as any).protocol || \"http\";\n const host = req.headers.host ?? \"localhost\";\n const url = `${protocol}://${host}${(req as any).originalUrl ?? req.url ?? \"\"}`;\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value === undefined) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n\n // Wire an AbortSignal so client disconnects propagate to the fetch handler\n const controller = new AbortController();\n res.on(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers,\n signal: controller.signal,\n };\n\n const { body, contentType } = synthesizeBody(expressReq.body);\n if (contentType) {\n headers.set(\"content-type\", contentType);\n }\n headers.delete(\"content-length\");\n if (body !== undefined) {\n init.body = body;\n }\n\n return new Request(url, init);\n}\n\nfunction hasPreParsedBody(req: IncomingMessage & { body?: unknown }): boolean {\n if (req.body === undefined || req.body === null) return false;\n\n // Only `readableEnded` means \"a parser drained this stream to its end\".\n // `req.complete` and the private `_readableState.ended` are set by the HTTP\n // parser once the socket has all the bytes, whether or not anything read them.\n //\n // That distinction matters because `req.body` being set does not prove a parser\n // ran: body-parser 1.x (Express 4) assigns `req.body = req.body || {}` before\n // its own content-type checks, so a request it declines to parse — multipart\n // upload, text/plain — reaches us with `req.body === {}` and a full, unread\n // stream. Treating that as pre-parsed rebuilt the request from `{}` and\n // dropped the real payload.\n return Boolean(req.readableEnded);\n}\n\nfunction synthesizeBody(body: unknown): {\n body?: BodyInit;\n contentType?: string;\n} {\n if (Buffer.isBuffer(body) || body instanceof Uint8Array) {\n // Buffer/Uint8Array<ArrayBufferLike> are valid fetch bodies at runtime,\n // but the DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return { body: body as BodyInit };\n }\n if (typeof body === \"string\") {\n return { body };\n }\n if (typeof body === \"object\" && body !== null) {\n return { body: JSON.stringify(body), contentType: \"application/json\" };\n }\n return {};\n}\n"],"mappings":";;;;;;AAoBA,MAAM,uBAAuB,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAU,CAAC;;;;;;;;;AAehE,SAAgB,yBACd,SACoB;CACpB,MAAM,cAAc,yBAAyB,QAAQ;AAErD,QAAO,OAAO,KAAsB,QAAwB;EAC1D,MAAM,UAAU,IAAI,UAAU,OAAO,aAAa;AAGlD,MAAI,qBAAqB,IAAI,OAAO,IAAI,CAAC,iBAAiB,IAAI,CAC5D,QAAO,YAAY,KAAK,IAAI;AAI9B,MAAI;AAGF,SAAM,aAAa,KADF,MAAM,QADN,sBAAsB,KAAK,IAAI,CACR,CACP;WAC1B,KAAc;AACrB,UAAO,MAAM,EAAE,KAAK,EAAE,kDAAkD;AACxE,OAAI,CAAC,IAAI,aAAa;A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|
@@ -9,7 +9,7 @@ let cors = require("cors");
|
|
|
9
9
|
cors = require_runtime.__toESM(cors);
|
|
10
10
|
|
|
11
11
|
//#region src/v2/runtime/endpoints/express.ts
|
|
12
|
-
function createCopilotExpressHandler({ runtime, basePath, mode = "multi-route", cors: corsOption = true, hooks,
|
|
12
|
+
function createCopilotExpressHandler({ runtime, basePath, mode = "multi-route", cors: corsOption = true, hooks, activateChannels, __channelEngine }) {
|
|
13
13
|
const normalizedBase = normalizeBasePath(basePath);
|
|
14
14
|
const handler = require_fetch_handler.createCopilotRuntimeHandler({
|
|
15
15
|
runtime,
|
|
@@ -17,7 +17,6 @@ function createCopilotExpressHandler({ runtime, basePath, mode = "multi-route",
|
|
|
17
17
|
mode,
|
|
18
18
|
cors: false,
|
|
19
19
|
hooks,
|
|
20
|
-
inspectorLearning,
|
|
21
20
|
activateChannels,
|
|
22
21
|
__channelEngine
|
|
23
22
|
});
|
|
@@ -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 { 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
|
|
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"}
|
|
@@ -38,11 +38,6 @@ interface CopilotExpressEndpointParams {
|
|
|
38
38
|
* Lifecycle hooks for request processing.
|
|
39
39
|
*/
|
|
40
40
|
hooks?: CopilotRuntimeHooks;
|
|
41
|
-
/**
|
|
42
|
-
* Whether to expose the debug-gated Inspector Learning snapshot route.
|
|
43
|
-
* Defaults to `false`.
|
|
44
|
-
*/
|
|
45
|
-
inspectorLearning?: boolean;
|
|
46
41
|
/**
|
|
47
42
|
* Whether the underlying handler builds the control surface for the runtime's
|
|
48
43
|
* declared managed Channels — and, because Express is a long-running host,
|
|
@@ -63,7 +58,6 @@ declare function createCopilotExpressHandler({
|
|
|
63
58
|
mode,
|
|
64
59
|
cors: corsOption,
|
|
65
60
|
hooks,
|
|
66
|
-
inspectorLearning,
|
|
67
61
|
activateChannels,
|
|
68
62
|
__channelEngine
|
|
69
63
|
}: CopilotExpressEndpointParams): CopilotExpressRouter;
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
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"}
|
|
@@ -38,11 +38,6 @@ interface CopilotExpressEndpointParams {
|
|
|
38
38
|
* Lifecycle hooks for request processing.
|
|
39
39
|
*/
|
|
40
40
|
hooks?: CopilotRuntimeHooks;
|
|
41
|
-
/**
|
|
42
|
-
* Whether to expose the debug-gated Inspector Learning snapshot route.
|
|
43
|
-
* Defaults to `false`.
|
|
44
|
-
*/
|
|
45
|
-
inspectorLearning?: boolean;
|
|
46
41
|
/**
|
|
47
42
|
* Whether the underlying handler builds the control surface for the runtime's
|
|
48
43
|
* declared managed Channels — and, because Express is a long-running host,
|
|
@@ -63,7 +58,6 @@ declare function createCopilotExpressHandler({
|
|
|
63
58
|
mode,
|
|
64
59
|
cors: corsOption,
|
|
65
60
|
hooks,
|
|
66
|
-
inspectorLearning,
|
|
67
61
|
activateChannels,
|
|
68
62
|
__channelEngine
|
|
69
63
|
}: CopilotExpressEndpointParams): CopilotExpressRouter;
|
|
@@ -1 +1 @@
|
|
|
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;
|
|
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"}
|