@copilotkit/runtime 1.59.3 → 1.59.4
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/index.cjs +0 -18
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +0 -18
- package/dist/agent/index.mjs.map +1 -1
- package/dist/package.cjs +4 -3
- package/dist/package.mjs +4 -3
- package/dist/v2/runtime/core/fetch-handler.cjs +5 -0
- package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/v2/runtime/core/fetch-handler.mjs +5 -0
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.cjs +1 -0
- package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.mjs +1 -0
- package/dist/v2/runtime/core/fetch-router.mjs.map +1 -1
- package/dist/v2/runtime/core/hooks.cjs.map +1 -1
- package/dist/v2/runtime/core/hooks.d.cts +2 -0
- package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
- package/dist/v2/runtime/core/hooks.d.mts +2 -0
- package/dist/v2/runtime/core/hooks.d.mts.map +1 -1
- package/dist/v2/runtime/core/hooks.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +5 -0
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +6 -1
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/annotate.cjs +84 -0
- package/dist/v2/runtime/handlers/intelligence/annotate.cjs.map +1 -0
- package/dist/v2/runtime/handlers/intelligence/annotate.mjs +83 -0
- package/dist/v2/runtime/handlers/intelligence/annotate.mjs.map +1 -0
- package/dist/v2/runtime/handlers/intelligence/run.cjs +2 -16
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +2 -16
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/thread-names.cjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/thread-names.mjs +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +47 -0
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +48 -2
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +51 -11
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +81 -13
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +81 -13
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +51 -11
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +5 -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 {\n parseMethodCall,\n createJsonRequest,\n expectString,\n type MethodCall,\n} 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 \"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":";;;;;;;;;;;;;;;;;AAmHA,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;AAEjE,8BAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,kBAAkB,KAAK;AAE1C,QAAO,OAAO,YAAwC;EAEpD,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,SAAS;EAGnD,MAAM,UAAuB;GAAE;GAAS;GAAM;GAAS;EAEvD,IAAI;AAEJ,MAAI;AAEF,OAAI,YAAY;IACd,MAAM,YAAY,WAAW,SAAS,WAAW;AACjD,QAAI,UAAW,QAAO;;AAIxB,aAAU,MAAM,aAAa,OAAO;IAAE,GAAG;IAAS;IAAS,CAAC;AAG5D,OAAI;IACF,MAAM,gBAAgB,MAAM,4BAA4B;KACtD;KACA;KACA;KACD,CAAC;AACF,QAAI,cACF,WAAU;YAEL,SAAkB;AACzB,WAAO,MACL;KAAE,KAAK;KAAS,KAAK,QAAQ;KAAK;KAAM,EACxC,0CACD;AACD,QAAI,mBAAmB,SACrB,QAAO,aAAa,SAAS,YAAY,cAAc;AAEzD,UAAM;;GAIR,IAAI;AAEJ,OAAI,SAAS,gBAAgB;IAC3B,MAAM,WAAW,MAAM,mBAAmB,SAAS,UAAU,KAAK;AAClE,YAAQ,SAAS;IACjB,MAAM,EAAE,eAAe;AAEvB,cAAU,MAAM,mBAAmB,OAAO;KACxC;KACA;KACA;KACA;KACD,CAAC;AAEF,QACE,MAAM,WAAW,eACjB,MAAM,WAAW,mBACjB,MAAM,WAAW,aAEjB,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AAC1B,KAAI,CAAC,KAAM,QAAO;AAClB,KAAI,SAAS,KAAM,QAAO,EAAE;AAC5B,QAAO;;AAGT,SAAS,aACP,UACA,QACA,eACU;AACV,KAAI,CAAC,OAAQ,QAAO;AACpB,QAAO,eAAe,UAAU,QAAQ,cAAc;;AAGxD,SAAS,aACP,MACA,QACA,cACU;AACV,QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
|
|
1
|
+
{"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime/v2\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n */\n\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 type MethodCall,\n} 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\": \"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,kBAAkB,KAAK;AAE1C,QAAO,OAA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1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-router.cjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO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GAAU;;AAIjD,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,UACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAkB;GAAU;;AAI/C,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,SACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAiB;GAAU;;AAI9C,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,WACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAmB;GAAU;;AAIhD,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,QAEtB,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,eACtB,SAAS,MAAM,OAAO,SACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AAEtB,SAAO;GAAE,QAAQ;GAAkB;GAAU;;AAI/C,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,UACpC,QAAO,EAAE,QAAQ,gBAAgB;
|
|
1
|
+
{"version":3,"file":"fetch-router.cjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n // /annotate (1 segment) — annotate a thread event\n if (len >= 1 && segments[len - 1] === \"annotate\") {\n return { method: \"annotate\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO;;;AAIX,SAAS,cAAc,MAAgC;CACrD,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;CAChD,MAAM,MAAM,SAAS;AAKrB,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,OACpC,QAAO,EAAE,QAAQ,QAAQ;AAI3B,KAAI,OAAO,KAAK,S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KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,SACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAiB;GAAU;;AAI9C,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,WACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAmB;GAAU;;AAIhD,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,QAEtB,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,eACtB,SAAS,MAAM,OAAO,SACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AAEtB,SAAO;GAAE,QAAQ;GAAkB;GAAU;;AAI/C,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,UACpC,QAAO,EAAE,QAAQ,gBAAgB;AAInC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,YAAY;AAG/B,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch-router.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO;;;AAIX,SAAS,cAAc,MAAgC;CACrD,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;CAChD,MAAM,MAAM,SAAS;AAKrB,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,OACpC,QAAO,EAAE,QAAQ,QAAQ;AAI3B,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,aACpC,QAAO,EAAE,QAAQ,cAAc;AAUjC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,mBACpC,QAAO,EAAE,QAAQ,oBAAoB;AAIvC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,WACtB,SAAS,MAAM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,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,WACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO;GAAE,QAAQ;GAAmB;GAAU;;AAIhD,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,QAEtB,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,eACtB,SAAS,MAAM,OAAO,SACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AAEtB,SAAO;GAAE,QAAQ;GAAkB;GAAU;;AAI/C,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,UACpC,QAAO,EAAE,QAAQ,gBAAgB;
|
|
1
|
+
{"version":3,"file":"fetch-router.mjs","names":[],"sources":["../../../../src/v2/runtime/core/fetch-router.ts"],"sourcesContent":["/**\n * Lightweight URL router for framework-agnostic CopilotKit runtime handler.\n *\n * Two strategies:\n * - With `basePath`: strict prefix strip → match remainder\n * - Without `basePath`: suffix matching on known patterns\n *\n * Single-route mode: delegates to `parseMethodCall` for JSON envelope dispatch.\n */\n\nimport type { RouteInfo } from \"./hooks\";\n\n/**\n * Match a request URL against known CopilotKit route patterns.\n *\n * @param pathname - The URL pathname to match\n * @param basePath - Optional base path prefix to strip first\n * @returns RouteInfo if matched, null otherwise\n */\nexport function matchRoute(\n pathname: string,\n basePath?: string,\n): RouteInfo | null {\n let remainder: string;\n\n if (basePath) {\n // Normalize: ensure basePath doesn't end with /\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n\n // Special case: basePath === \"/\" matches everything\n if (normalizedBase === \"/\") {\n remainder = pathname;\n } else {\n if (!pathname.startsWith(normalizedBase)) return null;\n\n // The character after basePath must be \"/\" or end of string\n const afterBase = pathname.slice(normalizedBase.length);\n if (afterBase.length > 0 && !afterBase.startsWith(\"/\")) return null;\n\n remainder = afterBase || \"/\";\n }\n } else {\n // Suffix matching: find known patterns at the end of the pathname\n remainder = pathname;\n }\n\n return matchSegments(remainder);\n}\n\nfunction safeDecodeURIComponent(value: string): string | null {\n try {\n return decodeURIComponent(value);\n } catch {\n return null;\n }\n}\n\nfunction matchSegments(path: string): RouteInfo | null {\n const segments = path.split(\"/\").filter(Boolean);\n const len = segments.length;\n\n // Try suffix matching — scan from the end for known patterns\n\n // /info (1 segment)\n if (len >= 1 && segments[len - 1] === \"info\") {\n return { method: \"info\" };\n }\n\n // /transcribe (1 segment)\n if (len >= 1 && segments[len - 1] === \"transcribe\") {\n return { method: \"transcribe\" };\n }\n\n // /cpk-debug-events (1 segment)\n // Reserved route name: the `cpk-` prefix makes collision with a\n // user-named agent essentially impossible (the router only treats\n // `agent/:agentId/...` patterns as agent lookups, so a bare\n // `cpk-debug-events` segment would never fall through to one —\n // the prefix is the real guard, not this branch's position).\n // Handler returns 404 in production.\n if (len >= 1 && segments[len - 1] === \"cpk-debug-events\") {\n return { method: \"cpk-debug-events\" };\n }\n\n // /agent/:agentId/run (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"run\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/run\", agentId };\n }\n\n // /agent/:agentId/connect (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"agent\" &&\n segments[len - 1] === \"connect\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 2]!);\n if (!agentId) return null;\n return { method: \"agent/connect\", agentId };\n }\n\n // /agent/:agentId/stop/:threadId (4 segments)\n if (\n len >= 4 &&\n segments[len - 4] === \"agent\" &&\n segments[len - 2] === \"stop\"\n ) {\n const agentId = safeDecodeURIComponent(segments[len - 3]!);\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!agentId || !threadId) return null;\n return { method: \"agent/stop\", agentId, threadId };\n }\n\n // /threads/subscribe (2 segments)\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"subscribe\"\n ) {\n return { method: \"threads/subscribe\" };\n }\n\n // /threads/:threadId/messages (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"messages\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/messages\", threadId };\n }\n\n // /threads/:threadId/events (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"events\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/events\", threadId };\n }\n\n // /threads/:threadId/state (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"state\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/state\", threadId };\n }\n\n // /threads/:threadId/archive (3 segments)\n if (\n len >= 3 &&\n segments[len - 3] === \"threads\" &&\n segments[len - 1] === \"archive\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 2]!);\n if (!threadId) return null;\n return { method: \"threads/archive\", threadId };\n }\n\n // /threads/clear (2 segments) — wipe in-memory thread history\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] === \"clear\"\n ) {\n return { method: \"threads/clear\" };\n }\n\n // /threads/:threadId (2 segments) — update or delete\n if (\n len >= 2 &&\n segments[len - 2] === \"threads\" &&\n segments[len - 1] !== \"subscribe\" &&\n segments[len - 1] !== \"clear\"\n ) {\n const threadId = safeDecodeURIComponent(segments[len - 1]!);\n if (!threadId) return null;\n // Disambiguated by HTTP method in the handler\n return { method: \"threads/update\", threadId };\n }\n\n // /threads (1 segment) — list\n if (len >= 1 && segments[len - 1] === \"threads\") {\n return { method: \"threads/list\" };\n }\n\n // /annotate (1 segment) — annotate a thread event\n if (len >= 1 && segments[len - 1] === \"annotate\") {\n return { method: \"annotate\" };\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;AAmBA,SAAgB,WACd,UACA,UACkB;CAClB,IAAI;AAEJ,KAAI,UAAU;EAEZ,MAAM,iBACJ,SAAS,SAAS,KAAK,SAAS,SAAS,IAAI,GACzC,SAAS,MAAM,GAAG,GAAG,GACrB;AAGN,MAAI,mBAAmB,IACrB,aAAY;OACP;AACL,OAAI,CAAC,SAAS,WAAW,eAAe,CAAE,QAAO;GAGjD,MAAM,YAAY,SAAS,MAAM,eAAe,OAAO;AACvD,OAAI,UAAU,SAAS,KAAK,CAAC,UAAU,WAAW,IAAI,CAAE,QAAO;AAE/D,eAAY,aAAa;;OAI3B,aAAY;AAGd,QAAO,cAAc,UAAU;;AAGjC,SAAS,uBAAuB,OAA8B;AAC5D,KAAI;AACF,SAAO,mBAAmB,MAAM;SAC1B;AACN,SAAO;;;AAIX,SAAS,cAAc,MAAgC;CACrD,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;CAChD,MAAM,MAAM,SAAS;AAKrB,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,OACpC,QAAO,EAAE,QAAQ,QAAQ;AAI3B,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,aACpC,QAAO,EAAE,QAAQ,cAAc;AAUjC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,mBACpC,QAAO,EAAE,QAAQ,oBAAoB;AAIvC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,WACtB,SAAS,MAAM,OAAO,OACtB;EACA,MAAM,UAAU,uBAAuB,SAAS,MAAM,GAAI;AAC1D,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO;GAAE,QAAQ;GAAa;GAAS;;AAIzC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,WACtB,SAAS,MAAM,OAAO,WACtB;EACA,MAAM,UAA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tB,SAAS,MAAM,OAAO,QAEtB,QAAO,EAAE,QAAQ,iBAAiB;AAIpC,KACE,OAAO,KACP,SAAS,MAAM,OAAO,aACtB,SAAS,MAAM,OAAO,eACtB,SAAS,MAAM,OAAO,SACtB;EACA,MAAM,WAAW,uBAAuB,SAAS,MAAM,GAAI;AAC3D,MAAI,CAAC,SAAU,QAAO;AAEtB,SAAO;GAAE,QAAQ;GAAkB;GAAU;;AAI/C,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,UACpC,QAAO,EAAE,QAAQ,gBAAgB;AAInC,KAAI,OAAO,KAAK,SAAS,MAAM,OAAO,WACpC,QAAO,EAAE,QAAQ,YAAY;AAG/B,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.cjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"hooks.cjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;;AA+HA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"mappings":";;;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;EAA4B,QAAA;AAAA;EAC5B,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAAyB,QAAA;AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;
|
|
1
|
+
{"version":3,"file":"hooks.d.cts","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"mappings":";;;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B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,KAAuB,YAAA,CAAa,OAAA;EAc5D;;;;;;EANA,UAAA,IAAc,GAAA,EAAK,mBAAA,KAAwB,YAAA,CAAa,QAAA;;;;;EAMxD,OAAA,IAAW,GAAA,EAAK,gBAAA,KAAqB,YAAA,CAAa,QAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.mjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"hooks.mjs","names":[],"sources":["../../../../src/v2/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;AA+HA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
|
|
@@ -23,6 +23,11 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
23
23
|
agentId,
|
|
24
24
|
agent
|
|
25
25
|
});
|
|
26
|
+
await require_agent_utils.attachIntelligenceEnterpriseLearning({
|
|
27
|
+
runtime,
|
|
28
|
+
request,
|
|
29
|
+
agent
|
|
30
|
+
});
|
|
26
31
|
if (runtime.licenseChecker && !runtime.licenseChecker.checkFeature("agents")) console.warn("[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing");
|
|
27
32
|
const input = await require_agent_utils.parseRunRequest(request);
|
|
28
33
|
if (input instanceof Response) return input;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","parseRunRequest","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"handle-run.cjs","names":["cloneAgentForRequest","attachIntelligenceEnterpriseLearning","parseRunRequest","isIntelligenceRuntime","handleIntelligenceRun","handleSseRun"],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n await attachIntelligenceEnterpriseLearning({ runtime, request, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAYA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,kCAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;AAEhB,+CAAyB;GAAE;GAAS;GAAS;GAAS;GAAO,CAAC;AAC9D,QAAMC,yDAAqC;GAAE;GAAS;GAAS;GAAO,CAAC;AAEvE,MACE,QAAQ,kBACR,CAAC,QAAQ,eAAe,aAAa,SAAS,CAE9C,SAAQ,KACN,gGACD;EAGH,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,MAAI,iBAAiB,SACnB,QAAO;AAGT,QAAM,YAAY,MAAM,SAAS;AACjC,QAAM,SAAS,MAAM,MAAM;AAC3B,QAAM,WAAW,MAAM;AAEvB,MAAI,QAAQ,OAAO,aAAa,QAAQ,YACtC,SAAQ,YAAY,MAClB;GAAE,WAAW;GAAS,UAAU,MAAM;GAAU,EAChD,oBACD;AAGH,MAAIC,sCAAsB,QAAQ,CAChC,QAAOC,kCAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAOC,2BAAa;GAClB;GACA;GACA;GACA;GACA;GACA,OAAO,QAAQ;GACf,QAAQ,QAAQ;GACjB,CAAC;UACK,OAAO;AACd,UAAQ,MAAM,wBAAwB,MAAM;AAC5C,UAAQ,MACN,gBACA,iBAAiB,QAAQ,MAAM,QAAQ,iBACxC;AACD,UAAQ,MAAM,kBAAkB;GAC9B,MAAM,iBAAiB,QAAQ,MAAM,OAAO;GAC5C,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D,OAAO,iBAAiB,QAAQ,MAAM,QAAQ;GAC/C,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
import telemetry from "../telemetry/telemetry-client.mjs";
|
|
3
3
|
import { isIntelligenceRuntime } from "../core/runtime.mjs";
|
|
4
|
-
import { cloneAgentForRequest, configureAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
|
|
4
|
+
import { attachIntelligenceEnterpriseLearning, cloneAgentForRequest, configureAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
|
|
5
5
|
import { handleIntelligenceRun } from "./intelligence/run.mjs";
|
|
6
6
|
import { handleSseRun } from "./sse/run.mjs";
|
|
7
7
|
|
|
@@ -23,6 +23,11 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
23
23
|
agentId,
|
|
24
24
|
agent
|
|
25
25
|
});
|
|
26
|
+
await attachIntelligenceEnterpriseLearning({
|
|
27
|
+
runtime,
|
|
28
|
+
request,
|
|
29
|
+
agent
|
|
30
|
+
});
|
|
26
31
|
if (runtime.licenseChecker && !runtime.licenseChecker.checkFeature("agents")) console.warn("[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing");
|
|
27
32
|
const input = await parseRunRequest(request);
|
|
28
33
|
if (input instanceof Response) return input;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"handle-run.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-run.ts"],"sourcesContent":["import { isIntelligenceRuntime } from \"../core/runtime\";\nimport { telemetry } from \"../telemetry\";\nimport {\n attachIntelligenceEnterpriseLearning,\n cloneAgentForRequest,\n configureAgentForRequest,\n parseRunRequest,\n RunAgentParameters,\n} from \"./shared/agent-utils\";\nimport { handleIntelligenceRun } from \"./intelligence/run\";\nimport { handleSseRun } from \"./sse/run\";\n\nexport async function handleRunAgent({\n runtime,\n request,\n agentId,\n}: RunAgentParameters) {\n telemetry.capture(\"oss.runtime.copilot_request_created\", {\n \"cloud.guardrails.enabled\": false,\n requestType: \"run\",\n \"cloud.api_key_provided\": !!request.headers.get(\n \"x-copilotcloud-public-api-key\",\n ),\n ...(request.headers.get(\"x-copilotcloud-public-api-key\")\n ? {\n \"cloud.public_api_key\": request.headers.get(\n \"x-copilotcloud-public-api-key\",\n )!,\n }\n : {}),\n });\n\n try {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Ensure the clone carries the registry key so InMemoryAgentRunner can\n // tag historic runs with the correct agentId for filtering.\n agent.agentId = agentId;\n\n configureAgentForRequest({ runtime, request, agentId, agent });\n await attachIntelligenceEnterpriseLearning({ runtime, request, agent });\n\n if (\n runtime.licenseChecker &&\n !runtime.licenseChecker.checkFeature(\"agents\")\n ) {\n console.warn(\n '[CopilotKit Runtime] Warning: \"agents\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n if (runtime.debug?.lifecycle && runtime.debugLogger) {\n runtime.debugLogger.debug(\n { agentName: agentId, threadId: input.threadId },\n \"Agent run started\",\n );\n }\n\n if (isIntelligenceRuntime(runtime)) {\n return handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n });\n }\n\n return handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug: runtime.debug,\n logger: runtime.debugLogger,\n });\n } catch (error) {\n console.error(\"Error running agent:\", error);\n console.error(\n \"Error stack:\",\n error instanceof Error ? error.stack : \"No stack trace\",\n );\n console.error(\"Error details:\", {\n name: error instanceof Error ? error.name : \"Unknown\",\n message: error instanceof Error ? error.message : String(error),\n cause: error instanceof Error ? error.cause : undefined,\n });\n\n return new Response(\n JSON.stringify({\n error: \"Failed to run agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;AAYA,eAAsB,eAAe,EACnC,SACA,SACA,WACqB;AACrB,WAAU,QAAQ,uCAAuC;EACvD,4BAA4B;EAC5B,aAAa;EACb,0BAA0B,CAAC,CAAC,QAAQ,QAAQ,IAC1C,gCACD;EACD,GAAI,QAAQ,QAAQ,IAAI,gCAAgC,GACpD,EACE,wBAAwB,QAAQ,QAAQ,IACtC,gCACD,EACF,GACD,EAAE;EACP,CAAC;AAEF,KAAI;EACF,MAAM,QAAQ,MAAM,qBAAqB,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/_rolldown/runtime.cjs');
|
|
3
|
+
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
4
|
+
const require_client = require('../../intelligence-platform/client.cjs');
|
|
5
|
+
const require_json_response = require('../shared/json-response.cjs');
|
|
6
|
+
const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
|
|
7
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
8
|
+
|
|
9
|
+
//#region src/v2/runtime/handlers/intelligence/annotate.ts
|
|
10
|
+
async function parseJsonBody(request) {
|
|
11
|
+
try {
|
|
12
|
+
return await request.json();
|
|
13
|
+
} catch (error) {
|
|
14
|
+
_copilotkit_shared.logger.error({ err: error }, "Malformed JSON in annotate body");
|
|
15
|
+
return require_json_response.errorResponse("Invalid request body", 400);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function requireIntelligenceRuntime(runtime) {
|
|
19
|
+
if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
20
|
+
return runtime;
|
|
21
|
+
}
|
|
22
|
+
function isNonEmptyString(value) {
|
|
23
|
+
return typeof value === "string" && value.length > 0;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* `POST /annotate` handler.
|
|
27
|
+
*
|
|
28
|
+
* Three-tier flow:
|
|
29
|
+
* recordAnnotation() (frontend lib; called by useLearnFromUserAction / useLearningContainers)
|
|
30
|
+
* → POST ${runtimeUrl}/annotate
|
|
31
|
+
* → this handler resolves the Intel user from BFF auth
|
|
32
|
+
* → intelligence.annotate(...)
|
|
33
|
+
* → PUT ${apiUrl}/connector/annotate/:clientEventId
|
|
34
|
+
*
|
|
35
|
+
* The frontend hook may auto-generate a UUID `clientEventId` per call
|
|
36
|
+
* so retries are idempotent end-to-end (the platform collapses to the
|
|
37
|
+
* original row).
|
|
38
|
+
*/
|
|
39
|
+
async function handleAnnotate({ runtime, request }) {
|
|
40
|
+
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
41
|
+
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
42
|
+
const body = await parseJsonBody(request);
|
|
43
|
+
if (require_json_response.isHandlerResponse(body)) return body;
|
|
44
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
45
|
+
runtime: intelligenceRuntime,
|
|
46
|
+
request
|
|
47
|
+
});
|
|
48
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
49
|
+
const parsed = parseAnnotateBody(body);
|
|
50
|
+
if (require_json_response.isHandlerResponse(parsed)) return parsed;
|
|
51
|
+
try {
|
|
52
|
+
const result = await intelligenceRuntime.intelligence.annotate({
|
|
53
|
+
userId: user.id,
|
|
54
|
+
threadId: parsed.threadId,
|
|
55
|
+
type: parsed.type,
|
|
56
|
+
payload: parsed.payload,
|
|
57
|
+
clientEventId: parsed.clientEventId,
|
|
58
|
+
occurredAt: parsed.occurredAt
|
|
59
|
+
});
|
|
60
|
+
return new Response(JSON.stringify(result), {
|
|
61
|
+
status: 200,
|
|
62
|
+
headers: { "Content-Type": "application/json" }
|
|
63
|
+
});
|
|
64
|
+
} catch (err) {
|
|
65
|
+
_copilotkit_shared.logger.error({ err }, "annotate: platform call failed");
|
|
66
|
+
if (err instanceof require_client.PlatformRequestError && err.status >= 400 && err.status < 500) return require_json_response.errorResponse(err.message, err.status);
|
|
67
|
+
return require_json_response.errorResponse("Failed to annotate", 502);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function parseAnnotateBody(body) {
|
|
71
|
+
if (!isNonEmptyString(body.threadId)) return require_json_response.errorResponse("Valid threadId is required", 400);
|
|
72
|
+
if (!isNonEmptyString(body.type)) return require_json_response.errorResponse("Valid type is required", 400);
|
|
73
|
+
return {
|
|
74
|
+
type: body.type,
|
|
75
|
+
payload: body.payload,
|
|
76
|
+
threadId: body.threadId,
|
|
77
|
+
clientEventId: isNonEmptyString(body.clientEventId) ? body.clientEventId : void 0,
|
|
78
|
+
occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : void 0
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
exports.handleAnnotate = handleAnnotate;
|
|
84
|
+
//# sourceMappingURL=annotate.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in annotate body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction / useLearningContainers)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIA,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAIA,wCAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,4BAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAeE,uCACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAOJ,oCAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAOA,oCAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAOA,oCAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import "reflect-metadata";
|
|
2
|
+
import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
3
|
+
import { PlatformRequestError } from "../../intelligence-platform/client.mjs";
|
|
4
|
+
import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
|
|
5
|
+
import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs";
|
|
6
|
+
import { logger } from "@copilotkit/shared";
|
|
7
|
+
|
|
8
|
+
//#region src/v2/runtime/handlers/intelligence/annotate.ts
|
|
9
|
+
async function parseJsonBody(request) {
|
|
10
|
+
try {
|
|
11
|
+
return await request.json();
|
|
12
|
+
} catch (error) {
|
|
13
|
+
logger.error({ err: error }, "Malformed JSON in annotate body");
|
|
14
|
+
return errorResponse("Invalid request body", 400);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function requireIntelligenceRuntime(runtime) {
|
|
18
|
+
if (!isIntelligenceRuntime(runtime)) return errorResponse("Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
19
|
+
return runtime;
|
|
20
|
+
}
|
|
21
|
+
function isNonEmptyString(value) {
|
|
22
|
+
return typeof value === "string" && value.length > 0;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* `POST /annotate` handler.
|
|
26
|
+
*
|
|
27
|
+
* Three-tier flow:
|
|
28
|
+
* recordAnnotation() (frontend lib; called by useLearnFromUserAction / useLearningContainers)
|
|
29
|
+
* → POST ${runtimeUrl}/annotate
|
|
30
|
+
* → this handler resolves the Intel user from BFF auth
|
|
31
|
+
* → intelligence.annotate(...)
|
|
32
|
+
* → PUT ${apiUrl}/connector/annotate/:clientEventId
|
|
33
|
+
*
|
|
34
|
+
* The frontend hook may auto-generate a UUID `clientEventId` per call
|
|
35
|
+
* so retries are idempotent end-to-end (the platform collapses to the
|
|
36
|
+
* original row).
|
|
37
|
+
*/
|
|
38
|
+
async function handleAnnotate({ runtime, request }) {
|
|
39
|
+
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
40
|
+
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
41
|
+
const body = await parseJsonBody(request);
|
|
42
|
+
if (isHandlerResponse(body)) return body;
|
|
43
|
+
const user = await resolveIntelligenceUser({
|
|
44
|
+
runtime: intelligenceRuntime,
|
|
45
|
+
request
|
|
46
|
+
});
|
|
47
|
+
if (isHandlerResponse(user)) return user;
|
|
48
|
+
const parsed = parseAnnotateBody(body);
|
|
49
|
+
if (isHandlerResponse(parsed)) return parsed;
|
|
50
|
+
try {
|
|
51
|
+
const result = await intelligenceRuntime.intelligence.annotate({
|
|
52
|
+
userId: user.id,
|
|
53
|
+
threadId: parsed.threadId,
|
|
54
|
+
type: parsed.type,
|
|
55
|
+
payload: parsed.payload,
|
|
56
|
+
clientEventId: parsed.clientEventId,
|
|
57
|
+
occurredAt: parsed.occurredAt
|
|
58
|
+
});
|
|
59
|
+
return new Response(JSON.stringify(result), {
|
|
60
|
+
status: 200,
|
|
61
|
+
headers: { "Content-Type": "application/json" }
|
|
62
|
+
});
|
|
63
|
+
} catch (err) {
|
|
64
|
+
logger.error({ err }, "annotate: platform call failed");
|
|
65
|
+
if (err instanceof PlatformRequestError && err.status >= 400 && err.status < 500) return errorResponse(err.message, err.status);
|
|
66
|
+
return errorResponse("Failed to annotate", 502);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function parseAnnotateBody(body) {
|
|
70
|
+
if (!isNonEmptyString(body.threadId)) return errorResponse("Valid threadId is required", 400);
|
|
71
|
+
if (!isNonEmptyString(body.type)) return errorResponse("Valid type is required", 400);
|
|
72
|
+
return {
|
|
73
|
+
type: body.type,
|
|
74
|
+
payload: body.payload,
|
|
75
|
+
threadId: body.threadId,
|
|
76
|
+
clientEventId: isNonEmptyString(body.clientEventId) ? body.clientEventId : void 0,
|
|
77
|
+
occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : void 0
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//#endregion
|
|
82
|
+
export { handleAnnotate };
|
|
83
|
+
//# sourceMappingURL=annotate.mjs.map
|