@copilotkit/runtime 1.61.0 → 1.61.2
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/agent/converters/aisdk.cjs +52 -1
- package/dist/agent/converters/aisdk.cjs.map +1 -1
- package/dist/agent/converters/aisdk.d.cts +6 -2
- package/dist/agent/converters/aisdk.d.cts.map +1 -1
- package/dist/agent/converters/aisdk.d.mts +6 -2
- package/dist/agent/converters/aisdk.d.mts.map +1 -1
- package/dist/agent/converters/aisdk.mjs +52 -1
- package/dist/agent/converters/aisdk.mjs.map +1 -1
- package/dist/agent/converters/tanstack.cjs +68 -9
- package/dist/agent/converters/tanstack.cjs.map +1 -1
- package/dist/agent/converters/tanstack.d.cts +30 -2
- package/dist/agent/converters/tanstack.d.cts.map +1 -1
- package/dist/agent/converters/tanstack.d.mts +30 -2
- package/dist/agent/converters/tanstack.d.mts.map +1 -1
- package/dist/agent/converters/tanstack.mjs +68 -9
- package/dist/agent/converters/tanstack.mjs.map +1 -1
- package/dist/agent/index.cjs +165 -39
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +42 -4
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +42 -4
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +165 -40
- package/dist/agent/index.mjs.map +1 -1
- package/dist/graphql/message-conversion/agui-to-gql.cjs +5 -3
- package/dist/graphql/message-conversion/agui-to-gql.cjs.map +1 -1
- package/dist/graphql/message-conversion/agui-to-gql.mjs +5 -3
- package/dist/graphql/message-conversion/agui-to-gql.mjs.map +1 -1
- package/dist/lib/integrations/node-http/request-handler.cjs.map +1 -1
- package/dist/lib/integrations/node-http/request-handler.mjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/package.cjs +3 -3
- package/dist/package.mjs +3 -3
- package/dist/service-adapters/openai/openai-assistant-adapter.cjs.map +1 -1
- package/dist/service-adapters/openai/openai-assistant-adapter.d.cts.map +1 -1
- package/dist/service-adapters/openai/openai-assistant-adapter.d.mts.map +1 -1
- package/dist/service-adapters/openai/openai-assistant-adapter.mjs.map +1 -1
- package/dist/service-adapters/openai/utils.cjs.map +1 -1
- package/dist/service-adapters/openai/utils.mjs.map +1 -1
- package/dist/v2/index.cjs +2 -0
- package/dist/v2/index.d.cts +3 -3
- package/dist/v2/index.d.mts +3 -3
- package/dist/v2/index.mjs +3 -3
- package/dist/v2/runtime/core/fetch-handler.cjs +5 -4
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +5 -4
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/runtime.cjs +3 -3
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +10 -3
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +10 -3
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs +3 -3
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/endpoints/express-fetch-bridge.cjs.map +1 -1
- package/dist/v2/runtime/endpoints/express-fetch-bridge.mjs.map +1 -1
- package/dist/v2/runtime/endpoints/single-route-helpers.cjs +1 -1
- package/dist/v2/runtime/endpoints/single-route-helpers.cjs.map +1 -1
- package/dist/v2/runtime/endpoints/single-route-helpers.mjs +1 -1
- package/dist/v2/runtime/endpoints/single-route-helpers.mjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.cjs +14 -1
- package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs +14 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +4 -3
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +4 -3
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/thread-names.cjs +0 -2
- package/dist/v2/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/thread-names.mjs +0 -2
- package/dist/v2/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.cjs +6 -6
- package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.mjs +6 -6
- package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +8 -4
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +8 -4
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -1
- package/dist/v2/runtime/index.d.mts +1 -1
- package/dist/v2/runtime/runner/agent-runner.cjs +4 -0
- package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.cts +21 -1
- package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.d.mts +21 -1
- package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -1
- package/dist/v2/runtime/runner/agent-runner.mjs +4 -1
- package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.cjs +4 -0
- package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.cts +1 -0
- package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.mts +1 -0
- package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.mjs +4 -0
- package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
- package/dist/v2/runtime/runner/index.d.cts +1 -1
- package/dist/v2/runtime/runner/index.d.mts +1 -1
- package/dist/v2/runtime/runner/index.mjs +1 -1
- package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -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\nimport type { CopilotRuntimeLike } from \"./runtime\";\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 { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n}\n\nexport type CopilotRuntimeFetchHandler = (\n request: Request,\n) => Promise<Response>;\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\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 return async (request: Request): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route);\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route);\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/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({ runtime, request });\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 \"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 }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"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\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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\nimport type { CopilotRuntimeLike } from \"./runtime\";\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 { handleConnectAgent } from \"../handlers/handle-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n expectString,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n}\n\nexport type CopilotRuntimeFetchHandler = (\n request: Request,\n) => Promise<Response>;\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\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 return async (request: Request): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(request, basePath, path);\n route = resolved.route;\n const { methodCall } = resolved;\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: false,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client.\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path },\n \"Error running after request middleware\",\n );\n });\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n { err: hookError, originalErr: error, url: request.url, path },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: { threadEndpointsEnabled: boolean },\n): Promise<Response> {\n switch (route.method) {\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return Promise.resolve(handleClearThreads({ runtime, request }));\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"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 }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n if (!pathname.startsWith(normalizedBase)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n }\n\n return { route, methodCall };\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"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":";;;;;;;;;;;;;;;;;;AAoHA,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;AAEjE,8BAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,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AI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
@@ -37,6 +37,8 @@ var BaseCopilotRuntime = class {
|
|
|
37
37
|
this.mcpApps = mcpApps;
|
|
38
38
|
this.openGenerativeUI = openGenerativeUI;
|
|
39
39
|
this.runner = runner;
|
|
40
|
+
this.resolvedLicenseToken = options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;
|
|
41
|
+
if (this.resolvedLicenseToken) require_telemetry_client.default.setLicenseToken(this.resolvedLicenseToken);
|
|
40
42
|
if (process.env.NODE_ENV !== "production") this.debugEventBus = new require_debug_event_bus.DebugEventBus();
|
|
41
43
|
this.debug = (0, _copilotkit_shared.resolveDebugConfig)(options.debug);
|
|
42
44
|
if (this.debug.enabled) this.debugLogger = require_logger.createLogger({
|
|
@@ -70,9 +72,7 @@ var CopilotIntelligenceRuntime = class CopilotIntelligenceRuntime extends BaseCo
|
|
|
70
72
|
this.intelligence = options.intelligence;
|
|
71
73
|
this.identifyUser = options.identifyUser;
|
|
72
74
|
this.generateThreadNames = options.generateThreadNames ?? true;
|
|
73
|
-
|
|
74
|
-
this.licenseChecker = (0, _copilotkit_license_verifier.createLicenseChecker)(licenseToken);
|
|
75
|
-
if (licenseToken) require_telemetry_client.default.setLicenseToken(licenseToken);
|
|
75
|
+
this.licenseChecker = (0, _copilotkit_license_verifier.createLicenseChecker)(this.resolvedLicenseToken);
|
|
76
76
|
this.lockTtlSeconds = Math.min(options.lockTtlSeconds ?? 20, CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS);
|
|
77
77
|
this.lockKeyPrefix = options.lockKeyPrefix;
|
|
78
78
|
this.lockHeartbeatIntervalSeconds = Math.min(options.lockHeartbeatIntervalSeconds ?? 15, CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.cjs","names":["pkg","DebugEventBus","createLogger","InMemoryAgentRunner","RUNTIME_MODE_SSE","IntelligenceAgentRunner","RUNTIME_MODE_INTELLIGENCE"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n mode: RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Match license-verifier's env fallback so telemetry attribution\n // resolves the same way as feature gating — otherwise customers who\n // set only COPILOTKIT_LICENSE_TOKEN would get a working license but\n // anonymous telemetry.\n const licenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n this.licenseChecker = createLicenseChecker(licenseToken);\n if (licenseToken) {\n telemetry.setLicenseToken(licenseToken);\n }\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,UAAUA,uBAAI;;;;;;AAyE3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAyGT,IAAe,qBAAf,MAAgE;CAiB9D,YAAY,SAAoC,QAAqB;AACnE,8DAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,SAAS;AAEd,MAAI,QAAQ,IAAI,aAAa,aAC3B,MAAK,gBAAgB,IAAIC,uCAAe;AAE1C,OAAK,mDAA2B,QAAQ,MAAM;AAC9C,MAAI,KAAK,MAAM,QACb,MAAK,cAAcC,4BAAa;GAC9B,OAAO;GACP,WAAW;GACZ,CAAC;;;AAKR,IAAa,oBAAb,cACU,mBAEV;CAIE,YAAY,SAAmC;AAC7C,QAAM,SAAS,QAA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,KAAK,SAAS;;CAGvB,IAAI,SAAsB;AACxB,SAAO,KAAK,SAAS;;CAGvB,IAAI,OAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,UAA4C;AAC9C,SAAO,KAAK,SAAS;;CAGvB,IAAI,mBAA8D;AAChE,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAmD;AACrD,SAAO,KAAK,SAAS;;CAGvB,IAAI,sBAA2C;AAC7C,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS"}
|
|
1
|
+
{"version":3,"file":"runtime.cjs","names":["pkg","DebugEventBus","createLogger","InMemoryAgentRunner","RUNTIME_MODE_SSE","IntelligenceAgentRunner","RUNTIME_MODE_INTELLIGENCE"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: typeof RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n mode: typeof RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's licenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n\n // Attribute telemetry to the licensed customer for *every* runtime mode.\n // Done in the shared base (not the subclasses) so SSE and Intelligence\n // runtimes behave identically — previously only CopilotIntelligenceRuntime\n // set this, so self-hosted SSE users never got a telemetry_id on their\n // runtime events even with a license token configured.\n if (this.resolvedLicenseToken) {\n telemetry.setLicenseToken(this.resolvedLicenseToken);\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken);\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,UAAUA,uBAAI;;;;;;AAyE3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAyGT,IAAe,qBAAf,MAAgE;CAyB9D,YAAY,SAAoC,QAAqB;AACnE,8DAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,SAAS;AAKd,OAAK,uBACH,QAAQ,gBAAgB,QAAQ,IAAI;AAOtC,MAAI,KAAK,qBACP,kCAAU,gBAAgB,KAAK,qBAAqB;AAGtD,MAAI,QAAQ,IAAI,aAAa,aAC3B,MAAK,gBAAgB,IAAIC,uCAAe;AAE1C,OAAK,mDAA2B,QAAQ,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,SAAS;;CAGvB,IAAI,0BAA4E;AAC9E,SAAO,KAAK,SAAS;;CAGvB,IAAI,yBAA0E;AAC5E,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAsB;AACxB,SAAO,KAAK,SAAS;;CAGvB,IAAI,OAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,UAA4C;AAC9C,SAAO,KAAK,SAAS;;CAGvB,IAAI,mBAA8D;AAChE,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAmD;AACrD,SAAO,KAAK,SAAS;;CAGvB,IAAI,sBAA2C;AAC7C,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS"}
|
|
@@ -5,7 +5,7 @@ import { TranscriptionService } from "../transcription-service/transcription-ser
|
|
|
5
5
|
import { DebugEventBus } from "./debug-event-bus.cjs";
|
|
6
6
|
import { AgentRunner } from "../runner/agent-runner.cjs";
|
|
7
7
|
import { CopilotKitIntelligence } from "../intelligence-platform/client.cjs";
|
|
8
|
-
import { DebugConfig, MaybePromise, NonEmptyRecord, ResolvedDebugConfig, RuntimeMode } from "@copilotkit/shared";
|
|
8
|
+
import { DebugConfig, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, ResolvedDebugConfig, RuntimeMode } from "@copilotkit/shared";
|
|
9
9
|
import { LicenseChecker } from "@copilotkit/license-verifier";
|
|
10
10
|
import { AbstractAgent } from "@ag-ui/client";
|
|
11
11
|
import { MCPClientConfig } from "@ag-ui/mcp-apps-middleware";
|
|
@@ -148,7 +148,7 @@ interface CopilotRuntimeLike {
|
|
|
148
148
|
}
|
|
149
149
|
interface CopilotSseRuntimeLike extends CopilotRuntimeLike {
|
|
150
150
|
intelligence?: undefined;
|
|
151
|
-
mode: RUNTIME_MODE_SSE;
|
|
151
|
+
mode: typeof RUNTIME_MODE_SSE;
|
|
152
152
|
}
|
|
153
153
|
interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {
|
|
154
154
|
intelligence: CopilotKitIntelligence;
|
|
@@ -157,7 +157,7 @@ interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {
|
|
|
157
157
|
lockTtlSeconds: number;
|
|
158
158
|
lockKeyPrefix?: string;
|
|
159
159
|
lockHeartbeatIntervalSeconds: number;
|
|
160
|
-
mode: RUNTIME_MODE_INTELLIGENCE;
|
|
160
|
+
mode: typeof RUNTIME_MODE_INTELLIGENCE;
|
|
161
161
|
}
|
|
162
162
|
declare abstract class BaseCopilotRuntime implements CopilotRuntimeLike {
|
|
163
163
|
agents: CopilotRuntimeOptions["agents"];
|
|
@@ -172,6 +172,13 @@ declare abstract class BaseCopilotRuntime implements CopilotRuntimeLike {
|
|
|
172
172
|
readonly debugEventBus?: DebugEventBus;
|
|
173
173
|
debug: ResolvedDebugConfig;
|
|
174
174
|
debugLogger?: CopilotRuntimeLogger;
|
|
175
|
+
/**
|
|
176
|
+
* License token resolved once with the env fallback, so telemetry
|
|
177
|
+
* attribution (below) and subclass feature gating
|
|
178
|
+
* (CopilotIntelligenceRuntime's licenseChecker) read the exact same value
|
|
179
|
+
* instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.
|
|
180
|
+
*/
|
|
181
|
+
protected readonly resolvedLicenseToken?: string;
|
|
175
182
|
abstract readonly intelligence?: CopilotKitIntelligence;
|
|
176
183
|
abstract readonly mode: RuntimeMode;
|
|
177
184
|
constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;cAgCa,OAAA;AAAA,UAEH,mCAAA
|
|
1
|
+
{"version":3,"file":"runtime.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;cAgCa,OAAA;AAAA,UAEH,mCAAA;;EAER,MAAA;AAAA;AAAA,KAGU,mBAAA,GAAsB,eAAA;EALW,uFAO3C,OAAA;AAAA;AAAA,UAGe,aAAA;EALL;EAOV,OAAA,EAAS,mBAAA;AAAA;AAAA,UAGM,uBAAA,SAAgC,mCAAA;AAAA,KAErC,sBAAA,aAAmC,uBAAA;AAAA,UAErC,yBAAA;;;;AAJV;EASE,IAAA,GAAO,mCAAA,GACL,oBAAA;IAV6C;;;AAEjD;;;IAeM,OAAA;EAAA;EAbI;EAgBR,OAAA,GAAU,aAAA;;EAEV,gBAAA,GAAmB,sBAAA;AAAA;;;;UAMJ,mBAAA;EAnBf;EAqBA,OAAA,EAAS,OAAA;AAAA;;;;;KAOC,aAAA,IACV,GAAA,EAAK,mBAAA,KACF,YAAA,CAAa,cAAA,CAAe,MAAA,SAAe,aAAA;;;AAXhD;;;;KAmBY,YAAA,GACR,YAAA,CAAa,cAAA,CAAe,MAAA,SAAe,aAAA,MAC3C,aAAA;AAZJ;;;;;AAAA,iBAmBsB,aAAA,CACpB,MAAA,EAAQ,YAAA,EACR,OAAA,GAAU,OAAA,GACT,OAAA,CAAQ,MAAA,SAAe,aAAA;AAAA,UAYhB,y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,QAC7B,QAAA;cAEI,OAAA,EAAS,qBAAA;EAAA,IAMjB,MAAA,CAAA,GAAU,qBAAA;EAAA,IAIV,oBAAA,CAAA,GAAwB,qBAAA;EAAA,IAIxB,uBAAA,CAAA,GAA2B,qBAAA;EAAA,IAI3B,sBAAA,CAAA,GAA0B,qBAAA;EAAA,IAI1B,MAAA,CAAA,GAAU,WAAA;EAAA,IAIV,IAAA,CAAA,GAAQ,qBAAA;EAAA,IAIR,OAAA,CAAA,GAAW,qBAAA;EAAA,IAIX,gBAAA,CAAA,GAAoB,qBAAA;EAAA,IAIpB,YAAA,CAAA,GAAgB,sBAAA;EAAA,IAIhB,mBAAA,CAAA;EAAA,IAMA,YAAA,CAAA,GAAgB,oBAAA;EAAA,IAMhB,cAAA,CAAA;EAAA,IAMA,aAAA,CAAA;EAAA,IAMA,4BAAA,CAAA;EAAA,IAMA,IAAA,CAAA,GAAQ,WAAA;EAAA,IAIR,cAAA,CAAA,GAAc,cAAA;EAAA,IAId,aAAA,CAAA,GAAa,aAAA;EAAA,IAIb,KAAA,CAAA,GAAS,mBAAA;EAAA,IAIT,WAAA,CAAA,GAAe,oBAAA;AAAA"}
|
|
@@ -5,7 +5,7 @@ import { TranscriptionService } from "../transcription-service/transcription-ser
|
|
|
5
5
|
import { DebugEventBus } from "./debug-event-bus.mjs";
|
|
6
6
|
import { AgentRunner } from "../runner/agent-runner.mjs";
|
|
7
7
|
import { CopilotKitIntelligence } from "../intelligence-platform/client.mjs";
|
|
8
|
-
import { DebugConfig, MaybePromise, NonEmptyRecord, ResolvedDebugConfig, RuntimeMode } from "@copilotkit/shared";
|
|
8
|
+
import { DebugConfig, MaybePromise, NonEmptyRecord, RUNTIME_MODE_INTELLIGENCE, RUNTIME_MODE_SSE, ResolvedDebugConfig, RuntimeMode } from "@copilotkit/shared";
|
|
9
9
|
import { LicenseChecker } from "@copilotkit/license-verifier";
|
|
10
10
|
import { AbstractAgent } from "@ag-ui/client";
|
|
11
11
|
import { A2UIMiddlewareConfig } from "@ag-ui/a2ui-middleware";
|
|
@@ -148,7 +148,7 @@ interface CopilotRuntimeLike {
|
|
|
148
148
|
}
|
|
149
149
|
interface CopilotSseRuntimeLike extends CopilotRuntimeLike {
|
|
150
150
|
intelligence?: undefined;
|
|
151
|
-
mode: RUNTIME_MODE_SSE;
|
|
151
|
+
mode: typeof RUNTIME_MODE_SSE;
|
|
152
152
|
}
|
|
153
153
|
interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {
|
|
154
154
|
intelligence: CopilotKitIntelligence;
|
|
@@ -157,7 +157,7 @@ interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {
|
|
|
157
157
|
lockTtlSeconds: number;
|
|
158
158
|
lockKeyPrefix?: string;
|
|
159
159
|
lockHeartbeatIntervalSeconds: number;
|
|
160
|
-
mode: RUNTIME_MODE_INTELLIGENCE;
|
|
160
|
+
mode: typeof RUNTIME_MODE_INTELLIGENCE;
|
|
161
161
|
}
|
|
162
162
|
declare abstract class BaseCopilotRuntime implements CopilotRuntimeLike {
|
|
163
163
|
agents: CopilotRuntimeOptions["agents"];
|
|
@@ -172,6 +172,13 @@ declare abstract class BaseCopilotRuntime implements CopilotRuntimeLike {
|
|
|
172
172
|
readonly debugEventBus?: DebugEventBus;
|
|
173
173
|
debug: ResolvedDebugConfig;
|
|
174
174
|
debugLogger?: CopilotRuntimeLogger;
|
|
175
|
+
/**
|
|
176
|
+
* License token resolved once with the env fallback, so telemetry
|
|
177
|
+
* attribution (below) and subclass feature gating
|
|
178
|
+
* (CopilotIntelligenceRuntime's licenseChecker) read the exact same value
|
|
179
|
+
* instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.
|
|
180
|
+
*/
|
|
181
|
+
protected readonly resolvedLicenseToken?: string;
|
|
175
182
|
abstract readonly intelligence?: CopilotKitIntelligence;
|
|
176
183
|
abstract readonly mode: RuntimeMode;
|
|
177
184
|
constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;cAgCa,OAAA;AAAA,UAEH,mCAAA
|
|
1
|
+
{"version":3,"file":"runtime.d.mts","names":[],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"mappings":";;;;;;;;;;;;;;cAgCa,OAAA;AAAA,UAEH,mCAAA;;EAER,MAAA;AAAA;AAAA,KAGU,mBAAA,GAAsB,eAAA;EALW,uFAO3C,OAAA;AAAA;AAAA,UAGe,aAAA;EALL;EAOV,OAAA,EAAS,mBAAA;AAAA;AAAA,UAGM,uBAAA,SAAgC,mCAAA;AAAA,KAErC,sBAAA,aAAmC,uBAAA;AAAA,UAErC,yBAAA;;;;AAJV;EASE,IAAA,GAAO,mCAAA,GACL,oBAAA;IAV6C;;;AAEjD;;;IAeM,OAAA;EAAA;EAbI;EAgBR,OAAA,GAAU,aAAA;;EAEV,gBAAA,GAAmB,sBAAA;AAAA;;;;UAMJ,mBAAA;EAnBf;EAqBA,OAAA,EAAS,OAAA;AAAA;;;;;KAOC,aAAA,IACV,GAAA,EAAK,mBAAA,KACF,YAAA,CAAa,cAAA,CAAe,MAAA,SAAe,aAAA;;;AAXhD;;;;KAmBY,YAAA,GACR,YAAA,CAAa,cAAA,CAAe,MAAA,SAAe,aAAA,MAC3C,aAAA;AAZJ;;;;;AAAA,iBAmBsB,aAAA,CACpB,MAAA,EAAQ,YAAA,EACR,OAAA,GAAU,OAAA,GACT,OAAA,CAAQ,MAAA,SAAe,aAAA;AAAA,UAYhB,yBAAA,SAAkC,yBAAA;EAhCvC;;;;;;;;;;;AAQL;;;;;EAyCE,MAAA,EAAQ,YAAA;EAxCN;EA0CF,oBAAA,GAAuB,oBAAA;EAzCR;EA2Cf,uBAAA,GAA0B,uBAAA;EA5CxB;EA8CF,sBAAA,GAAyB,sBAAA;EA9CK;EAgD9B,YAAA;EA/CE;EAiDF,KAAA,G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AAA;EAAA,IAIV,IAAA,CAAA,GAAQ,qBAAA;EAAA,IAIR,OAAA,CAAA,GAAW,qBAAA;EAAA,IAIX,gBAAA,CAAA,GAAoB,qBAAA;EAAA,IAIpB,YAAA,CAAA,GAAgB,sBAAA;EAAA,IAIhB,mBAAA,CAAA;EAAA,IAMA,YAAA,CAAA,GAAgB,oBAAA;EAAA,IAMhB,cAAA,CAAA;EAAA,IAMA,aAAA,CAAA;EAAA,IAMA,4BAAA,CAAA;EAAA,IAMA,IAAA,CAAA,GAAQ,WAAA;EAAA,IAIR,cAAA,CAAA,GAAc,cAAA;EAAA,IAId,aAAA,CAAA,GAAa,aAAA;EAAA,IAIb,KAAA,CAAA,GAAS,mBAAA;EAAA,IAIT,WAAA,CAAA,GAAe,oBAAA;AAAA"}
|
|
@@ -37,6 +37,8 @@ var BaseCopilotRuntime = class {
|
|
|
37
37
|
this.mcpApps = mcpApps;
|
|
38
38
|
this.openGenerativeUI = openGenerativeUI;
|
|
39
39
|
this.runner = runner;
|
|
40
|
+
this.resolvedLicenseToken = options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;
|
|
41
|
+
if (this.resolvedLicenseToken) telemetry.setLicenseToken(this.resolvedLicenseToken);
|
|
40
42
|
if (process.env.NODE_ENV !== "production") this.debugEventBus = new DebugEventBus();
|
|
41
43
|
this.debug = resolveDebugConfig(options.debug);
|
|
42
44
|
if (this.debug.enabled) this.debugLogger = createLogger({
|
|
@@ -70,9 +72,7 @@ var CopilotIntelligenceRuntime = class CopilotIntelligenceRuntime extends BaseCo
|
|
|
70
72
|
this.intelligence = options.intelligence;
|
|
71
73
|
this.identifyUser = options.identifyUser;
|
|
72
74
|
this.generateThreadNames = options.generateThreadNames ?? true;
|
|
73
|
-
|
|
74
|
-
this.licenseChecker = createLicenseChecker(licenseToken);
|
|
75
|
-
if (licenseToken) telemetry.setLicenseToken(licenseToken);
|
|
75
|
+
this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken);
|
|
76
76
|
this.lockTtlSeconds = Math.min(options.lockTtlSeconds ?? 20, CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS);
|
|
77
77
|
this.lockKeyPrefix = options.lockKeyPrefix;
|
|
78
78
|
this.lockHeartbeatIntervalSeconds = Math.min(options.lockHeartbeatIntervalSeconds ?? 15, CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n mode: RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Match license-verifier's env fallback so telemetry attribution\n // resolves the same way as feature gating — otherwise customers who\n // set only COPILOTKIT_LICENSE_TOKEN would get a working license but\n // anonymous telemetry.\n const licenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n this.licenseChecker = createLicenseChecker(licenseToken);\n if (licenseToken) {\n telemetry.setLicenseToken(licenseToken);\n }\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,UAAUA,uBAAI;;;;;;AAyE3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAyGT,IAAe,qBAAf,MAAgE;CAiB9D,YAAY,SAAoC,QAAqB;AACnE,iCAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,SAAS;AAEd,MAAI,QAAQ,IAAI,aAAa,aAC3B,MAAK,gBAAgB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AA2B,QAAQ,GACvC,IAAI,kBAAkB,QAAQ;;CAGpC,IAAI,SAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,uBAAsE;AACxE,SAAO,KAAK,SAAS;;CAGvB,IAAI,0BAA4E;AAC9E,SAAO,KAAK,SAAS;;CAGvB,IAAI,yBAA0E;AAC5E,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAsB;AACxB,SAAO,KAAK,SAAS;;CAGvB,IAAI,OAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,UAA4C;AAC9C,SAAO,KAAK,SAAS;;CAGvB,IAAI,mBAA8D;AAChE,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAmD;AACrD,SAAO,KAAK,SAAS;;CAGvB,IAAI,sBAA2C;AAC7C,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":["pkg"],"sources":["../../../../src/v2/runtime/core/runtime.ts"],"sourcesContent":["import type {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n} from \"@copilotkit/shared\";\nimport {\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n} from \"@copilotkit/shared\";\nimport { createLicenseChecker } from \"@copilotkit/license-verifier\";\nimport type { LicenseChecker } from \"@copilotkit/license-verifier\";\nimport { resolveDebugConfig } from \"@copilotkit/shared\";\nimport type { ResolvedDebugConfig, DebugConfig } from \"@copilotkit/shared\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport type { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { createLogger } from \"../../../lib/logger\";\nimport type { CopilotRuntimeLogger } from \"../../../lib/logger\";\nimport { logRuntimeTelemetryDisclosure } from \"../../../lib/telemetry-disclosure\";\nimport type { TranscriptionService } from \"../transcription-service/transcription-service\";\nimport { DebugEventBus } from \"./debug-event-bus\";\nimport type { AgentRunner } from \"../runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"../runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"../runner/intelligence\";\nimport type { CopilotKitIntelligence } from \"../intelligence-platform\";\nimport telemetry from \"../telemetry/telemetry-client\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\nexport interface OpenGenerativeUIOptions extends BaseCopilotRuntimeMiddlewareOptions {}\n\nexport type OpenGenerativeUIConfig = boolean | OpenGenerativeUIOptions;\n\ninterface CopilotRuntimeMiddlewares {\n /**\n * Auto-apply A2UIMiddleware to agents at run time.\n * Pass an object to enable and customise behaviour, or omit to disable.\n */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions &\n A2UIMiddlewareConfig & {\n /**\n * Explicit on/off switch. Omit (or set `true`) to enable; set `false`\n * to disable A2UI for this runtime while keeping the rest of the config\n * (e.g. a `schema`/`catalog`) in place. A bare `a2ui: {}` stays enabled\n * for backwards compatibility.\n */\n enabled?: boolean;\n };\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n /** Auto-apply OpenGenerativeUIMiddleware to agents at run time. */\n openGenerativeUI?: OpenGenerativeUIConfig;\n}\n\n/**\n * Context passed to agent factory functions for per-request agent resolution.\n */\nexport interface AgentFactoryContext {\n /** The incoming HTTP request. */\n request: Request;\n}\n\n/**\n * A function that dynamically creates agents on a per-request basis.\n * Useful for multi-tenant scenarios or request-scoped agent configuration.\n */\nexport type AgentsFactory = (\n ctx: AgentFactoryContext,\n) => MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n\n/**\n * Agents can be provided as:\n * - A static record of agents\n * - A Promise that resolves to a record of agents\n * - A factory function that receives request context and returns agents (or a Promise of agents)\n */\nexport type AgentsConfig =\n | MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>\n | AgentsFactory;\n\n/**\n * Resolve an AgentsConfig value to a concrete record of agents.\n * If the config is a factory function, it is called with the given request context.\n * Otherwise it is awaited directly (static record or Promise).\n */\nexport async function resolveAgents(\n agents: AgentsConfig,\n request?: Request,\n): Promise<Record<string, AbstractAgent>> {\n if (typeof agents === \"function\") {\n if (!request) {\n throw new Error(\n \"Agent factory function requires a request context, but none was provided.\",\n );\n }\n return agents({ request });\n }\n return agents;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /**\n * Map of available agents, or a factory function for per-request agent resolution.\n *\n * Static record:\n * ```ts\n * agents: { support: new SupportAgent(), technical: new TechnicalAgent() }\n * ```\n *\n * Factory function (called per-request):\n * ```ts\n * agents: ({ request }) => {\n * const tenantId = request.headers.get(\"x-tenant-id\");\n * return { default: createAgentForTenant(tenantId) };\n * }\n * ```\n */\n agents: AgentsConfig;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n /** Enable debug logging for the event pipeline. */\n debug?: DebugConfig;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n name: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n /** Max delay (ms) for WebSocket reconnect backoff. @default 10_000 */\n maxReconnectMs?: number;\n /** Max delay (ms) for channel rejoin backoff. @default 30_000 */\n maxRejoinMs?: number;\n /** Lock TTL in seconds. Clamped to a maximum of 3600 (1 hour). @default 20 */\n lockTtlSeconds?: number;\n /** Custom Redis key prefix for the thread lock. */\n lockKeyPrefix?: string;\n /** Interval in seconds at which the runtime renews the thread lock. Clamped to a maximum of 3000 (50 minutes). @default 15 */\n lockHeartbeatIntervalSeconds?: number;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n debugEventBus?: DebugEventBus;\n debug: ResolvedDebugConfig;\n debugLogger?: CopilotRuntimeLogger;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: typeof RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n lockTtlSeconds: number;\n lockKeyPrefix?: string;\n lockHeartbeatIntervalSeconds: number;\n mode: typeof RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public openGenerativeUI: CopilotRuntimeOptions[\"openGenerativeUI\"];\n public licenseChecker?: LicenseChecker;\n public readonly debugEventBus?: DebugEventBus;\n public debug: ResolvedDebugConfig;\n public debugLogger?: CopilotRuntimeLogger;\n\n /**\n * License token resolved once with the env fallback, so telemetry\n * attribution (below) and subclass feature gating\n * (CopilotIntelligenceRuntime's licenseChecker) read the exact same value\n * instead of each re-applying `?? COPILOTKIT_LICENSE_TOKEN`.\n */\n protected readonly resolvedLicenseToken?: string;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n logRuntimeTelemetryDisclosure();\n\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n openGenerativeUI,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui || undefined;\n this.mcpApps = mcpApps;\n this.openGenerativeUI = openGenerativeUI;\n this.runner = runner;\n\n // Resolve the license token once (matching the license-verifier's env\n // fallback) so telemetry attribution and subclass feature gating share\n // one value.\n this.resolvedLicenseToken =\n options.licenseToken ?? process.env.COPILOTKIT_LICENSE_TOKEN;\n\n // Attribute telemetry to the licensed customer for *every* runtime mode.\n // Done in the shared base (not the subclasses) so SSE and Intelligence\n // runtimes behave identically — previously only CopilotIntelligenceRuntime\n // set this, so self-hosted SSE users never got a telemetry_id on their\n // runtime events even with a license token configured.\n if (this.resolvedLicenseToken) {\n telemetry.setLicenseToken(this.resolvedLicenseToken);\n }\n\n if (process.env.NODE_ENV !== \"production\") {\n this.debugEventBus = new DebugEventBus();\n }\n this.debug = resolveDebugConfig(options.debug);\n if (this.debug.enabled) {\n this.debugLogger = createLogger({\n level: \"debug\",\n component: \"copilotkit-debug\",\n });\n }\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly lockTtlSeconds: number;\n readonly lockKeyPrefix?: string;\n readonly lockHeartbeatIntervalSeconds: number;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n /** Maximum allowed lock TTL in seconds (1 hour). */\n static readonly MAX_LOCK_TTL_SECONDS = 3_600;\n /** Maximum allowed heartbeat interval in seconds (50 minutes). */\n static readonly MAX_HEARTBEAT_INTERVAL_SECONDS = 3_000;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n maxReconnectMs: options.maxReconnectMs,\n maxRejoinMs: options.maxRejoinMs,\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n // Telemetry attribution is handled by the base constructor for all modes;\n // here we only need the token for feature gating. Reuse the base-resolved\n // value so gating and attribution can never disagree.\n this.licenseChecker = createLicenseChecker(this.resolvedLicenseToken);\n this.lockTtlSeconds = Math.min(\n options.lockTtlSeconds ?? 20,\n CopilotIntelligenceRuntime.MAX_LOCK_TTL_SECONDS,\n );\n this.lockKeyPrefix = options.lockKeyPrefix;\n this.lockHeartbeatIntervalSeconds = Math.min(\n options.lockHeartbeatIntervalSeconds ?? 15,\n CopilotIntelligenceRuntime.MAX_HEARTBEAT_INTERVAL_SECONDS,\n );\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Single source of truth for \"is A2UI on for this runtime?\". Both the run path\n * (which applies `A2UIMiddleware`) and the `/info` response (which tells the\n * client whether to mount the A2UI renderer + catalog context) MUST go through\n * this, so they can never disagree — the divergence between them was the root\n * of CopilotKit/CopilotKit#5369.\n *\n * Backwards compatible: any config object is enabled (matching the historical\n * `!!runtime.a2ui`); only an explicit `enabled: false` turns it off.\n */\nexport function isA2UIEnabled(\n a2ui: CopilotRuntimeOptions[\"a2ui\"],\n): a2ui is NonNullable<CopilotRuntimeOptions[\"a2ui\"]> {\n return !!a2ui && a2ui.enabled !== false;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get openGenerativeUI(): CopilotRuntimeOptions[\"openGenerativeUI\"] {\n return this.delegate.openGenerativeUI;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get lockTtlSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockTtlSeconds\n : undefined;\n }\n\n get lockKeyPrefix(): string | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockKeyPrefix\n : undefined;\n }\n\n get lockHeartbeatIntervalSeconds(): number | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.lockHeartbeatIntervalSeconds\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n\n get debugEventBus() {\n return this.delegate.debugEventBus;\n }\n\n get debug(): ResolvedDebugConfig {\n return this.delegate.debug;\n }\n\n get debugLogger(): CopilotRuntimeLogger | undefined {\n return this.delegate.debugLogger;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAgCA,MAAa,UAAUA,uBAAI;;;;;;AAyE3B,eAAsB,cACpB,QACA,SACwC;AACxC,KAAI,OAAO,WAAW,YAAY;AAChC,MAAI,CAAC,QACH,OAAM,IAAI,MACR,4EACD;AAEH,SAAO,OAAO,EAAE,SAAS,CAAC;;AAE5B,QAAO;;AAyGT,IAAe,qBAAf,MAAgE;CAyB9D,YAAY,SAAoC,QAAqB;AACnE,iCAA+B;EAE/B,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,SACA,qBACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO,QAAQ;AACpB,OAAK,UAAU;AACf,OAAK,mBAAmB;AACxB,OAAK,SAAS;AAKd,OAAK,uBACH,QAAQ,gBAAgB,QAAQ,IAAI;AAOtC,MAAI,KAAK,qBACP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AI,2BAA2B,QAAQ,GACvC,IAAI,kBAAkB,QAAQ;;CAGpC,IAAI,SAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,uBAAsE;AACxE,SAAO,KAAK,SAAS;;CAGvB,IAAI,0BAA4E;AAC9E,SAAO,KAAK,SAAS;;CAGvB,IAAI,yBAA0E;AAC5E,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAsB;AACxB,SAAO,KAAK,SAAS;;CAGvB,IAAI,OAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,UAA4C;AAC9C,SAAO,KAAK,SAAS;;CAGvB,IAAI,mBAA8D;AAChE,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAmD;AACrD,SAAO,KAAK,SAAS;;CAGvB,IAAI,sBAA2C;AAC7C,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,iBAAqC;AACvC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,iBACd;;CAGN,IAAI,gBAAoC;AACtC,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,gBACd;;CAGN,IAAI,+BAAmD;AACrD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,+BACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS;;CAGvB,IAAI,gBAAgB;AAClB,SAAO,KAAK,SAAS;;CAGvB,IAAI,QAA6B;AAC/B,SAAO,KAAK,SAAS;;CAGvB,IAAI,cAAgD;AAClD,SAAO,KAAK,SAAS"}
|
|
@@ -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 // Check if the stream has already been consumed.\n const state = (req as any)._readableState;\n return Boolean(\n req.readableEnded || req.complete || state?.ended || state?.endEmitted,\n );\n}\n\nfunction synthesizeBody(body: unknown): {\n body?: BodyInit;\n contentType?: string;\n} {\n if (Buffer.isBuffer(body) || body instanceof Uint8Array) {\n return { body };\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,cAAcA,oDAAyB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,SAAS,UAAa,IAAI,SAAS,KAAM,QAAO;CAGxD,MAAM,QAAS,IAAY;AAC3B,QAAO,QACL,IAAI,iBAAiB,IAAI,YAAY,OAAO,SAAS,OAAO,WAC7D;;AAGH,SAAS,eAAe,MAGtB;AACA,KAAI,OAAO,SAAS,KAAK,IAAI,gBAAgB,
|
|
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 // Check if the stream has already been consumed.\n const state = (req as any)._readableState;\n return Boolean(\n req.readableEnded || req.complete || state?.ended || state?.endEmitted,\n );\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,cAAcA,oDAAyB,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,wDAAmB,KADF,MAAM,QADN,sBAAsB,KAAK,IAAI,CACR,CACP;WAC1B,KAAc;AACrB,6BAAO,MAAM,EAAE,KAAK,EAAE,kDAAkD;AACxE,OAAI,CAAC,IAAI,aAAa;AACpB,QAAI,aAAa;AACjB,QAAI,IAAI,wBAAwB;;;;;;;;;AAUxC,SAAS,sBACP,KACA,KACS;CACT,MAAM,aAAa;CACnB,MAAM,UAAU,IAAI,UAAU,OAAO,aAAa;CAIlD,MAAM,MAAM,GAFM,IAAY,YAAY,OAElB,KADX,IAAI,QAAQ,QAAQ,cACI,IAAY,eAAe,IAAI,OAAO;CAE3E,MAAM,UAAU,IAAI,SAAS;AAC7B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,QAAQ,EAAE;AACtD,MAAI,UAAU,OAAW;AACzB,MAAI,MAAM,QAAQ,MAAM,CACtB,MAAK,MAAM,KAAK,MAAO,SAAQ,OAAO,KAAK,EAAE;MAE7C,SAAQ,IAAI,KAAK,MAAM;;CAK3B,MAAM,aAAa,IAAI,iBAAiB;AACxC,KAAI,GAAG,eAAe;AACpB,MAAI,CAAC,IAAI,iBAAkB,YAAW,OAAO;GAC7C;CAEF,MAAM,OAA0C;EAC9C;EACA;EACA,QAAQ,WAAW;EACpB;CAED,MAAM,EAAE,MAAM,gBAAgB,eAAe,WAAW,KAAK;AAC7D,KAAI,YACF,SAAQ,IAAI,gBAAgB,YAAY;AAE1C,SAAQ,OAAO,iBAAiB;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;CAGxD,MAAM,QAAS,IAAY;AAC3B,QAAO,QACL,IAAI,iBAAiB,IAAI,YAAY,OAAO,SAAS,OAAO,WAC7D;;AAGH,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"}
|
|
@@ -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 // Check if the stream has already been consumed.\n const state = (req as any)._readableState;\n return Boolean(\n req.readableEnded || req.complete || state?.ended || state?.endEmitted,\n );\n}\n\nfunction synthesizeBody(body: unknown): {\n body?: BodyInit;\n contentType?: string;\n} {\n if (Buffer.isBuffer(body) || body instanceof Uint8Array) {\n return { body };\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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],"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 // Check if the stream has already been consumed.\n const state = (req as any)._readableState;\n return Boolean(\n req.readableEnded || req.complete || state?.ended || state?.endEmitted,\n );\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,uBAA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,SAAS,OACX,MAAK,OAAO;AAGd,QAAO,IAAI,QAAQ,KAAK,KAAK;;AAG/B,SAAS,iBAAiB,KAAoD;AAC5E,KAAI,IAAI,SAAS,UAAa,IAAI,SAAS,KAAM,QAAO;CAGxD,MAAM,QAAS,IAAY;AAC3B,QAAO,QACL,IAAI,iBAAiB,IAAI,YAAY,OAAO,SAAS,OAAO,WAC7D;;AAGH,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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"single-route-helpers.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/connect\",\n \"agent/stop\",\n \"info\",\n \"transcribe\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch
|
|
1
|
+
{"version":3,"file":"single-route-helpers.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/single-route-helpers.ts"],"sourcesContent":["const METHOD_NAMES = [\n \"agent/run\",\n \"agent/connect\",\n \"agent/stop\",\n \"info\",\n \"transcribe\",\n] as const;\n\nexport type EndpointMethod = (typeof METHOD_NAMES)[number];\n\ninterface JsonEnvelope {\n method?: string;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport interface MethodCall {\n method: EndpointMethod;\n params?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport async function parseMethodCall(request: Request): Promise<MethodCall> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n if (!contentType.includes(\"application/json\")) {\n throw createResponseError(\n \"Single-route endpoint expects JSON payloads\",\n 415,\n );\n }\n\n let jsonEnvelope: JsonEnvelope;\n try {\n jsonEnvelope = (await request.clone().json()) as JsonEnvelope;\n } catch {\n throw createResponseError(\"Invalid JSON payload\", 400);\n }\n\n const method = validateMethod(jsonEnvelope.method);\n\n return {\n method,\n params: jsonEnvelope.params,\n body: jsonEnvelope.body,\n };\n}\n\nexport function expectString(\n params: Record<string, unknown> | undefined,\n key: string,\n): string {\n const value = params?.[key];\n if (typeof value === \"string\" && value.trim().length > 0) {\n return value;\n }\n\n throw createResponseError(`Missing or invalid parameter '${key}'`, 400);\n}\n\nexport function createJsonRequest(base: Request, body: unknown): Request {\n if (body === undefined || body === null) {\n throw createResponseError(\"Missing request body for JSON handler\", 400);\n }\n\n const headers = new Headers(base.headers);\n headers.set(\"content-type\", \"application/json\");\n headers.delete(\"content-length\");\n\n const serializedBody = serializeJsonBody(body);\n\n return new Request(base.url, {\n method: \"POST\",\n headers,\n body: serializedBody,\n signal: base.signal,\n });\n}\n\nexport function createResponseError(message: string, status: number): Response {\n return new Response(\n JSON.stringify({\n error: \"invalid_request\",\n message,\n }),\n {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n}\n\nfunction validateMethod(method: string | undefined): EndpointMethod {\n if (!method) {\n throw createResponseError(\"Missing method field\", 400);\n }\n\n if ((METHOD_NAMES as readonly string[]).includes(method)) {\n return method as EndpointMethod;\n }\n\n throw createResponseError(`Unsupported method '${method}'`, 400);\n}\n\nfunction serializeJsonBody(body: unknown): BodyInit {\n if (typeof body === \"string\") {\n return body;\n }\n\n if (\n body instanceof Blob ||\n body instanceof ArrayBuffer ||\n body instanceof Uint8Array\n ) {\n // Uint8Array<ArrayBufferLike> is a valid fetch body at runtime, but the\n // DOM lib's BodyInit only admits ArrayBuffer-backed views.\n return body as BodyInit;\n }\n\n if (body instanceof FormData || body instanceof URLSearchParams) {\n return body;\n }\n\n return JSON.stringify(body);\n}\n"],"mappings":";;;AAAA,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACD;AAgBD,eAAsB,gBAAgB,SAAuC;AAG3E,KAAI,EAFgB,QAAQ,QAAQ,IAAI,eAAe,IAAI,IAE1C,SAAS,mBAAmB,CAC3C,OAAM,oBACJ,+CACA,IACD;CAGH,IAAI;AACJ,KAAI;AACF,iBAAgB,MAAM,QAAQ,OAAO,CAAC,MAAM;SACtC;AACN,QAAM,oBAAoB,wBAAwB,IAAI;;AAKxD,QAAO;EACL,QAHa,eAAe,aAAa,OAAO;EAIhD,QAAQ,aAAa;EACrB,MAAM,aAAa;EACpB;;AAGH,SAAgB,aACd,QACA,KACQ;CACR,MAAM,QAAQ,SAAS;AACvB,KAAI,OAAO,UAAU,YAAY,MAAM,MAAM,CAAC,SAAS,EACrD,QAAO;AAGT,OAAM,oBAAoB,iCAAiC,IAAI,IAAI,IAAI;;AAGzE,SAAgB,kBAAkB,MAAe,MAAwB;AACvE,KAAI,SAAS,UAAa,SAAS,KACjC,OAAM,oBAAoB,yCAAyC,IAAI;CAGzE,MAAM,UAAU,IAAI,QAAQ,KAAK,QAAQ;AACzC,SAAQ,IAAI,gBAAgB,mBAAmB;AAC/C,SAAQ,OAAO,iBAAiB;CAEhC,MAAM,iBAAiB,kBAAkB,KAAK;AAE9C,QAAO,IAAI,QAAQ,KAAK,KAAK;EAC3B,QAAQ;EACR;EACA,MAAM;EACN,QAAQ,KAAK;EACd,CAAC;;AAGJ,SAAgB,oBAAoB,SAAiB,Q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