@copilotkit/runtime 2.0.0-rc.7 → 2.0.0-rc.9

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.
Files changed (68) hide show
  1. package/README.md +19 -1
  2. package/dist/agent/converters/tanstack.cjs +1 -1
  3. package/dist/agent/converters/tanstack.cjs.map +1 -1
  4. package/dist/agent/converters/tanstack.mjs +1 -1
  5. package/dist/agent/converters/tanstack.mjs.map +1 -1
  6. package/dist/agent/index.cjs +9 -8
  7. package/dist/agent/index.cjs.map +1 -1
  8. package/dist/agent/index.d.cts.map +1 -1
  9. package/dist/agent/index.d.mts.map +1 -1
  10. package/dist/agent/index.mjs +9 -8
  11. package/dist/agent/index.mjs.map +1 -1
  12. package/dist/index.cjs +12 -0
  13. package/dist/index.d.cts +4 -1
  14. package/dist/index.d.mts +4 -1
  15. package/dist/index.mjs +4 -1
  16. package/dist/runtime/core/logger.cjs +1 -4
  17. package/dist/runtime/core/logger.cjs.map +1 -1
  18. package/dist/runtime/core/logger.d.cts.map +1 -1
  19. package/dist/runtime/core/logger.d.mts.map +1 -1
  20. package/dist/runtime/core/logger.mjs +1 -3
  21. package/dist/runtime/core/logger.mjs.map +1 -1
  22. package/dist/runtime/core/package-info.cjs +1 -1
  23. package/dist/runtime/core/package-info.mjs +1 -1
  24. package/dist/runtime/core/runtime.d.mts +1 -1
  25. package/dist/runtime/event-transforms/index.d.cts +4 -0
  26. package/dist/runtime/event-transforms/index.d.mts +4 -0
  27. package/dist/runtime/event-transforms/index.mjs +5 -0
  28. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +286 -0
  29. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  30. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +60 -0
  31. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  32. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +60 -0
  33. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  34. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +283 -0
  35. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  36. package/dist/runtime/event-transforms/recorded-events.cjs +59 -0
  37. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  38. package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
  39. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  40. package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
  41. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  42. package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
  43. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  44. package/dist/runtime/handlers/shared/agent-utils.cjs +4 -3
  45. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  46. package/dist/runtime/handlers/shared/agent-utils.mjs +2 -1
  47. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  48. package/dist/runtime/index.d.cts +3 -0
  49. package/dist/runtime/index.d.mts +3 -0
  50. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -7
  51. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  52. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  53. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  54. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -109
  55. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  56. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  57. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  58. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  59. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  60. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  61. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  62. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -2
  63. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  64. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  65. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  66. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  67. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  68. package/package.json +8 -9
@@ -5,12 +5,13 @@ const require_client = require('../../intelligence-platform/client.cjs');
5
5
  const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
6
6
  const require_runtime$1 = require('../../core/runtime.cjs');
7
7
  const require_generative_ui_middleware = require('../../generative-ui/generative-ui-middleware.cjs');
8
+ const require_open_generative_ui_middleware = require('../../event-transforms/open-generative-ui-middleware.cjs');
8
9
  const require_mcp_apps_servers = require('./mcp-apps-servers.cjs');
9
10
  const require_memory_policy = require('./memory-policy.cjs');
10
11
  let _copilotkit_shared = require("@copilotkit/shared");
12
+ let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
11
13
  let _ag_ui_mcp_middleware = require("@ag-ui/mcp-middleware");
12
14
  let _ag_ui_core_schemas = require("@ag-ui/core/schemas");
13
- let _copilotkit_shared_event_transforms = require("@copilotkit/shared/event-transforms");
14
15
  let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
15
16
 
16
17
  //#region src/runtime/handlers/shared/agent-utils.ts
