@copilotkit/runtime 1.59.5 → 1.60.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/index.cjs +16 -6
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +16 -6
- package/dist/agent/index.mjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.cts +0 -8
- package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.d.mts +0 -8
- package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
- package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
- package/dist/package.cjs +6 -6
- package/dist/package.mjs +6 -6
- package/dist/v2/runtime/handlers/get-runtime-info.cjs +4 -0
- package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/v2/runtime/handlers/get-runtime-info.mjs +4 -0
- package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs +4 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +4 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.cjs +4 -1
- package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.mjs +4 -1
- package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +18 -6
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +2 -0
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +2 -0
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +18 -6
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +7 -7
- package/skills/runtime/SKILL.md +2 -2
- package/skills/runtime/references/agent-runners.md +6 -6
- package/skills/runtime/references/intelligence-mode.md +9 -13
- package/skills/runtime/references/setup-endpoint.md +1 -1
- package/skills/runtime/references/wiring-agno.md +5 -4
- package/skills/runtime/references/wiring-external-agents.md +20 -20
- package/skills/runtime/references/wiring-langgraph.md +5 -6
|
@@ -1 +1 @@
|
|
|
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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}
|
|
1
|
+
{"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","InMemoryAgentRunner"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } 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({\n threadId,\n userId: user.id,\n });\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,Q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AgB,SAAS;AACvD,SAAO,SAAS,KAAK,EAAE,QAAQ,CAAC;UACzB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,+BAA+B;AACtE,SAAOL,oCAAc,iCAAiC,IAAI;;AAI9D,QAAOA,oCACL,uJACA,IACD;;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAIC,wCAAsB,QAAQ,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"}
|
|
@@ -177,7 +177,10 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
|
|
|
177
177
|
request
|
|
178
178
|
});
|
|
179
179
|
if (isHandlerResponse(user)) return user;
|
|
180
|
-
const data = await runtime.intelligence.getThreadMessages({
|
|
180
|
+
const data = await runtime.intelligence.getThreadMessages({
|
|
181
|
+
threadId,
|
|
182
|
+
userId: user.id
|
|
183
|
+
});
|
|
181
184
|
return Response.json(data);
|
|
182
185
|
} catch (error) {
|
|
183
186
|
logger.error({
|
|
@@ -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\";\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,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;AAE1C,KAAI,sBAAsB,QAAQ,CAChC,KAA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;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAI,sBAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,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,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,KAAI,QAAQ,kBAAkB,oBAC5B,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,QAAO,cACL,uJACA,IACD"}
|
|
1
|
+
{"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } 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({\n threadId,\n userId: user.id,\n });\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.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AM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,QAAO,cACL,uJACA,IACD"}
|
|
@@ -24,7 +24,7 @@ const INTELLIGENCE_USER_ID_HEADER = "x-cpki-user-id";
|
|
|
24
24
|
* @example
|
|
25
25
|
* ```ts
|
|
26
26
|
* try {
|
|
27
|
-
* await intelligence.getThread({ threadId });
|
|
27
|
+
* await intelligence.getThread({ threadId, userId });
|
|
28
28
|
* } catch (error) {
|
|
29
29
|
* if (error instanceof PlatformRequestError && error.status === 404) {
|
|
30
30
|
* // thread does not exist yet
|
|
@@ -236,7 +236,8 @@ var CopilotKitIntelligence = class {
|
|
|
236
236
|
* not exist.
|
|
237
237
|
*/
|
|
238
238
|
async getThread(params) {
|
|
239
|
-
|
|
239
|
+
const qs = new URLSearchParams({ userId: params.userId }).toString();
|
|
240
|
+
return (await this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`)).thread;
|
|
240
241
|
}
|
|
241
242
|
/**
|
|
242
243
|
* Get an existing thread or create it if it does not exist.
|
|
@@ -256,7 +257,10 @@ var CopilotKitIntelligence = class {
|
|
|
256
257
|
async getOrCreateThread(params) {
|
|
257
258
|
try {
|
|
258
259
|
return {
|
|
259
|
-
thread: await this.getThread({
|
|
260
|
+
thread: await this.getThread({
|
|
261
|
+
threadId: params.threadId,
|
|
262
|
+
userId: params.userId
|
|
263
|
+
}),
|
|
260
264
|
created: false
|
|
261
265
|
};
|
|
262
266
|
} catch (error) {
|
|
@@ -269,7 +273,10 @@ var CopilotKitIntelligence = class {
|
|
|
269
273
|
};
|
|
270
274
|
} catch (error) {
|
|
271
275
|
if (error instanceof PlatformRequestError && error.status === 409) return {
|
|
272
|
-
thread: await this.getThread({
|
|
276
|
+
thread: await this.getThread({
|
|
277
|
+
threadId: params.threadId,
|
|
278
|
+
userId: params.userId
|
|
279
|
+
}),
|
|
273
280
|
created: false
|
|
274
281
|
};
|
|
275
282
|
throw error;
|
|
@@ -282,7 +289,8 @@ var CopilotKitIntelligence = class {
|
|
|
282
289
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
283
290
|
*/
|
|
284
291
|
async getThreadMessages(params) {
|
|
285
|
-
|
|
292
|
+
const qs = new URLSearchParams({ userId: params.userId }).toString();
|
|
293
|
+
return this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`);
|
|
286
294
|
}
|
|
287
295
|
/**
|
|
288
296
|
* Fetch the persisted AG-UI event stream for a thread.
|
|
@@ -339,7 +347,11 @@ var CopilotKitIntelligence = class {
|
|
|
339
347
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
340
348
|
*/
|
|
341
349
|
async deleteThread(params) {
|
|
342
|
-
await this.#request("DELETE", `/api/threads/${encodeURIComponent(params.threadId)}`, {
|
|
350
|
+
await this.#request("DELETE", `/api/threads/${encodeURIComponent(params.threadId)}`, {
|
|
351
|
+
userId: params.userId,
|
|
352
|
+
agentId: params.agentId,
|
|
353
|
+
reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`
|
|
354
|
+
});
|
|
343
355
|
this.#invokeLifecycleCallback("onThreadDeleted", params);
|
|
344
356
|
}
|
|
345
357
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#enterpriseLearningEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —\n * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`\n * and bakes this header onto the `MCPMiddleware`'s transport config, so every\n * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the\n * public user API.\n *\n * @internal\n */\nexport const INTELLIGENCE_USER_ID_HEADER = \"x-cpki-user-id\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Enable Enterprise Learning — expose the Intelligence platform's\n * built-in tools (bash + thread/memory tools) to agent runs on an\n * intelligence runtime that resolve a user. Attached uniformly across\n * agent frameworks by `attachIntelligenceEnterpriseLearning` via\n * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey\n * baked into the transport headers for that request's clone.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue\n * to work without these tools unless they flip this flag.\n */\n enableEnterpriseLearning?: boolean;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Canonical platform thread identifier for the run or connection. */\n threadId: string;\n /** Canonical platform run identifier for an active run lock. */\n runId?: string;\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport type ConnectThreadResponse = ThreadConnectionResponse | null;\n\nexport interface AcquireThreadLockResponse extends ThreadConnectionResponse {\n /** Canonical platform run identifier for the acquired lock. */\n runId: string;\n}\n\n/**\n * Parameters for annotating a thread event via\n * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId`\n * from the customer's BFF auth before calling this; the platform prefixes\n * it with the project id at write time.\n *\n * `payload` is the type-specific JSON blob for the annotation (e.g. a\n * `\"user_action\"` event carries the recorded fields, a\n * `\"set_learning_containers\"` event carries the container list). The exact\n * shape per type is validated by the Intelligence backend; canonical shapes\n * are documented on the Intelligence react-core side.\n */\nexport interface AnnotateParams {\n /** The user the annotation belongs to. */\n userId: string;\n /** The thread the annotation is associated with. May be unknown to the platform. */\n threadId: string;\n /**\n * Discriminator identifying the annotation type.\n * Must match a type known to the Intelligence platform\n * (e.g. `\"user_action\"`, `\"set_learning_containers\"`).\n */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /**\n * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted,\n * a UUID is auto-generated. Every call hits the platform's idempotent\n * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the\n * same id collapses to the original row.\n */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.annotate}. */\nexport interface AnnotateResponse {\n /** Database id of the annotation row (BIGINT, returned as a string). */\n id: string;\n /**\n * True when the platform recognized the `clientEventId` as a retry of\n * a previous call and returned the original row id instead of inserting\n * a new one.\n */\n duplicate: boolean;\n}\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\n/**\n * Persisted AG-UI event for the inspector's debugging views. The platform\n * stores raw events keyed by run; the `_inspect` route returns them in\n * replay order (oldest first) across every run that targeted the thread.\n */\nexport interface ThreadInspectEvent {\n type: string;\n [key: string]: unknown;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the\n * `ThreadEventsResult` shape returned by the platform's\n * `GET /api/_inspect/threads/:id/events` endpoint.\n */\nexport interface ThreadEventsResponse {\n events: ThreadInspectEvent[];\n /** Row IDs the platform failed to decode (raw column corrupted). */\n decodeErrorRowIds: string[];\n /** True when the platform hit its per-thread event cap. */\n truncated: boolean;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the\n * discriminated `ThreadStateResult` returned by the platform's\n * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902\n * STATE_DELTA events on top of the latest STATE_SNAPSHOT.\n */\nexport type ThreadStateResponse =\n | { kind: \"no-snapshot\" }\n | { kind: \"snapshot-decode-error\" }\n | { kind: \"snapshot\"; state: unknown; skippedDeltas: number };\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface CleanupThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #enterpriseLearningEnabled: boolean;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */\n ɵisEnterpriseLearningEnabled(): boolean {\n return this.#enterpriseLearningEnabled;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: { threadId: string }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({ threadId: params.threadId });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n }): Promise<ThreadMessagesResponse> {\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages`,\n );\n }\n\n /**\n * Fetch the persisted AG-UI event stream for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/events`\n * introspection endpoint (see Intelligence PR #144). Events are returned\n * in replay order across every run that targeted the thread. The\n * `_inspect/` prefix flags this as debug-only — production code paths\n * must not depend on it.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadEvents(params: {\n threadId: string;\n }): Promise<ThreadEventsResponse> {\n return this.#request<ThreadEventsResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events`,\n );\n }\n\n /**\n * Fetch the current agent state for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/state`\n * introspection endpoint (see Intelligence PR #144). The platform folds\n * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so\n * the returned state reflects the thread's current state — not just the\n * last snapshot. The discriminated response distinguishes \"no snapshot\n * persisted yet\" from \"snapshot present\" so consumers can render the\n * correct empty state.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadState(params: {\n threadId: string;\n }): Promise<ThreadStateResponse> {\n return this.#request<ThreadStateResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n /**\n * Annotate a thread event on the Intelligence platform's general annotation\n * endpoint (`PUT /connector/annotate/:clientEventId`).\n *\n * This is the generalized replacement for the old\n * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports\n * multiple annotation types via the `type` discriminator:\n * - `\"user_action\"` — records a user UI interaction for the self-learning loop.\n * - `\"set_learning_containers\"` — sets the learning containers for a thread.\n *\n * `userId` must be resolved on the runtime side before calling this — the\n * platform prefixes it with the project id from the API key.\n *\n * Always hits the idempotent `PUT /connector/annotate/:clientEventId`\n * endpoint. A retry with the same `clientEventId` returns\n * `{ id: <original>, duplicate: true }` instead of creating a new row.\n * When `clientEventId` is omitted, a UUID is auto-generated for this call.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses, OR when the\n * platform returns an empty 2xx body (which would otherwise corrupt the\n * caller's typed result).\n */\n async annotate(params: AnnotateParams): Promise<AnnotateResponse> {\n const clientEventId = params.clientEventId ?? randomUUID();\n const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;\n const body: Record<string, unknown> = {\n type: params.type,\n userId: params.userId,\n threadId: params.threadId,\n };\n if (params.payload !== undefined) {\n body.payload = params.payload;\n }\n if (params.occurredAt !== undefined) {\n body.occurredAt = params.occurredAt;\n }\n const response = await this.#request<AnnotateResponse | null | undefined>(\n \"PUT\",\n path,\n body,\n );\n // `== null` catches both `undefined` (empty body from `#request`)\n // and JSON `null` (which would otherwise corrupt the typed result\n // and surface as a `TypeError` deep in caller code).\n if (response == null) {\n logger.error(\n { path },\n \"annotate: Intelligence platform returned 200 with empty or null body\",\n );\n throw new PlatformRequestError(\n \"annotate: empty or null response body from Intelligence platform\",\n 502,\n );\n }\n return response;\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<AcquireThreadLockResponse> {\n return this.#request<AcquireThreadLockResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void> {\n return this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/connect`,\n {\n userId: params.userId,\n agentId: params.agentId,\n },\n );\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\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AS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#enterpriseLearningEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { randomUUID } from \"crypto\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —\n * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`\n * and bakes this header onto the `MCPMiddleware`'s transport config, so every\n * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the\n * public user API.\n *\n * @internal\n */\nexport const INTELLIGENCE_USER_ID_HEADER = \"x-cpki-user-id\";\n\n/**\n * Error thrown when an Intelligence platform HTTP request returns a non-2xx\n * status. Carries the HTTP {@link status} code so callers can branch on\n * specific failures (e.g. 404 for \"not found\", 409 for \"conflict\") without\n * parsing the error message string.\n *\n * @example\n * ```ts\n * try {\n * await intelligence.getThread({ threadId, userId });\n * } catch (error) {\n * if (error instanceof PlatformRequestError && error.status === 404) {\n * // thread does not exist yet\n * }\n * }\n * ```\n */\nexport class PlatformRequestError extends Error {\n constructor(\n message: string,\n /** The HTTP status code returned by the platform (e.g. 404, 409, 500). */\n public readonly status: number,\n ) {\n super(message);\n this.name = \"PlatformRequestError\";\n }\n}\n\n/**\n * Client for the CopilotKit Intelligence Platform REST API.\n *\n * Construct the client once and pass it to any consumers that need it\n * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):\n *\n * ```ts\n * import { CopilotKitIntelligence, CopilotRuntime } from \"@copilotkit/runtime\";\n *\n * const intelligence = new CopilotKitIntelligence({\n * apiUrl: \"https://api.copilotkit.ai\",\n * wsUrl: \"wss://api.copilotkit.ai\",\n * apiKey: process.env.COPILOTKIT_API_KEY!,\n * });\n *\n * const runtime = new CopilotRuntime({\n * agents,\n * intelligence,\n * });\n * ```\n */\n\n/** Payload passed to `onThreadDeleted` listeners. */\nexport interface ThreadDeletedPayload {\n threadId: string;\n userId: string;\n agentId: string;\n}\n\nexport interface CopilotKitIntelligenceConfig {\n /** Base URL of the intelligence platform API, e.g. \"https://api.copilotkit.ai\" */\n apiUrl: string;\n /** Intelligence websocket base URL. Runner and client socket URLs are derived from this. */\n wsUrl: string;\n /** API key for authenticating with the intelligence platform */\n apiKey: string;\n /**\n * Enable Enterprise Learning — expose the Intelligence platform's\n * built-in tools (bash + thread/memory tools) to agent runs on an\n * intelligence runtime that resolve a user. Attached uniformly across\n * agent frameworks by `attachIntelligenceEnterpriseLearning` via\n * `@ag-ui/mcp-middleware`, with the resolved user-id and project apiKey\n * baked into the transport headers for that request's clone.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue\n * to work without these tools unless they flip this flag.\n */\n enableEnterpriseLearning?: boolean;\n /**\n * Initial listener invoked after a thread is created.\n * Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.\n */\n onThreadCreated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is updated.\n * Prefer {@link CopilotKitIntelligence.onThreadUpdated} for multiple listeners.\n */\n onThreadUpdated?: (thread: ThreadSummary) => void;\n /**\n * Initial listener invoked after a thread is deleted.\n * Prefer {@link CopilotKitIntelligence.onThreadDeleted} for multiple listeners.\n */\n onThreadDeleted?: (params: ThreadDeletedPayload) => void;\n}\n\n/**\n * Summary metadata for a single thread returned by the platform.\n *\n * This is the shape returned by list, get, create, and update operations.\n * It does not include the thread's message history — use\n * {@link CopilotKitIntelligence.getThreadMessages} for that.\n */\nexport interface ThreadSummary {\n /** Platform-assigned unique identifier. */\n id: string;\n /** Human-readable display name, or `null` if the thread has not been named. */\n name: string | null;\n /** ISO-8601 timestamp of the most recent agent run on this thread. */\n lastRunAt?: string;\n /** ISO-8601 timestamp of the most recent metadata update. */\n lastUpdatedAt?: string;\n /** ISO-8601 timestamp when the thread was created. */\n createdAt?: string;\n /** ISO-8601 timestamp when the thread was last updated. */\n updatedAt?: string;\n /** Whether the thread has been archived. Archived threads are excluded from default list results. */\n archived?: boolean;\n /** The agent that owns this thread. */\n agentId?: string;\n /** The user who created this thread. */\n createdById?: string;\n /** The organization this thread belongs to. */\n organizationId?: string;\n}\n\n/** Response from listing threads for a user/agent pair. */\nexport interface ListThreadsResponse {\n /** The matching threads, sorted by the platform's default ordering. */\n threads: ThreadSummary[];\n /** Join code for subscribing to realtime metadata updates for these threads. */\n joinCode: string;\n /** Short-lived token for authenticating the realtime subscription. */\n joinToken?: string;\n /** Opaque cursor for fetching the next page. `null` or absent when there are no more pages. */\n nextCursor?: string | null;\n}\n\n/**\n * Fields that can be updated on a thread via {@link CopilotKitIntelligence.updateThread}.\n *\n * Additional platform-specific fields can be passed as extra keys and will be\n * forwarded to the PATCH request body.\n */\nexport interface UpdateThreadRequest {\n /** New human-readable display name for the thread. */\n name?: string;\n [key: string]: unknown;\n}\n\n/** Parameters for creating a new thread via {@link CopilotKitIntelligence.createThread}. */\nexport interface CreateThreadRequest {\n /** Client-generated unique identifier for the new thread. */\n threadId: string;\n /** The user creating the thread. Used for authorization and scoping. */\n userId: string;\n /** The agent this thread belongs to. */\n agentId: string;\n /** Optional initial display name. If omitted, the thread is unnamed until explicitly renamed. */\n name?: string;\n}\n\n/** Credentials returned when locking or joining a thread's realtime channel. */\nexport interface ThreadConnectionResponse {\n /** Canonical platform thread identifier for the run or connection. */\n threadId: string;\n /** Canonical platform run identifier for an active run lock. */\n runId?: string;\n /** Short-lived token for authenticating the Phoenix channel join. */\n joinToken: string;\n /** Lock metadata echoed back by the platform. */\n lock?: ThreadLockInfo;\n}\n\nexport interface SubscribeToThreadsRequest {\n userId: string;\n}\n\nexport interface SubscribeToThreadsResponse {\n joinToken: string;\n}\n\nexport type ConnectThreadResponse = ThreadConnectionResponse | null;\n\nexport interface AcquireThreadLockResponse extends ThreadConnectionResponse {\n /** Canonical platform run identifier for the acquired lock. */\n runId: string;\n}\n\n/**\n * Parameters for annotating a thread event via\n * {@link CopilotKitIntelligence.annotate}. The runtime resolves `userId`\n * from the customer's BFF auth before calling this; the platform prefixes\n * it with the project id at write time.\n *\n * `payload` is the type-specific JSON blob for the annotation (e.g. a\n * `\"user_action\"` event carries the recorded fields, a\n * `\"set_learning_containers\"` event carries the container list). The exact\n * shape per type is validated by the Intelligence backend; canonical shapes\n * are documented on the Intelligence react-core side.\n */\nexport interface AnnotateParams {\n /** The user the annotation belongs to. */\n userId: string;\n /** The thread the annotation is associated with. May be unknown to the platform. */\n threadId: string;\n /**\n * Discriminator identifying the annotation type.\n * Must match a type known to the Intelligence platform\n * (e.g. `\"user_action\"`, `\"set_learning_containers\"`).\n */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /**\n * Caller-supplied idempotency key (any RFC-compliant UUID). When omitted,\n * a UUID is auto-generated. Every call hits the platform's idempotent\n * `PUT /connector/annotate/:clientEventId` endpoint; a retry with the\n * same id collapses to the original row.\n */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.annotate}. */\nexport interface AnnotateResponse {\n /** Database id of the annotation row (BIGINT, returned as a string). */\n id: string;\n /**\n * True when the platform recognized the `clientEventId` as a retry of\n * a previous call and returned the original row id instead of inserting\n * a new one.\n */\n duplicate: boolean;\n}\n\n/** A single message within a thread's persisted history. */\nexport interface ThreadMessage {\n /** Unique identifier for this message. */\n id: string;\n /** Message role, e.g. `\"user\"`, `\"assistant\"`, `\"tool\"`. */\n role: string;\n /** Text content of the message. May be absent for tool-call-only messages. */\n content?: string;\n /** Tool calls initiated by this message (assistant role only). */\n toolCalls?: Array<{\n id: string;\n name: string;\n /** JSON-encoded arguments passed to the tool. */\n args: string;\n }>;\n /** For tool-result messages, the ID of the tool call this message responds to. */\n toolCallId?: string;\n}\n\n/** Response from {@link CopilotKitIntelligence.getThreadMessages}. */\nexport interface ThreadMessagesResponse {\n messages: ThreadMessage[];\n}\n\n/**\n * Persisted AG-UI event for the inspector's debugging views. The platform\n * stores raw events keyed by run; the `_inspect` route returns them in\n * replay order (oldest first) across every run that targeted the thread.\n */\nexport interface ThreadInspectEvent {\n type: string;\n [key: string]: unknown;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadEvents}. Mirrors the\n * `ThreadEventsResult` shape returned by the platform's\n * `GET /api/_inspect/threads/:id/events` endpoint.\n */\nexport interface ThreadEventsResponse {\n events: ThreadInspectEvent[];\n /** Row IDs the platform failed to decode (raw column corrupted). */\n decodeErrorRowIds: string[];\n /** True when the platform hit its per-thread event cap. */\n truncated: boolean;\n}\n\n/**\n * Response from {@link CopilotKitIntelligence.getThreadState}. Mirrors the\n * discriminated `ThreadStateResult` returned by the platform's\n * `GET /api/_inspect/threads/:id/state` endpoint, which folds RFC 6902\n * STATE_DELTA events on top of the latest STATE_SNAPSHOT.\n */\nexport type ThreadStateResponse =\n | { kind: \"no-snapshot\" }\n | { kind: \"snapshot-decode-error\" }\n | { kind: \"snapshot\"; state: unknown; skippedDeltas: number };\n\nexport interface AcquireThreadLockRequest {\n threadId: string;\n runId: string;\n userId: string;\n agentId: string;\n /** Custom Redis key prefix for the lock (default: \"thread\"). */\n lockKeyPrefix?: string;\n /** Lock TTL in seconds. When set, the lock auto-expires after this duration. */\n ttlSeconds?: number;\n}\n\nexport interface RenewThreadLockRequest {\n threadId: string;\n runId: string;\n /** New TTL to set on the lock in seconds. */\n ttlSeconds: number;\n /** Must match the prefix used when acquiring. */\n lockKeyPrefix?: string;\n}\n\nexport interface CleanupThreadLockRequest {\n threadId: string;\n runId: string;\n}\n\nexport interface RenewThreadLockResponse {\n ttlSeconds: number;\n}\n\nexport interface ThreadLockInfo {\n key: string;\n ttlSeconds: number | null;\n}\n\ninterface ThreadEnvelope {\n thread: ThreadSummary;\n}\n\nexport class CopilotKitIntelligence {\n #apiUrl: string;\n #runnerWsUrl: string;\n #clientWsUrl: string;\n #apiKey: string;\n #enterpriseLearningEnabled: boolean;\n #threadCreatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadUpdatedListeners = new Set<(thread: ThreadSummary) => void>();\n #threadDeletedListeners = new Set<(params: ThreadDeletedPayload) => void>();\n\n constructor(config: CopilotKitIntelligenceConfig) {\n const intelligenceWsUrl = normalizeIntelligenceWsUrl(config.wsUrl);\n\n this.#apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);\n this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);\n this.#apiKey = config.apiKey;\n this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;\n\n if (config.onThreadCreated) {\n this.onThreadCreated(config.onThreadCreated);\n }\n if (config.onThreadUpdated) {\n this.onThreadUpdated(config.onThreadUpdated);\n }\n if (config.onThreadDeleted) {\n this.onThreadDeleted(config.onThreadDeleted);\n }\n }\n\n /**\n * Register a listener invoked whenever a thread is created.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the newly created {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n *\n * @example\n * ```ts\n * const unsubscribe = intelligence.onThreadCreated((thread) => {\n * console.log(\"Thread created:\", thread.id);\n * });\n * // later…\n * unsubscribe();\n * ```\n */\n onThreadCreated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadCreatedListeners.add(callback);\n return () => {\n this.#threadCreatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is updated (including archive).\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the updated {@link ThreadSummary}.\n * @returns A function that removes this listener when called.\n */\n onThreadUpdated(callback: (thread: ThreadSummary) => void): () => void {\n this.#threadUpdatedListeners.add(callback);\n return () => {\n this.#threadUpdatedListeners.delete(callback);\n };\n }\n\n /**\n * Register a listener invoked whenever a thread is deleted.\n *\n * Multiple listeners can be registered. Each call returns an unsubscribe\n * function that removes the listener when called.\n *\n * @param callback - Receives the {@link ThreadDeletedPayload} identifying\n * the deleted thread.\n * @returns A function that removes this listener when called.\n */\n onThreadDeleted(\n callback: (params: ThreadDeletedPayload) => void,\n ): () => void {\n this.#threadDeletedListeners.add(callback);\n return () => {\n this.#threadDeletedListeners.delete(callback);\n };\n }\n\n ɵgetApiUrl(): string {\n return this.#apiUrl;\n }\n\n ɵgetRunnerWsUrl(): string {\n return this.#runnerWsUrl;\n }\n\n ɵgetClientWsUrl(): string {\n return this.#clientWsUrl;\n }\n\n ɵgetRunnerAuthToken(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */\n ɵisEnterpriseLearningEnabled(): boolean {\n return this.#enterpriseLearningEnabled;\n }\n\n async #request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.#apiUrl}${path}`;\n\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.#apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n\n const response = await fetch(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n logger.error(\n { status: response.status, body: text, path },\n \"Intelligence platform request failed\",\n );\n throw new PlatformRequestError(\n `Intelligence platform error ${response.status}: ${text || response.statusText}`,\n response.status,\n );\n }\n\n const text = await response.text();\n if (!text) {\n return undefined as T;\n }\n return JSON.parse(text) as T;\n }\n\n #invokeLifecycleCallback(\n callbackName: \"onThreadCreated\" | \"onThreadUpdated\" | \"onThreadDeleted\",\n payload: ThreadSummary | ThreadDeletedPayload,\n ): void {\n const listeners =\n callbackName === \"onThreadCreated\"\n ? this.#threadCreatedListeners\n : callbackName === \"onThreadUpdated\"\n ? this.#threadUpdatedListeners\n : this.#threadDeletedListeners;\n\n for (const callback of listeners) {\n try {\n (callback as (p: typeof payload) => void)(payload);\n } catch (error) {\n logger.error(\n { err: error, callbackName, payload },\n \"Intelligence lifecycle callback failed\",\n );\n }\n }\n }\n\n /**\n * List all non-archived threads for a given user and agent.\n *\n * @param params.userId - User whose threads to list.\n * @param params.agentId - Agent whose threads to list.\n * @returns The thread list along with realtime subscription credentials.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async listThreads(params: {\n userId: string;\n agentId: string;\n includeArchived?: boolean;\n limit?: number;\n cursor?: string;\n }): Promise<ListThreadsResponse> {\n const query: Record<string, string> = {\n userId: params.userId,\n agentId: params.agentId,\n };\n if (params.includeArchived) query.includeArchived = \"true\";\n if (params.limit != null) query.limit = String(params.limit);\n if (params.cursor) query.cursor = params.cursor;\n\n const qs = new URLSearchParams(query).toString();\n return this.#request<ListThreadsResponse>(\"GET\", `/api/threads?${qs}`);\n }\n\n async ɵsubscribeToThreads(\n params: SubscribeToThreadsRequest,\n ): Promise<SubscribeToThreadsResponse> {\n return this.#request<SubscribeToThreadsResponse>(\n \"POST\",\n \"/api/threads/subscribe\",\n {\n userId: params.userId,\n },\n );\n }\n\n /**\n * Update thread metadata (e.g. name).\n *\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @returns The updated thread summary.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async updateThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n updates: UpdateThreadRequest;\n }): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n ...params.updates,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n return response.thread;\n }\n\n /**\n * Create a new thread on the platform.\n *\n * Triggers the `onThreadCreated` lifecycle callback on success.\n *\n * @returns The newly created thread summary.\n * @throws {@link PlatformRequestError} with status 409 if a thread with the\n * same `threadId` already exists.\n */\n async createThread(params: CreateThreadRequest): Promise<ThreadSummary> {\n const response = await this.#request<ThreadEnvelope>(\n \"POST\",\n `/api/threads`,\n {\n threadId: params.threadId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.name !== undefined ? { name: params.name } : {}),\n },\n );\n this.#invokeLifecycleCallback(\"onThreadCreated\", response.thread);\n return response.thread;\n }\n\n /**\n * Fetch a single thread by ID.\n *\n * @returns The thread summary.\n * @throws {@link PlatformRequestError} with status 404 if the thread does\n * not exist.\n */\n async getThread(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadSummary> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n const response = await this.#request<ThreadEnvelope>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`,\n );\n return response.thread;\n }\n\n /**\n * Get an existing thread or create it if it does not exist.\n *\n * Handles the race where a concurrent request creates the thread between\n * the initial 404 and the subsequent `createThread` call by catching the\n * 409 Conflict and retrying the get.\n *\n * Triggers the `onThreadCreated` lifecycle callback when a new thread is\n * created.\n *\n * @returns An object containing the thread and a `created` flag indicating\n * whether the thread was newly created (`true`) or already existed (`false`).\n * @throws {@link PlatformRequestError} on non-2xx responses other than\n * 404 (get) and 409 (create race).\n */\n async getOrCreateThread(\n params: CreateThreadRequest,\n ): Promise<{ thread: ThreadSummary; created: boolean }> {\n try {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n } catch (error) {\n if (!(error instanceof PlatformRequestError && error.status === 404)) {\n throw error;\n }\n }\n\n try {\n const thread = await this.createThread(params);\n return { thread, created: true };\n } catch (error) {\n // Another request created the thread between our get and create — retry get.\n if (error instanceof PlatformRequestError && error.status === 409) {\n const thread = await this.getThread({\n threadId: params.threadId,\n userId: params.userId,\n });\n return { thread, created: false };\n }\n throw error;\n }\n }\n\n /**\n * Fetch the full message history for a thread.\n *\n * @returns All persisted messages in chronological order.\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadMessages(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadMessagesResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadMessagesResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`,\n );\n }\n\n /**\n * Fetch the persisted AG-UI event stream for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/events`\n * introspection endpoint (see Intelligence PR #144). Events are returned\n * in replay order across every run that targeted the thread. The\n * `_inspect/` prefix flags this as debug-only — production code paths\n * must not depend on it.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadEvents(params: {\n threadId: string;\n }): Promise<ThreadEventsResponse> {\n return this.#request<ThreadEventsResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events`,\n );\n }\n\n /**\n * Fetch the current agent state for a thread.\n *\n * Backed by the platform's `GET /api/_inspect/threads/:id/state`\n * introspection endpoint (see Intelligence PR #144). The platform folds\n * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so\n * the returned state reflects the thread's current state — not just the\n * last snapshot. The discriminated response distinguishes \"no snapshot\n * persisted yet\" from \"snapshot present\" so consumers can render the\n * correct empty state.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async getThreadState(params: {\n threadId: string;\n }): Promise<ThreadStateResponse> {\n return this.#request<ThreadStateResponse>(\n \"GET\",\n `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state`,\n );\n }\n\n /**\n * Mark a thread as archived.\n *\n * Archived threads are excluded from {@link listThreads} results.\n * Triggers the `onThreadUpdated` lifecycle callback on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async archiveThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n const response = await this.#request<ThreadEnvelope>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n { userId: params.userId, agentId: params.agentId, archived: true },\n );\n this.#invokeLifecycleCallback(\"onThreadUpdated\", response.thread);\n }\n\n /**\n * Permanently delete a thread and its message history.\n *\n * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback\n * on success.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses.\n */\n async deleteThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<void> {\n await this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}`,\n {\n userId: params.userId,\n agentId: params.agentId,\n reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`,\n },\n );\n this.#invokeLifecycleCallback(\"onThreadDeleted\", params);\n }\n\n /**\n * Annotate a thread event on the Intelligence platform's general annotation\n * endpoint (`PUT /connector/annotate/:clientEventId`).\n *\n * This is the generalized replacement for the old\n * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports\n * multiple annotation types via the `type` discriminator:\n * - `\"user_action\"` — records a user UI interaction for the self-learning loop.\n * - `\"set_learning_containers\"` — sets the learning containers for a thread.\n *\n * `userId` must be resolved on the runtime side before calling this — the\n * platform prefixes it with the project id from the API key.\n *\n * Always hits the idempotent `PUT /connector/annotate/:clientEventId`\n * endpoint. A retry with the same `clientEventId` returns\n * `{ id: <original>, duplicate: true }` instead of creating a new row.\n * When `clientEventId` is omitted, a UUID is auto-generated for this call.\n *\n * @throws {@link PlatformRequestError} on non-2xx responses, OR when the\n * platform returns an empty 2xx body (which would otherwise corrupt the\n * caller's typed result).\n */\n async annotate(params: AnnotateParams): Promise<AnnotateResponse> {\n const clientEventId = params.clientEventId ?? randomUUID();\n const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;\n const body: Record<string, unknown> = {\n type: params.type,\n userId: params.userId,\n threadId: params.threadId,\n };\n if (params.payload !== undefined) {\n body.payload = params.payload;\n }\n if (params.occurredAt !== undefined) {\n body.occurredAt = params.occurredAt;\n }\n const response = await this.#request<AnnotateResponse | null | undefined>(\n \"PUT\",\n path,\n body,\n );\n // `== null` catches both `undefined` (empty body from `#request`)\n // and JSON `null` (which would otherwise corrupt the typed result\n // and surface as a `TypeError` deep in caller code).\n if (response == null) {\n logger.error(\n { path },\n \"annotate: Intelligence platform returned 200 with empty or null body\",\n );\n throw new PlatformRequestError(\n \"annotate: empty or null response body from Intelligence platform\",\n 502,\n );\n }\n return response;\n }\n\n async ɵacquireThreadLock(\n params: AcquireThreadLockRequest,\n ): Promise<AcquireThreadLockResponse> {\n return this.#request<AcquireThreadLockResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n userId: params.userId,\n agentId: params.agentId,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n ...(params.ttlSeconds !== undefined\n ? { ttlSeconds: params.ttlSeconds }\n : {}),\n },\n );\n }\n\n async ɵcleanupThreadLock(params: CleanupThreadLockRequest): Promise<void> {\n return this.#request<void>(\n \"DELETE\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n },\n );\n }\n\n async ɵrenewThreadLock(\n params: RenewThreadLockRequest,\n ): Promise<RenewThreadLockResponse> {\n return this.#request<RenewThreadLockResponse>(\n \"PATCH\",\n `/api/threads/${encodeURIComponent(params.threadId)}/lock`,\n {\n runId: params.runId,\n ttlSeconds: params.ttlSeconds,\n ...(params.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: params.lockKeyPrefix }\n : {}),\n },\n );\n }\n\n async ɵgetActiveJoinCode(params: {\n threadId: string;\n userId: string;\n }): Promise<ThreadConnectionResponse> {\n const qs = new URLSearchParams({ userId: params.userId }).toString();\n return this.#request<ThreadConnectionResponse>(\n \"GET\",\n `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`,\n );\n }\n\n async ɵconnectThread(params: {\n threadId: string;\n userId: string;\n agentId: string;\n }): Promise<ConnectThreadResponse> {\n const result = await this.#request<ThreadConnectionResponse>(\n \"POST\",\n `/api/threads/${encodeURIComponent(params.threadId)}/connect`,\n {\n userId: params.userId,\n agentId: params.agentId,\n },\n );\n\n // request() returns undefined for empty/204 responses\n return result ?? null;\n }\n}\n\nfunction normalizeIntelligenceWsUrl(wsUrl: string): string {\n return wsUrl.replace(/\\/$/, \"\");\n}\n\nfunction deriveRunnerWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/runner\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/client\")) {\n return `${wsUrl.slice(0, -\"/client\".length)}/runner`;\n }\n\n return `${wsUrl}/runner`;\n}\n\nfunction deriveClientWsUrl(wsUrl: string): string {\n if (wsUrl.endsWith(\"/client\")) {\n return wsUrl;\n }\n\n if (wsUrl.endsWith(\"/runner\")) {\n return `${wsUrl.slice(0, -\"/runner\".length)}/client`;\n }\n\n return `${wsUrl}/client`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAkThB,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA;CACA,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAAsC;CACpE,0CAA0B,IAAI,KAA6C;CAE3E,YAAY,QAAsC;EAChD,MAAM,oBAAoB,2BAA2B,OAAO,MAAM;AAElE,QAAKA,SAAU,OAAO,OAAO,QAAQ,OAAO,GAAG;AAC/C,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,cAAe,kBAAkB,kBAAkB;AACxD,QAAKC,SAAU,OAAO;AACtB,QAAKC,4B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EACE,OAAO,OAAO,OACf,CACF;;CAGH,MAAM,iBACJ,QACkC;AAClC,SAAO,MAAKA,QACV,SACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,QACpD;GACE,OAAO,OAAO;GACd,YAAY,OAAO;GACnB,GAAI,OAAO,kBAAkB,SACzB,EAAE,eAAe,OAAO,eAAe,GACvC,EAAE;GACP,CACF;;CAGH,MAAM,mBAAmB,QAGa;EACpC,MAAM,KAAK,IAAI,gBAAgB,EAAE,QAAQ,OAAO,QAAQ,CAAC,CAAC,UAAU;AACpE,SAAO,MAAKA,QACV,OACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,aAAa,KAClE;;CAGH,MAAM,eAAe,QAIc;AAWjC,SAVe,MAAM,MAAKA,QACxB,QACA,gBAAgB,mBAAmB,OAAO,SAAS,CAAC,WACpD;GACE,QAAQ,OAAO;GACf,SAAS,OAAO;GACjB,CACF,IAGgB;;;AAIrB,SAAS,2BAA2B,OAAuB;AACzD,QAAO,MAAM,QAAQ,OAAO,GAAG;;AAGjC,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM;;AAGlB,SAAS,kBAAkB,OAAuB;AAChD,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO;AAGT,KAAI,MAAM,SAAS,UAAU,CAC3B,QAAO,GAAG,MAAM,MAAM,GAAG,GAAkB,CAAC;AAG9C,QAAO,GAAG,MAAM"}
|
|
@@ -378,6 +378,7 @@ declare class CopilotKitIntelligence {
|
|
|
378
378
|
*/
|
|
379
379
|
getThread(params: {
|
|
380
380
|
threadId: string;
|
|
381
|
+
userId: string;
|
|
381
382
|
}): Promise<ThreadSummary>;
|
|
382
383
|
/**
|
|
383
384
|
* Get an existing thread or create it if it does not exist.
|
|
@@ -406,6 +407,7 @@ declare class CopilotKitIntelligence {
|
|
|
406
407
|
*/
|
|
407
408
|
getThreadMessages(params: {
|
|
408
409
|
threadId: string;
|
|
410
|
+
userId: string;
|
|
409
411
|
}): Promise<ThreadMessagesResponse>;
|
|
410
412
|
/**
|
|
411
413
|
* Fetch the persisted AG-UI event stream for a thread.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.cts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;;;;AA2IA;;;;;;;;UAzEiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EAsFf;EApFA,MAAA;EAyFe;EAvFf,KAAA;;EAEA,MAAA;EAuFA;;;;;;AAUF;;;;;EArFE,wBAAA;EA2FA;;;;EAtFA,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA2FZ;;;;EAtFf,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA0FZ;;;;EArFf,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;;AA2F7B;;;UAjFiB,aAAA;EAmFV;EAjFL,EAAA;EAgG6B;EA9F7B,IAAA;EA8F6B;EA5F7B,SAAA;EAgGA;EA9FA,aAAA;EAsGA;EApGA,SAAA;EA6GA;EA3GA,SAAA;EA2GU;EAzGV,QAAA;EA6G+B;EA3G/B,OAAA;EA6GA;EA3GA,WAAA;EAqHe;EAnHf,cAAA;AAAA;;UAIe,mBAAA;EAmHf;EAjHA,OAAA,EAAS,aAAA;EAqHT;EAnHA,QAAA;EAoHE;EAlHF,SAAA;EAqHE;EAnHF,UAAA;AAAA;;AA0HF;;;;;UAjHiB,mBAAA;EA0HkB;EAxHjC,IAAA;EAAA,CACC,GAAA;AAAA;AAiIH;AAAA,UA7HiB,mBAAA;;EAEf,QAAA;EA4HA;EA1HA,MAAA;EA4HA;EA1HA,OAAA;EA4HS;EA1HT,IAAA;AAAA;;UAIe,wBAAA;EA+Hc;EA7H7B,Q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IACd,QAAA;IACA,MAAA;EAAA,IACE,OAAA,CAAQ,aAAA;;;;;;;;;;;;;;;;EAwBN,iBAAA,CACJ,MAAA,EAAQ,mBAAA,GACP,OAAA;IAAU,MAAA,EAAQ,aAAA;IAAe,OAAA;EAAA;;;;;;;EAmC9B,iBAAA,CAAkB,MAAA;IACtB,QAAA;IACA,MAAA;EAAA,IACE,OAAA,CAAQ,sBAAA;;;;;;;;;;;;EAmBN,eAAA,CAAgB,MAAA;IACpB,QAAA;EAAA,IACE,OAAA,CAAQ,oBAAA;;;;;;;;;;;;;;EAoBN,cAAA,CAAe,MAAA;IACnB,QAAA;EAAA,IACE,OAAA,CAAQ,mBAAA;;;;;;;;;EAeN,aAAA,CAAc,MAAA;IAClB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA;;;;;;;;;EAiBE,YAAA,CAAa,MAAA;IACjB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA;;;;;;;;;;;;;;;;;;;;;;;EAmCE,QAAA,CAAS,MAAA,EAAQ,cAAA,GAAiB,OAAA,CAAQ,gBAAA;EAmC1C,kBAAA,CACJ,MAAA,EAAQ,wBAAA,GACP,OAAA,CAAQ,yBAAA;EAkBL,kBAAA,CAAmB,MAAA,EAAQ,wBAAA,GAA2B,OAAA;EAUtD,gBAAA,CACJ,MAAA,EAAQ,sBAAA,GACP,OAAA,CAAQ,uBAAA;EAcL,kBAAA,CAAmB,MAAA;IACvB,QAAA;IACA,MAAA;EAAA,IACE,OAAA,CAAQ,wBAAA;EAQN,cAAA,CAAe,MAAA;IACnB,QAAA;IACA,MAAA;IACA,OAAA;EAAA,IACE,OAAA,CAAQ,qBAAA;AAAA"}
|
|
@@ -378,6 +378,7 @@ declare class CopilotKitIntelligence {
|
|
|
378
378
|
*/
|
|
379
379
|
getThread(params: {
|
|
380
380
|
threadId: string;
|
|
381
|
+
userId: string;
|
|
381
382
|
}): Promise<ThreadSummary>;
|
|
382
383
|
/**
|
|
383
384
|
* Get an existing thread or create it if it does not exist.
|
|
@@ -406,6 +407,7 @@ declare class CopilotKitIntelligence {
|
|
|
406
407
|
*/
|
|
407
408
|
getThreadMessages(params: {
|
|
408
409
|
threadId: string;
|
|
410
|
+
userId: string;
|
|
409
411
|
}): Promise<ThreadMessagesResponse>;
|
|
410
412
|
/**
|
|
411
413
|
* Fetch the persisted AG-UI event stream for a thread.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.mts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;;;;AA2IA;;;;;;;;UAzEiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EAsFf;EApFA,MAAA;EAyFe;EAvFf,KAAA;;EAEA,MAAA;EAuFA;;;;;;AAUF;;;;;EArFE,wBAAA;EA2FA;;;;EAtFA,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA2FZ;;;;EAtFf,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA0FZ;;;;EArFf,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;;AA2F7B;;;UAjFiB,aAAA;EAmFV;EAjFL,EAAA;EAgG6B;EA9F7B,IAAA;EA8F6B;EA5F7B,SAAA;EAgGA;EA9FA,aAAA;EAsGA;EApGA,SAAA;EA6GA;EA3GA,SAAA;EA2GU;EAzGV,QAAA;EA6G+B;EA3G/B,OAAA;EA6GA;EA3GA,WAAA;EAqHe;EAnHf,cAAA;AAAA;;UAIe,mBAAA;EAmHf;EAjHA,OAAA,EAAS,aAAA;EAqHT;EAnHA,QAAA;EAoHE;EAlHF,SAAA;EAqHE;EAnHF,UAAA;AAAA;;AA0HF;;;;;UAjHiB,mBAAA;EA0HkB;EAxHjC,IAAA;EAAA,CACC,GAAA;AAAA;AAiIH;AAAA,UA7HiB,mBAAA;;EAEf,QAAA;EA4HA;EA1HA,MAAA;EA4HA;EA1HA,OAAA;EA4HS;E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-
* await intelligence.getThread({ threadId });
|
|
26
|
+
* await intelligence.getThread({ threadId, userId });
|
|
27
27
|
* } catch (error) {
|
|
28
28
|
* if (error instanceof PlatformRequestError && error.status === 404) {
|
|
29
29
|
* // thread does not exist yet
|
|
@@ -235,7 +235,8 @@ var CopilotKitIntelligence = class {
|
|
|
235
235
|
* not exist.
|
|
236
236
|
*/
|
|
237
237
|
async getThread(params) {
|
|
238
|
-
|
|
238
|
+
const qs = new URLSearchParams({ userId: params.userId }).toString();
|
|
239
|
+
return (await this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`)).thread;
|
|
239
240
|
}
|
|
240
241
|
/**
|
|
241
242
|
* Get an existing thread or create it if it does not exist.
|
|
@@ -255,7 +256,10 @@ var CopilotKitIntelligence = class {
|
|
|
255
256
|
async getOrCreateThread(params) {
|
|
256
257
|
try {
|
|
257
258
|
return {
|
|
258
|
-
thread: await this.getThread({
|
|
259
|
+
thread: await this.getThread({
|
|
260
|
+
threadId: params.threadId,
|
|
261
|
+
userId: params.userId
|
|
262
|
+
}),
|
|
259
263
|
created: false
|
|
260
264
|
};
|
|
261
265
|
} catch (error) {
|
|
@@ -268,7 +272,10 @@ var CopilotKitIntelligence = class {
|
|
|
268
272
|
};
|
|
269
273
|
} catch (error) {
|
|
270
274
|
if (error instanceof PlatformRequestError && error.status === 409) return {
|
|
271
|
-
thread: await this.getThread({
|
|
275
|
+
thread: await this.getThread({
|
|
276
|
+
threadId: params.threadId,
|
|
277
|
+
userId: params.userId
|
|
278
|
+
}),
|
|
272
279
|
created: false
|
|
273
280
|
};
|
|
274
281
|
throw error;
|
|
@@ -281,7 +288,8 @@ var CopilotKitIntelligence = class {
|
|
|
281
288
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
282
289
|
*/
|
|
283
290
|
async getThreadMessages(params) {
|
|
284
|
-
|
|
291
|
+
const qs = new URLSearchParams({ userId: params.userId }).toString();
|
|
292
|
+
return this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`);
|
|
285
293
|
}
|
|
286
294
|
/**
|
|
287
295
|
* Fetch the persisted AG-UI event stream for a thread.
|
|
@@ -338,7 +346,11 @@ var CopilotKitIntelligence = class {
|
|
|
338
346
|
* @throws {@link PlatformRequestError} on non-2xx responses.
|
|
339
347
|
*/
|
|
340
348
|
async deleteThread(params) {
|
|
341
|
-
await this.#request("DELETE", `/api/threads/${encodeURIComponent(params.threadId)}`, {
|
|
349
|
+
await this.#request("DELETE", `/api/threads/${encodeURIComponent(params.threadId)}`, {
|
|
350
|
+
userId: params.userId,
|
|
351
|
+
agentId: params.agentId,
|
|
352
|
+
reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`
|
|
353
|
+
});
|
|
342
354
|
this.#invokeLifecycleCallback("onThreadDeleted", params);
|
|
343
355
|
}
|
|
344
356
|
/**
|