@copilotkit/runtime 1.71.0 → 1.71.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/agent/index.cjs +15 -3
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +1 -0
- package/dist/agent/index.d.cts.map +1 -1
- package/dist/agent/index.d.mts +1 -0
- package/dist/agent/index.d.mts.map +1 -1
- package/dist/agent/index.mjs +15 -3
- package/dist/agent/index.mjs.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +9 -1
- package/dist/index.d.mts +9 -1
- package/dist/index.mjs +2 -2
- package/dist/lib/telemetry-client.cjs.map +1 -1
- package/dist/lib/telemetry-client.mjs.map +1 -1
- package/dist/package.cjs +8 -6
- package/dist/package.mjs +8 -6
- package/dist/service-adapters/anthropic/anthropic-adapter.cjs +59 -25
- package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.cts +30 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.mts +30 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
- package/dist/service-adapters/anthropic/anthropic-adapter.mjs +59 -26
- package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
- package/dist/service-adapters/index.d.cts +1 -1
- package/dist/service-adapters/index.d.mts +1 -1
- package/dist/v2/index.cjs +2 -0
- package/dist/v2/index.d.cts +2 -1
- package/dist/v2/index.d.mts +2 -1
- package/dist/v2/index.mjs +2 -1
- package/dist/v2/runtime/core/runtime.cjs.map +1 -1
- package/dist/v2/runtime/core/runtime.d.cts +2 -1
- package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
- package/dist/v2/runtime/core/runtime.d.mts +2 -1
- package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
- package/dist/v2/runtime/core/runtime.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.cjs +2 -1
- package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-run.mjs +2 -1
- package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-stop.cjs +41 -1
- package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
- package/dist/v2/runtime/handlers/handle-stop.mjs +42 -2
- package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs +1 -1
- package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.cjs +2 -3
- package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/v2/runtime/handlers/intelligence/threads.mjs +2 -3
- package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs +8 -2
- package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs +8 -2
- package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/v2/runtime/index.d.cts +1 -0
- package/dist/v2/runtime/index.d.cts.map +1 -1
- package/dist/v2/runtime/index.d.mts +1 -0
- package/dist/v2/runtime/index.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs +106 -1
- package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.cts +11 -0
- package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.d.mts +11 -0
- package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs +106 -1
- package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/v2/runtime/intelligence-platform/index.d.cts +1 -0
- package/dist/v2/runtime/intelligence-platform/index.d.mts +1 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.cjs +43 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.cjs.map +1 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.d.cts +34 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.d.cts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.d.mts +34 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.d.mts.map +1 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.mjs +41 -0
- package/dist/v2/runtime/intelligence-platform/learned-skills.mjs.map +1 -0
- package/dist/v2/runtime/runner/intelligence.cjs +82 -25
- package/dist/v2/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.cts +3 -0
- package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.d.mts +3 -0
- package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/v2/runtime/runner/intelligence.mjs +83 -26
- package/dist/v2/runtime/runner/intelligence.mjs.map +1 -1
- package/package.json +10 -7
- package/skills/runtime/SKILL.md +0 -98
- package/skills/runtime/references/agent-runners-custom.md +0 -161
- package/skills/runtime/references/agent-runners-in-memory.md +0 -79
- package/skills/runtime/references/agent-runners-sqlite.md +0 -90
- package/skills/runtime/references/agent-runners.md +0 -336
- package/skills/runtime/references/built-in-agent-factory-modes.md +0 -232
- package/skills/runtime/references/built-in-agent-helper-utilities.md +0 -123
- package/skills/runtime/references/built-in-agent-model-identifiers.md +0 -58
- package/skills/runtime/references/built-in-agent.md +0 -523
- package/skills/runtime/references/intelligence-mode.md +0 -364
- package/skills/runtime/references/middleware.md +0 -376
- package/skills/runtime/references/server-side-tools.md +0 -414
- package/skills/runtime/references/setup-endpoint.md +0 -503
- package/skills/runtime/references/transcription.md +0 -287
- package/skills/runtime/references/wiring-a2a.md +0 -40
- package/skills/runtime/references/wiring-adk.md +0 -45
- package/skills/runtime/references/wiring-ag2.md +0 -41
- package/skills/runtime/references/wiring-agno.md +0 -40
- package/skills/runtime/references/wiring-aws-strands.md +0 -59
- package/skills/runtime/references/wiring-crewai-crews.md +0 -51
- package/skills/runtime/references/wiring-crewai-flows.md +0 -45
- package/skills/runtime/references/wiring-external-agents.md +0 -348
- package/skills/runtime/references/wiring-langgraph.md +0 -49
- package/skills/runtime/references/wiring-llamaindex.md +0 -39
- package/skills/runtime/references/wiring-mastra.md +0 -70
- package/skills/runtime/references/wiring-mcp-apps-middleware.md +0 -73
- package/skills/runtime/references/wiring-ms-agent-framework.md +0 -41
- package/skills/runtime/references/wiring-pydantic-ai.md +0 -45
|
@@ -1 +1 @@
|
|
|
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 { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\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\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\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 /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\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 // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAA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ErC,MACE,qBAAsB,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"}
|
|
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 { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\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\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\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 /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\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 // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,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,QAchC;CACP,MAAM,EACJ,SACA,SACA,SACA,wBACA,sBACE;CACJ,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAI,cAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAI,eAAe;GACjB,GAAG;GAIH,gBACE,mBAAmB,yBAAyB,OAAO;GACtD,CAAC,CACH;;AAIL,KAAI,sBAAsB,QAAQ,IAAI,OAAO,MAAM,QAAQ,YAAY;EAGrE,MAAM,aAAa,sBACjB,QAAQ,SAAS,WAAW,EAAE,EAC9B,QACD;AACD,MAAI,WAAW,SAAS,KAAK,kBAC3B,OAAM,IACJ,IAAI,kBAAkB;GAAE;GAAY,sBAAsB;GAAS,CAAC,CACrE;YAEM,QAAQ,SAAS,SAAS,QAAQ;EAC3C,MAAM,aAAa,sBAAsB,QAAQ,QAAQ,SAAS,QAAQ;AAE1E,MAAI,WAAW,SAAS,KAAK,OAAO,MAAM,Q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,YAAY;UACtC,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,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;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,oBAAoB,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,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"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
|
|
3
3
|
import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.cjs";
|
|
4
4
|
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.cjs";
|
|
5
|
+
import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.cjs";
|
|
5
6
|
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
|
|
6
7
|
import "./intelligence-platform/index.cjs";
|
|
7
8
|
import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
|
|
@@ -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":";;;;;;;;;;;;;;;;;;;;;;;;KAyDY,wBAAA,IAA4B,MAAA;EACtC,OAAA,EAAS,OAAA;AAAA,MACL,OAAA,CAAQ,QAAA"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.mjs";
|
|
3
3
|
import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, supportsLocalThreadEndpoints } from "./runner/agent-runner.mjs";
|
|
4
4
|
import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.mjs";
|
|
5
|
+
import { GetLearnedSkillsSnapshotRequest, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.mjs";
|
|
5
6
|
import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
|
|
6
7
|
import "./intelligence-platform/index.mjs";
|
|
7
8
|
import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
|
|
@@ -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":";;;;;;;;;;;;;;;;;;;;;;;;KAyDY,wBAAA,IAA4B,MAAA;EACtC,OAAA,EAAS,OAAA;AAAA,MACL,OAAA,CAAQ,QAAA"}
|
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
require("reflect-metadata");
|
|
2
2
|
const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_learned_skills = require('./learned-skills.cjs');
|
|
3
4
|
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
5
|
let crypto = require("crypto");
|
|
5
6
|
let zod = require("zod");
|
|
6
7
|
|
|
7
8
|
//#region src/v2/runtime/intelligence-platform/client.ts
|
|
9
|
+
/** Let a confirmed HTTP denial survive an error body that never completes. */
|
|
10
|
+
async function learnedSkillsErrorBody(response, signal) {
|
|
11
|
+
if (!signal) return response.json();
|
|
12
|
+
let onAbort;
|
|
13
|
+
try {
|
|
14
|
+
return await new Promise((resolve, reject) => {
|
|
15
|
+
onAbort = () => reject(signal.reason);
|
|
16
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
17
|
+
if (signal.aborted) onAbort();
|
|
18
|
+
else response.json().then(resolve, reject);
|
|
19
|
+
});
|
|
20
|
+
} finally {
|
|
21
|
+
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
8
24
|
const RUNTIME_ENTITLEMENTS_REQUEST_TIMEOUT_MS = 1500;
|
|
9
25
|
const RUNTIME_ENTITLEMENTS_SUCCESS_TTL_MS = 3e4;
|
|
10
26
|
const RUNTIME_ENTITLEMENTS_NEGATIVE_TTL_MS = 5e3;
|
|
@@ -299,6 +315,91 @@ var CopilotKitIntelligence = class {
|
|
|
299
315
|
return this.#enterpriseLearningEnabled;
|
|
300
316
|
}
|
|
301
317
|
/**
|
|
318
|
+
* Fetch one authorized learned-skills ZIP with this client's project key.
|
|
319
|
+
* No retries, archive parsing, or cache. A caller signal bounds the request
|
|
320
|
+
* and body read. Native cancellation is preserved; deadline failures use
|
|
321
|
+
* {@link LearnedSkillsError} with code `TIMEOUT`.
|
|
322
|
+
*/
|
|
323
|
+
async getLearnedSkillsSnapshot(params) {
|
|
324
|
+
try {
|
|
325
|
+
params.signal?.throwIfAborted();
|
|
326
|
+
if (typeof params.containerId !== "string" || !params.containerId.trim() || params.revision !== void 0 && (typeof params.revision !== "string" || !params.revision.length) || params.ifNoneMatch !== void 0 && (typeof params.ifNoneMatch !== "string" || !params.ifNoneMatch.length || /[\r\n]/.test(params.ifNoneMatch))) throw new require_learned_skills.LearnedSkillsError("INVALID_CONFIG", false);
|
|
327
|
+
let url;
|
|
328
|
+
try {
|
|
329
|
+
url = new URL(`${this.#apiUrl}/api/v1/learning/containers/${encodeURIComponent(params.containerId)}/skills`);
|
|
330
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error("Invalid API URL");
|
|
331
|
+
if (params.revision !== void 0) url.searchParams.set("revision", params.revision);
|
|
332
|
+
} catch {
|
|
333
|
+
throw new require_learned_skills.LearnedSkillsError("INVALID_CONFIG", false);
|
|
334
|
+
}
|
|
335
|
+
const response = await fetch(url.toString(), {
|
|
336
|
+
method: "GET",
|
|
337
|
+
headers: {
|
|
338
|
+
Authorization: `Bearer ${this.#apiKey}`,
|
|
339
|
+
Accept: "application/zip",
|
|
340
|
+
...params.ifNoneMatch !== void 0 ? { "If-None-Match": params.ifNoneMatch } : {}
|
|
341
|
+
},
|
|
342
|
+
signal: params.signal,
|
|
343
|
+
redirect: "error"
|
|
344
|
+
});
|
|
345
|
+
if (response.status === 401) {
|
|
346
|
+
response.body?.cancel().catch(() => {});
|
|
347
|
+
throw new require_learned_skills.LearnedSkillsError("AUTHENTICATION_FAILED", false);
|
|
348
|
+
}
|
|
349
|
+
if (response.status !== 403) params.signal?.throwIfAborted();
|
|
350
|
+
if (response.status !== 200 && response.status !== 304) {
|
|
351
|
+
const denialCode = response.status === 403 ? "AUTHORIZATION_FAILED" : void 0;
|
|
352
|
+
let body;
|
|
353
|
+
try {
|
|
354
|
+
body = await learnedSkillsErrorBody(response, params.signal);
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (denialCode) throw new require_learned_skills.LearnedSkillsError(denialCode, false, error instanceof SyntaxError ? void 0 : error);
|
|
357
|
+
params.signal?.throwIfAborted();
|
|
358
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
359
|
+
}
|
|
360
|
+
const responseError = require_learned_skills.learnedSkillsResponseError(body);
|
|
361
|
+
if (response.status === 403 && ![
|
|
362
|
+
"AUTHENTICATION_FAILED",
|
|
363
|
+
"AUTHORIZATION_FAILED",
|
|
364
|
+
"ENTITLEMENT_REQUIRED",
|
|
365
|
+
"DELIVERY_DISABLED",
|
|
366
|
+
"CONTAINER_NOT_FOUND",
|
|
367
|
+
"REVISION_NOT_FOUND",
|
|
368
|
+
"REVISION_REVOKED"
|
|
369
|
+
].includes(responseError.code)) throw new require_learned_skills.LearnedSkillsError(denialCode, false);
|
|
370
|
+
throw responseError;
|
|
371
|
+
}
|
|
372
|
+
const revision = response.headers.get("X-CopilotKit-Skills-Revision");
|
|
373
|
+
const etag = response.headers.get("ETag");
|
|
374
|
+
if (!revision || !etag || !/^"[a-f0-9]{64}"$/.test(etag) || params.revision !== void 0 && revision !== params.revision) throw new require_learned_skills.LearnedSkillsError("INVALID_SNAPSHOT", false);
|
|
375
|
+
if (response.status === 304) {
|
|
376
|
+
if (params.ifNoneMatch === void 0) throw new require_learned_skills.LearnedSkillsError("INVALID_SNAPSHOT", false);
|
|
377
|
+
return {
|
|
378
|
+
status: "unchanged",
|
|
379
|
+
revision,
|
|
380
|
+
etag
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
const contentType = response.headers.get("Content-Type");
|
|
384
|
+
if (!contentType || contentType.split(";", 1)[0].trim().toLowerCase() !== "application/zip") throw new require_learned_skills.LearnedSkillsError("INVALID_SNAPSHOT", false);
|
|
385
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
386
|
+
params.signal?.throwIfAborted();
|
|
387
|
+
return {
|
|
388
|
+
status: "snapshot",
|
|
389
|
+
bytes,
|
|
390
|
+
revision,
|
|
391
|
+
etag,
|
|
392
|
+
contentType
|
|
393
|
+
};
|
|
394
|
+
} catch (error) {
|
|
395
|
+
if (error instanceof require_learned_skills.LearnedSkillsError) throw error;
|
|
396
|
+
const cause = params.signal?.aborted ? params.signal.reason : error;
|
|
397
|
+
if (cause instanceof Error && cause.name === "TimeoutError") throw new require_learned_skills.LearnedSkillsError("TIMEOUT", true, cause);
|
|
398
|
+
if (params.signal?.aborted || cause instanceof Error && cause.name === "AbortError") throw cause;
|
|
399
|
+
throw new require_learned_skills.LearnedSkillsError("NETWORK_ERROR", true, error);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
302
403
|
* Fetch trusted Inspector metadata for this runtime's Intelligence project.
|
|
303
404
|
*
|
|
304
405
|
* The request always uses the server-configured Intelligence API key. A 404
|
|
@@ -429,7 +530,8 @@ var CopilotKitIntelligence = class {
|
|
|
429
530
|
let payload;
|
|
430
531
|
try {
|
|
431
532
|
payload = await response.json();
|
|
432
|
-
} catch {
|
|
533
|
+
} catch (error) {
|
|
534
|
+
if (controller.signal.aborted) throw error;
|
|
433
535
|
throw new PlatformRequestError("Runtime entitlement response was malformed", 502, false);
|
|
434
536
|
}
|
|
435
537
|
const normalized = normalizeRuntimeEntitlementTransport(payload);
|
|
@@ -589,6 +691,9 @@ var CopilotKitIntelligence = class {
|
|
|
589
691
|
/**
|
|
590
692
|
* Update thread metadata (e.g. name).
|
|
591
693
|
*
|
|
694
|
+
* Fields in updates take precedence, preserving the server-side SDK contract.
|
|
695
|
+
* HTTP handlers must remove untrusted identity fields before calling this method.
|
|
696
|
+
*
|
|
592
697
|
* Triggers the `onThreadUpdated` lifecycle callback on success.
|
|
593
698
|
*
|
|
594
699
|
* @returns The updated thread summary.
|