@copilotkit/runtime 1.57.0 → 1.57.1-canary.1778272612
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 +21 -2
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +9 -16
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +9 -16
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +22 -3
- package/dist/agent/index.mjs.map +1 -1
- package/dist/package.cjs +2 -2
- package/dist/package.mjs +2 -2
- package/dist/v2/index.d.cts +2 -2
- package/dist/v2/index.d.mts +2 -2
- package/dist/v2/runtime/handlers/intelligence/run.cjs +15 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +15 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +2 -1
- package/dist/v2/runtime/index.d.cts.map +1 -1
- package/dist/v2/runtime/index.d.mts +2 -1
- package/dist/v2/runtime/index.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +22 -0
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +17 -0
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +17 -0
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +22 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/package.json +3 -3
- package/src/agent/__tests__/mcp-clients.test.ts +11 -25
- package/src/agent/index.ts +75 -32
- package/src/v2/runtime/handlers/intelligence/run.ts +33 -5
- package/src/v2/runtime/handlers/shared/agent-utils.ts +4 -6
- package/src/v2/runtime/index.ts +5 -0
- package/src/v2/runtime/intelligence-platform/__tests__/intelligence-mcp-helper.test.ts +246 -0
- package/src/v2/runtime/intelligence-platform/client.ts +37 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import {\n AbstractAgent,\n BaseEvent,\n EventType,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport { Observable } from \"rxjs\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: canonicalThreadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Start heartbeat timer to renew the thread lock.\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n heartbeatTimer = setInterval(() => {\n runtime.intelligence\n .ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n })\n .catch((err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n clearHeartbeat();\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n });\n }, runtime.lockHeartbeatIntervalSeconds * 1_000);\n\n const clearHeartbeat = () => {\n if (heartbeatTimer !== undefined) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n }\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR && !runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n },\n error: (error) => {\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n await runStart.startup;\n } catch (error) {\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(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AAQ,4CAA4C,EAAE,CAAC;;GAEpE,CAAC;AAEF,QAAM,SAAS;UACR,OAAO;AACd,kBAAgB;AAChB,SAAO,2BAA2B,YAAY,qBAAqB;AACnE,SAAO,MAAM,gCAAgC,MAAM;AACnD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB;;AAGH,KAAI,8BAA8B;AAChC,QAAM;AACN,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS;GACV,EACD,EAAE,QAAQ,KAAK,CAChB;;AAKH,QAAO,SAAS,KACd;EACE,UAAU;EACV,OAAO;EACP;EACA,UAAU,4BAA4B;GACpC,WAAW,QAAQ,aAAa,iBAAiB;GACjD,UAAU;GACX,CAAC;EACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
|
|
1
|
+
{"version":3,"file":"run.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/run.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\nimport type { CopilotIntelligenceRuntimeLike } from \"../../core/runtime\";\nimport { generateThreadNameForNewThread } from \"./thread-names\";\nimport { logger } from \"@copilotkit/shared\";\nimport { telemetry } from \"../../telemetry\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"../shared/json-response\";\nimport type { AgentRunnerRunRequest } from \"../../runner/agent-runner\";\nimport type { Observable } from \"rxjs\";\n\n/**\n * Builds browser-facing realtime connection metadata owned by the runtime.\n */\nfunction buildRealtimeConnectionInfo(params: {\n clientUrl: string;\n threadId: string;\n}): { clientUrl: string; topic: string } {\n return {\n clientUrl: params.clientUrl,\n topic: `thread:${params.threadId}`,\n };\n}\n\ninterface RunnerStartupBoundary {\n events: Observable<BaseEvent>;\n startup: Promise<void>;\n}\n\ninterface RunnerWithStartupBoundary {\n runWithStartupBoundary(request: AgentRunnerRunRequest): RunnerStartupBoundary;\n}\n\nfunction hasRunnerStartupBoundary(\n runner: CopilotIntelligenceRuntimeLike[\"runner\"],\n): runner is CopilotIntelligenceRuntimeLike[\"runner\"] &\n RunnerWithStartupBoundary {\n const candidate = runner as { runWithStartupBoundary?: unknown };\n\n return (\n typeof candidate.runWithStartupBoundary === \"function\" &&\n (Object.prototype.hasOwnProperty.call(runner, \"runWithStartupBoundary\") ||\n Object.prototype.hasOwnProperty.call(runner, \"threads\"))\n );\n}\n\ninterface HandleIntelligenceRunParams {\n runtime: CopilotIntelligenceRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\nexport async function handleIntelligenceRun({\n runtime,\n request,\n agentId,\n agent,\n input,\n}: HandleIntelligenceRunParams): Promise<Response> {\n if (!runtime.intelligence) {\n return Response.json(\n {\n error: \"Intelligence not configured\",\n message: \"Intelligence mode requires a CopilotKitIntelligence\",\n },\n { status: 500 },\n );\n }\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) {\n return user;\n }\n const userId = user.id;\n\n try {\n const { thread, created } = await runtime.intelligence.getOrCreateThread({\n threadId: input.threadId,\n userId,\n agentId,\n });\n\n if (created && runtime.generateThreadNames && !thread.name?.trim()) {\n void generateThreadNameForNewThread({\n runtime,\n request,\n agentId,\n sourceInput: input,\n thread,\n userId,\n }).catch((nameError) => {\n logger.error(\"Failed to generate thread name:\", nameError);\n });\n }\n } catch (error) {\n logger.error(\"Failed to get or create thread:\", error);\n return Response.json(\n {\n error: \"Failed to initialize thread\",\n },\n { status: 502 },\n );\n }\n\n let canonicalThreadId = input.threadId;\n let canonicalRunId = input.runId;\n let joinToken: string | undefined;\n try {\n const lockResult = await runtime.intelligence.ɵacquireThreadLock({\n threadId: input.threadId,\n runId: input.runId,\n userId,\n agentId,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n ttlSeconds: runtime.lockTtlSeconds,\n });\n canonicalThreadId = lockResult.threadId;\n canonicalRunId = lockResult.runId;\n joinToken = lockResult.joinToken;\n } catch (error) {\n logger.error(\"Thread lock denied:\", error);\n return Response.json(\n {\n error: \"Thread lock denied\",\n },\n { status: 409 },\n );\n }\n\n const cleanupLock = (reason: string): Promise<void> =>\n runtime.intelligence\n .ɵcleanupThreadLock({\n threadId: canonicalThreadId || input.threadId,\n runId: canonicalRunId || input.runId,\n })\n .catch((cleanupError) => {\n logger.error(\n { err: cleanupError, reason },\n \"Failed to cleanup thread lock\",\n );\n });\n\n if (!canonicalThreadId || !canonicalRunId || !joinToken) {\n await cleanupLock(\"malformed-lock-response\");\n return Response.json(\n {\n error: \"Run connection credentials not available\",\n message:\n \"Intelligence platform did not return canonical threadId, runId, and joinToken\",\n },\n { status: 502 },\n );\n }\n\n // When Intelligence has `mcpServer: true`, hand the agent the per-request\n // bits it needs to attach the platform's MCP server: the resolved user-id,\n // the project Bearer (`apiKey`), and the MCP URL. These ride through\n // `forwardedProps.auth.copilotkitIntelligence` so the agent doesn't need a\n // typed reference to the Intelligence client. `BuiltInAgent` reads the\n // bag and builds a per-request MCP config with a closure-baked fetch;\n // non-BuiltInAgent agents naturally ignore the key. The `auth` namespace\n // is the convention for credentials that downstream redaction policies\n // strip before durable storage and FE replay.\n const upstreamAuth =\n (input.forwardedProps as { auth?: Record<string, unknown> } | undefined)\n ?.auth ?? {};\n const copilotkitIntelligenceAuth =\n runtime.intelligence.ɵisMcpServerEnabled?.()\n ? {\n copilotkitIntelligence: {\n userId,\n apiKey: runtime.intelligence.ɵgetApiKey(),\n mcpUrl: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n },\n }\n : {};\n const mergedAuth = { ...upstreamAuth, ...copilotkitIntelligenceAuth };\n\n const canonicalInput: RunAgentInput = {\n ...input,\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n forwardedProps: {\n ...input.forwardedProps,\n ...(Object.keys(mergedAuth).length > 0 ? { auth: mergedAuth } : {}),\n },\n };\n\n let persistedInputMessages: Message[] | undefined;\n if (Array.isArray(input.messages)) {\n try {\n const history = await runtime.intelligence.getThreadMessages({\n threadId: canonicalThreadId,\n });\n const historicMessageIds = new Set(\n history.messages.map((message) => message.id),\n );\n persistedInputMessages = input.messages.filter(\n (message) => !historicMessageIds.has(message.id),\n );\n } catch (error) {\n logger.error(\"Thread history lookup failed:\", error);\n await cleanupLock(\"thread-history-lookup-failed\");\n return Response.json(\n {\n error: \"Thread history lookup failed\",\n },\n { status: 502 },\n );\n }\n }\n\n telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n\n // Start heartbeat timer to renew the thread lock.\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n heartbeatTimer = setInterval(() => {\n runtime.intelligence\n .ɵrenewThreadLock({\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n ttlSeconds: runtime.lockTtlSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n })\n .catch((err) => {\n logger.error(\"Failed to renew thread lock:\", err);\n clearHeartbeat();\n try {\n agent.abortRun();\n } catch (abortError) {\n logger.error(\n \"Failed to abort agent after lock renewal failure:\",\n abortError,\n );\n }\n });\n }, runtime.lockHeartbeatIntervalSeconds * 1_000);\n\n const clearHeartbeat = () => {\n if (heartbeatTimer !== undefined) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = undefined;\n }\n };\n\n const runStarted = { current: false };\n let immediateStartupErrorMessage: string | undefined;\n let immediateStartupCleanup: Promise<void> | undefined;\n\n const runRequest: AgentRunnerRunRequest = {\n threadId: canonicalThreadId,\n agent,\n input: canonicalInput,\n ...(persistedInputMessages !== undefined ? { persistedInputMessages } : {}),\n };\n\n try {\n const runStart = hasRunnerStartupBoundary(runtime.runner)\n ? runtime.runner.runWithStartupBoundary(runRequest)\n : {\n events: runtime.runner.run(runRequest),\n startup: Promise.resolve(),\n };\n\n runStart.events.subscribe({\n next: (event: BaseEvent) => {\n if (event.type === EventType.RUN_STARTED) {\n runStarted.current = true;\n }\n if (event.type === EventType.RUN_ERROR && !runStarted.current) {\n clearHeartbeat();\n immediateStartupErrorMessage =\n \"message\" in event && typeof event.message === \"string\"\n ? event.message\n : \"Runner failed before the run started\";\n immediateStartupCleanup = cleanupLock(\"runner-start-failed\");\n }\n },\n error: (error) => {\n clearHeartbeat();\n if (!runStarted.current) {\n immediateStartupErrorMessage =\n error instanceof Error ? error.message : String(error);\n immediateStartupCleanup = cleanupLock(\"runner-start-error\");\n } else {\n cleanupLock(\"runner-error\");\n }\n telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n error: error instanceof Error ? error.message : String(error),\n });\n logger.error(\"Error running agent:\", error);\n },\n complete: () => {\n clearHeartbeat();\n telemetry.capture(\"oss.runtime.agent_execution_stream_ended\", {});\n },\n });\n\n await runStart.startup;\n } catch (error) {\n clearHeartbeat();\n await (immediateStartupCleanup ?? cleanupLock(\"runner-start-threw\"));\n logger.error(\"Error starting agent runner:\", error);\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n\n if (immediateStartupErrorMessage) {\n await immediateStartupCleanup;\n return Response.json(\n {\n error: \"Failed to start runner\",\n message: immediateStartupErrorMessage,\n },\n { status: 502 },\n );\n }\n\n // IntelligenceAgentRunner resolves this boundary after Phoenix channel join.\n // Other runner implementations fall back to construction/subscription errors.\n return Response.json(\n {\n threadId: canonicalThreadId,\n runId: canonicalRunId,\n joinToken,\n realtime: buildRealtimeConnectionInfo({\n clientUrl: runtime.intelligence.ɵgetClientWsUrl(),\n threadId: canonicalThreadId,\n }),\n },\n {\n headers: { \"Cache-Control\": \"no-cache\" },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAS,4BAA4B,QAGI;AACvC,QAAO;EACL,WAAW,OAAO;EAClB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AA0B,YAAY,qBAAqB;UAE3D,aAAY,eAAe;AAE7B,cAAU,QAAQ,8CAA8C,EAC9D,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC9D,CAAC;AACF,WAAO,MAAM,wBAAwB,MAAM;;GAE7C,gBAAgB;AACd,oBAAgB;AAChB,cAAU,QAAQ,4CAA4C,EAAE,CAAC;;GAEpE,CAAC;AAEF,QAAM,SAAS;UACR,OAAO;AACd,kBAAgB;AAChB,SAAO,2BAA2B,YAAY,qBAAqB;AACnE,SAAO,MAAM,gCAAgC,MAAM;AACnD,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,EACD,EAAE,QAAQ,KAAK,CAChB;;AAGH,KAAI,8BAA8B;AAChC,QAAM;AACN,SAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS;GACV,EACD,EAAE,QAAQ,KAAK,CAChB;;AAKH,QAAO,SAAS,KACd;EACE,UAAU;EACV,OAAO;EACP;EACA,UAAU,4BAA4B;GACpC,WAAW,QAAQ,aAAa,iBAAiB;GACjD,UAAU;GACX,CAAC;EACH,EACD,EACE,SAAS,EAAE,iBAAiB,YAAY,EACzC,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-utils.cjs","names":["resolveAgents","A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","extractForwardableHeaders","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"agent-utils.cjs","names":["resolveAgents","A2UIMiddleware","MCPAppsMiddleware","OpenGenerativeUIMiddleware","extractForwardableHeaders","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { resolveAgents } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;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SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { resolveAgents } from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport { extractForwardableHeaders } from \"../header-utils\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n}): void {\n const { runtime, request, agentId } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (runtime.a2ui) {\n const { agents: targetAgents, ...a2uiOptions } = runtime.a2ui;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new A2UIMiddleware(a2uiOptions));\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = runtime.mcpApps.servers\n .filter((server) => !server.agentId || server.agentId === agentId)\n .map((server) => {\n const mcpServer = { ...server };\n delete mcpServer.agentId;\n return mcpServer;\n });\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n if (agent.headers) {\n agent.headers = {\n ...agent.headers,\n ...extractForwardableHeaders(request),\n };\n }\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAyBA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAKhC;CACP,MAAM,EAAE,SAAS,SAAS,YAAY;CACtC,MAAM,QAAQ,OAAO;AAErB,KAAI,QAAQ,MAAM;EAChB,MAAM,EAAE,QAAQ,cAAc,GAAG,gB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B,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
|
|
@@ -14,6 +14,7 @@ import { InMemoryAgentRunner, InMemoryThread } from "./runner/in-memory.cjs";
|
|
|
14
14
|
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
|
|
15
15
|
import { finalizeRunEvents } from "./runner/index.cjs";
|
|
16
16
|
import { CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.cjs";
|
|
17
|
+
import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
|
|
17
18
|
|
|
18
19
|
//#region src/v2/runtime/index.d.ts
|
|
19
20
|
/** @deprecated Use `CopilotRuntimeFetchHandler` instead. Note: the new type takes `Request` directly, not `{ request: Request }`. */
|
|
@@ -21,5 +22,5 @@ type CopilotKitRequestHandler = (params: {
|
|
|
21
22
|
request: Request;
|
|
22
23
|
}) => Promise<Response>;
|
|
23
24
|
//#endregion
|
|
24
|
-
export { CopilotKitRequestHandler };
|
|
25
|
+
export { CopilotKitRequestHandler, type MCPClient, type MCPTransport };
|
|
25
26
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/v2/runtime/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/v2/runtime/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;KAgDY,wBAAA,IAA4B,MAAA;EACtC,OAAA,EAAS,OAAA;AAAA,MACL,OAAA,CAAQ,QAAA"}
|
|
@@ -14,6 +14,7 @@ import { InMemoryAgentRunner, InMemoryThread } from "./runner/in-memory.mjs";
|
|
|
14
14
|
import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
|
|
15
15
|
import { finalizeRunEvents } from "./runner/index.mjs";
|
|
16
16
|
import { CopilotRuntimeFetchHandler, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.mjs";
|
|
17
|
+
import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
|
|
17
18
|
|
|
18
19
|
//#region src/v2/runtime/index.d.ts
|
|
19
20
|
/** @deprecated Use `CopilotRuntimeFetchHandler` instead. Note: the new type takes `Request` directly, not `{ request: Request }`. */
|
|
@@ -21,5 +22,5 @@ type CopilotKitRequestHandler = (params: {
|
|
|
21
22
|
request: Request;
|
|
22
23
|
}) => Promise<Response>;
|
|
23
24
|
//#endregion
|
|
24
|
-
export { CopilotKitRequestHandler };
|
|
25
|
+
export { CopilotKitRequestHandler, type MCPClient, type MCPTransport };
|
|
25
26
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/v2/runtime/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/v2/runtime/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;KAgDY,wBAAA,IAA4B,MAAA;EACtC,OAAA,EAAS,OAAA;AAAA,MACL,OAAA,CAAQ,QAAA"}
|
|
@@ -4,6 +4,17 @@ let _copilotkit_shared = require("@copilotkit/shared");
|
|
|
4
4
|
|
|
5
5
|
//#region src/v2/runtime/intelligence-platform/client.ts
|
|
6
6
|
/**
|
|
7
|
+
* Header name carrying the per-call end-user identity that the CopilotKit
|
|
8
|
+
* Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery — the
|
|
9
|
+
* runtime stamps this onto `agent.headers` after `identifyUser` resolves,
|
|
10
|
+
* and the auto-attach in `configureAgentForRequest` reads it back to gate
|
|
11
|
+
* MCP-server attachment and to populate the outbound `X-Cpki-User-Id`
|
|
12
|
+
* header on every MCP request. Not part of the public user API.
|
|
13
|
+
*
|
|
14
|
+
* @internal
|
|
15
|
+
*/
|
|
16
|
+
const INTELLIGENCE_USER_ID_HEADER = "x-cpki-user-id";
|
|
17
|
+
/**
|
|
7
18
|
* Error thrown when an Intelligence platform HTTP request returns a non-2xx
|
|
8
19
|
* status. Carries the HTTP {@link status} code so callers can branch on
|
|
9
20
|
* specific failures (e.g. 404 for "not found", 409 for "conflict") without
|
|
@@ -32,6 +43,7 @@ var CopilotKitIntelligence = class {
|
|
|
32
43
|
#runnerWsUrl;
|
|
33
44
|
#clientWsUrl;
|
|
34
45
|
#apiKey;
|
|
46
|
+
#mcpServerEnabled;
|
|
35
47
|
#threadCreatedListeners = /* @__PURE__ */ new Set();
|
|
36
48
|
#threadUpdatedListeners = /* @__PURE__ */ new Set();
|
|
37
49
|
#threadDeletedListeners = /* @__PURE__ */ new Set();
|
|
@@ -41,6 +53,7 @@ var CopilotKitIntelligence = class {
|
|
|
41
53
|
this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
|
|
42
54
|
this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
|
|
43
55
|
this.#apiKey = config.apiKey;
|
|
56
|
+
this.#mcpServerEnabled = config.mcpServer ?? false;
|
|
44
57
|
if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
|
|
45
58
|
if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
|
|
46
59
|
if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
|
|
@@ -112,6 +125,14 @@ var CopilotKitIntelligence = class {
|
|
|
112
125
|
ɵgetRunnerAuthToken() {
|
|
113
126
|
return this.#apiKey;
|
|
114
127
|
}
|
|
128
|
+
/** @internal Used by the runtime's auto-attach to populate `Authorization`. */
|
|
129
|
+
ɵgetApiKey() {
|
|
130
|
+
return this.#apiKey;
|
|
131
|
+
}
|
|
132
|
+
/** @internal Used by the runtime's auto-attach to gate MCP attachment. */
|
|
133
|
+
ɵisMcpServerEnabled() {
|
|
134
|
+
return this.#mcpServerEnabled;
|
|
135
|
+
}
|
|
115
136
|
async #request(method, path, body) {
|
|
116
137
|
const url = `${this.#apiUrl}${path}`;
|
|
117
138
|
const headers = {
|
|
@@ -366,5 +387,6 @@ function deriveClientWsUrl(wsUrl) {
|
|
|
366
387
|
|
|
367
388
|
//#endregion
|
|
368
389
|
exports.CopilotKitIntelligence = CopilotKitIntelligence;
|
|
390
|
+
exports.INTELLIGENCE_USER_ID_HEADER = INTELLIGENCE_USER_ID_HEADER;
|
|
369
391
|
exports.PlatformRequestError = PlatformRequestError;
|
|
370
392
|
//# sourceMappingURL=client.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\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 * 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/** 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 #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\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 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 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":";;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,OAAO;;;AAsPhB,IAAa,yBAAb,MAAoC;CAClC;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;AAEtB,MAAI,OAAO,gBACT,MAAK,g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BAAkB,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"}
|
|
1
|
+
{"version":3,"file":"client.cjs","names":["#apiUrl","#runnerWsUrl","#clientWsUrl","#apiKey","#mcpServerEnabled","#threadCreatedListeners","#threadUpdatedListeners","#threadDeletedListeners","#request","#invokeLifecycleCallback"],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\n\n/**\n * Header name carrying the per-call end-user identity that the CopilotKit\n * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery — the\n * runtime stamps this onto `agent.headers` after `identifyUser` resolves,\n * and the auto-attach in `configureAgentForRequest` reads it back to gate\n * MCP-server attachment and to populate the outbound `X-Cpki-User-Id`\n * header on every MCP request. Not part of the 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 the Intelligence platform's MCP server (bash + thread tools) on\n * every `BuiltInAgent` run that resolves a user. The auto-attach is\n * implemented in `configureAgentForRequest`: when this flag is `true`\n * AND the runtime's `identifyUser` callback has placed a user-id onto\n * the agent's forwarded headers AND the user has not already configured\n * an MCP server pointing at the same URL, the server is appended to the\n * agent's effective MCP server list for that run.\n *\n * Defaults to `false` — opt-in. Existing intelligence setups continue to\n * work without the bash MCP server unless they flip this flag.\n */\n mcpServer?: 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/** 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 #mcpServerEnabled: 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.#mcpServerEnabled = config.mcpServer ?? 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 the runtime's auto-attach to populate `Authorization`. */\n ɵgetApiKey(): string {\n return this.#apiKey;\n }\n\n /** @internal Used by the runtime's auto-attach to gate MCP attachment. */\n ɵisMcpServerEnabled(): boolean {\n return this.#mcpServerEnabled;\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 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":";;;;;;;;;;;;;;;AAYA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;AAmB3C,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YACE,SAEA,AAAgB,QAChB;AACA,QAAM,QAAQ;EAFE;AAGhB,OAAK,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,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"}
|
|
@@ -34,6 +34,19 @@ interface CopilotKitIntelligenceConfig {
|
|
|
34
34
|
wsUrl: string;
|
|
35
35
|
/** API key for authenticating with the intelligence platform */
|
|
36
36
|
apiKey: string;
|
|
37
|
+
/**
|
|
38
|
+
* Enable the Intelligence platform's MCP server (bash + thread tools) on
|
|
39
|
+
* every `BuiltInAgent` run that resolves a user. The auto-attach is
|
|
40
|
+
* implemented in `configureAgentForRequest`: when this flag is `true`
|
|
41
|
+
* AND the runtime's `identifyUser` callback has placed a user-id onto
|
|
42
|
+
* the agent's forwarded headers AND the user has not already configured
|
|
43
|
+
* an MCP server pointing at the same URL, the server is appended to the
|
|
44
|
+
* agent's effective MCP server list for that run.
|
|
45
|
+
*
|
|
46
|
+
* Defaults to `false` — opt-in. Existing intelligence setups continue to
|
|
47
|
+
* work without the bash MCP server unless they flip this flag.
|
|
48
|
+
*/
|
|
49
|
+
mcpServer?: boolean;
|
|
37
50
|
/**
|
|
38
51
|
* Initial listener invoked after a thread is created.
|
|
39
52
|
* Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.
|
|
@@ -267,6 +280,10 @@ declare class CopilotKitIntelligence {
|
|
|
267
280
|
ɵgetRunnerWsUrl(): string;
|
|
268
281
|
ɵgetClientWsUrl(): string;
|
|
269
282
|
ɵgetRunnerAuthToken(): string;
|
|
283
|
+
/** @internal Used by the runtime's auto-attach to populate `Authorization`. */
|
|
284
|
+
ɵgetApiKey(): string;
|
|
285
|
+
/** @internal Used by the runtime's auto-attach to gate MCP attachment. */
|
|
286
|
+
ɵisMcpServerEnabled(): boolean;
|
|
270
287
|
/**
|
|
271
288
|
* List all non-archived threads for a given user and agent.
|
|
272
289
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.cts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.cts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;;;;AA2IA;;;;;;;;UA1EiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EAuFf;EArFA,MAAA;EA0Fe;EAxFf,KAAA;;EAEA,MAAA;EAwFA;;;;;;AAUF;;;;;;EArFE,SAAA;EA6FA;;;;EAxFA,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA2Fa;;;;EAtFxC,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA0Fc;;;;EArFzC,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;AA2F7B;;;;UAjFiB,aAAA;EAuFA;EArFf,EAAA;;EAEA,IAAA;EAqFA;EAnFA,SAAA;EAuFA;EArFA,aAAA;EAuFY;EArFZ,SAAA;EAuFE;EArFF,SAAA;EA0FA;EAxFA,QAAA;EAwFU;EAtFV,OAAA;EA0FqC;EAxFrC,WAAA;EAy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A;;;;;;;;;;;;EAkBN,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;EAWE,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"}
|
|
@@ -34,6 +34,19 @@ interface CopilotKitIntelligenceConfig {
|
|
|
34
34
|
wsUrl: string;
|
|
35
35
|
/** API key for authenticating with the intelligence platform */
|
|
36
36
|
apiKey: string;
|
|
37
|
+
/**
|
|
38
|
+
* Enable the Intelligence platform's MCP server (bash + thread tools) on
|
|
39
|
+
* every `BuiltInAgent` run that resolves a user. The auto-attach is
|
|
40
|
+
* implemented in `configureAgentForRequest`: when this flag is `true`
|
|
41
|
+
* AND the runtime's `identifyUser` callback has placed a user-id onto
|
|
42
|
+
* the agent's forwarded headers AND the user has not already configured
|
|
43
|
+
* an MCP server pointing at the same URL, the server is appended to the
|
|
44
|
+
* agent's effective MCP server list for that run.
|
|
45
|
+
*
|
|
46
|
+
* Defaults to `false` — opt-in. Existing intelligence setups continue to
|
|
47
|
+
* work without the bash MCP server unless they flip this flag.
|
|
48
|
+
*/
|
|
49
|
+
mcpServer?: boolean;
|
|
37
50
|
/**
|
|
38
51
|
* Initial listener invoked after a thread is created.
|
|
39
52
|
* Prefer {@link CopilotKitIntelligence.onThreadCreated} for multiple listeners.
|
|
@@ -267,6 +280,10 @@ declare class CopilotKitIntelligence {
|
|
|
267
280
|
ɵgetRunnerWsUrl(): string;
|
|
268
281
|
ɵgetClientWsUrl(): string;
|
|
269
282
|
ɵgetRunnerAuthToken(): string;
|
|
283
|
+
/** @internal Used by the runtime's auto-attach to populate `Authorization`. */
|
|
284
|
+
ɵgetApiKey(): string;
|
|
285
|
+
/** @internal Used by the runtime's auto-attach to gate MCP attachment. */
|
|
286
|
+
ɵisMcpServerEnabled(): boolean;
|
|
270
287
|
/**
|
|
271
288
|
* List all non-archived threads for a given user and agent.
|
|
272
289
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.mts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.d.mts","names":[],"sources":["../../../../src/v2/runtime/intelligence-platform/client.ts"],"mappings":";;;;;;;;;;;;;;;;AA2IA;;;;;;;;UA1EiB,oBAAA;EACf,QAAA;EACA,MAAA;EACA,OAAA;AAAA;AAAA,UAGe,4BAAA;EAuFf;EArFA,MAAA;EA0Fe;EAxFf,KAAA;;EAEA,MAAA;EAwFA;;;;;;AAUF;;;;;;EArFE,SAAA;EA6FA;;;;EAxFA,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA2Fa;;;;EAtFxC,eAAA,IAAmB,MAAA,EAAQ,aAAA;EA0Fc;;;;EArFzC,eAAA,IAAmB,MAAA,EAAQ,oBAAA;AAAA;;;;AA2F7B;;;;UAjFiB,aAAA;EAuFA;EArFf,EAAA;;EAEA,IAAA;EAqFA;EAnFA,SAAA;EAuFA;EArFA,aAAA;EAuFY;EArFZ,SAAA;EAuFE;EArFF,SAAA;EA0FA;EAxFA,QAAA;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MAAA;IACtB,QAAA;EAAA,IACE,OAAA,CAAQ,sBAAA;;;;;;;;;;;;EAkBN,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;EAWE,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"}
|
|
@@ -3,6 +3,17 @@ import { logger } from "@copilotkit/shared";
|
|
|
3
3
|
|
|
4
4
|
//#region src/v2/runtime/intelligence-platform/client.ts
|
|
5
5
|
/**
|
|
6
|
+
* Header name carrying the per-call end-user identity that the CopilotKit
|
|
7
|
+
* Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery — the
|
|
8
|
+
* runtime stamps this onto `agent.headers` after `identifyUser` resolves,
|
|
9
|
+
* and the auto-attach in `configureAgentForRequest` reads it back to gate
|
|
10
|
+
* MCP-server attachment and to populate the outbound `X-Cpki-User-Id`
|
|
11
|
+
* header on every MCP request. Not part of the public user API.
|
|
12
|
+
*
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
const INTELLIGENCE_USER_ID_HEADER = "x-cpki-user-id";
|
|
16
|
+
/**
|
|
6
17
|
* Error thrown when an Intelligence platform HTTP request returns a non-2xx
|
|
7
18
|
* status. Carries the HTTP {@link status} code so callers can branch on
|
|
8
19
|
* specific failures (e.g. 404 for "not found", 409 for "conflict") without
|
|
@@ -31,6 +42,7 @@ var CopilotKitIntelligence = class {
|
|
|
31
42
|
#runnerWsUrl;
|
|
32
43
|
#clientWsUrl;
|
|
33
44
|
#apiKey;
|
|
45
|
+
#mcpServerEnabled;
|
|
34
46
|
#threadCreatedListeners = /* @__PURE__ */ new Set();
|
|
35
47
|
#threadUpdatedListeners = /* @__PURE__ */ new Set();
|
|
36
48
|
#threadDeletedListeners = /* @__PURE__ */ new Set();
|
|
@@ -40,6 +52,7 @@ var CopilotKitIntelligence = class {
|
|
|
40
52
|
this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
|
|
41
53
|
this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
|
|
42
54
|
this.#apiKey = config.apiKey;
|
|
55
|
+
this.#mcpServerEnabled = config.mcpServer ?? false;
|
|
43
56
|
if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
|
|
44
57
|
if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
|
|
45
58
|
if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
|
|
@@ -111,6 +124,14 @@ var CopilotKitIntelligence = class {
|
|
|
111
124
|
ɵgetRunnerAuthToken() {
|
|
112
125
|
return this.#apiKey;
|
|
113
126
|
}
|
|
127
|
+
/** @internal Used by the runtime's auto-attach to populate `Authorization`. */
|
|
128
|
+
ɵgetApiKey() {
|
|
129
|
+
return this.#apiKey;
|
|
130
|
+
}
|
|
131
|
+
/** @internal Used by the runtime's auto-attach to gate MCP attachment. */
|
|
132
|
+
ɵisMcpServerEnabled() {
|
|
133
|
+
return this.#mcpServerEnabled;
|
|
134
|
+
}
|
|
114
135
|
async #request(method, path, body) {
|
|
115
136
|
const url = `${this.#apiUrl}${path}`;
|
|
116
137
|
const headers = {
|
|
@@ -364,5 +385,5 @@ function deriveClientWsUrl(wsUrl) {
|
|
|
364
385
|
}
|
|
365
386
|
|
|
366
387
|
//#endregion
|
|
367
|
-
export { CopilotKitIntelligence, PlatformRequestError };
|
|
388
|
+
export { CopilotKitIntelligence, INTELLIGENCE_USER_ID_HEADER, PlatformRequestError };
|
|
368
389
|
//# sourceMappingURL=client.mjs.map
|