@copilotkit/runtime 1.56.5 → 1.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/v2/index.d.cts +2 -2
- package/dist/v2/index.d.mts +2 -2
- package/dist/v2/runtime/core/fetch-handler.cjs +16 -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 +17 -1
- package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.cjs +18 -1
- package/dist/v2/runtime/core/fetch-router.cjs.map +1 -1
- package/dist/v2/runtime/core/fetch-router.mjs +18 -1
- 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 +8 -0
- package/dist/v2/runtime/core/hooks.d.cts.map +1 -1
- package/dist/v2/runtime/core/hooks.d.mts +8 -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 +1 -0
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +1 -0
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.cjs +124 -12
- package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.mjs +122 -13
- package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -1
- package/dist/v2/runtime/index.d.mts +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +30 -0
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +66 -0
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +66 -0
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +30 -0
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.cjs +94 -22
- package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.cts +65 -2
- package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.d.mts +65 -2
- package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -1
- package/dist/v2/runtime/runner/in-memory.mjs +94 -22
- package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
- package/dist/v2/runtime/runner/index.d.cts +1 -1
- package/dist/v2/runtime/runner/index.d.mts +1 -1
- package/package.json +2 -2
- package/src/v2/runtime/__tests__/fetch-handler-validation.test.ts +68 -0
- package/src/v2/runtime/__tests__/fetch-router.test.ts +46 -0
- package/src/v2/runtime/__tests__/handle-run.test.ts +97 -1
- package/src/v2/runtime/__tests__/handle-threads.test.ts +493 -13
- package/src/v2/runtime/core/fetch-handler.ts +19 -0
- package/src/v2/runtime/core/fetch-router.ts +33 -1
- package/src/v2/runtime/core/hooks.ts +3 -0
- package/src/v2/runtime/handlers/handle-run.ts +4 -0
- package/src/v2/runtime/handlers/handle-threads.ts +3 -0
- package/src/v2/runtime/handlers/intelligence/threads.ts +200 -41
- package/src/v2/runtime/intelligence-platform/client.ts +76 -0
- package/src/v2/runtime/runner/__tests__/in-memory-runner.test.ts +417 -3
- package/src/v2/runtime/runner/in-memory.ts +137 -51
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.mts","names":[],"sources":["../../../../src/v2/runtime/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AAA,IAAa,GAAA,EAAK,WAAA,KAAgB,YAAA,CAAa,OAAA;EAU/C;;;;;;;;EAAA,eAAA,IAAmB,GAAA,EAAK,kBAAA,KAAuB,YAAA,CAAa,OAAA;EAQJ;;;;;;EAAxD,UAAA,IAAc,GAAA,EAAK,mBAAA,KAAwB,YAAA,CAAa,QAAA;EAME;;;;EAA1D,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: \"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: \"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":";;AA8HA,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"}
|
|
@@ -16,6 +16,7 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
16
16
|
try {
|
|
17
17
|
const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId, request);
|
|
18
18
|
if (agent instanceof Response) return agent;
|
|
19
|
+
agent.agentId = agentId;
|
|
19
20
|
require_agent_utils.configureAgentForRequest({
|
|
20
21
|
runtime,
|
|
21
22
|
request,
|
|
@@ -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 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":";;;;;;;;AAWA,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;
|
|
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":";;;;;;;;AAWA,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;AAE9D,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"}
|
|
@@ -16,6 +16,7 @@ async function handleRunAgent({ runtime, request, agentId }) {
|
|
|
16
16
|
try {
|
|
17
17
|
const agent = await cloneAgentForRequest(runtime, agentId, request);
|
|
18
18
|
if (agent instanceof Response) return agent;
|
|
19
|
+
agent.agentId = agentId;
|
|
19
20
|
configureAgentForRequest({
|
|
20
21
|
runtime,
|
|
21
22
|
request,
|
|
@@ -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 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":";;;;;;;;AAWA,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,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;
|
|
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":";;;;;;;;AAWA,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,SAAS,SAAS,QAAQ;AACnE,MAAI,iBAAiB,SACnB,QAAO;AAKT,QAAM,UAAU;AAEhB,2BAAyB;GAAE;GAAS;GAAS;GAAS;GAAO,CAAC;AAE9D,MACE,QAAQ,kBACR,CAAC,QAAQ,eAAe,aAAa,SAAS,CAE9C,SAAQ,KACN,gGACD;EAGH,MAAM,QAAQ,MAAM,gBAAgB,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,MAAI,sBAAsB,QAAQ,CAChC,QAAO,sBAAsB;GAC3B;GACA;GACA;GACA;GACA;GACD,CAAC;AAGJ,SAAO,aAAa;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,5 +1,6 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_in_memory = require('../../runner/in-memory.cjs');
|
|
3
4
|
const require_runtime$1 = require('../../core/runtime.cjs');
|
|
4
5
|
const require_json_response = require('../shared/json-response.cjs');
|
|
5
6
|
const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
|
|
@@ -36,21 +37,19 @@ async function resolveThreadMutationContext(runtime, request) {
|
|
|
36
37
|
};
|
|
37
38
|
}
|
|
38
39
|
async function handleListThreads({ runtime, request }) {
|
|
39
|
-
|
|
40
|
-
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
41
|
-
try {
|
|
40
|
+
if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
|
|
42
41
|
const url = new URL(request.url);
|
|
43
42
|
const agentId = url.searchParams.get("agentId");
|
|
44
43
|
const includeArchived = url.searchParams.get("includeArchived") === "true";
|
|
45
44
|
const limitParam = url.searchParams.get("limit");
|
|
46
45
|
const cursor = url.searchParams.get("cursor");
|
|
47
46
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
48
|
-
runtime
|
|
47
|
+
runtime,
|
|
49
48
|
request
|
|
50
49
|
});
|
|
51
50
|
if (require_json_response.isHandlerResponse(user)) return user;
|
|
52
51
|
if (!require_intelligence_utils.isValidIdentifier(agentId)) return require_json_response.errorResponse("Valid agentId query param is required", 400);
|
|
53
|
-
const data = await
|
|
52
|
+
const data = await runtime.intelligence.listThreads({
|
|
54
53
|
userId: user.id,
|
|
55
54
|
agentId,
|
|
56
55
|
...includeArchived ? { includeArchived: true } : {},
|
|
@@ -62,6 +61,29 @@ async function handleListThreads({ runtime, request }) {
|
|
|
62
61
|
_copilotkit_shared.logger.error({ err: error }, "Error listing threads");
|
|
63
62
|
return require_json_response.errorResponse("Failed to list threads", 500);
|
|
64
63
|
}
|
|
64
|
+
if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) {
|
|
65
|
+
const agentId = new URL(request.url).searchParams.get("agentId");
|
|
66
|
+
let threads = runtime.runner.listThreads();
|
|
67
|
+
if (agentId) threads = threads.filter((t) => t.agentId === agentId);
|
|
68
|
+
return Response.json({
|
|
69
|
+
threads,
|
|
70
|
+
nextCursor: null
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Clears all in-memory thread history for the local-dev InMemory fallback.
|
|
77
|
+
*
|
|
78
|
+
* The local-dev fallback exposes this so consumers (e.g. the demo's Clear
|
|
79
|
+
* button) can wipe in-memory thread history without restarting the runtime.
|
|
80
|
+
* Intentionally a no-op when the Intelligence platform is configured: real
|
|
81
|
+
* thread history lives in the database and must not be wiped by a
|
|
82
|
+
* client-side page load.
|
|
83
|
+
*/
|
|
84
|
+
function handleClearThreads({ runtime }) {
|
|
85
|
+
if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) runtime.runner.clearThreads();
|
|
86
|
+
return new Response(null, { status: 204 });
|
|
65
87
|
}
|
|
66
88
|
async function handleUpdateThread({ runtime, request, threadId }) {
|
|
67
89
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
@@ -150,29 +172,119 @@ async function handleDeleteThread({ runtime, request, threadId }) {
|
|
|
150
172
|
}
|
|
151
173
|
}
|
|
152
174
|
async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
153
|
-
|
|
154
|
-
if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
155
|
-
try {
|
|
175
|
+
if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
|
|
156
176
|
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
157
|
-
runtime
|
|
177
|
+
runtime,
|
|
158
178
|
request
|
|
159
179
|
});
|
|
160
180
|
if (require_json_response.isHandlerResponse(user)) return user;
|
|
161
|
-
const data = await
|
|
181
|
+
const data = await runtime.intelligence.getThreadMessages({ threadId });
|
|
162
182
|
return Response.json(data);
|
|
163
183
|
} catch (error) {
|
|
164
184
|
_copilotkit_shared.logger.error({
|
|
165
185
|
err: error,
|
|
166
186
|
threadId
|
|
167
|
-
}, "Error
|
|
168
|
-
return require_json_response.errorResponse("Failed to
|
|
187
|
+
}, "Error fetching thread messages");
|
|
188
|
+
return require_json_response.errorResponse("Failed to fetch thread messages", 500);
|
|
189
|
+
}
|
|
190
|
+
if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) {
|
|
191
|
+
const mapped = runtime.runner.getThreadMessages(threadId).map((msg) => {
|
|
192
|
+
switch (msg.role) {
|
|
193
|
+
case "assistant": {
|
|
194
|
+
const toolCalls = msg.toolCalls ?? [];
|
|
195
|
+
return {
|
|
196
|
+
id: msg.id,
|
|
197
|
+
role: msg.role,
|
|
198
|
+
...msg.content !== void 0 ? { content: msg.content } : {},
|
|
199
|
+
...toolCalls.length > 0 ? { toolCalls: toolCalls.map((tc) => ({
|
|
200
|
+
id: tc.id,
|
|
201
|
+
name: tc.function.name,
|
|
202
|
+
args: tc.function.arguments
|
|
203
|
+
})) } : {}
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
case "tool": return {
|
|
207
|
+
id: msg.id,
|
|
208
|
+
role: msg.role,
|
|
209
|
+
content: msg.content,
|
|
210
|
+
toolCallId: msg.toolCallId
|
|
211
|
+
};
|
|
212
|
+
default: return {
|
|
213
|
+
id: msg.id,
|
|
214
|
+
role: msg.role,
|
|
215
|
+
..."content" in msg && msg.content !== void 0 ? { content: msg.content } : {}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
return Response.json({ messages: mapped });
|
|
220
|
+
}
|
|
221
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
222
|
+
}
|
|
223
|
+
async function handleGetThreadEvents({ runtime, request, threadId }) {
|
|
224
|
+
if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
|
|
225
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
226
|
+
runtime,
|
|
227
|
+
request
|
|
228
|
+
});
|
|
229
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
230
|
+
const data = await runtime.intelligence.getThreadEvents({ threadId });
|
|
231
|
+
return Response.json({ events: data.events });
|
|
232
|
+
} catch (error) {
|
|
233
|
+
_copilotkit_shared.logger.error({
|
|
234
|
+
err: error,
|
|
235
|
+
threadId
|
|
236
|
+
}, "Error fetching thread events");
|
|
237
|
+
return require_json_response.errorResponse("Failed to fetch thread events", 500);
|
|
238
|
+
}
|
|
239
|
+
if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) try {
|
|
240
|
+
const events = runtime.runner.getThreadEvents(threadId);
|
|
241
|
+
return Response.json({ events });
|
|
242
|
+
} catch (error) {
|
|
243
|
+
_copilotkit_shared.logger.error({
|
|
244
|
+
err: error,
|
|
245
|
+
threadId
|
|
246
|
+
}, "Error fetching thread events");
|
|
247
|
+
return require_json_response.errorResponse("Failed to fetch thread events", 500);
|
|
248
|
+
}
|
|
249
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
250
|
+
}
|
|
251
|
+
async function handleGetThreadState({ runtime, request, threadId }) {
|
|
252
|
+
if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
|
|
253
|
+
const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
|
|
254
|
+
runtime,
|
|
255
|
+
request
|
|
256
|
+
});
|
|
257
|
+
if (require_json_response.isHandlerResponse(user)) return user;
|
|
258
|
+
const data = await runtime.intelligence.getThreadState({ threadId });
|
|
259
|
+
const state = data.kind === "snapshot" ? data.state : null;
|
|
260
|
+
return Response.json({ state });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
_copilotkit_shared.logger.error({
|
|
263
|
+
err: error,
|
|
264
|
+
threadId
|
|
265
|
+
}, "Error fetching thread state");
|
|
266
|
+
return require_json_response.errorResponse("Failed to fetch thread state", 500);
|
|
267
|
+
}
|
|
268
|
+
if (runtime.runner instanceof require_in_memory.InMemoryAgentRunner) try {
|
|
269
|
+
const state = runtime.runner.getThreadState(threadId);
|
|
270
|
+
return Response.json({ state });
|
|
271
|
+
} catch (error) {
|
|
272
|
+
_copilotkit_shared.logger.error({
|
|
273
|
+
err: error,
|
|
274
|
+
threadId
|
|
275
|
+
}, "Error fetching thread state");
|
|
276
|
+
return require_json_response.errorResponse("Failed to fetch thread state", 500);
|
|
169
277
|
}
|
|
278
|
+
return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
170
279
|
}
|
|
171
280
|
|
|
172
281
|
//#endregion
|
|
173
282
|
exports.handleArchiveThread = handleArchiveThread;
|
|
283
|
+
exports.handleClearThreads = handleClearThreads;
|
|
174
284
|
exports.handleDeleteThread = handleDeleteThread;
|
|
285
|
+
exports.handleGetThreadEvents = handleGetThreadEvents;
|
|
175
286
|
exports.handleGetThreadMessages = handleGetThreadMessages;
|
|
287
|
+
exports.handleGetThreadState = handleGetThreadState;
|
|
176
288
|
exports.handleListThreads = handleListThreads;
|
|
177
289
|
exports.handleSubscribeToThreads = handleSubscribeToThreads;
|
|
178
290
|
exports.handleUpdateThread = handleUpdateThread;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request 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. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived = url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const data = await intelligenceRuntime.intelligence.getThreadMessages({\n threadId,\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error getting thread messages\");\n return errorResponse(\"Failed to get thread messages\", 500);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIE,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0D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M,CAAC;UAC3C,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,yBAAyB;AAChE,SAAOF,oCAAc,4BAA4B,IAAI;;;AAIzD,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CACxC,QAAO;AAGT,KAAI;EACF,MAAM,WAAW,MAAM,6BACrB,qBACA,QACD;AACD,MAAIA,wCAAkB,SAAS,CAAE,QAAO;AAExC,QAAM,oBAAoB,aAAa,aAAa;GAClD;GACA,QAAQ,SAAS;GACjB,SAAS,SAAS;GACnB,CAAC;AAEF,SAAO,SAAS,KAAK;GAAE;GAAU,SAAS;GAAM,CAAC;UAC1C,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,wBAAwB;AAC/D,SAAOF,oCAAc,2BAA2B,IAAI;;;AAIxD,eAAsB,wBAAwB,EAC5C,SACA,SACA,YAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CACxC,QAAO;AAGT,KAAI;EACF,MAAM,OAAO,MAAMC,0DAAwB;GACzC,SAAS;GACT;GACD,CAAC;AACF,MAAID,wCAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,oBAAoB,aAAa,kBAAkB,EACpE,UACD,CAAC;AAEF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,gCAAgC;AACvE,SAAOF,oCAAc,iCAAiC,IAAI"}
|
|
1
|
+
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","InMemoryAgentRunner"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { InMemoryAgentRunner } from \"../../runner/in-memory\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request 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. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (runtime.runner instanceof InMemoryAgentRunner) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({ threadId });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIE,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAACE,6CAAkB,QAAQ,CAC7B,QAAOJ,oCAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;AAE1C,KAAIC,wCAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAChC,MAAM,UAAU,IAAI,aAAa,IAAI,UAAU;EAC/C,MAAM,kBACJ,IAAI,aAAa,IAAI,kBAAk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,CAChC,KAAI;EACF,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAID,wCAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe,EAAE,UAAU,CAAC;EAMpE,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOF,oCAAc,gCAAgC,IAAI;;AAI7D,KAAI,QAAQ,kBAAkBK,sCAC5B,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOL,oCAAc,gCAAgC,IAAI;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
|
+
import { InMemoryAgentRunner } from "../../runner/in-memory.mjs";
|
|
2
3
|
import { isIntelligenceRuntime } from "../../core/runtime.mjs";
|
|
3
4
|
import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
|
|
4
5
|
import { isValidIdentifier } from "../shared/intelligence-utils.mjs";
|
|
@@ -35,21 +36,19 @@ async function resolveThreadMutationContext(runtime, request) {
|
|
|
35
36
|
};
|
|
36
37
|
}
|
|
37
38
|
async function handleListThreads({ runtime, request }) {
|
|
38
|
-
|
|
39
|
-
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
40
|
-
try {
|
|
39
|
+
if (isIntelligenceRuntime(runtime)) try {
|
|
41
40
|
const url = new URL(request.url);
|
|
42
41
|
const agentId = url.searchParams.get("agentId");
|
|
43
42
|
const includeArchived = url.searchParams.get("includeArchived") === "true";
|
|
44
43
|
const limitParam = url.searchParams.get("limit");
|
|
45
44
|
const cursor = url.searchParams.get("cursor");
|
|
46
45
|
const user = await resolveIntelligenceUser({
|
|
47
|
-
runtime
|
|
46
|
+
runtime,
|
|
48
47
|
request
|
|
49
48
|
});
|
|
50
49
|
if (isHandlerResponse(user)) return user;
|
|
51
50
|
if (!isValidIdentifier(agentId)) return errorResponse("Valid agentId query param is required", 400);
|
|
52
|
-
const data = await
|
|
51
|
+
const data = await runtime.intelligence.listThreads({
|
|
53
52
|
userId: user.id,
|
|
54
53
|
agentId,
|
|
55
54
|
...includeArchived ? { includeArchived: true } : {},
|
|
@@ -61,6 +60,29 @@ async function handleListThreads({ runtime, request }) {
|
|
|
61
60
|
logger.error({ err: error }, "Error listing threads");
|
|
62
61
|
return errorResponse("Failed to list threads", 500);
|
|
63
62
|
}
|
|
63
|
+
if (runtime.runner instanceof InMemoryAgentRunner) {
|
|
64
|
+
const agentId = new URL(request.url).searchParams.get("agentId");
|
|
65
|
+
let threads = runtime.runner.listThreads();
|
|
66
|
+
if (agentId) threads = threads.filter((t) => t.agentId === agentId);
|
|
67
|
+
return Response.json({
|
|
68
|
+
threads,
|
|
69
|
+
nextCursor: null
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Clears all in-memory thread history for the local-dev InMemory fallback.
|
|
76
|
+
*
|
|
77
|
+
* The local-dev fallback exposes this so consumers (e.g. the demo's Clear
|
|
78
|
+
* button) can wipe in-memory thread history without restarting the runtime.
|
|
79
|
+
* Intentionally a no-op when the Intelligence platform is configured: real
|
|
80
|
+
* thread history lives in the database and must not be wiped by a
|
|
81
|
+
* client-side page load.
|
|
82
|
+
*/
|
|
83
|
+
function handleClearThreads({ runtime }) {
|
|
84
|
+
if (runtime.runner instanceof InMemoryAgentRunner) runtime.runner.clearThreads();
|
|
85
|
+
return new Response(null, { status: 204 });
|
|
64
86
|
}
|
|
65
87
|
async function handleUpdateThread({ runtime, request, threadId }) {
|
|
66
88
|
const intelligenceRuntime = requireIntelligenceRuntime(runtime);
|
|
@@ -149,25 +171,112 @@ async function handleDeleteThread({ runtime, request, threadId }) {
|
|
|
149
171
|
}
|
|
150
172
|
}
|
|
151
173
|
async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
152
|
-
|
|
153
|
-
if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
|
|
154
|
-
try {
|
|
174
|
+
if (isIntelligenceRuntime(runtime)) try {
|
|
155
175
|
const user = await resolveIntelligenceUser({
|
|
156
|
-
runtime
|
|
176
|
+
runtime,
|
|
157
177
|
request
|
|
158
178
|
});
|
|
159
179
|
if (isHandlerResponse(user)) return user;
|
|
160
|
-
const data = await
|
|
180
|
+
const data = await runtime.intelligence.getThreadMessages({ threadId });
|
|
161
181
|
return Response.json(data);
|
|
162
182
|
} catch (error) {
|
|
163
183
|
logger.error({
|
|
164
184
|
err: error,
|
|
165
185
|
threadId
|
|
166
|
-
}, "Error
|
|
167
|
-
return errorResponse("Failed to
|
|
186
|
+
}, "Error fetching thread messages");
|
|
187
|
+
return errorResponse("Failed to fetch thread messages", 500);
|
|
188
|
+
}
|
|
189
|
+
if (runtime.runner instanceof InMemoryAgentRunner) {
|
|
190
|
+
const mapped = runtime.runner.getThreadMessages(threadId).map((msg) => {
|
|
191
|
+
switch (msg.role) {
|
|
192
|
+
case "assistant": {
|
|
193
|
+
const toolCalls = msg.toolCalls ?? [];
|
|
194
|
+
return {
|
|
195
|
+
id: msg.id,
|
|
196
|
+
role: msg.role,
|
|
197
|
+
...msg.content !== void 0 ? { content: msg.content } : {},
|
|
198
|
+
...toolCalls.length > 0 ? { toolCalls: toolCalls.map((tc) => ({
|
|
199
|
+
id: tc.id,
|
|
200
|
+
name: tc.function.name,
|
|
201
|
+
args: tc.function.arguments
|
|
202
|
+
})) } : {}
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
case "tool": return {
|
|
206
|
+
id: msg.id,
|
|
207
|
+
role: msg.role,
|
|
208
|
+
content: msg.content,
|
|
209
|
+
toolCallId: msg.toolCallId
|
|
210
|
+
};
|
|
211
|
+
default: return {
|
|
212
|
+
id: msg.id,
|
|
213
|
+
role: msg.role,
|
|
214
|
+
..."content" in msg && msg.content !== void 0 ? { content: msg.content } : {}
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
return Response.json({ messages: mapped });
|
|
219
|
+
}
|
|
220
|
+
return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
221
|
+
}
|
|
222
|
+
async function handleGetThreadEvents({ runtime, request, threadId }) {
|
|
223
|
+
if (isIntelligenceRuntime(runtime)) try {
|
|
224
|
+
const user = await resolveIntelligenceUser({
|
|
225
|
+
runtime,
|
|
226
|
+
request
|
|
227
|
+
});
|
|
228
|
+
if (isHandlerResponse(user)) return user;
|
|
229
|
+
const data = await runtime.intelligence.getThreadEvents({ threadId });
|
|
230
|
+
return Response.json({ events: data.events });
|
|
231
|
+
} catch (error) {
|
|
232
|
+
logger.error({
|
|
233
|
+
err: error,
|
|
234
|
+
threadId
|
|
235
|
+
}, "Error fetching thread events");
|
|
236
|
+
return errorResponse("Failed to fetch thread events", 500);
|
|
237
|
+
}
|
|
238
|
+
if (runtime.runner instanceof InMemoryAgentRunner) try {
|
|
239
|
+
const events = runtime.runner.getThreadEvents(threadId);
|
|
240
|
+
return Response.json({ events });
|
|
241
|
+
} catch (error) {
|
|
242
|
+
logger.error({
|
|
243
|
+
err: error,
|
|
244
|
+
threadId
|
|
245
|
+
}, "Error fetching thread events");
|
|
246
|
+
return errorResponse("Failed to fetch thread events", 500);
|
|
247
|
+
}
|
|
248
|
+
return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
249
|
+
}
|
|
250
|
+
async function handleGetThreadState({ runtime, request, threadId }) {
|
|
251
|
+
if (isIntelligenceRuntime(runtime)) try {
|
|
252
|
+
const user = await resolveIntelligenceUser({
|
|
253
|
+
runtime,
|
|
254
|
+
request
|
|
255
|
+
});
|
|
256
|
+
if (isHandlerResponse(user)) return user;
|
|
257
|
+
const data = await runtime.intelligence.getThreadState({ threadId });
|
|
258
|
+
const state = data.kind === "snapshot" ? data.state : null;
|
|
259
|
+
return Response.json({ state });
|
|
260
|
+
} catch (error) {
|
|
261
|
+
logger.error({
|
|
262
|
+
err: error,
|
|
263
|
+
threadId
|
|
264
|
+
}, "Error fetching thread state");
|
|
265
|
+
return errorResponse("Failed to fetch thread state", 500);
|
|
266
|
+
}
|
|
267
|
+
if (runtime.runner instanceof InMemoryAgentRunner) try {
|
|
268
|
+
const state = runtime.runner.getThreadState(threadId);
|
|
269
|
+
return Response.json({ state });
|
|
270
|
+
} catch (error) {
|
|
271
|
+
logger.error({
|
|
272
|
+
err: error,
|
|
273
|
+
threadId
|
|
274
|
+
}, "Error fetching thread state");
|
|
275
|
+
return errorResponse("Failed to fetch thread state", 500);
|
|
168
276
|
}
|
|
277
|
+
return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
|
|
169
278
|
}
|
|
170
279
|
|
|
171
280
|
//#endregion
|
|
172
|
-
export { handleArchiveThread, handleDeleteThread, handleGetThreadMessages, handleListThreads, handleSubscribeToThreads, handleUpdateThread };
|
|
281
|
+
export { handleArchiveThread, handleClearThreads, handleDeleteThread, handleGetThreadEvents, handleGetThreadMessages, handleGetThreadState, handleListThreads, handleSubscribeToThreads, handleUpdateThread };
|
|
173
282
|
//# sourceMappingURL=threads.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request 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. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived = url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await intelligenceRuntime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const data = await intelligenceRuntime.intelligence.getThreadMessages({\n threadId,\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error getting thread messages\");\n return errorResponse(\"Failed to get thread messages\", 500);\n }\n}\n"],"mappings":";;;;;;;;AAyBA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;CAC1C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAI,kBAAkB,oBAAoB,CACxC,QAAO;AAGT,KAAI;EACF,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAChC,MAAM,UAAU,IAAI,aAAa,IAAI,UAAU;EAC/C,MAAM,kBAAkB,IAAI,aAAa,IAAI,kBAAkB,KAAK;EACpE,MAAM,aAAa,IAAI,aAAa,IAAI,QAAQ;EAChD,MAAM,SAAS,IAAI,aAAa,IAAI,SAAS;EAC7C,MAAM,OAAO,MAAM,wBAAwB;GACzC,SAAS;GACT;GACD,CAAC;AACF,MAAI,kBAAkB,KAAK,CAAE,QAAO;AAEpC,MAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,yCAAyC,IAAI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T;GACD,CAAC;AACF,MAAI,kBAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,oBAAoB,aAAa,kBAAkB,EACpE,UACD,CAAC;AAEF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,gCAAgC;AACvE,SAAO,cAAc,iCAAiC,IAAI"}
|
|
1
|
+
{"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n isIntelligenceRuntime,\n} from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { InMemoryAgentRunner } from \"../../runner/in-memory\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\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 request 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. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (runtime.runner instanceof InMemoryAgentRunner) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({ threadId });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (runtime.runner instanceof InMemoryAgentRunner) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (runtime.runner instanceof InMemoryAgentRunner) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kB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