@copilotkit/runtime 2.0.0-rc.49 → 2.0.0-rc.50
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 +1 -1
- package/dist/index.cjs +8 -3
- package/dist/index.d.cts +9 -9
- package/dist/index.d.mts +9 -9
- package/dist/index.mjs +4 -3
- package/dist/node.cjs +2 -0
- package/dist/node.d.cts +3 -3
- package/dist/node.d.mts +3 -3
- package/dist/node.mjs +3 -3
- package/dist/runtime/core/channel-manager.cjs.map +1 -1
- package/dist/runtime/core/channel-manager.mjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.cts +2 -2
- package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
- package/dist/runtime/core/debug-event-bus.d.mts +2 -2
- package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
- package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
- package/dist/runtime/core/fetch-cors.cjs.map +1 -1
- package/dist/runtime/core/fetch-cors.d.cts +2 -2
- package/dist/runtime/core/fetch-cors.d.cts.map +1 -1
- package/dist/runtime/core/fetch-cors.d.mts +2 -2
- package/dist/runtime/core/fetch-cors.d.mts.map +1 -1
- package/dist/runtime/core/fetch-cors.mjs.map +1 -1
- package/dist/runtime/core/fetch-handler.cjs +9 -1
- package/dist/runtime/core/fetch-handler.cjs.map +1 -1
- package/dist/runtime/core/fetch-handler.d.cts +27 -14
- package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
- package/dist/runtime/core/fetch-handler.d.mts +27 -14
- package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
- package/dist/runtime/core/fetch-handler.mjs +9 -2
- package/dist/runtime/core/fetch-handler.mjs.map +1 -1
- package/dist/runtime/core/hooks.cjs.map +1 -1
- package/dist/runtime/core/hooks.d.cts +5 -5
- package/dist/runtime/core/hooks.d.cts.map +1 -1
- package/dist/runtime/core/hooks.d.mts +5 -5
- package/dist/runtime/core/hooks.d.mts.map +1 -1
- package/dist/runtime/core/hooks.mjs.map +1 -1
- package/dist/runtime/core/learning.cjs.map +1 -1
- package/dist/runtime/core/learning.d.cts +8 -8
- package/dist/runtime/core/learning.d.cts.map +1 -1
- package/dist/runtime/core/learning.d.mts +8 -8
- package/dist/runtime/core/learning.d.mts.map +1 -1
- package/dist/runtime/core/learning.mjs.map +1 -1
- package/dist/runtime/core/logger.cjs.map +1 -1
- package/dist/runtime/core/logger.d.cts +3 -3
- package/dist/runtime/core/logger.d.cts.map +1 -1
- package/dist/runtime/core/logger.d.mts +3 -3
- package/dist/runtime/core/logger.d.mts.map +1 -1
- package/dist/runtime/core/logger.mjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
- package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
- package/dist/runtime/core/middleware.cjs.map +1 -1
- package/dist/runtime/core/middleware.d.cts +3 -3
- package/dist/runtime/core/middleware.d.cts.map +1 -1
- package/dist/runtime/core/middleware.d.mts +3 -3
- package/dist/runtime/core/middleware.d.mts.map +1 -1
- package/dist/runtime/core/middleware.mjs.map +1 -1
- package/dist/runtime/core/package-info.cjs +1 -1
- package/dist/runtime/core/package-info.mjs +1 -1
- package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -1
- package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -1
- package/dist/runtime/core/runtime.cjs +17 -17
- package/dist/runtime/core/runtime.cjs.map +1 -1
- package/dist/runtime/core/runtime.d.cts +65 -65
- package/dist/runtime/core/runtime.d.cts.map +1 -1
- package/dist/runtime/core/runtime.d.mts +65 -65
- package/dist/runtime/core/runtime.d.mts.map +1 -1
- package/dist/runtime/core/runtime.mjs +15 -15
- package/dist/runtime/core/runtime.mjs.map +1 -1
- package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
- package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.cjs +9 -1
- package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.cts +9 -4
- package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.d.mts +9 -4
- package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
- package/dist/runtime/endpoints/node-fetch-handler.mjs +9 -2
- package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
- package/dist/runtime/endpoints/node.cjs +11 -3
- package/dist/runtime/endpoints/node.cjs.map +1 -1
- package/dist/runtime/endpoints/node.d.cts +39 -16
- package/dist/runtime/endpoints/node.d.cts.map +1 -1
- package/dist/runtime/endpoints/node.d.mts +39 -16
- package/dist/runtime/endpoints/node.d.mts.map +1 -1
- package/dist/runtime/endpoints/node.mjs +13 -6
- package/dist/runtime/endpoints/node.mjs.map +1 -1
- package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -1
- package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
- package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
- package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -1
- package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
- package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
- package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
- package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
- package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -1
- package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -1
- package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
- package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.cjs +1 -1
- package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/annotate.mjs +1 -1
- package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.cjs +1 -1
- package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/memories.mjs +1 -1
- package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.cjs +5 -5
- package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
- package/dist/runtime/handlers/intelligence/threads.mjs +5 -5
- package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
- package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
- package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -1
- package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
- package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
- package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.cjs +1 -1
- package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
- package/dist/runtime/handlers/shared/thread-access.mjs +1 -1
- package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
- package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
- package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
- package/dist/runtime/handlers/sse/run.cjs.map +1 -1
- package/dist/runtime/handlers/sse/run.mjs.map +1 -1
- package/dist/runtime/index.cjs +29 -0
- package/dist/runtime/index.cjs.map +1 -0
- package/dist/runtime/index.d.cts +58 -7
- package/dist/runtime/index.d.cts.map +1 -0
- package/dist/runtime/index.d.mts +58 -7
- package/dist/runtime/index.d.mts.map +1 -0
- package/dist/runtime/index.mjs +27 -0
- package/dist/runtime/index.mjs.map +1 -0
- package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/client.cjs +3 -3
- package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/client.d.cts +1 -1
- package/dist/runtime/intelligence-platform/client.d.mts +1 -1
- package/dist/runtime/intelligence-platform/client.mjs +3 -3
- package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
- package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
- package/dist/runtime/node.d.cts +2 -2
- package/dist/runtime/node.d.mts +2 -2
- package/dist/runtime/runner/intelligence.cjs.map +1 -1
- package/dist/runtime/runner/intelligence.d.cts +2 -2
- package/dist/runtime/runner/intelligence.d.cts.map +1 -1
- package/dist/runtime/runner/intelligence.d.mts +2 -2
- package/dist/runtime/runner/intelligence.d.mts.map +1 -1
- package/dist/runtime/runner/intelligence.mjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
- package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
- package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/core/schemas\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { OpenGenerativeUIMiddleware } from \"../../event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport {\n A2UIV09BridgeMiddleware,\n GenerativeUIMiddleware,\n resolveA2UIVersion,\n} from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../../core/runtime\";\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 { grantAllowsMemory, resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { processEnv } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\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 * The transport of the generative UI envelope that the client sent on this\n * run (`forwardedProps.copilotkit.ui`). Not set when the run has no envelope.\n */\n providerGenerativeUITransport?: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const { runtime, request, agentId, isMcpProxyRequest } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // Generative UI is on for a run with a \"tool\" envelope, and for every run\n // when the runtime turns it on. A \"markdown\" envelope means the model writes\n // ```a2ui fences, so the run gets no render tool, even when the runtime\n // turns generative UI on. `false` and the `agents` filter always win.\n const generativeUI = runtime.generativeUI;\n const generativeUIOptions =\n typeof generativeUI === \"object\" ? generativeUI : undefined;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n generativeUI !== false &&\n (transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI)) &&\n (!generativeUIOptions?.agents ||\n generativeUIOptions.agents.includes(agentId)) &&\n typeof agent.use === \"function\";\n const a2uiVersion = resolveA2UIVersion(generativeUI, agentId);\n\n if (isGenerativeUIRun) {\n // The bridge comes first, so it is the outermost middleware: it changes\n // the input before `A2UIMiddleware` reads it, and converts the v0.9\n // surfaces that `A2UIMiddleware` emits.\n agent.use(new A2UIV09BridgeMiddleware({ agentVersion: a2uiVersion }));\n if (a2uiVersion === \"0.9\") {\n const {\n agents: _agents,\n a2uiVersion: _a2uiVersion,\n injectA2UITool,\n ...a2uiOptions\n } = generativeUIOptions ?? {};\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // The envelope of a \"tool\" run carries the client's catalog, so the\n // agent gets the render tool. An explicit value (also `false`) wins.\n injectA2UITool: injectA2UITool ?? transport === \"tool\",\n }),\n );\n } else {\n // No tool and no schema, so the agent gets no v0.9 prompt. It still\n // turns v0.9 operations in tool results (`{ \"a2ui_operations\": [...] }`)\n // into surfaces, which the bridge converts to 1.0.\n agent.use(new A2UIMiddleware());\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 // A v0.9 agent gets `render_a2ui` (above) instead of `render_ui`.\n if (isGenerativeUIRun && a2uiVersion === \"1.0\") {\n agent.use(new GenerativeUIMiddleware());\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 * Shared by the two places a run meets a middleware-less agent: before Memory\n * is resolved (nothing left to resolve) and after (Memory resolved to nothing).\n */\nconst NO_MIDDLEWARE_WARNING =\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/**\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 (!isIntelligenceRuntime(runtime)) return;\n\n const learningEnabled =\n runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;\n if (runtime.memory === undefined && !learningEnabled) return;\n\n // Nothing here is resolvable for an agent whose framework can't take\n // middleware and whose runtime configures no Memory — bail before paying for\n // `identifyUser`, so an enterprise-learning-only run keeps warning rather\n // than acquiring a new way to fail.\n if (runtime.memory === undefined && typeof agent.use !== \"function\") {\n getRuntimeLogger(runtime).warn(NO_MIDDLEWARE_WARNING);\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 const memoryGranted =\n runtime.memory !== undefined && grantAllowsMemory(access.grant);\n\n // A policy that grants no scope means this run gets no Memory — it does NOT\n // mean the run is refused. Attach nothing and let the conversation proceed,\n // exactly as a Channel does when its grant asks for nothing\n // (`hasMemoryAccess` in @copilotkit/channels-core). Returning a 403 here\n // instead fails the whole run, so switching Memory off for one tenant would\n // leave that tenant with no assistant, and the only signal is a run error the\n // chat surface has no reason to render.\n //\n // Enterprise learning rides the SAME MCP server, so \"no Memory\" must not cost\n // an operator the learning tools too. When it is on, attach anyway and let\n // Intelligence filter: it registers one Memory tool per granted scope and\n // none at all for an all-none grant, leaving the learning tools untouched.\n if (!memoryGranted && !learningEnabled) return;\n\n // Whatever is left to attach needs middleware. Failing the run is right only\n // when Memory was actually granted and cannot be delivered; a run that merely\n // wanted learning tools warns and proceeds, as it always has.\n if (typeof agent.use !== \"function\") {\n if (memoryGranted) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n getRuntimeLogger(runtime).warn(NO_MIDDLEWARE_WARNING);\n return;\n }\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\n// Intentional local exception: HTTP request parsing runs before AG-UI's event\n// compatibility boundary. Mirror its historically accepted optional-null rules\n// and its legacy binary-part upgrade here, without depending on a new public\n// AG-UI helper (AG-UI does not export one). Keep these aligned\n// with client/src/middleware/compatibility-boundary.ts and AG-UI's migration guide.\n// Required nulls and nulls within application data must remain untouched.\nfunction warnCompatibility(\n what: string,\n replacement: string,\n logger: CopilotRuntimeLogger,\n) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n logger.warn(\n `[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction omitLegacyNull(\n value: unknown,\n field: string,\n context: string,\n logger: CopilotRuntimeLogger,\n): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\", logger);\n const { [field]: _null, ...rest } = value;\n return rest;\n}\n\nfunction mapProtocolArray(\n value: unknown,\n field: string,\n normalize: (entry: unknown) => unknown,\n): unknown {\n if (!isRecord(value) || !Array.isArray(value[field])) return value;\n const original = value[field];\n const entries = original.map(normalize);\n return entries.some((entry, index) => entry !== original[index])\n ? { ...value, [field]: entries }\n : value;\n}\n\nfunction mediaTypeFor(\n mimeType: string,\n): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction sameSource(part: unknown, converted: Record<string, unknown>) {\n if (!isRecord(part) || part.type !== converted.type) return false;\n const a = part.source;\n const b = converted.source as Record<string, unknown>;\n return (\n isRecord(a) &&\n a.type === b.type &&\n a.value === b.value &&\n a.mimeType === b.mimeType\n );\n}\n\n/**\n * The 0.x `{ type: \"binary\" }` part, which 1.0 retired and main accepted.\n * Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):\n * data or url becomes the media part its mime type names, and a binary part\n * that only mirrors a modern part already in the message is dropped. A part\n * with only an `id` has no 1.0 form; it is dropped with a warning instead of\n * failing the whole request, which is what BuiltInAgent already did with it.\n */\nfunction upgradeLegacyBinaryParts(\n content: unknown[],\n logger: CopilotRuntimeLogger,\n): unknown[] {\n return content.flatMap((part) => {\n if (\n !isRecord(part) ||\n part.type !== \"binary\" ||\n typeof part.mimeType !== \"string\"\n )\n return [part];\n const kind =\n typeof part.data === \"string\"\n ? \"data\"\n : typeof part.url === \"string\"\n ? \"url\"\n : null;\n if (kind === null) {\n logger.warn(\n \"[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.\",\n );\n return [];\n }\n warnCompatibility(\n \"binary input content\",\n \"the modern media content part\",\n logger,\n );\n const converted: Record<string, unknown> = {\n type: mediaTypeFor(part.mimeType),\n source: {\n type: kind,\n value: kind === \"data\" ? part.data : part.url,\n mimeType: part.mimeType,\n },\n ...(typeof part.filename === \"string\"\n ? { metadata: { filename: part.filename } }\n : {}),\n };\n return content.some((other) => sameSource(other, converted))\n ? []\n : [converted];\n });\n}\n\nfunction normalizeLegacyMessageContent(\n message: unknown,\n logger: CopilotRuntimeLogger,\n): unknown {\n const upgraded =\n isRecord(message) &&\n Array.isArray(message.content) &&\n message.content.some((part) => isRecord(part) && part.type === \"binary\")\n ? {\n ...message,\n content: upgradeLegacyBinaryParts(message.content, logger),\n }\n : message;\n return mapProtocolArray(upgraded, \"content\", (part) => {\n if (!isRecord(part)) return part;\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return omitLegacyNull(\n part,\n \"metadata\",\n `${part.type} input content`,\n logger,\n );\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(\n input: unknown,\n logger: CopilotRuntimeLogger,\n): unknown {\n let normalized = omitLegacyNull(\n input,\n \"forwardedProps\",\n \"RunAgentInput\",\n logger,\n );\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\", logger),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\", logger),\n );\n return mapProtocolArray(normalized, \"messages\", (message) =>\n normalizeLegacyMessageContent(message, logger),\n );\n}\n\nfunction parseRunAgentInput(\n value: unknown,\n logger: CopilotRuntimeLogger,\n): RunAgentInput {\n // With strictNullChecks disabled, Zod infers some required nested fields\n // (such as image.source) as optional. The schema still validates them.\n return RunAgentInputSchema.parse(\n normalizeLegacyRunAgentInput(value, logger),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n logger: CopilotRuntimeLogger = getRuntimeLogger(),\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody, logger);\n } catch (error) {\n logger.error({ err: error }, \"Invalid run request body\");\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(\n request: Request,\n logger: CopilotRuntimeLogger = getRuntimeLogger(),\n): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody, logger);\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({ err: error }, \"Invalid connect request body\");\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,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,QAYhC;CACP,MAAM,EAAE,SAAS,SAAS,SAAS,sBAAsB;CACzD,MAAM,QAAQ,OAAO;CAMrB,MAAM,eAAe,QAAQ;CAC7B,MAAM,sBACJ,OAAO,iBAAiB,WAAW,eAAe;CACpD,MAAM,YAAY,OAAO;CACzB,MAAM,oBACJ,iBAAiB,UAChB,cAAc,UAAW,cAAc,cAAc,CAAC,CAAC,kBACvD,CAAC,qBAAqB,UACrB,oBAAoB,OAAO,SAAS,QAAQ,KAC9C,OAAO,MAAM,QAAQ;CACvB,M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AM,EAAE,KAAK,OAAO,EAAE,2BAA2B;AACxD,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,oBACpB,SACA,SAA+B,kBAAkB,EAOjD;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,aAAa,OAAO;EACrD,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,EAAE,KAAK,OAAO,EAAE,+BAA+B;AAC5D,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/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/core/schemas\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { OpenGenerativeUIMiddleware } from \"../../event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport {\n A2UIV09BridgeMiddleware,\n GenerativeUIMiddleware,\n resolveA2UIVersion,\n} from \"../../generative-ui\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../../core/runtime\";\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 { grantAllowsMemory, resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { processEnv } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../../core/logger\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotKitRuntimeLike;\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: CopilotKitRuntimeLike,\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: CopilotKitRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * The transport of the generative UI envelope that the client sent on this\n * run (`forwardedProps.copilotkit.ui`). Not set when the run has no envelope.\n */\n providerGenerativeUITransport?: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const { runtime, request, agentId, isMcpProxyRequest } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // Generative UI is on for a run with a \"tool\" envelope, and for every run\n // when the runtime turns it on. A \"markdown\" envelope means the model writes\n // ```a2ui fences, so the run gets no render tool, even when the runtime\n // turns generative UI on. `false` and the `agents` filter always win.\n const generativeUI = runtime.generativeUI;\n const generativeUIOptions =\n typeof generativeUI === \"object\" ? generativeUI : undefined;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n generativeUI !== false &&\n (transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI)) &&\n (!generativeUIOptions?.agents ||\n generativeUIOptions.agents.includes(agentId)) &&\n typeof agent.use === \"function\";\n const a2uiVersion = resolveA2UIVersion(generativeUI, agentId);\n\n if (isGenerativeUIRun) {\n // The bridge comes first, so it is the outermost middleware: it changes\n // the input before `A2UIMiddleware` reads it, and converts the v0.9\n // surfaces that `A2UIMiddleware` emits.\n agent.use(new A2UIV09BridgeMiddleware({ agentVersion: a2uiVersion }));\n if (a2uiVersion === \"0.9\") {\n const {\n agents: _agents,\n a2uiVersion: _a2uiVersion,\n injectA2UITool,\n ...a2uiOptions\n } = generativeUIOptions ?? {};\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // The envelope of a \"tool\" run carries the client's catalog, so the\n // agent gets the render tool. An explicit value (also `false`) wins.\n injectA2UITool: injectA2UITool ?? transport === \"tool\",\n }),\n );\n } else {\n // No tool and no schema, so the agent gets no v0.9 prompt. It still\n // turns v0.9 operations in tool results (`{ \"a2ui_operations\": [...] }`)\n // into surfaces, which the bridge converts to 1.0.\n agent.use(new A2UIMiddleware());\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 // A v0.9 agent gets `render_a2ui` (above) instead of `render_ui`.\n if (isGenerativeUIRun && a2uiVersion === \"1.0\") {\n agent.use(new GenerativeUIMiddleware());\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 `CopilotKitRuntimeLike`\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 * Shared by the two places a run meets a middleware-less agent: before Memory\n * is resolved (nothing left to resolve) and after (Memory resolved to nothing).\n */\nconst NO_MIDDLEWARE_WARNING =\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/**\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: CopilotKitRuntimeLike;\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 (!isIntelligenceRuntime(runtime)) return;\n\n const learningEnabled =\n runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;\n if (runtime.memory === undefined && !learningEnabled) return;\n\n // Nothing here is resolvable for an agent whose framework can't take\n // middleware and whose runtime configures no Memory — bail before paying for\n // `identifyUser`, so an enterprise-learning-only run keeps warning rather\n // than acquiring a new way to fail.\n if (runtime.memory === undefined && typeof agent.use !== \"function\") {\n getRuntimeLogger(runtime).warn(NO_MIDDLEWARE_WARNING);\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 const memoryGranted =\n runtime.memory !== undefined && grantAllowsMemory(access.grant);\n\n // A policy that grants no scope means this run gets no Memory — it does NOT\n // mean the run is refused. Attach nothing and let the conversation proceed,\n // exactly as a Channel does when its grant asks for nothing\n // (`hasMemoryAccess` in @copilotkit/channels-core). Returning a 403 here\n // instead fails the whole run, so switching Memory off for one tenant would\n // leave that tenant with no assistant, and the only signal is a run error the\n // chat surface has no reason to render.\n //\n // Enterprise learning rides the SAME MCP server, so \"no Memory\" must not cost\n // an operator the learning tools too. When it is on, attach anyway and let\n // Intelligence filter: it registers one Memory tool per granted scope and\n // none at all for an all-none grant, leaving the learning tools untouched.\n if (!memoryGranted && !learningEnabled) return;\n\n // Whatever is left to attach needs middleware. Failing the run is right only\n // when Memory was actually granted and cannot be delivered; a run that merely\n // wanted learning tools warns and proceeds, as it always has.\n if (typeof agent.use !== \"function\") {\n if (memoryGranted) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n getRuntimeLogger(runtime).warn(NO_MIDDLEWARE_WARNING);\n return;\n }\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\n// Intentional local exception: HTTP request parsing runs before AG-UI's event\n// compatibility boundary. Mirror its historically accepted optional-null rules\n// and its legacy binary-part upgrade here, without depending on a new public\n// AG-UI helper (AG-UI does not export one). Keep these aligned\n// with client/src/middleware/compatibility-boundary.ts and AG-UI's migration guide.\n// Required nulls and nulls within application data must remain untouched.\nfunction warnCompatibility(\n what: string,\n replacement: string,\n logger: CopilotKitRuntimeLogger,\n) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n logger.warn(\n `[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction omitLegacyNull(\n value: unknown,\n field: string,\n context: string,\n logger: CopilotKitRuntimeLogger,\n): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\", logger);\n const { [field]: _null, ...rest } = value;\n return rest;\n}\n\nfunction mapProtocolArray(\n value: unknown,\n field: string,\n normalize: (entry: unknown) => unknown,\n): unknown {\n if (!isRecord(value) || !Array.isArray(value[field])) return value;\n const original = value[field];\n const entries = original.map(normalize);\n return entries.some((entry, index) => entry !== original[index])\n ? { ...value, [field]: entries }\n : value;\n}\n\nfunction mediaTypeFor(\n mimeType: string,\n): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction sameSource(part: unknown, converted: Record<string, unknown>) {\n if (!isRecord(part) || part.type !== converted.type) return false;\n const a = part.source;\n const b = converted.source as Record<string, unknown>;\n return (\n isRecord(a) &&\n a.type === b.type &&\n a.value === b.value &&\n a.mimeType === b.mimeType\n );\n}\n\n/**\n * The 0.x `{ type: \"binary\" }` part, which 1.0 retired and main accepted.\n * Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):\n * data or url becomes the media part its mime type names, and a binary part\n * that only mirrors a modern part already in the message is dropped. A part\n * with only an `id` has no 1.0 form; it is dropped with a warning instead of\n * failing the whole request, which is what BuiltInAgent already did with it.\n */\nfunction upgradeLegacyBinaryParts(\n content: unknown[],\n logger: CopilotKitRuntimeLogger,\n): unknown[] {\n return content.flatMap((part) => {\n if (\n !isRecord(part) ||\n part.type !== \"binary\" ||\n typeof part.mimeType !== \"string\"\n )\n return [part];\n const kind =\n typeof part.data === \"string\"\n ? \"data\"\n : typeof part.url === \"string\"\n ? \"url\"\n : null;\n if (kind === null) {\n logger.warn(\n \"[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.\",\n );\n return [];\n }\n warnCompatibility(\n \"binary input content\",\n \"the modern media content part\",\n logger,\n );\n const converted: Record<string, unknown> = {\n type: mediaTypeFor(part.mimeType),\n source: {\n type: kind,\n value: kind === \"data\" ? part.data : part.url,\n mimeType: part.mimeType,\n },\n ...(typeof part.filename === \"string\"\n ? { metadata: { filename: part.filename } }\n : {}),\n };\n return content.some((other) => sameSource(other, converted))\n ? []\n : [converted];\n });\n}\n\nfunction normalizeLegacyMessageContent(\n message: unknown,\n logger: CopilotKitRuntimeLogger,\n): unknown {\n const upgraded =\n isRecord(message) &&\n Array.isArray(message.content) &&\n message.content.some((part) => isRecord(part) && part.type === \"binary\")\n ? {\n ...message,\n content: upgradeLegacyBinaryParts(message.content, logger),\n }\n : message;\n return mapProtocolArray(upgraded, \"content\", (part) => {\n if (!isRecord(part)) return part;\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return omitLegacyNull(\n part,\n \"metadata\",\n `${part.type} input content`,\n logger,\n );\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(\n input: unknown,\n logger: CopilotKitRuntimeLogger,\n): unknown {\n let normalized = omitLegacyNull(\n input,\n \"forwardedProps\",\n \"RunAgentInput\",\n logger,\n );\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\", logger),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\", logger),\n );\n return mapProtocolArray(normalized, \"messages\", (message) =>\n normalizeLegacyMessageContent(message, logger),\n );\n}\n\nfunction parseRunAgentInput(\n value: unknown,\n logger: CopilotKitRuntimeLogger,\n): RunAgentInput {\n // With strictNullChecks disabled, Zod infers some required nested fields\n // (such as image.source) as optional. The schema still validates them.\n return RunAgentInputSchema.parse(\n normalizeLegacyRunAgentInput(value, logger),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n logger: CopilotKitRuntimeLogger = getRuntimeLogger(),\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody, logger);\n } catch (error) {\n logger.error({ err: error }, \"Invalid run request body\");\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(\n request: Request,\n logger: CopilotKitRuntimeLogger = getRuntimeLogger(),\n): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody, logger);\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({ err: error }, \"Invalid connect request body\");\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(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AO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,+BAA+B;AAC5D,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":"memory-policy.cjs","names":["errorResponse"],"sources":["../../../../src/runtime/handlers/shared/memory-policy.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"memory-policy.cjs","names":["errorResponse"],"sources":["../../../../src/runtime/handlers/shared/memory-policy.ts"],"sourcesContent":["import type {\n CopilotKitIntelligenceRuntimeLike,\n CopilotKitRuntimeUser,\n MemoryConsumer,\n MemoryGrant,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\n\nconst ACCESS = new Set([\"none\", \"read\", \"read-write\"]);\n\n/** What a policy that declines Memory entirely resolves to. */\nconst NO_MEMORY: MemoryGrant = Object.freeze({\n user: \"none\",\n project: \"none\",\n});\n\nexport interface ResolvedWebMemory {\n readonly user: CopilotKitRuntimeUser;\n readonly grant: MemoryGrant;\n}\n\n/**\n * True when a grant asks for any Memory operation at all.\n *\n * The web counterpart of `hasMemoryAccess` in `@copilotkit/channels-core`, and\n * deliberately the same predicate: a grant with every scope at `\"none\"` means\n * \"this request gets no Memory\", NOT \"refuse this request\". Channels has always\n * read it that way — there both scopes are optional and default to `\"none\"`, so\n * all-none is the grant you get by writing nothing, which could not coherently\n * mean refusal.\n */\nexport function grantAllowsMemory(grant: MemoryGrant): boolean {\n return grant.user !== \"none\" || grant.project !== \"none\";\n}\n\n/**\n * Evaluates and validates one configured web Memory policy.\n *\n * Resolving is separate from ACTING on the result, because the two callers want\n * opposite things from a policy that grants nothing:\n *\n * - An agent run wants to proceed WITHOUT Memory tools. `memory.access` is a\n * Memory policy, not an authorization gate on the conversation; a runtime\n * that wants to reject the request outright has `beforeRequestMiddleware`\n * for exactly that. Failing the run here means a deployment that switches\n * Memory off for one tenant gets no assistant at all, and the failure\n * surfaces as a bare run error rather than as anything a user can read.\n * - The browser Memory routes want a 403. There the caller asked for memories\n * specifically, so \"you may not have them\" is the honest answer, and an\n * empty list would imply none exist.\n *\n * So this returns the grant (or a Response for a genuinely broken policy), and\n * each call site applies `grantAllowsMemory` to its own case.\n */\nexport async function resolveWebMemory(\n runtime: CopilotKitIntelligenceRuntimeLike,\n request: Request,\n user: CopilotKitRuntimeUser,\n consumer: MemoryConsumer,\n): Promise<ResolvedWebMemory | Response> {\n if (!runtime.memory) {\n return {\n user,\n grant: { user: \"read-write\", project: \"read-write\" },\n };\n }\n\n try {\n const grant = await runtime.memory.access({ request, user, consumer });\n // `null` is the policy declining to grant anything, which is the same\n // outcome as an explicit all-none grant — not a distinct third state.\n //\n // `undefined` is NOT that. The contract is `MemoryGrant | null`, so a\n // missing return is a policy that is broken rather than restrictive — a\n // JavaScript caller who forgot one, or a branch that falls off the end.\n // Reading it as \"grant nothing\" would switch Memory off silently for the\n // exact deployments least able to notice; it fails loudly instead.\n if (grant === undefined) {\n return errorResponse(\"Memory policy returned an invalid grant\", 500);\n }\n const resolved = grant ?? NO_MEMORY;\n if (!ACCESS.has(resolved.user) || !ACCESS.has(resolved.project)) {\n return errorResponse(\"Memory policy returned an invalid grant\", 500);\n }\n return { user, grant: { user: resolved.user, project: resolved.project } };\n } catch {\n return errorResponse(\"Memory policy failed\", 500);\n }\n}\n"],"mappings":";;;AAQA,MAAM,SAAS,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAa,CAAC;;AAGtD,MAAM,YAAyB,OAAO,OAAO;CAC3C,MAAM;CACN,SAAS;CACV,CAAC;;;;;;;;;;;AAiBF,SAAgB,kBAAkB,OAA6B;AAC7D,QAAO,MAAM,SAAS,UAAU,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;AAsBpD,eAAsB,iBACpB,SACA,SACA,MACA,UACuC;AACvC,KAAI,CAAC,QAAQ,OACX,QAAO;EACL;EACA,OAAO;GAAE,MAAM;GAAc,SAAS;GAAc;EACrD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,OAAO,OAAO;GAAE;GAAS;GAAM;GAAU,CAAC;AAStE,MAAI,UAAU,OACZ,QAAOA,oCAAc,2CAA2C,IAAI;EAEtE,MAAM,WAAW,SAAS;AAC1B,MAAI,CAAC,OAAO,IAAI,SAAS,KAAK,IAAI,CAAC,OAAO,IAAI,SAAS,QAAQ,CAC7D,QAAOA,oCAAc,2CAA2C,IAAI;AAEtE,SAAO;GAAE;GAAM,OAAO;IAAE,MAAM,SAAS;IAAM,SAAS,SAAS;IAAS;GAAE;SACpE;AACN,SAAOA,oCAAc,wBAAwB,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory-policy.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/memory-policy.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"memory-policy.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/memory-policy.ts"],"sourcesContent":["import type {\n CopilotKitIntelligenceRuntimeLike,\n CopilotKitRuntimeUser,\n MemoryConsumer,\n MemoryGrant,\n} from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\n\nconst ACCESS = new Set([\"none\", \"read\", \"read-write\"]);\n\n/** What a policy that declines Memory entirely resolves to. */\nconst NO_MEMORY: MemoryGrant = Object.freeze({\n user: \"none\",\n project: \"none\",\n});\n\nexport interface ResolvedWebMemory {\n readonly user: CopilotKitRuntimeUser;\n readonly grant: MemoryGrant;\n}\n\n/**\n * True when a grant asks for any Memory operation at all.\n *\n * The web counterpart of `hasMemoryAccess` in `@copilotkit/channels-core`, and\n * deliberately the same predicate: a grant with every scope at `\"none\"` means\n * \"this request gets no Memory\", NOT \"refuse this request\". Channels has always\n * read it that way — there both scopes are optional and default to `\"none\"`, so\n * all-none is the grant you get by writing nothing, which could not coherently\n * mean refusal.\n */\nexport function grantAllowsMemory(grant: MemoryGrant): boolean {\n return grant.user !== \"none\" || grant.project !== \"none\";\n}\n\n/**\n * Evaluates and validates one configured web Memory policy.\n *\n * Resolving is separate from ACTING on the result, because the two callers want\n * opposite things from a policy that grants nothing:\n *\n * - An agent run wants to proceed WITHOUT Memory tools. `memory.access` is a\n * Memory policy, not an authorization gate on the conversation; a runtime\n * that wants to reject the request outright has `beforeRequestMiddleware`\n * for exactly that. Failing the run here means a deployment that switches\n * Memory off for one tenant gets no assistant at all, and the failure\n * surfaces as a bare run error rather than as anything a user can read.\n * - The browser Memory routes want a 403. There the caller asked for memories\n * specifically, so \"you may not have them\" is the honest answer, and an\n * empty list would imply none exist.\n *\n * So this returns the grant (or a Response for a genuinely broken policy), and\n * each call site applies `grantAllowsMemory` to its own case.\n */\nexport async function resolveWebMemory(\n runtime: CopilotKitIntelligenceRuntimeLike,\n request: Request,\n user: CopilotKitRuntimeUser,\n consumer: MemoryConsumer,\n): Promise<ResolvedWebMemory | Response> {\n if (!runtime.memory) {\n return {\n user,\n grant: { user: \"read-write\", project: \"read-write\" },\n };\n }\n\n try {\n const grant = await runtime.memory.access({ request, user, consumer });\n // `null` is the policy declining to grant anything, which is the same\n // outcome as an explicit all-none grant — not a distinct third state.\n //\n // `undefined` is NOT that. The contract is `MemoryGrant | null`, so a\n // missing return is a policy that is broken rather than restrictive — a\n // JavaScript caller who forgot one, or a branch that falls off the end.\n // Reading it as \"grant nothing\" would switch Memory off silently for the\n // exact deployments least able to notice; it fails loudly instead.\n if (grant === undefined) {\n return errorResponse(\"Memory policy returned an invalid grant\", 500);\n }\n const resolved = grant ?? NO_MEMORY;\n if (!ACCESS.has(resolved.user) || !ACCESS.has(resolved.project)) {\n return errorResponse(\"Memory policy returned an invalid grant\", 500);\n }\n return { user, grant: { user: resolved.user, project: resolved.project } };\n } catch {\n return errorResponse(\"Memory policy failed\", 500);\n }\n}\n"],"mappings":";;;AAQA,MAAM,SAAS,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAa,CAAC;;AAGtD,MAAM,YAAyB,OAAO,OAAO;CAC3C,MAAM;CACN,SAAS;CACV,CAAC;;;;;;;;;;;AAiBF,SAAgB,kBAAkB,OAA6B;AAC7D,QAAO,MAAM,SAAS,UAAU,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;AAsBpD,eAAsB,iBACpB,SACA,SACA,MACA,UACuC;AACvC,KAAI,CAAC,QAAQ,OACX,QAAO;EACL;EACA,OAAO;GAAE,MAAM;GAAc,SAAS;GAAc;EACrD;AAGH,KAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,OAAO,OAAO;GAAE;GAAS;GAAM;GAAU,CAAC;AAStE,MAAI,UAAU,OACZ,QAAO,cAAc,2CAA2C,IAAI;EAEtE,MAAM,WAAW,SAAS;AAC1B,MAAI,CAAC,OAAO,IAAI,SAAS,KAAK,IAAI,CAAC,OAAO,IAAI,SAAS,QAAQ,CAC7D,QAAO,cAAc,2CAA2C,IAAI;AAEtE,SAAO;GAAE;GAAM,OAAO;IAAE,MAAM,SAAS;IAAM,SAAS,SAAS;IAAS;GAAE;SACpE;AACN,SAAO,cAAc,wBAAwB,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-intelligence-user.cjs","names":["errorResponse","isValidIdentifier","isIntelligenceRuntime"],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"resolve-intelligence-user.cjs","names":["errorResponse","isValidIdentifier","isIntelligenceRuntime"],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotKitIntelligenceRuntimeLike,\n CopilotKitRuntimeLike,\n CopilotKitRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotKitRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotKitRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotKitRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotKitIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotKitRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing !== undefined) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotKitRuntimeLike,\n request: Request,\n): Promise<CopilotKitRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n getRuntimeLogger(runtime).error(\n \"Error identifying user: identifyUser is not configured\",\n );\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n getRuntimeLogger(runtime).error({ err: error }, \"Error identifying user\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGA;CAC5C,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,aAAa,OAAW,QAAO;CAEnC,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SAC2C;AAC3C,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,kCAAiB,QAAQ,CAAC,MACxB,yDACD;AACD,SAAOA,oCAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAACC,6CAAkB,MAAM,GAAG,CAC9B,QAAOD,oCAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAWE,sCAAsB,QAAQ,CAC5C,QAAOF,oCAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,kCAAiB,QAAQ,CAAC,MAAM,EAAE,KAAK,OAAO,EAAE,yBAAyB;AACzE,SAAOA,oCAAc,2BAA2B,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n
|
|
1
|
+
{"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotKitIntelligenceRuntimeLike,\n CopilotKitRuntimeLike,\n CopilotKitRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotKitRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotKitRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotKitRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotKitIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotKitRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing !== undefined) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotKitRuntimeLike,\n request: Request,\n): Promise<CopilotKitRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n getRuntimeLogger(runtime).error(\n \"Error identifying user: identifyUser is not configured\",\n );\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n getRuntimeLogger(runtime).error({ err: error }, \"Error identifying user\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;;AAiBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGA;CAC5C,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,aAAa,OAAW,QAAO;CAEnC,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SAC2C;AAC3C,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,mBAAiB,QAAQ,CAAC,MACxB,yDACD;AACD,SAAO,cAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAW,sBAAsB,QAAQ,CAC5C,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,mBAAiB,QAAQ,CAAC,MAAM,EAAE,KAAK,OAAO,EAAE,yBAAyB;AACzE,SAAO,cAAc,2BAA2B,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sse-response.cjs","names":["THREAD_ALREADY_RUNNING_ERROR_CODE","getRuntimeLogger","defaultTelemetry","resolveSseKeepAliveIntervalSeconds","EventEncoder","createDebugLogger","EventType","isThreadAccessDeniedError","THREAD_ACCESS_DENIED_ERROR_CODE","telemetry","keepAliveSse"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport {\n keepAliveSse,\n resolveSseKeepAliveIntervalSeconds,\n} from \"./sse-keep-alive\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createDebugLogger, getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created debug logger, so a request does not create its own. */\n debugLogger?: CopilotRuntimeLogger;\n /** Where errors and warnings go. Default: the console. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n debugLogger: preCreatedDebugLogger,\n logger = getRuntimeLogger(),\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (preCreatedDebugLogger ?? createDebugLogger())\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\n }\n };\n\n const logError = (error: unknown) => {\n logger.error({ err: error }, \"Error running agent\");\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n logger.warn(\n { err: error },\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n };\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n void telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n };\n const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n };\n\n subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n const body =\n keepAliveSeconds > 0\n ? keepAliveSse(stream.readable, keepAliveSeconds * 1_000)\n : stream.readable;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = metadata.langgraph_version;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE,iBAAiB,UACf,MAA6B,SAASA,wDACtC,MAAM,YAAY;;AA2CxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,aAAa,uBACb,SAASC,iCAAkB,EAC3B,yBAAYC,kCACZ,eACA,mBAAmB,MACnB,sBACA,WACA,4BACyC;CACzC,MAAM,mBAAmBC,0DACvB,yBACD;CACD,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAIC,6BAAc;CAClC,IAAI,eAAe;CAInB,IAAI,uBAAuB;CAC3B,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,yBAAyBC,kCAAmB,GAC7C;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAYZ,MAAM,gBAAgB,OAAO,UAAmB;AAC9C,MAAI,wBAAwB,gBAAgB,Q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,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO;;;;;;;;;;;;;AAcT,SAAS,qBACP,OACA,MACM;CACN,MAAM,WACJ,MAMA;AACF,KAAI,CAAC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
|
|
1
|
+
{"version":3,"file":"sse-response.cjs","names":["THREAD_ALREADY_RUNNING_ERROR_CODE","getRuntimeLogger","defaultTelemetry","resolveSseKeepAliveIntervalSeconds","EventEncoder","createDebugLogger","EventType","isThreadAccessDeniedError","THREAD_ACCESS_DENIED_ERROR_CODE","telemetry","keepAliveSse"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport {\n keepAliveSse,\n resolveSseKeepAliveIntervalSeconds,\n} from \"./sse-keep-alive\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createDebugLogger, getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../../core/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created debug logger, so a request does not create its own. */\n debugLogger?: CopilotKitRuntimeLogger;\n /** Where errors and warnings go. Default: the console. */\n logger?: CopilotKitRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n debugLogger: preCreatedDebugLogger,\n logger = getRuntimeLogger(),\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (preCreatedDebugLogger ?? createDebugLogger())\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\n }\n };\n\n const logError = (error: unknown) => {\n logger.error({ err: error }, \"Error running agent\");\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n logger.warn(\n { err: error },\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n };\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n void telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n };\n const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n };\n\n subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n const body =\n keepAliveSeconds > 0\n ? keepAliveSse(stream.readable, keepAliveSeconds * 1_000)\n : stream.readable;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = metadata.langgraph_version;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAS,uBA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@
|
|
|
1
|
-
{"version":3,"file":"sse-response.mjs","names":["defaultTelemetry","telemetry"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport {\n keepAliveSse,\n resolveSseKeepAliveIntervalSeconds,\n} from \"./sse-keep-alive\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createDebugLogger, getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created debug logger, so a request does not create its own. */\n debugLogger?: CopilotRuntimeLogger;\n /** Where errors and warnings go. Default: the console. */\n logger?: CopilotRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n debugLogger: preCreatedDebugLogger,\n logger = getRuntimeLogger(),\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (preCreatedDebugLogger ?? createDebugLogger())\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\n }\n };\n\n const logError = (error: unknown) => {\n logger.error({ err: error }, \"Error running agent\");\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n logger.warn(\n { err: error },\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n };\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n void telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n };\n const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n };\n\n subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n const body =\n keepAliveSeconds > 0\n ? keepAliveSse(stream.readable, keepAliveSeconds * 1_000)\n : stream.readable;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = metadata.langgraph_version;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE,iBAAiB,UACf,MAA6B,SAAS,qCACtC,MAAM,YAAY;;AA2CxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,aAAa,uBACb,SAAS,kBAAkB,EAC3B,yBAAYA,WACZ,eACA,mBAAmB,MACnB,sBACA,WACA,4BACyC;CACzC,MAAM,mBAAmB,mCACvB,yBACD;CACD,MAAM,SAAS,IAAI,iBAAiB;CACpC,MAAM,SAAS,OAAO,SAAS,WAAW;CAC1C,MAAM,UAAU,IAAI,cAAc;CAClC,IAAI,eAAe;CAInB,IAAI,uBAAuB;CAC3B,IAAI,gBAAgB;CACpB,IAAI,aAAa;CAEjB,MAAM,cAAc,OAAO,UACtB,yBAAyB,mBAAmB,GAC7C;CAEJ,MAAM,cAAc,YAAY;AAC9B,MAAI,CAAC,aACH,KAAI;AACF,SAAM,OAAO,OAAO;AACpB,kBAAe;UACT;;CAYZ,MAAM,gBAAgB,OAAO,UAAmB;AAC9C,MAAI,wBAAwB,gBAAgB,QAAQ,OAAO,QACzD;AAEF,yBAAuB;EACvB,MAAM,QAAQ,uBAAuB,MAAM,GACvC;GACE,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,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO;;;;;;;;;;;;;AAcT,SAAS,qBACP,OACA,MACM;CACN,MAAM,WACJ,MAMA;AACF,KAAI,CAAC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
|
|
1
|
+
{"version":3,"file":"sse-response.mjs","names":["defaultTelemetry","telemetry"],"sources":["../../../../src/runtime/handlers/shared/sse-response.ts"],"sourcesContent":["import { EventType } from \"@ag-ui/client\";\nimport type { BaseEvent } from \"@ag-ui/client\";\nimport { EventEncoder } from \"@ag-ui/encoder\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport {\n keepAliveSse,\n resolveSseKeepAliveIntervalSeconds,\n} from \"./sse-keep-alive\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\nimport {\n THREAD_ACCESS_DENIED_ERROR_CODE,\n isThreadAccessDeniedError,\n} from \"../../runner/agent-runner\";\nimport type { ResolvedDebugConfig } from \"@copilotkit/shared\";\nimport { createDebugLogger, getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../../core/logger\";\nimport { telemetry as defaultTelemetry } from \"../../telemetry\";\nimport type { TelemetryCapture } from \"../../telemetry/telemetry-client\";\nimport type { AgentExecutionResponseInfo } from \"../../telemetry/events\";\nimport type { DebugEventBus } from \"../../core/debug-event-bus\";\nimport type {\n RuntimeErrorPhase,\n RuntimeErrorReporter,\n} from \"../../core/runtime-error-reporter\";\n\n/**\n * Whether a runner rejected the run because the thread is busy. Matches the\n * `code` of {@link ThreadAlreadyRunningError}, and the plain message that\n * custom runners copied from the built-in ones still throw.\n */\nfunction isThreadAlreadyRunning(error: unknown): boolean {\n return (\n error instanceof Error &&\n ((error as { code?: unknown }).code === THREAD_ALREADY_RUNNING_ERROR_CODE ||\n error.message === \"Thread already running\")\n );\n}\n\ninterface CreateSseEventResponseParams {\n request: Request;\n observableFactory: () =>\n | Promise<Observable<BaseEvent>>\n | Observable<BaseEvent>;\n debugEventBus?: DebugEventBus;\n agentId?: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created debug logger, so a request does not create its own. */\n debugLogger?: CopilotKitRuntimeLogger;\n /** Where errors and warnings go. Default: the console. */\n logger?: CopilotKitRuntimeLogger;\n /** Runtime-bound telemetry capture. Falls back for external direct callers. */\n telemetry?: TelemetryCapture;\n /**\n * Execution facts known before the stream opens, merged under anything the\n * upstream reports as it runs. Carries `llmHostClass`, which is knowable\n * from the agent's configuration and never appears on a streamed event.\n */\n executionSeed?: AgentExecutionResponseInfo;\n /**\n * Whether to emit `oss.runtime.agent_execution_stream_*` telemetry for this\n * stream. Defaults to `true`. The stateless `/suggest` path sets this to\n * `false`: a suggestion is a side-effect-free structured completion, not a\n * tracked run, and under `available: \"always\"` it fires often enough to flood\n * run telemetry.\n */\n captureTelemetry?: boolean;\n runtimeErrorReporter?: RuntimeErrorReporter;\n startTime?: number;\n /**\n * Seconds of silence before a `: keep-alive` SSE comment is written.\n * `0` disables the keep-alive. Resolved by\n * {@link resolveSseKeepAliveIntervalSeconds}, which supplies the default\n * and enforces the timer bound for every caller.\n */\n keepAliveIntervalSeconds?: number;\n}\n\nexport function createSseEventResponse({\n request,\n observableFactory,\n debugEventBus,\n agentId,\n debug,\n debugLogger: preCreatedDebugLogger,\n logger = getRuntimeLogger(),\n telemetry = defaultTelemetry,\n executionSeed,\n captureTelemetry = true,\n runtimeErrorReporter,\n startTime,\n keepAliveIntervalSeconds,\n}: CreateSseEventResponseParams): Response {\n const keepAliveSeconds = resolveSseKeepAliveIntervalSeconds(\n keepAliveIntervalSeconds,\n );\n const stream = new TransformStream();\n const writer = stream.writable.getWriter();\n const encoder = new EventEncoder();\n let streamClosed = false;\n // Set once the current run's RUN_FINISHED or RUN_ERROR has been queued for\n // the client. AG-UI allows nothing after either until the next RUN_STARTED,\n // so a later failure must not add a RUN_ERROR.\n let terminalEventWritten = false;\n let debugThreadId = \"\";\n let debugRunId = \"\";\n\n const debugLogger = debug?.enabled\n ? (preCreatedDebugLogger ?? createDebugLogger())\n : undefined;\n\n const closeStream = async () => {\n if (!streamClosed) {\n try {\n await writer.close();\n streamClosed = true;\n } catch {\n // Stream already closed.\n }\n }\n };\n\n // Report a failure to the client as a terminal RUN_ERROR. Without it the\n // client sees an empty stream that ends normally, so its run \"succeeds\"\n // with no reply and no error (e.g. \"Thread already running\" on a busy\n // thread). Only a busy thread is named, with a code clients can branch on;\n // anything else may carry internal detail, so the client gets a generic\n // message and the full error stays in the server log.\n const writeRunError = async (error: unknown) => {\n if (terminalEventWritten || streamClosed || request.signal.aborted) {\n return;\n }\n terminalEventWritten = true;\n const event = isThreadAlreadyRunning(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread already running\",\n code: THREAD_ALREADY_RUNNING_ERROR_CODE,\n }\n : isThreadAccessDeniedError(error)\n ? {\n type: EventType.RUN_ERROR,\n message: \"Thread access denied\",\n code: THREAD_ACCESS_DENIED_ERROR_CODE,\n }\n : { type: EventType.RUN_ERROR, message: \"Agent run failed\" };\n // The inspector sees every streamed event, so it needs this one too or\n // the run it saw start never ends there. A run that never started has\n // no ids to file it under, so it is not sent.\n if (debugEventBus && debugRunId) {\n try {\n debugEventBus.broadcast(event as BaseEvent, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n try {\n await writer.write(encoder.encodeBinary(event as BaseEvent));\n } catch {\n // The client is already gone; closeStream() handles the rest.\n }\n };\n\n const logError = (error: unknown) => {\n logger.error({ err: error }, \"Error running agent\");\n };\n\n let subscription: Subscription | undefined;\n let agentErrorReported = false;\n\n // A refused run is an access decision, not an agent failure: log it as a\n // warning and keep it out of the error reporter.\n const logAccessDenied = (error: unknown) => {\n logger.warn(\n { err: error },\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n };\n\n const reportAgentError = (error: unknown, phase: RuntimeErrorPhase) => {\n if (agentErrorReported) return;\n agentErrorReported = true;\n runtimeErrorReporter?.report({\n request,\n error,\n operation: \"agent.run\",\n agentId,\n threadId: debugThreadId || undefined,\n runId: debugRunId || undefined,\n phase,\n startTime,\n });\n };\n\n (async () => {\n const observable = await observableFactory();\n\n if (captureTelemetry) {\n void telemetry.capture(\"oss.runtime.agent_execution_stream_started\", {});\n }\n\n if (debug?.lifecycle) {\n debugLogger!.debug(\"SSE stream opened\");\n }\n\n let eventCount = 0;\n let loggedEventCount = 0;\n\n // Provider/model/LangGraph facts, scraped off raw upstream events as\n // they pass and reported once the stream finishes. This moved here from\n // the v1 TelemetryAgentRunner, which wrapped the runner purely to\n // collect it and emitted its own duplicate copy of every stream event\n // to carry it. v2 callers had no equivalent and reported `{}`.\n // Seeded rather than empty: `llmHostClass` comes from the agent's config,\n // not from the wire, so nothing streamed will ever fill it in. Scraped\n // fields still win, since `collectExecutionInfo` writes over this.\n const executionInfo: AgentExecutionResponseInfo = { ...executionSeed };\n\n // RxJS ignores what an observer returns, so these async handlers run\n // fire-and-forget.\n const onNext = async (event: BaseEvent) => {\n collectExecutionInfo(event, executionInfo);\n\n // Extract threadId/runId from RUN_STARTED\n if (event.type === \"RUN_STARTED\") {\n const e = event as { threadId?: string; runId?: string };\n debugThreadId = e.threadId ?? \"\";\n debugRunId = e.runId ?? \"\";\n }\n\n if (event.type === \"RUN_ERROR\") {\n const e = event as {\n message?: unknown;\n threadId?: string;\n runId?: string;\n };\n debugThreadId = e.threadId ?? debugThreadId;\n debugRunId = e.runId ?? debugRunId;\n reportAgentError(\n new Error(\n typeof e.message === \"string\"\n ? e.message\n : \"Runner reported a run error\",\n ),\n \"sse.subscription\",\n );\n }\n\n // Broadcast to debug listeners BEFORE the stream-closed gate below.\n // Intentional: debug subscribers (e.g. the VS Code Inspector panel)\n // should still receive trailing events after the SSE client for\n // this request closed its connection — they're independent\n // consumers observing the underlying runtime, not the request's\n // response stream.\n //\n // Wrapped in try/catch so a buggy debug subscriber can't propagate\n // an exception into this observer — if the throw reached the\n // `next` callback it would get routed to `error` by RxJS, closing\n // the SSE stream for an unrelated reason. Log via `logError` and\n // move on.\n if (debugEventBus) {\n try {\n debugEventBus.broadcast(event, {\n agentId: agentId ?? \"\",\n threadId: debugThreadId,\n runId: debugRunId,\n });\n } catch (broadcastError) {\n logError(broadcastError);\n }\n }\n\n if (!request.signal.aborted && !streamClosed) {\n try {\n eventCount++;\n if (debug?.events) {\n loggedEventCount++;\n if (debug.verbose) {\n debugLogger!.debug({ event }, \"Event emitted\");\n } else {\n debugLogger!.debug(\n { type: event.type, ...summarizeEvent(event) },\n \"Event emitted\",\n );\n }\n }\n // /connect replays finished runs before the live one, so a new\n // RUN_STARTED reopens the stream for a RUN_ERROR.\n if (event.type === EventType.RUN_STARTED) {\n terminalEventWritten = false;\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n terminalEventWritten = true;\n }\n await writer.write(encoder.encodeBinary(event));\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n streamClosed = true;\n } else {\n // Non-abort write failures (backpressure disconnects,\n // transform-stream exceptions, …) were previously swallowed\n // silently — `streamClosed` stayed `false` and the next\n // event re-attempted a broken writer. Log and mark the\n // stream closed so we stop trying.\n logError(error);\n streamClosed = true;\n }\n }\n }\n };\n const onError = async (error: unknown) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n await writeRunError(error);\n await closeStream();\n return;\n }\n reportAgentError(error, \"sse.subscription\");\n if (captureTelemetry) {\n // Analytics gets the outcome, not the message: provider and tool\n // errors can quote prompts, arguments or URLs. Same as Intelligence.\n void telemetry.capture(\"oss.runtime.agent_execution_stream_errored\", {\n ...executionInfo,\n error: \"AGENT_EXECUTION_FAILED\",\n });\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { error: error instanceof Error ? error.message : String(error) },\n \"SSE stream errored\",\n );\n }\n logError(error);\n await writeRunError(error);\n await closeStream();\n };\n const onComplete = async () => {\n if (captureTelemetry) {\n void telemetry.capture(\n \"oss.runtime.agent_execution_stream_ended\",\n executionInfo,\n );\n }\n if (debug?.lifecycle) {\n debugLogger!.debug(\n { eventCount, loggedEventCount },\n \"SSE stream completed\",\n );\n }\n await closeStream();\n };\n\n subscription = observable.subscribe({\n next: (event) => {\n void onNext(event);\n },\n error: (error: unknown) => {\n void onError(error);\n },\n complete: () => {\n void onComplete();\n },\n });\n\n // If the client disconnected before the subscription was created,\n // unsubscribe immediately to avoid leaking the observable.\n if (request.signal.aborted) {\n subscription.unsubscribe();\n }\n })().catch(async (error) => {\n if (isThreadAccessDeniedError(error)) {\n logAccessDenied(error);\n } else {\n reportAgentError(error, \"sse.factory\");\n logError(error);\n }\n await writeRunError(error);\n await closeStream();\n });\n\n request.signal.addEventListener(\"abort\", () => {\n subscription?.unsubscribe();\n });\n\n const body =\n keepAliveSeconds > 0\n ? keepAliveSse(stream.readable, keepAliveSeconds * 1_000)\n : stream.readable;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n },\n });\n}\n\nfunction summarizeEvent(event: BaseEvent): Record<string, unknown> {\n const e = event as any;\n const summary: Record<string, unknown> = {};\n\n if (e.messageId) summary.messageId = e.messageId;\n if (e.toolCallId) summary.toolCallId = e.toolCallId;\n if (e.toolCallName) summary.toolCallName = e.toolCallName;\n if (e.role) summary.role = e.role;\n if (e.delta != null && typeof e.delta === \"string\")\n summary.deltaLength = e.delta.length;\n if (e.snapshot && typeof e.snapshot === \"object\")\n summary.snapshotKeys = Object.keys(e.snapshot);\n if (e.delta && Array.isArray(e.delta))\n summary.operationCount = e.delta.length;\n if (e.threadId) summary.threadId = e.threadId;\n if (e.runId) summary.runId = e.runId;\n if (e.message) summary.message = e.message;\n if (e.code) summary.code = e.code;\n if (e.stepName) summary.stepName = e.stepName;\n\n return summary;\n}\n\n/**\n * Accumulate provider, model, and LangGraph facts from one upstream event.\n *\n * Mutates rather than returns so the caller keeps one record across the whole\n * stream: these arrive on different events and the last one wins. Only fields\n * the upstream actually sent are set, so an agent that reports none leaves the\n * record empty and the stream events carry `{}` as before.\n *\n * `rawEvent` is the untransformed upstream payload, present on AG-UI events\n * that wrap one. Its shape is the provider's, not ours, hence the narrowing.\n */\nfunction collectExecutionInfo(\n event: BaseEvent,\n into: AgentExecutionResponseInfo,\n): void {\n const rawEvent = (\n event as {\n rawEvent?: {\n metadata?: Record<string, unknown>;\n data?: Record<string, unknown>;\n };\n }\n ).rawEvent;\n if (!rawEvent) return;\n\n const model = (rawEvent.data as { output?: { model?: string } } | undefined)\n ?.output?.model;\n if (model) {\n into.model = model;\n // Carried forward from the v1 implementation, which set both from the\n // same field. The upstream sends no separate provider name.\n into.provider = model;\n }\n\n const metadata = rawEvent.metadata as\n | { langgraph_host?: string; langgraph_version?: string }\n | undefined;\n if (metadata?.langgraph_host) into.langGraphHost = metadata.langgraph_host;\n if (metadata?.langgraph_version) {\n into.langGraphVersion = metadata.langgraph_version;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAS,uBAAuB,OAAyB;AACvD,QACE,iBAAiB,UACf,MAA6B,SAAS,qCACtC,MAAM,YAAY;;AA2CxB,SAAgB,uBAAuB,EACrC,SACA,mBACA,eACA,SACA,OACA,aAAa,uBACb,SAAS,kBAAkB,EAC3B,yBAAYA,WACZ,eACA,mBAAmB,MACnB,sBACA,WACA,4BACyC;CACzC,MAAM,mBAAmB,mCACvB,yB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AI,EAAE,UAAW,SAAQ,YAAY,EAAE;AACvC,KAAI,EAAE,WAAY,SAAQ,aAAa,EAAE;AACzC,KAAI,EAAE,aAAc,SAAQ,eAAe,EAAE;AAC7C,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAS,QAAQ,OAAO,EAAE,UAAU,SACxC,SAAQ,cAAc,EAAE,MAAM;AAChC,KAAI,EAAE,YAAY,OAAO,EAAE,aAAa,SACtC,SAAQ,eAAe,OAAO,KAAK,EAAE,SAAS;AAChD,KAAI,EAAE,SAAS,MAAM,QAAQ,EAAE,MAAM,CACnC,SAAQ,iBAAiB,EAAE,MAAM;AACnC,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AACrC,KAAI,EAAE,MAAO,SAAQ,QAAQ,EAAE;AAC/B,KAAI,EAAE,QAAS,SAAQ,UAAU,EAAE;AACnC,KAAI,EAAE,KAAM,SAAQ,OAAO,EAAE;AAC7B,KAAI,EAAE,SAAU,SAAQ,WAAW,EAAE;AAErC,QAAO;;;;;;;;;;;;;AAcT,SAAS,qBACP,OACA,MACM;CACN,MAAM,WACJ,MAMA;AACF,KAAI,CAAC,SAAU;CAEf,MAAM,QAAS,SAAS,MACpB,QAAQ;AACZ,KAAI,OAAO;AACT,OAAK,QAAQ;AAGb,OAAK,WAAW;;CAGlB,MAAM,WAAW,SAAS;AAG1B,KAAI,UAAU,eAAgB,MAAK,gBAAgB,SAAS;AAC5D,KAAI,UAAU,kBACZ,MAAK,mBAAmB,SAAS"}
|
|
@@ -38,7 +38,7 @@ const ANONYMOUS_THREAD_ACCESS = {
|
|
|
38
38
|
isRunning: true
|
|
39
39
|
}
|
|
40
40
|
};
|
|
41
|
-
const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to
|
|
41
|
+
const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to CopilotKitRuntime so each user lists and clears only their own threads, or pass `threads: { access: \"open\" }` to let every caller share threads created without identity (insecure for multi-user deployments).";
|
|
42
42
|
/**
|
|
43
43
|
* The configuration error for `identifyUser` with a runner that cannot keep
|
|
44
44
|
* users apart. Every Thread operation is refused rather than served unscoped.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-access.cjs","names":["hasIdentifyUser","enforcesThreadOwnership","supportsLocalThreadEndpoints","resolveIntelligenceUser","errorResponse"],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;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cJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAID,kDAAgB,QAAQ,EAAE;AAG5B,MAAI,CAACC,6CAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAOC,oCAAc,oBAAoB,IAAI"}
|
|
1
|
+
{"version":3,"file":"thread-access.cjs","names":["hasIdentifyUser","enforcesThreadOwnership","supportsLocalThreadEndpoints","resolveIntelligenceUser","errorResponse"],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotKitRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotKitRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotKitRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotKitRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAIA,kDAAgB,QAAQ,IAAI,CAACC,6CAAwB,QAAQ,OAAO,CACtE,iCAAiB,QAAQ,CAAC,KACxB,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAsC;AAC5E,KAAI,wBAAyB;AAC7B,KAAI,CAACC,kDAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,iCAAiB,QAAQ,CAAC,KACxB,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAAIF,kDAAgB,QAAQ,CAC1B,QAAOC,6CAAwB,QAAQ,OAAO;AAEhD,QAAO,wBAAwB,QAAQ,gBAAgB,uBACrD;;;;;;;;;;;;AAcJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAID,kDAAgB,QAAQ,EAAE;AAG5B,MAAI,CAACC,6CAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAOC,oCAAc,oBAAoB,IAAI"}
|
|
@@ -38,7 +38,7 @@ const ANONYMOUS_THREAD_ACCESS = {
|
|
|
38
38
|
isRunning: true
|
|
39
39
|
}
|
|
40
40
|
};
|
|
41
|
-
const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to
|
|
41
|
+
const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to CopilotKitRuntime so each user lists and clears only their own threads, or pass `threads: { access: \"open\" }` to let every caller share threads created without identity (insecure for multi-user deployments).";
|
|
42
42
|
/**
|
|
43
43
|
* The configuration error for `identifyUser` with a runner that cannot keep
|
|
44
44
|
* users apart. Every Thread operation is refused rather than served unscoped.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-access.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;E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AO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAO,cAAc,oBAAoB,IAAI"}
|
|
1
|
+
{"version":3,"file":"thread-access.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotKitRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotKitRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotKitRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotKitRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAI,gBAAgB,QAAQ,IAAI,CAAC,wBAAwB,QAAQ,OAAO,CACtE,kBAAiB,QAAQ,CAAC,KACxB,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAsC;AAC5E,KAAI,wBAAyB;AAC7B,KAAI,CAAC,6BAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,kBAAiB,QAAQ,CAAC,KACxB,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAA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