@@ -47,7 +48,7 @@ function configureAgentForRequest(params) {
47
48
  const a2uiEnabledByCatalog = !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;
48
49
  if (require_runtime$1.isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {
49
50
  const { agents: targetAgents, enabled: _enabled, injectA2UITool, ...a2uiOptions } = runtime.a2ui ?? {};
50
- if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _copilotkit_shared_event_transforms.A2UIMiddleware({
51
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _ag_ui_a2ui_middleware.A2UIMiddleware({
51
52
  ...a2uiOptions,
52
53
  injectA2UITool: injectA2UITool ?? (providerA2UIHasCatalog ? true : void 0)
53
54
  }));
@@ -65,7 +66,7 @@ function configureAgentForRequest(params) {
65
66
  if (runtime.openGenerativeUI) {
66
67
  const config = runtime.openGenerativeUI;
67
68
  const targetAgents = typeof config === "object" ? config.agents : void 0;
68
- if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _copilotkit_shared_event_transforms.OpenGenerativeUIMiddleware());
69
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new require_open_generative_ui_middleware.OpenGenerativeUIMiddleware());
69
70
  }
70
71
  const generativeUI = runtime.generativeUI;
71
72
  const transport = params.providerGenerativeUITransport;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","isIntelligenceRuntime","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","GenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","resolveIntelligenceUser","resolveWebMemory","grantAllowsMemory","errorResponse","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"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 {\n A2UIMiddleware,\n OpenGenerativeUIMiddleware,\n} from \"@copilotkit/shared/event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} 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 { logger, processEnv } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\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 {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * 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 logger.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 logger.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(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.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): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\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(content: unknown[]): 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 console.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(\"binary input content\", \"the modern media content part\");\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(message: unknown): 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),\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(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): 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),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,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,g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Ac,OAAO,CAC3C;AACD,cAAa,iBAAiB,YAAY,WAAW,UACnD,eAAe,OAAO,WAAW,cAAc,CAChD;AACD,QAAO,iBACL,YACA,YACA,8BACD;;AAGH,SAAS,mBAAmB,OAA+B;AAGzD,QAAOC,wCAAoB,MACzB,6BAA6B,MAAM,CACpC;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;AAEF,SAAO,mBADa,MAAM,QAAQ,MAAM,CACF;UAC/B,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,YAAY;EAC7C,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","isIntelligenceRuntime","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","GenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","resolveIntelligenceUser","resolveWebMemory","grantAllowsMemory","errorResponse","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"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 { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} 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 { logger, processEnv } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\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 {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * 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 logger.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 logger.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(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.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): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\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(content: unknown[]): 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 console.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(\"binary input content\", \"the modern media content part\");\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(message: unknown): 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),\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(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): 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),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,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,QAmBhC;CACP,MAAM,EACJ,SACA,SACA,SACA,wBACA,sBACE;CACJ,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAIC,sCAAe;GACjB,GAAG;GAIH,gBACE,mBAAmB,yBAAyB,OAAO;GACtD,CAAC,CACH;;AAIL,KAAIC,wCAAsB,QAAQ,IAAI,OAAO,MAAM,QAAQ,YAAY;EAGrE,MAAM,aAAaC,+CACjB,QAAQ,SAAS,WAAW,EAAE,EAC9B,QACD;AACD,MAAI,WAAW,SAAS,KAAK,kBAC3B,OAAM,IACJ,IAAIC,6CAAkB;GAAE;GAAY,sBAAsB;GAAS,CAAC,CACrE;YAEM,QAAQ,SAAS,SAAS,QAAQ;EAC3C,M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iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -4,12 +4,13 @@ import { INTELLIGENCE_MEMORY_GRANT_HEADER, INTELLIGENCE_USER_ID_HEADER } from ".
4
4
  import { resolveIntelligenceUser } from "./resolve-intelligence-user.mjs";
5
5
  import { isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "../../core/runtime.mjs";
6
6
  import { GenerativeUIMiddleware } from "../../generative-ui/generative-ui-middleware.mjs";
7
+ import { OpenGenerativeUIMiddleware } from "../../event-transforms/open-generative-ui-middleware.mjs";
7
8
  import { resolveMcpAppsServers } from "./mcp-apps-servers.mjs";
8
9
  import { grantAllowsMemory, resolveWebMemory } from "./memory-policy.mjs";
9
10
  import { logger, processEnv } from "@copilotkit/shared";
11
+ import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
10
12
  import { MCPMiddleware } from "@ag-ui/mcp-middleware";
11
13
  import { RunAgentInputSchema } from "@ag-ui/core/schemas";
12
- import { A2UIMiddleware, OpenGenerativeUIMiddleware } from "@copilotkit/shared/event-transforms";
13
14
  import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
14
15
 
15
16
  //#region src/runtime/handlers/shared/agent-utils.ts
@@ -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 {\n A2UIMiddleware,\n OpenGenerativeUIMiddleware,\n} from \"@copilotkit/shared/event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} 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 { logger, processEnv } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\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 {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * 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 logger.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 logger.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(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.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): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\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(content: unknown[]): 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 console.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(\"binary input content\", \"the modern media content part\");\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(message: unknown): 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),\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(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): 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),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,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BAAkB,gBAAgB;AACzE,cAAa,iBAAiB,YAAY,UAAU,SAClD,eAAe,MAAM,cAAc,OAAO,CAC3C;AACD,cAAa,iBAAiB,YAAY,WAAW,UACnD,eAAe,OAAO,WAAW,cAAc,CAChD;AACD,QAAO,iBACL,YACA,YACA,8BACD;;AAGH,SAAS,mBAAmB,OAA+B;AAGzD,QAAO,oBAAoB,MACzB,6BAA6B,MAAM,CACpC;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;AAEF,SAAO,mBADa,MAAM,QAAQ,MAAM,CACF;UAC/B,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,YAAY;EAC7C,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
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 { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} 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 { logger, processEnv } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\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 {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * 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 logger.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 logger.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(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.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): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\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(content: unknown[]): 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 console.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(\"binary input content\", \"the modern media content part\");\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(message: unknown): 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),\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(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): 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),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;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gentsFactory, CopilotIntelligenceRu
10
10
  import { GenerativeUIMiddleware } from "./generative-ui/generative-ui-middleware.cjs";
11
11
  import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./generative-ui/surface-writer.cjs";
12
12
  import "./generative-ui/index.cjs";
13
+ import { ArgsParser, GenerateSandboxedUIParams, OnParamEvent, OpenGenerativeUIMiddleware } from "./event-transforms/open-generative-ui-middleware.cjs";
14
+ import { RecordedEventTransformOptions, transformRecordedEvents } from "./event-transforms/recorded-events.cjs";
15
+ import { A2UIMiddleware, A2UIMiddlewareConfig } from "./event-transforms/index.cjs";
13
16
  import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
14
17
  import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
15
18
  import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.cjs";
@@ -10,6 +10,9 @@ import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRu
10
10
  import { GenerativeUIMiddleware } from "./generative-ui/generative-ui-middleware.mjs";
11
11
  import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./generative-ui/surface-writer.mjs";
12
12
  import "./generative-ui/index.mjs";
13
+ import { ArgsParser, GenerateSandboxedUIParams, OnParamEvent, OpenGenerativeUIMiddleware } from "./event-transforms/open-generative-ui-middleware.mjs";
14
+ import { RecordedEventTransformOptions, transformRecordedEvents } from "./event-transforms/recorded-events.mjs";
15
+ import { A2UIMiddleware, A2UIMiddlewareConfig } from "./event-transforms/index.mjs";
13
16
  import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
14
17
  import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
15
18
  import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.mjs";
@@ -9,8 +9,8 @@ const learningContainerSchema = zod.z.object({
9
9
  name: zod.z.string().min(1),
10
10
  projectId: zod.z.number().int().positive(),
11
11
  promptContext: zod.z.string().nullable(),
12
- createdAt: zod.z.string().datetime({ offset: true }),
13
- updatedAt: zod.z.string().datetime({ offset: true })
12
+ createdAt: zod.z.iso.datetime({ offset: true }),
13
+ updatedAt: zod.z.iso.datetime({ offset: true })
14
14
  });
15
15
  const learningContainerPageSchema = zod.z.object({
16
16
  containers: zod.z.array(learningContainerSchema).max(500),
@@ -52,8 +52,8 @@ async function readLearningJson(response, limit = 16 * 1024 * 1024, signal) {
52
52
  }
53
53
  }
54
54
  const learningSha256Schema = zod.z.string().regex(/^[a-f0-9]{64}$/u);
55
- const learningUuidSchema = zod.z.string().uuid();
56
- const learningDateTimeSchema = zod.z.string().datetime({ offset: true });
55
+ const learningUuidSchema = zod.z.guid();
56
+ const learningDateTimeSchema = zod.z.iso.datetime({ offset: true });
57
57
  /** One immutable file in a proposed Skill candidate bundle. */
58
58
  const learningSkillBundleFileSchema = zod.z.object({
59
59
  content: zod.z.string(),
@@ -130,7 +130,7 @@ const learningCandidateReviewSchema = zod.z.object({
130
130
  status: zod.z.enum(["approved", "rejected"])
131
131
  });
132
132
  const learningRunSchema = zod.z.object({
133
- id: zod.z.string().uuid(),
133
+ id: zod.z.guid(),
134
134
  learningContainerId: learningContainerIdSchema,
135
135
  projectId: zod.z.number().int().positive(),
136
136
  status: zod.z.enum([
@@ -172,7 +172,7 @@ const learningInsightEvidenceSchema = zod.z.union([zod.z.object({
172
172
  unavailable: unavailableSchema
173
173
  }), zod.z.object({
174
174
  kind: zod.z.literal("trajectory"),
175
- trajectoryId: zod.z.string().uuid(),
175
+ trajectoryId: zod.z.guid(),
176
176
  trajectoryPresent: zod.z.boolean(),
177
177
  eventCount: zod.z.number().int().nonnegative(),
178
178
  events: zod.z.array(zod.z.object({
@@ -186,7 +186,7 @@ const learningInsightEvidenceSchema = zod.z.union([zod.z.object({
186
186
  })]);
187
187
  /** Validates object IDs independently from container IDs; neither may alter the path. */
188
188
  function learningObjectId(id) {
189
- return zod.z.string().uuid().parse(id);
189
+ return zod.z.guid().parse(id);
190
190
  }
191
191
 
192
192
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"learning-management.cjs","names":["z"],"sources":["../../../src/runtime/intelligence-platform/learning-management.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/** Wire contracts for the project-key Learning API; keep aligned with Intelligence. */\nexport const learningContainerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);\nexport const learningContainerSchema = z.object({\n id: learningContainerIdSchema,\n name: z.string().min(1),\n projectId: z.number().int().positive(),\n promptContext: z.string().nullable(),\n createdAt: z.string().datetime({ offset: true }),\n updatedAt: z.string().datetime({ offset: true }),\n});\nexport const learningContainerPageSchema = z.object({\n containers: z.array(learningContainerSchema).max(500),\n nextCursor: z.string().min(1).nullable(),\n});\n/** Explicit wire types preserve required/null fields in declarations emitted with strictNullChecks disabled. */\nexport interface LearningContainer {\n id: string;\n name: string;\n projectId: number;\n promptContext: string | null;\n createdAt: string;\n updatedAt: string;\n}\nexport interface LearningContainerPage {\n containers: LearningContainer[];\n nextCursor: string | null;\n}\nexport interface LearningRequestOptions {\n readonly signal?: AbortSignal;\n}\nexport interface LearningContainerRequest extends LearningRequestOptions {\n readonly containerId: string;\n}\n\n/** Validates a stable identifier before constructing a request path. */\nexport function learningContainerPath(containerId: string): string {\n return `/api/v1/learning/containers/${encodeURIComponent(learningContainerIdSchema.parse(containerId))}`;\n}\n\n/** Reads a bounded JSON response while the request's signal governs stream cancellation. */\nexport async function readLearningJson(\n response: Response,\n limit = 16 * 1024 * 1024,\n signal?: AbortSignal,\n): Promise<unknown> {\n if (!response.body) throw new Error(\"Missing Learning response body\");\n const reader = response.body.getReader();\n const abort = () => {\n void reader.cancel(signal?.reason).catch(() => undefined);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n const decoder = new TextDecoder();\n let text = \"\";\n let bytes = 0;\n try {\n while (true) {\n signal?.throwIfAborted();\n const next = await reader.read();\n signal?.throwIfAborted();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > limit) {\n await reader.cancel();\n throw new Error(\"Learning response exceeds its size limit\");\n }\n text += decoder.decode(next.value, { stream: true });\n }\n return JSON.parse(text + decoder.decode());\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n reader.releaseLock();\n }\n}\n\nconst learningSha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);\nconst learningUuidSchema = z.string().uuid();\nconst learningDateTimeSchema = z.string().datetime({ offset: true });\n\n/** One immutable file in a proposed Skill candidate bundle. */\nexport const learningSkillBundleFileSchema = z.object({\n content: z.string(),\n path: z\n .string()\n .min(1)\n .refine(\n (path) =>\n !path.startsWith(\"/\") &&\n !path.split(\"/\").some((segment) => segment === \"..\"),\n \"Bundle paths must be relative and may not traverse parent directories.\",\n ),\n sha256: learningSha256Schema,\n});\n\n/** Complete Skill files attached to one review candidate. */\nexport const learningSkillBundleSchema = z\n .object({\n files: z.array(learningSkillBundleFileSchema).min(1),\n schemaVersion: z.literal(1),\n })\n\n .superRefine(({ files }, context) => {\n const paths = new Set<string>();\n for (const file of files) {\n if (paths.has(file.path)) {\n context.addIssue({\n code: \"custom\",\n message: `Duplicate bundle path: ${file.path}`,\n path: [\"files\"],\n });\n }\n paths.add(file.path);\n }\n if (!paths.has(\"SKILL.md\")) {\n context.addIssue({\n code: \"custom\",\n message: \"A Skill bundle must contain SKILL.md.\",\n path: [\"files\"],\n });\n }\n });\n\n/** Review state and summary returned for one proposed Skill change. */\nexport const learningCandidateSchema = z.object({\n bundleSha256: learningSha256Schema,\n createdAt: learningDateTimeSchema,\n description: z.string().min(1),\n id: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n reason: z.string().min(1),\n registryBaseRevision: z.number().int().nonnegative(),\n reviewedAt: learningDateTimeSchema.nullable(),\n runId: learningUuidSchema,\n status: z.enum([\"pending_review\", \"approved\", \"rejected\"]),\n subjectSha256: learningSha256Schema,\n targetSkillId: learningUuidSchema.nullable(),\n targetSkillRevision: z.number().int().positive().nullable(),\n title: z.string().min(1),\n});\n\n/** Full proposed Skill change, including evidence and every bundle file. */\nexport const learningCandidateDetailSchema = learningCandidateSchema.extend({\n bundle: learningSkillBundleSchema,\n supportingInsights: z.array(\n z.object({\n alias: z.string().min(1),\n id: learningUuidSchema,\n impact: z.string().min(1),\n statement: z.string().min(1),\n }),\n ),\n});\n\n/** Result returned after a human or agent reviews a Skill candidate. */\nexport const learningCandidateReviewSchema = z.object({\n candidateId: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n status: z.enum([\"approved\", \"rejected\"]),\n});\n\nexport interface LearningCandidate {\n id: string;\n bundleSha256: string;\n createdAt: string;\n description: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n reason: string;\n registryBaseRevision: number;\n reviewedAt: string | null;\n runId: string;\n status: \"pending_review\" | \"approved\" | \"rejected\";\n subjectSha256: string;\n targetSkillId: string | null;\n targetSkillRevision: number | null;\n title: string;\n}\nexport interface LearningCandidateDetail extends LearningCandidate {\n bundle: {\n schemaVersion: 1;\n files: Array<{ path: string; content: string; sha256: string }>;\n };\n supportingInsights: Array<{\n alias: string;\n id: string;\n impact: string;\n statement: string;\n }>;\n}\nexport interface LearningCandidateReview {\n candidateId: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n status: \"approved\" | \"rejected\";\n}\nexport interface LearningCandidateRequest extends LearningContainerRequest {\n readonly candidateId: string;\n}\n\nexport const learningRunSchema = z.object({\n id: z.string().uuid(),\n learningContainerId: learningContainerIdSchema,\n projectId: z.number().int().positive(),\n status: z.enum([\n \"queued\",\n \"freezing\",\n \"batching\",\n \"reducing\",\n \"finalizing\",\n \"succeeded\",\n \"failed\",\n ]),\n triggerSource: z.enum([\"automatic\", \"manual\"]),\n attemptCount: z.number().int().nonnegative(),\n candidateCount: z.number().int().nonnegative().nullable(),\n insightCount: z.number().int().nonnegative().nullable(),\n evidenceThreadCount: z.number().int().nonnegative().nullable().optional(),\n createdAt: learningDateTimeSchema,\n updatedAt: learningDateTimeSchema,\n startedAt: learningDateTimeSchema.nullable(),\n completedAt: learningDateTimeSchema.nullable(),\n failureCode: z.string().nullable(),\n kubernetesJobName: z.string().nullable(),\n});\nexport interface LearningRun {\n id: string;\n learningContainerId: string;\n projectId: number;\n status:\n | \"queued\"\n | \"freezing\"\n | \"batching\"\n | \"reducing\"\n | \"finalizing\"\n | \"succeeded\"\n | \"failed\";\n triggerSource: \"automatic\" | \"manual\";\n attemptCount: number;\n candidateCount: number | null;\n insightCount: number | null;\n evidenceThreadCount?: number | null;\n createdAt: string;\n updatedAt: string;\n startedAt: string | null;\n completedAt: string | null;\n failureCode: string | null;\n kubernetesJobName: string | null;\n}\nconst unavailableSchema = z\n .enum([\"snapshot-missing\", \"snapshot-unreadable\"])\n .nullable();\nexport const learningInsightEvidenceSchema = z.union([\n z.object({\n cited: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n role: z.enum([\"assistant\", \"tool\", \"user\"]),\n }),\n ),\n messageCount: z.number().int().nonnegative(),\n threadId: z.string(),\n threadName: z.string().nullable(),\n threadPresent: z.boolean(),\n unavailable: unavailableSchema,\n }),\n z.object({\n kind: z.literal(\"trajectory\"),\n trajectoryId: z.string().uuid(),\n trajectoryPresent: z.boolean(),\n eventCount: z.number().int().nonnegative(),\n events: z.array(\n z.object({\n seq: z.number().int().nonnegative(),\n name: z.string(),\n offsetMs: z.number(),\n value: z.unknown(),\n eventId: z.string().nullable(),\n }),\n ),\n unavailable: unavailableSchema,\n }),\n]);\nexport type LearningInsightEvidence =\n | {\n cited: Array<{\n id: string;\n content: string;\n role: \"assistant\" | \"tool\" | \"user\";\n }>;\n messageCount: number;\n threadId: string;\n threadName: string | null;\n threadPresent: boolean;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n }\n | {\n kind: \"trajectory\";\n trajectoryId: string;\n trajectoryPresent: boolean;\n eventCount: number;\n events: Array<{\n seq: number;\n name: string;\n offsetMs: number;\n value?: unknown;\n eventId: string | null;\n }>;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n };\n\n/** Validates object IDs independently from container IDs; neither may alter the path. */\nexport function learningObjectId(id: string): string {\n return z.string().uuid().parse(id);\n}\n"],"mappings":";;;;;AAGA,MAAa,4BAA4BA,MACtC,QAAQ,CACR,IAAI,EAAE,CACN,IAAI,GAAG,CACP,MAAM,6BAA6B;AACtC,MAAa,0BAA0BA,MAAE,OAAO;CAC9C,IAAI;CACJ,MAAMA,MAAE,QAAQ,CAAC,IAAI,EAAE;CACvB,WAAWA,MAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;CACtC,eAAeA,MAAE,QAAQ,CAAC,UAAU;CACpC,WAAWA,MAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,MAAM,CAAC;CAChD,WAAWA,MAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,MAAM,CAAC;CACjD,CAAC;AACF,MAAa,8BAA8BA,MAAE,OAAO;CAClD,YAAYA,MAAE,MAAM,wBAAwB,CAAC,IAAI,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AU;CACzC,CAAC;AAyBF,MAAM,oBAAoBA,MACvB,KAAK,CAAC,oBAAoB,sBAAsB,CAAC,CACjD,UAAU;AACb,MAAa,gCAAgCA,MAAE,MAAM,CACnDA,MAAE,OAAO;CACP,OAAOA,MAAE,MACPA,MAAE,OAAO;EACP,IAAIA,MAAE,QAAQ;EACd,SAASA,MAAE,QAAQ;EACnB,MAAMA,MAAE,KAAK;GAAC;GAAa;GAAQ;GAAO,CAAC;EAC5C,CAAC,CACH;CACD,cAAcA,MAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;CAC5C,UAAUA,MAAE,QAAQ;CACpB,YAAYA,MAAE,QAAQ,CAAC,UAAU;CACjC,eAAeA,MAAE,SAAS;CAC1B,aAAa;CACd,CAAC,EACFA,MAAE,OAAO;CACP,MAAMA,MAAE,QAAQ,aAAa;CAC7B,cAAcA,MAAE,QAAQ,CAAC,MAAM;CAC/B,mBAAmBA,MAAE,SAAS;CAC9B,YAAYA,MAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;CAC1C,QAAQA,MAAE,MACRA,MAAE,OAAO;EACP,KAAKA,MAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;EACnC,MAAMA,MAAE,QAAQ;EAChB,UAAUA,MAAE,QAAQ;EACpB,OAAOA,MAAE,SAAS;EAClB,SAASA,MAAE,QAAQ,CAAC,UAAU;EAC/B,CAAC,CACH;CACD,aAAa;CACd,CAAC,CACH,CAAC;;AA8BF,SAAgB,iBAAiB,IAAoB;AACnD,QAAOA,MAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG"}
1
+ {"version":3,"file":"learning-management.cjs","names":["z"],"sources":["../../../src/runtime/intelligence-platform/learning-management.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/** Wire contracts for the project-key Learning API; keep aligned with Intelligence. */\nexport const learningContainerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);\nexport const learningContainerSchema = z.object({\n id: learningContainerIdSchema,\n name: z.string().min(1),\n projectId: z.number().int().positive(),\n promptContext: z.string().nullable(),\n createdAt: z.iso.datetime({ offset: true }),\n updatedAt: z.iso.datetime({ offset: true }),\n});\nexport const learningContainerPageSchema = z.object({\n containers: z.array(learningContainerSchema).max(500),\n nextCursor: z.string().min(1).nullable(),\n});\n/** Explicit wire types preserve required/null fields in declarations emitted with strictNullChecks disabled. */\nexport interface LearningContainer {\n id: string;\n name: string;\n projectId: number;\n promptContext: string | null;\n createdAt: string;\n updatedAt: string;\n}\nexport interface LearningContainerPage {\n containers: LearningContainer[];\n nextCursor: string | null;\n}\nexport interface LearningRequestOptions {\n readonly signal?: AbortSignal;\n}\nexport interface LearningContainerRequest extends LearningRequestOptions {\n readonly containerId: string;\n}\n\n/** Validates a stable identifier before constructing a request path. */\nexport function learningContainerPath(containerId: string): string {\n return `/api/v1/learning/containers/${encodeURIComponent(learningContainerIdSchema.parse(containerId))}`;\n}\n\n/** Reads a bounded JSON response while the request's signal governs stream cancellation. */\nexport async function readLearningJson(\n response: Response,\n limit = 16 * 1024 * 1024,\n signal?: AbortSignal,\n): Promise<unknown> {\n if (!response.body) throw new Error(\"Missing Learning response body\");\n const reader = response.body.getReader();\n const abort = () => {\n void reader.cancel(signal?.reason).catch(() => undefined);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n const decoder = new TextDecoder();\n let text = \"\";\n let bytes = 0;\n try {\n while (true) {\n signal?.throwIfAborted();\n const next = await reader.read();\n signal?.throwIfAborted();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > limit) {\n await reader.cancel();\n throw new Error(\"Learning response exceeds its size limit\");\n }\n text += decoder.decode(next.value, { stream: true });\n }\n return JSON.parse(text + decoder.decode());\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n reader.releaseLock();\n }\n}\n\nconst learningSha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);\nconst learningUuidSchema = z.guid();\nconst learningDateTimeSchema = z.iso.datetime({ offset: true });\n\n/** One immutable file in a proposed Skill candidate bundle. */\nexport const learningSkillBundleFileSchema = z.object({\n content: z.string(),\n path: z\n .string()\n .min(1)\n .refine(\n (path) =>\n !path.startsWith(\"/\") &&\n !path.split(\"/\").some((segment) => segment === \"..\"),\n \"Bundle paths must be relative and may not traverse parent directories.\",\n ),\n sha256: learningSha256Schema,\n});\n\n/** Complete Skill files attached to one review candidate. */\nexport const learningSkillBundleSchema = z\n .object({\n files: z.array(learningSkillBundleFileSchema).min(1),\n schemaVersion: z.literal(1),\n })\n\n .superRefine(({ files }, context) => {\n const paths = new Set<string>();\n for (const file of files) {\n if (paths.has(file.path)) {\n context.addIssue({\n code: \"custom\",\n message: `Duplicate bundle path: ${file.path}`,\n path: [\"files\"],\n });\n }\n paths.add(file.path);\n }\n if (!paths.has(\"SKILL.md\")) {\n context.addIssue({\n code: \"custom\",\n message: \"A Skill bundle must contain SKILL.md.\",\n path: [\"files\"],\n });\n }\n });\n\n/** Review state and summary returned for one proposed Skill change. */\nexport const learningCandidateSchema = z.object({\n bundleSha256: learningSha256Schema,\n createdAt: learningDateTimeSchema,\n description: z.string().min(1),\n id: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n reason: z.string().min(1),\n registryBaseRevision: z.number().int().nonnegative(),\n reviewedAt: learningDateTimeSchema.nullable(),\n runId: learningUuidSchema,\n status: z.enum([\"pending_review\", \"approved\", \"rejected\"]),\n subjectSha256: learningSha256Schema,\n targetSkillId: learningUuidSchema.nullable(),\n targetSkillRevision: z.number().int().positive().nullable(),\n title: z.string().min(1),\n});\n\n/** Full proposed Skill change, including evidence and every bundle file. */\nexport const learningCandidateDetailSchema = learningCandidateSchema.extend({\n bundle: learningSkillBundleSchema,\n supportingInsights: z.array(\n z.object({\n alias: z.string().min(1),\n id: learningUuidSchema,\n impact: z.string().min(1),\n statement: z.string().min(1),\n }),\n ),\n});\n\n/** Result returned after a human or agent reviews a Skill candidate. */\nexport const learningCandidateReviewSchema = z.object({\n candidateId: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n status: z.enum([\"approved\", \"rejected\"]),\n});\n\nexport interface LearningCandidate {\n id: string;\n bundleSha256: string;\n createdAt: string;\n description: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n reason: string;\n registryBaseRevision: number;\n reviewedAt: string | null;\n runId: string;\n status: \"pending_review\" | \"approved\" | \"rejected\";\n subjectSha256: string;\n targetSkillId: string | null;\n targetSkillRevision: number | null;\n title: string;\n}\nexport interface LearningCandidateDetail extends LearningCandidate {\n bundle: {\n schemaVersion: 1;\n files: Array<{ path: string; content: string; sha256: string }>;\n };\n supportingInsights: Array<{\n alias: string;\n id: string;\n impact: string;\n statement: string;\n }>;\n}\nexport interface LearningCandidateReview {\n candidateId: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n status: \"approved\" | \"rejected\";\n}\nexport interface LearningCandidateRequest extends LearningContainerRequest {\n readonly candidateId: string;\n}\n\nexport const learningRunSchema = z.object({\n id: z.guid(),\n learningContainerId: learningContainerIdSchema,\n projectId: z.number().int().positive(),\n status: z.enum([\n \"queued\",\n \"freezing\",\n \"batching\",\n \"reducing\",\n \"finalizing\",\n \"succeeded\",\n \"failed\",\n ]),\n triggerSource: z.enum([\"automatic\", \"manual\"]),\n attemptCount: z.number().int().nonnegative(),\n candidateCount: z.number().int().nonnegative().nullable(),\n insightCount: z.number().int().nonnegative().nullable(),\n evidenceThreadCount: z.number().int().nonnegative().nullable().optional(),\n createdAt: learningDateTimeSchema,\n updatedAt: learningDateTimeSchema,\n startedAt: learningDateTimeSchema.nullable(),\n completedAt: learningDateTimeSchema.nullable(),\n failureCode: z.string().nullable(),\n kubernetesJobName: z.string().nullable(),\n});\nexport interface LearningRun {\n id: string;\n learningContainerId: string;\n projectId: number;\n status:\n | \"queued\"\n | \"freezing\"\n | \"batching\"\n | \"reducing\"\n | \"finalizing\"\n | \"succeeded\"\n | \"failed\";\n triggerSource: \"automatic\" | \"manual\";\n attemptCount: number;\n candidateCount: number | null;\n insightCount: number | null;\n evidenceThreadCount?: number | null;\n createdAt: string;\n updatedAt: string;\n startedAt: string | null;\n completedAt: string | null;\n failureCode: string | null;\n kubernetesJobName: string | null;\n}\nconst unavailableSchema = z\n .enum([\"snapshot-missing\", \"snapshot-unreadable\"])\n .nullable();\nexport const learningInsightEvidenceSchema = z.union([\n z.object({\n cited: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n role: z.enum([\"assistant\", \"tool\", \"user\"]),\n }),\n ),\n messageCount: z.number().int().nonnegative(),\n threadId: z.string(),\n threadName: z.string().nullable(),\n threadPresent: z.boolean(),\n unavailable: unavailableSchema,\n }),\n z.object({\n kind: z.literal(\"trajectory\"),\n trajectoryId: z.guid(),\n trajectoryPresent: z.boolean(),\n eventCount: z.number().int().nonnegative(),\n events: z.array(\n z.object({\n seq: z.number().int().nonnegative(),\n name: z.string(),\n offsetMs: z.number(),\n value: z.unknown(),\n eventId: z.string().nullable(),\n }),\n ),\n unavailable: unavailableSchema,\n }),\n]);\nexport type LearningInsightEvidence =\n | {\n cited: Array<{\n id: string;\n content: string;\n role: \"assistant\" | \"tool\" | \"user\";\n }>;\n messageCount: number;\n threadId: string;\n threadName: string | null;\n threadPresent: boolean;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n }\n | {\n kind: \"trajectory\";\n trajectoryId: string;\n trajectoryPresent: boolean;\n eventCount: number;\n events: Array<{\n seq: number;\n name: string;\n offsetMs: number;\n value?: unknown;\n eventId: string | null;\n }>;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n };\n\n/** Validates object IDs independently from container IDs; neither may alter the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AAQ;EAChB,UAAUA,MAAE,QAAQ;EACpB,OAAOA,MAAE,SAAS;EAClB,SAASA,MAAE,QAAQ,CAAC,UAAU;EAC/B,CAAC,CACH;CACD,aAAa;CACd,CAAC,CACH,CAAC;;AA8BF,SAAgB,iBAAiB,IAAoB;AACnD,QAAOA,MAAE,MAAM,CAAC,MAAM,GAAG"}
@@ -8,8 +8,8 @@ const learningContainerSchema = z.object({
8
8
  name: z.string().min(1),
9
9
  projectId: z.number().int().positive(),
10
10
  promptContext: z.string().nullable(),
11
- createdAt: z.string().datetime({ offset: true }),
12
- updatedAt: z.string().datetime({ offset: true })
11
+ createdAt: z.iso.datetime({ offset: true }),
12
+ updatedAt: z.iso.datetime({ offset: true })
13
13
  });
14
14
  const learningContainerPageSchema = z.object({
15
15
  containers: z.array(learningContainerSchema).max(500),
@@ -51,8 +51,8 @@ async function readLearningJson(response, limit = 16 * 1024 * 1024, signal) {
51
51
  }
52
52
  }
53
53
  const learningSha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);
54
- const learningUuidSchema = z.string().uuid();
55
- const learningDateTimeSchema = z.string().datetime({ offset: true });
54
+ const learningUuidSchema = z.guid();
55
+ const learningDateTimeSchema = z.iso.datetime({ offset: true });
56
56
  /** One immutable file in a proposed Skill candidate bundle. */
57
57
  const learningSkillBundleFileSchema = z.object({
58
58
  content: z.string(),
@@ -129,7 +129,7 @@ const learningCandidateReviewSchema = z.object({
129
129
  status: z.enum(["approved", "rejected"])
130
130
  });
131
131
  const learningRunSchema = z.object({
132
- id: z.string().uuid(),
132
+ id: z.guid(),
133
133
  learningContainerId: learningContainerIdSchema,
134
134
  projectId: z.number().int().positive(),
135
135
  status: z.enum([
@@ -171,7 +171,7 @@ const learningInsightEvidenceSchema = z.union([z.object({
171
171
  unavailable: unavailableSchema
172
172
  }), z.object({
173
173
  kind: z.literal("trajectory"),
174
- trajectoryId: z.string().uuid(),
174
+ trajectoryId: z.guid(),
175
175
  trajectoryPresent: z.boolean(),
176
176
  eventCount: z.number().int().nonnegative(),
177
177
  events: z.array(z.object({
@@ -185,7 +185,7 @@ const learningInsightEvidenceSchema = z.union([z.object({
185
185
  })]);
186
186
  /** Validates object IDs independently from container IDs; neither may alter the path. */
187
187
  function learningObjectId(id) {
188
- return z.string().uuid().parse(id);
188
+ return z.guid().parse(id);
189
189
  }
190
190
 
191
191
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"learning-management.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/learning-management.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/** Wire contracts for the project-key Learning API; keep aligned with Intelligence. */\nexport const learningContainerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);\nexport const learningContainerSchema = z.object({\n id: learningContainerIdSchema,\n name: z.string().min(1),\n projectId: z.number().int().positive(),\n promptContext: z.string().nullable(),\n createdAt: z.string().datetime({ offset: true }),\n updatedAt: z.string().datetime({ offset: true }),\n});\nexport const learningContainerPageSchema = z.object({\n containers: z.array(learningContainerSchema).max(500),\n nextCursor: z.string().min(1).nullable(),\n});\n/** Explicit wire types preserve required/null fields in declarations emitted with strictNullChecks disabled. */\nexport interface LearningContainer {\n id: string;\n name: string;\n projectId: number;\n promptContext: string | null;\n createdAt: string;\n updatedAt: string;\n}\nexport interface LearningContainerPage {\n containers: LearningContainer[];\n nextCursor: string | null;\n}\nexport interface LearningRequestOptions {\n readonly signal?: AbortSignal;\n}\nexport interface LearningContainerRequest extends LearningRequestOptions {\n readonly containerId: string;\n}\n\n/** Validates a stable identifier before constructing a request path. */\nexport function learningContainerPath(containerId: string): string {\n return `/api/v1/learning/containers/${encodeURIComponent(learningContainerIdSchema.parse(containerId))}`;\n}\n\n/** Reads a bounded JSON response while the request's signal governs stream cancellation. */\nexport async function readLearningJson(\n response: Response,\n limit = 16 * 1024 * 1024,\n signal?: AbortSignal,\n): Promise<unknown> {\n if (!response.body) throw new Error(\"Missing Learning response body\");\n const reader = response.body.getReader();\n const abort = () => {\n void reader.cancel(signal?.reason).catch(() => undefined);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n const decoder = new TextDecoder();\n let text = \"\";\n let bytes = 0;\n try {\n while (true) {\n signal?.throwIfAborted();\n const next = await reader.read();\n signal?.throwIfAborted();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > limit) {\n await reader.cancel();\n throw new Error(\"Learning response exceeds its size limit\");\n }\n text += decoder.decode(next.value, { stream: true });\n }\n return JSON.parse(text + decoder.decode());\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n reader.releaseLock();\n }\n}\n\nconst learningSha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);\nconst learningUuidSchema = z.string().uuid();\nconst learningDateTimeSchema = z.string().datetime({ offset: true });\n\n/** One immutable file in a proposed Skill candidate bundle. */\nexport const learningSkillBundleFileSchema = z.object({\n content: z.string(),\n path: z\n .string()\n .min(1)\n .refine(\n (path) =>\n !path.startsWith(\"/\") &&\n !path.split(\"/\").some((segment) => segment === \"..\"),\n \"Bundle paths must be relative and may not traverse parent directories.\",\n ),\n sha256: learningSha256Schema,\n});\n\n/** Complete Skill files attached to one review candidate. */\nexport const learningSkillBundleSchema = z\n .object({\n files: z.array(learningSkillBundleFileSchema).min(1),\n schemaVersion: z.literal(1),\n })\n\n .superRefine(({ files }, context) => {\n const paths = new Set<string>();\n for (const file of files) {\n if (paths.has(file.path)) {\n context.addIssue({\n code: \"custom\",\n message: `Duplicate bundle path: ${file.path}`,\n path: [\"files\"],\n });\n }\n paths.add(file.path);\n }\n if (!paths.has(\"SKILL.md\")) {\n context.addIssue({\n code: \"custom\",\n message: \"A Skill bundle must contain SKILL.md.\",\n path: [\"files\"],\n });\n }\n });\n\n/** Review state and summary returned for one proposed Skill change. */\nexport const learningCandidateSchema = z.object({\n bundleSha256: learningSha256Schema,\n createdAt: learningDateTimeSchema,\n description: z.string().min(1),\n id: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n reason: z.string().min(1),\n registryBaseRevision: z.number().int().nonnegative(),\n reviewedAt: learningDateTimeSchema.nullable(),\n runId: learningUuidSchema,\n status: z.enum([\"pending_review\", \"approved\", \"rejected\"]),\n subjectSha256: learningSha256Schema,\n targetSkillId: learningUuidSchema.nullable(),\n targetSkillRevision: z.number().int().positive().nullable(),\n title: z.string().min(1),\n});\n\n/** Full proposed Skill change, including evidence and every bundle file. */\nexport const learningCandidateDetailSchema = learningCandidateSchema.extend({\n bundle: learningSkillBundleSchema,\n supportingInsights: z.array(\n z.object({\n alias: z.string().min(1),\n id: learningUuidSchema,\n impact: z.string().min(1),\n statement: z.string().min(1),\n }),\n ),\n});\n\n/** Result returned after a human or agent reviews a Skill candidate. */\nexport const learningCandidateReviewSchema = z.object({\n candidateId: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n status: z.enum([\"approved\", \"rejected\"]),\n});\n\nexport interface LearningCandidate {\n id: string;\n bundleSha256: string;\n createdAt: string;\n description: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n reason: string;\n registryBaseRevision: number;\n reviewedAt: string | null;\n runId: string;\n status: \"pending_review\" | \"approved\" | \"rejected\";\n subjectSha256: string;\n targetSkillId: string | null;\n targetSkillRevision: number | null;\n title: string;\n}\nexport interface LearningCandidateDetail extends LearningCandidate {\n bundle: {\n schemaVersion: 1;\n files: Array<{ path: string; content: string; sha256: string }>;\n };\n supportingInsights: Array<{\n alias: string;\n id: string;\n impact: string;\n statement: string;\n }>;\n}\nexport interface LearningCandidateReview {\n candidateId: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n status: \"approved\" | \"rejected\";\n}\nexport interface LearningCandidateRequest extends LearningContainerRequest {\n readonly candidateId: string;\n}\n\nexport const learningRunSchema = z.object({\n id: z.string().uuid(),\n learningContainerId: learningContainerIdSchema,\n projectId: z.number().int().positive(),\n status: z.enum([\n \"queued\",\n \"freezing\",\n \"batching\",\n \"reducing\",\n \"finalizing\",\n \"succeeded\",\n \"failed\",\n ]),\n triggerSource: z.enum([\"automatic\", \"manual\"]),\n attemptCount: z.number().int().nonnegative(),\n candidateCount: z.number().int().nonnegative().nullable(),\n insightCount: z.number().int().nonnegative().nullable(),\n evidenceThreadCount: z.number().int().nonnegative().nullable().optional(),\n createdAt: learningDateTimeSchema,\n updatedAt: learningDateTimeSchema,\n startedAt: learningDateTimeSchema.nullable(),\n completedAt: learningDateTimeSchema.nullable(),\n failureCode: z.string().nullable(),\n kubernetesJobName: z.string().nullable(),\n});\nexport interface LearningRun {\n id: string;\n learningContainerId: string;\n projectId: number;\n status:\n | \"queued\"\n | \"freezing\"\n | \"batching\"\n | \"reducing\"\n | \"finalizing\"\n | \"succeeded\"\n | \"failed\";\n triggerSource: \"automatic\" | \"manual\";\n attemptCount: number;\n candidateCount: number | null;\n insightCount: number | null;\n evidenceThreadCount?: number | null;\n createdAt: string;\n updatedAt: string;\n startedAt: string | null;\n completedAt: string | null;\n failureCode: string | null;\n kubernetesJobName: string | null;\n}\nconst unavailableSchema = z\n .enum([\"snapshot-missing\", \"snapshot-unreadable\"])\n .nullable();\nexport const learningInsightEvidenceSchema = z.union([\n z.object({\n cited: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n role: z.enum([\"assistant\", \"tool\", \"user\"]),\n }),\n ),\n messageCount: z.number().int().nonnegative(),\n threadId: z.string(),\n threadName: z.string().nullable(),\n threadPresent: z.boolean(),\n unavailable: unavailableSchema,\n }),\n z.object({\n kind: z.literal(\"trajectory\"),\n trajectoryId: z.string().uuid(),\n trajectoryPresent: z.boolean(),\n eventCount: z.number().int().nonnegative(),\n events: z.array(\n z.object({\n seq: z.number().int().nonnegative(),\n name: z.string(),\n offsetMs: z.number(),\n value: z.unknown(),\n eventId: z.string().nullable(),\n }),\n ),\n unavailable: unavailableSchema,\n }),\n]);\nexport type LearningInsightEvidence =\n | {\n cited: Array<{\n id: string;\n content: string;\n role: \"assistant\" | \"tool\" | \"user\";\n }>;\n messageCount: number;\n threadId: string;\n threadName: string | null;\n threadPresent: boolean;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n }\n | {\n kind: \"trajectory\";\n trajectoryId: string;\n trajectoryPresent: boolean;\n eventCount: number;\n events: Array<{\n seq: number;\n name: string;\n offsetMs: number;\n value?: unknown;\n eventId: string | null;\n }>;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n };\n\n/** Validates object IDs independently from container IDs; neither may alter the path. */\nexport function learningObjectId(id: string): string {\n return z.string().uuid().parse(id);\n}\n"],"mappings":";;;;AAGA,MAAa,4BAA4B,EACtC,QAAQ,CACR,IAAI,EAAE,CACN,IAAI,GAAG,CACP,MAAM,6BAA6B;AACtC,MAAa,0BAA0B,EAAE,OAAO;CAC9C,IAAI;CACJ,MAAM,EAAE,QAAQ,CAAC,IAAI,EAAE;CACvB,WAAW,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;CACtC,eAAe,EAAE,QAAQ,CAAC,UAAU;CACpC,WAAW,EAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,MAAM,CAAC;CAChD,WAAW,EAAE,QAAQ,CAAC,SAAS,EAAE,QAAQ,MAAM,CAAC;CACjD,CAAC;AACF,MAAa,8BAA8B,EAAE,OAAO;CAClD,YAAY,EAAE,MAAM,wBAAwB,CAAC,IAAI,IAAI;CACrD,YAAY,EAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,UAAU;CACzC,CAAC;;AAsBF,SAAgB,sBAAsB,aAA6B;AACjE,QAAO,+BAA+B,mBAAmB,0BAA0B,MAAM,YAAY,CAAC;;;AAIxG,eAAsB,iBACpB,UACA,QAAQ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AAE,KAAK;GAAC;GAAa;GAAQ;GAAO,CAAC;EAC5C,CAAC,CACH;CACD,cAAc,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;CAC5C,UAAU,EAAE,QAAQ;CACpB,YAAY,EAAE,QAAQ,CAAC,UAAU;CACjC,eAAe,EAAE,SAAS;CAC1B,aAAa;CACd,CAAC,EACF,EAAE,OAAO;CACP,MAAM,EAAE,QAAQ,aAAa;CAC7B,cAAc,EAAE,QAAQ,CAAC,MAAM;CAC/B,mBAAmB,EAAE,SAAS;CAC9B,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;CAC1C,QAAQ,EAAE,MACR,EAAE,OAAO;EACP,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;EACnC,MAAM,EAAE,QAAQ;EAChB,UAAU,EAAE,QAAQ;EACpB,OAAO,EAAE,SAAS;EAClB,SAAS,EAAE,QAAQ,CAAC,UAAU;EAC/B,CAAC,CACH;CACD,aAAa;CACd,CAAC,CACH,CAAC;;AA8BF,SAAgB,iBAAiB,IAAoB;AACnD,QAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,GAAG"}
1
+ {"version":3,"file":"learning-management.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/learning-management.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/** Wire contracts for the project-key Learning API; keep aligned with Intelligence. */\nexport const learningContainerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);\nexport const learningContainerSchema = z.object({\n id: learningContainerIdSchema,\n name: z.string().min(1),\n projectId: z.number().int().positive(),\n promptContext: z.string().nullable(),\n createdAt: z.iso.datetime({ offset: true }),\n updatedAt: z.iso.datetime({ offset: true }),\n});\nexport const learningContainerPageSchema = z.object({\n containers: z.array(learningContainerSchema).max(500),\n nextCursor: z.string().min(1).nullable(),\n});\n/** Explicit wire types preserve required/null fields in declarations emitted with strictNullChecks disabled. */\nexport interface LearningContainer {\n id: string;\n name: string;\n projectId: number;\n promptContext: string | null;\n createdAt: string;\n updatedAt: string;\n}\nexport interface LearningContainerPage {\n containers: LearningContainer[];\n nextCursor: string | null;\n}\nexport interface LearningRequestOptions {\n readonly signal?: AbortSignal;\n}\nexport interface LearningContainerRequest extends LearningRequestOptions {\n readonly containerId: string;\n}\n\n/** Validates a stable identifier before constructing a request path. */\nexport function learningContainerPath(containerId: string): string {\n return `/api/v1/learning/containers/${encodeURIComponent(learningContainerIdSchema.parse(containerId))}`;\n}\n\n/** Reads a bounded JSON response while the request's signal governs stream cancellation. */\nexport async function readLearningJson(\n response: Response,\n limit = 16 * 1024 * 1024,\n signal?: AbortSignal,\n): Promise<unknown> {\n if (!response.body) throw new Error(\"Missing Learning response body\");\n const reader = response.body.getReader();\n const abort = () => {\n void reader.cancel(signal?.reason).catch(() => undefined);\n };\n signal?.addEventListener(\"abort\", abort, { once: true });\n if (signal?.aborted) abort();\n const decoder = new TextDecoder();\n let text = \"\";\n let bytes = 0;\n try {\n while (true) {\n signal?.throwIfAborted();\n const next = await reader.read();\n signal?.throwIfAborted();\n if (next.done) break;\n bytes += next.value.byteLength;\n if (bytes > limit) {\n await reader.cancel();\n throw new Error(\"Learning response exceeds its size limit\");\n }\n text += decoder.decode(next.value, { stream: true });\n }\n return JSON.parse(text + decoder.decode());\n } finally {\n signal?.removeEventListener(\"abort\", abort);\n reader.releaseLock();\n }\n}\n\nconst learningSha256Schema = z.string().regex(/^[a-f0-9]{64}$/u);\nconst learningUuidSchema = z.guid();\nconst learningDateTimeSchema = z.iso.datetime({ offset: true });\n\n/** One immutable file in a proposed Skill candidate bundle. */\nexport const learningSkillBundleFileSchema = z.object({\n content: z.string(),\n path: z\n .string()\n .min(1)\n .refine(\n (path) =>\n !path.startsWith(\"/\") &&\n !path.split(\"/\").some((segment) => segment === \"..\"),\n \"Bundle paths must be relative and may not traverse parent directories.\",\n ),\n sha256: learningSha256Schema,\n});\n\n/** Complete Skill files attached to one review candidate. */\nexport const learningSkillBundleSchema = z\n .object({\n files: z.array(learningSkillBundleFileSchema).min(1),\n schemaVersion: z.literal(1),\n })\n\n .superRefine(({ files }, context) => {\n const paths = new Set<string>();\n for (const file of files) {\n if (paths.has(file.path)) {\n context.addIssue({\n code: \"custom\",\n message: `Duplicate bundle path: ${file.path}`,\n path: [\"files\"],\n });\n }\n paths.add(file.path);\n }\n if (!paths.has(\"SKILL.md\")) {\n context.addIssue({\n code: \"custom\",\n message: \"A Skill bundle must contain SKILL.md.\",\n path: [\"files\"],\n });\n }\n });\n\n/** Review state and summary returned for one proposed Skill change. */\nexport const learningCandidateSchema = z.object({\n bundleSha256: learningSha256Schema,\n createdAt: learningDateTimeSchema,\n description: z.string().min(1),\n id: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n reason: z.string().min(1),\n registryBaseRevision: z.number().int().nonnegative(),\n reviewedAt: learningDateTimeSchema.nullable(),\n runId: learningUuidSchema,\n status: z.enum([\"pending_review\", \"approved\", \"rejected\"]),\n subjectSha256: learningSha256Schema,\n targetSkillId: learningUuidSchema.nullable(),\n targetSkillRevision: z.number().int().positive().nullable(),\n title: z.string().min(1),\n});\n\n/** Full proposed Skill change, including evidence and every bundle file. */\nexport const learningCandidateDetailSchema = learningCandidateSchema.extend({\n bundle: learningSkillBundleSchema,\n supportingInsights: z.array(\n z.object({\n alias: z.string().min(1),\n id: learningUuidSchema,\n impact: z.string().min(1),\n statement: z.string().min(1),\n }),\n ),\n});\n\n/** Result returned after a human or agent reviews a Skill candidate. */\nexport const learningCandidateReviewSchema = z.object({\n candidateId: learningUuidSchema,\n operation: z.enum([\"add\", \"update\", \"remove\"]),\n publishedRegistryRevision: z.number().int().positive().nullable(),\n publishedSkillId: learningUuidSchema.nullable(),\n status: z.enum([\"approved\", \"rejected\"]),\n});\n\nexport interface LearningCandidate {\n id: string;\n bundleSha256: string;\n createdAt: string;\n description: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n reason: string;\n registryBaseRevision: number;\n reviewedAt: string | null;\n runId: string;\n status: \"pending_review\" | \"approved\" | \"rejected\";\n subjectSha256: string;\n targetSkillId: string | null;\n targetSkillRevision: number | null;\n title: string;\n}\nexport interface LearningCandidateDetail extends LearningCandidate {\n bundle: {\n schemaVersion: 1;\n files: Array<{ path: string; content: string; sha256: string }>;\n };\n supportingInsights: Array<{\n alias: string;\n id: string;\n impact: string;\n statement: string;\n }>;\n}\nexport interface LearningCandidateReview {\n candidateId: string;\n operation: \"add\" | \"update\" | \"remove\";\n publishedRegistryRevision: number | null;\n publishedSkillId: string | null;\n status: \"approved\" | \"rejected\";\n}\nexport interface LearningCandidateRequest extends LearningContainerRequest {\n readonly candidateId: string;\n}\n\nexport const learningRunSchema = z.object({\n id: z.guid(),\n learningContainerId: learningContainerIdSchema,\n projectId: z.number().int().positive(),\n status: z.enum([\n \"queued\",\n \"freezing\",\n \"batching\",\n \"reducing\",\n \"finalizing\",\n \"succeeded\",\n \"failed\",\n ]),\n triggerSource: z.enum([\"automatic\", \"manual\"]),\n attemptCount: z.number().int().nonnegative(),\n candidateCount: z.number().int().nonnegative().nullable(),\n insightCount: z.number().int().nonnegative().nullable(),\n evidenceThreadCount: z.number().int().nonnegative().nullable().optional(),\n createdAt: learningDateTimeSchema,\n updatedAt: learningDateTimeSchema,\n startedAt: learningDateTimeSchema.nullable(),\n completedAt: learningDateTimeSchema.nullable(),\n failureCode: z.string().nullable(),\n kubernetesJobName: z.string().nullable(),\n});\nexport interface LearningRun {\n id: string;\n learningContainerId: string;\n projectId: number;\n status:\n | \"queued\"\n | \"freezing\"\n | \"batching\"\n | \"reducing\"\n | \"finalizing\"\n | \"succeeded\"\n | \"failed\";\n triggerSource: \"automatic\" | \"manual\";\n attemptCount: number;\n candidateCount: number | null;\n insightCount: number | null;\n evidenceThreadCount?: number | null;\n createdAt: string;\n updatedAt: string;\n startedAt: string | null;\n completedAt: string | null;\n failureCode: string | null;\n kubernetesJobName: string | null;\n}\nconst unavailableSchema = z\n .enum([\"snapshot-missing\", \"snapshot-unreadable\"])\n .nullable();\nexport const learningInsightEvidenceSchema = z.union([\n z.object({\n cited: z.array(\n z.object({\n id: z.string(),\n content: z.string(),\n role: z.enum([\"assistant\", \"tool\", \"user\"]),\n }),\n ),\n messageCount: z.number().int().nonnegative(),\n threadId: z.string(),\n threadName: z.string().nullable(),\n threadPresent: z.boolean(),\n unavailable: unavailableSchema,\n }),\n z.object({\n kind: z.literal(\"trajectory\"),\n trajectoryId: z.guid(),\n trajectoryPresent: z.boolean(),\n eventCount: z.number().int().nonnegative(),\n events: z.array(\n z.object({\n seq: z.number().int().nonnegative(),\n name: z.string(),\n offsetMs: z.number(),\n value: z.unknown(),\n eventId: z.string().nullable(),\n }),\n ),\n unavailable: unavailableSchema,\n }),\n]);\nexport type LearningInsightEvidence =\n | {\n cited: Array<{\n id: string;\n content: string;\n role: \"assistant\" | \"tool\" | \"user\";\n }>;\n messageCount: number;\n threadId: string;\n threadName: string | null;\n threadPresent: boolean;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n }\n | {\n kind: \"trajectory\";\n trajectoryId: string;\n trajectoryPresent: boolean;\n eventCount: number;\n events: Array<{\n seq: number;\n name: string;\n offsetMs: number;\n value?: unknown;\n eventId: string | null;\n }>;\n unavailable: \"snapshot-missing\" | \"snapshot-unreadable\" | null;\n };\n\n/** Validates object IDs independently from container IDs; neither may alter the path. */\nexport function learningObjectId(id: string): string {\n return z.guid().parse(id);\n}\n"],"mappings":";;;;AAGA,MAAa,4BAA4B,EACtC,QAAQ,CACR,IAAI,EAAE,CACN,IAAI,GAAG,CACP,MAAM,6BAA6B;AACtC,MAAa,0BAA0B,EAAE,OAAO;CAC9C,IAAI;CACJ,MAAM,EAAE,QAAQ,CAAC,IAAI,EAAE;CACvB,WAAW,EAAE,QAAQ,CA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