@copilotkit/runtime 1.73.0 → 1.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/agent/index.cjs +1 -1
  2. package/dist/agent/index.d.mts +1 -1
  3. package/dist/agent/index.mjs +1 -1
  4. package/dist/lib/integrations/nextjs/app-router.cjs +1 -1
  5. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  6. package/dist/lib/integrations/nextjs/app-router.mjs +1 -1
  7. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  8. package/dist/lib/integrations/node-http/index.cjs +1 -1
  9. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  10. package/dist/lib/integrations/node-http/index.mjs +1 -1
  11. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  12. package/dist/lib/runtime/copilot-runtime.cjs +79 -37
  13. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  14. package/dist/lib/runtime/copilot-runtime.d.cts +52 -2
  15. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  16. package/dist/lib/runtime/copilot-runtime.d.mts +54 -4
  17. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  18. package/dist/lib/runtime/copilot-runtime.mjs +79 -37
  19. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  20. package/dist/lib/runtime/mcp-client-cache.cjs +135 -0
  21. package/dist/lib/runtime/mcp-client-cache.cjs.map +1 -0
  22. package/dist/lib/runtime/mcp-client-cache.mjs +132 -0
  23. package/dist/lib/runtime/mcp-client-cache.mjs.map +1 -0
  24. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  25. package/dist/lib/runtime/telemetry-agent-runner.d.cts +1 -1
  26. package/dist/lib/runtime/telemetry-agent-runner.d.mts +1 -1
  27. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  28. package/dist/package.cjs +7 -5
  29. package/dist/package.mjs +7 -5
  30. package/dist/v2/index.cjs +3 -3
  31. package/dist/v2/index.d.cts +7 -7
  32. package/dist/v2/index.d.mts +7 -7
  33. package/dist/v2/index.mjs +4 -4
  34. package/dist/v2/runtime/core/channel-manager.cjs +1 -1
  35. package/dist/v2/runtime/core/channel-manager.mjs +1 -1
  36. package/dist/v2/runtime/core/fetch-handler.cjs +1 -0
  37. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  38. package/dist/v2/runtime/core/fetch-handler.d.cts +2 -2
  39. package/dist/v2/runtime/core/fetch-handler.d.mts +2 -2
  40. package/dist/v2/runtime/core/fetch-handler.mjs +1 -0
  41. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  42. package/dist/v2/runtime/endpoints/express-single.cjs.map +1 -1
  43. package/dist/v2/runtime/endpoints/express-single.d.cts +2 -2
  44. package/dist/v2/runtime/endpoints/express-single.d.cts.map +1 -1
  45. package/dist/v2/runtime/endpoints/express-single.d.mts +2 -2
  46. package/dist/v2/runtime/endpoints/express-single.d.mts.map +1 -1
  47. package/dist/v2/runtime/endpoints/express-single.mjs.map +1 -1
  48. package/dist/v2/runtime/endpoints/express.cjs +2 -3
  49. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  50. package/dist/v2/runtime/endpoints/express.d.cts +26 -7
  51. package/dist/v2/runtime/endpoints/express.d.cts.map +1 -1
  52. package/dist/v2/runtime/endpoints/express.d.mts +26 -7
  53. package/dist/v2/runtime/endpoints/express.d.mts.map +1 -1
  54. package/dist/v2/runtime/endpoints/express.mjs +2 -2
  55. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  56. package/dist/v2/runtime/endpoints/hono.d.cts +2 -2
  57. package/dist/v2/runtime/endpoints/hono.d.mts +2 -2
  58. package/dist/v2/runtime/endpoints/index.d.cts +3 -3
  59. package/dist/v2/runtime/endpoints/index.d.mts +3 -3
  60. package/dist/v2/runtime/endpoints/load-express.cjs +36 -0
  61. package/dist/v2/runtime/endpoints/load-express.cjs.map +1 -0
  62. package/dist/v2/runtime/endpoints/load-express.mjs +35 -0
  63. package/dist/v2/runtime/endpoints/load-express.mjs.map +1 -0
  64. package/dist/v2/runtime/handlers/handle-stop.cjs +18 -14
  65. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  66. package/dist/v2/runtime/handlers/handle-stop.mjs +18 -14
  67. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  68. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -4
  69. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  70. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +1 -2
  71. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  72. package/dist/v2/runtime/index.d.cts +7 -7
  73. package/dist/v2/runtime/index.d.mts +7 -7
  74. package/dist/v2/runtime/intelligence-platform/client.cjs +1 -1
  75. package/dist/v2/runtime/intelligence-platform/client.mjs +1 -1
  76. package/package.json +10 -6
  77. package/dist/v2/runtime/open-generative-ui-middleware.cjs +0 -286
  78. package/dist/v2/runtime/open-generative-ui-middleware.cjs.map +0 -1
  79. package/dist/v2/runtime/open-generative-ui-middleware.mjs +0 -284
  80. package/dist/v2/runtime/open-generative-ui-middleware.mjs.map +0 -1
@@ -0,0 +1,36 @@
1
+ require("reflect-metadata");
2
+ const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
+ let node_module = require("node:module");
4
+
5
+ //#region src/v2/runtime/endpoints/load-express.ts
6
+ /**
7
+ * Load `express` at call time rather than at module load time.
8
+ *
9
+ * `express` is an OPTIONAL peer: an app that mounts the Hono or Node adapter
10
+ * never installs it. The Express adapter is re-exported from the
11
+ * `@copilotkit/runtime/v2` barrel, so a static `import express from "express"`
12
+ * there would make that barrel unimportable for every consumer who does not use
13
+ * Express. Loading it inside the factory keeps the barrel free of Express and
14
+ * moves the failure to the only place it is a real failure: calling an Express
15
+ * factory without Express installed.
16
+ *
17
+ * This lives in its own module, and not beside the factory, for two reasons: it
18
+ * is not part of the published surface (the endpoints barrel does not re-export
19
+ * it), and a test can reach it directly and inject `requireFrom`.
20
+ *
21
+ * `scripts/validate-optional-peer-entries.ts` is what keeps the loading lazy: it
22
+ * fails if any entry point reaches an optional peer at module-initialization
23
+ * time, in either published format.
24
+ */
25
+ function loadExpress(requireFrom = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href)) {
26
+ try {
27
+ requireFrom.resolve("express");
28
+ } catch (cause) {
29
+ throw new Error("@copilotkit/runtime: the Express adapter requires `express`, which is an optional peer dependency and is not installed. Install it with `npm install express` (^4.18.0 || ^5.0.0), or mount the Hono adapter from `@copilotkit/runtime/v2/hono` instead.", { cause });
30
+ }
31
+ return requireFrom("express");
32
+ }
33
+
34
+ //#endregion
35
+ exports.loadExpress = loadExpress;
36
+ //# sourceMappingURL=load-express.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-express.cjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/load-express.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\n/**\n * How `loadExpress` reaches the module system. `createRequire(...)` returns\n * exactly this shape; a test can pass its own.\n */\nexport interface RequireLike {\n (specifier: string): any;\n resolve(specifier: string): string;\n}\n\n/**\n * Load `express` at call time rather than at module load time.\n *\n * `express` is an OPTIONAL peer: an app that mounts the Hono or Node adapter\n * never installs it. The Express adapter is re-exported from the\n * `@copilotkit/runtime/v2` barrel, so a static `import express from \"express\"`\n * there would make that barrel unimportable for every consumer who does not use\n * Express. Loading it inside the factory keeps the barrel free of Express and\n * moves the failure to the only place it is a real failure: calling an Express\n * factory without Express installed.\n *\n * This lives in its own module, and not beside the factory, for two reasons: it\n * is not part of the published surface (the endpoints barrel does not re-export\n * it), and a test can reach it directly and inject `requireFrom`.\n *\n * `scripts/validate-optional-peer-entries.ts` is what keeps the loading lazy: it\n * fails if any entry point reaches an optional peer at module-initialization\n * time, in either published format.\n */\nexport function loadExpress(\n requireFrom: RequireLike = createRequire(import.meta.url) as RequireLike,\n): { Router: () => any } {\n // Resolve and evaluate in two steps, so that only a RESOLUTION failure is\n // reported as \"not installed\". Wrapping the whole load would also catch\n // express throwing while it evaluates -- a broken transitive dependency, a\n // failed native binding, a syntax error in a patched copy -- and would send\n // the reader off to install a package they already have. Those errors must\n // surface as themselves.\n try {\n requireFrom.resolve(\"express\");\n } catch (cause) {\n throw new Error(\n \"@copilotkit/runtime: the Express adapter requires `express`, which is an \" +\n \"optional peer dependency and is not installed. Install it with \" +\n \"`npm install express` (^4.18.0 || ^5.0.0), or mount the Hono adapter \" +\n \"from `@copilotkit/runtime/v2/hono` instead.\",\n { cause },\n );\n }\n\n return requireFrom(\"express\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,YACd,2FAAyD,EAClC;AAOvB,KAAI;AACF,cAAY,QAAQ,UAAU;UACvB,OAAO;AACd,QAAM,IAAI,MACR,4PAIA,EAAE,OAAO,CACV;;AAGH,QAAO,YAAY,UAAU"}
@@ -0,0 +1,35 @@
1
+ import "reflect-metadata";
2
+ import { createRequire } from "node:module";
3
+
4
+ //#region src/v2/runtime/endpoints/load-express.ts
5
+ /**
6
+ * Load `express` at call time rather than at module load time.
7
+ *
8
+ * `express` is an OPTIONAL peer: an app that mounts the Hono or Node adapter
9
+ * never installs it. The Express adapter is re-exported from the
10
+ * `@copilotkit/runtime/v2` barrel, so a static `import express from "express"`
11
+ * there would make that barrel unimportable for every consumer who does not use
12
+ * Express. Loading it inside the factory keeps the barrel free of Express and
13
+ * moves the failure to the only place it is a real failure: calling an Express
14
+ * factory without Express installed.
15
+ *
16
+ * This lives in its own module, and not beside the factory, for two reasons: it
17
+ * is not part of the published surface (the endpoints barrel does not re-export
18
+ * it), and a test can reach it directly and inject `requireFrom`.
19
+ *
20
+ * `scripts/validate-optional-peer-entries.ts` is what keeps the loading lazy: it
21
+ * fails if any entry point reaches an optional peer at module-initialization
22
+ * time, in either published format.
23
+ */
24
+ function loadExpress(requireFrom = createRequire(import.meta.url)) {
25
+ try {
26
+ requireFrom.resolve("express");
27
+ } catch (cause) {
28
+ throw new Error("@copilotkit/runtime: the Express adapter requires `express`, which is an optional peer dependency and is not installed. Install it with `npm install express` (^4.18.0 || ^5.0.0), or mount the Hono adapter from `@copilotkit/runtime/v2/hono` instead.", { cause });
29
+ }
30
+ return requireFrom("express");
31
+ }
32
+
33
+ //#endregion
34
+ export { loadExpress };
35
+ //# sourceMappingURL=load-express.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-express.mjs","names":[],"sources":["../../../../src/v2/runtime/endpoints/load-express.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\n\n/**\n * How `loadExpress` reaches the module system. `createRequire(...)` returns\n * exactly this shape; a test can pass its own.\n */\nexport interface RequireLike {\n (specifier: string): any;\n resolve(specifier: string): string;\n}\n\n/**\n * Load `express` at call time rather than at module load time.\n *\n * `express` is an OPTIONAL peer: an app that mounts the Hono or Node adapter\n * never installs it. The Express adapter is re-exported from the\n * `@copilotkit/runtime/v2` barrel, so a static `import express from \"express\"`\n * there would make that barrel unimportable for every consumer who does not use\n * Express. Loading it inside the factory keeps the barrel free of Express and\n * moves the failure to the only place it is a real failure: calling an Express\n * factory without Express installed.\n *\n * This lives in its own module, and not beside the factory, for two reasons: it\n * is not part of the published surface (the endpoints barrel does not re-export\n * it), and a test can reach it directly and inject `requireFrom`.\n *\n * `scripts/validate-optional-peer-entries.ts` is what keeps the loading lazy: it\n * fails if any entry point reaches an optional peer at module-initialization\n * time, in either published format.\n */\nexport function loadExpress(\n requireFrom: RequireLike = createRequire(import.meta.url) as RequireLike,\n): { Router: () => any } {\n // Resolve and evaluate in two steps, so that only a RESOLUTION failure is\n // reported as \"not installed\". Wrapping the whole load would also catch\n // express throwing while it evaluates -- a broken transitive dependency, a\n // failed native binding, a syntax error in a patched copy -- and would send\n // the reader off to install a package they already have. Those errors must\n // surface as themselves.\n try {\n requireFrom.resolve(\"express\");\n } catch (cause) {\n throw new Error(\n \"@copilotkit/runtime: the Express adapter requires `express`, which is an \" +\n \"optional peer dependency and is not installed. Install it with \" +\n \"`npm install express` (^4.18.0 || ^5.0.0), or mount the Hono adapter \" +\n \"from `@copilotkit/runtime/v2/hono` instead.\",\n { cause },\n );\n }\n\n return requireFrom(\"express\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,YACd,cAA2B,cAAc,OAAO,KAAK,IAAI,EAClC;AAOvB,KAAI;AACF,cAAY,QAAQ,UAAU;UACvB,OAAO;AACd,QAAM,IAAI,MACR,4PAIA,EAAE,OAAO,CACV;;AAGH,QAAO,YAAY,UAAU"}
@@ -7,29 +7,33 @@ const require_resolve_intelligence_user = require('./shared/resolve-intelligence
7
7
  let _ag_ui_client = require("@ag-ui/client");
8
8
 
9
9
  //#region src/v2/runtime/handlers/handle-stop.ts
10
+ /** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */
11
+ async function parseStopScope(request) {
12
+ try {
13
+ const raw = await request.text();
14
+ const body = raw.trim() ? JSON.parse(raw) : {};
15
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return Response.json({ error: "Invalid stop request" }, { status: 400 });
16
+ if (Object.keys(body).some((key) => key !== "runId")) return Response.json({ error: "Invalid stop request" }, { status: 400 });
17
+ if (!("runId" in body)) return {};
18
+ if (typeof body.runId !== "string" || !body.runId.trim()) return Response.json({ error: "Invalid runId" }, { status: 400 });
19
+ return { runId: body.runId };
20
+ } catch {
21
+ return Response.json({ error: "Invalid stop request" }, { status: 400 });
22
+ }
23
+ }
10
24
  /** Stop an active run after applying the runtime's application identity policy. */
11
25
  async function handleStopAgent({ runtime, request, agentId, threadId }) {
12
26
  try {
27
+ const scope = await parseStopScope(request.clone());
28
+ if (require_json_response.isHandlerResponse(scope)) return scope;
29
+ const { runId } = scope;
13
30
  let stopThreadId = threadId;
14
- let runId;
15
31
  if (require_runtime$1.isIntelligenceRuntime(runtime)) {
16
- const bodyRequest = request.clone();
17
32
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
18
33
  runtime,
19
34
  request
20
35
  });
21
36
  if (require_json_response.isHandlerResponse(user)) return user;
22
- try {
23
- const raw = await bodyRequest.text();
24
- const body = raw.trim() ? JSON.parse(raw) : {};
25
- if (typeof body !== "object" || body === null || Array.isArray(body)) return Response.json({ error: "Invalid stop request" }, { status: 400 });
26
- if ("runId" in body) {
27
- if (typeof body.runId !== "string" || !body.runId.trim()) return Response.json({ error: "Invalid runId" }, { status: 400 });
28
- runId = body.runId;
29
- }
30
- } catch {
31
- return Response.json({ error: "Invalid stop request" }, { status: 400 });
32
- }
33
37
  try {
34
38
  const thread = await runtime.intelligence.getThread({
35
39
  threadId,
@@ -55,7 +59,7 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
55
59
  ...runId === void 0 ? {} : { runId }
56
60
  })) return new Response(JSON.stringify({
57
61
  stopped: false,
58
- message: `No active run for thread '${threadId}'.`
62
+ message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
59
63
  }), {
60
64
  status: 200,
61
65
  headers: { "Content-Type": "application/json" }
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.cjs","names":["isIntelligenceRuntime","resolveIntelligenceUser","isHandlerResponse","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n let stopThreadId = threadId;\n let runId: string | undefined;\n if (isIntelligenceRuntime(runtime)) {\n const bodyRequest = request.clone();\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const raw = await bodyRequest.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json(\n { error: \"Invalid stop request\" },\n { status: 400 },\n );\n }\n if (\"runId\" in body) {\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n runId = body.runId;\n }\n } catch {\n return Response.json(\n { error: \"Invalid stop request\" },\n { status: 400 },\n );\n }\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\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 const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message: `No active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAeA,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EACF,IAAI,eAAe;EACnB,IAAI;AACJ,MAAIA,wCAAsB,QAAQ,EAAE;GAClC,MAAM,cAAc,QAAQ,OAAO;GACnC,MAAM,OAAO,MAAMC,0DAAwB;IAAE;IAAS;IAAS,CAAC;AAChE,OAAIC,wCAAkB,KAAK,CAAE,QAAO;AACpC,OAAI;IACF,MAAM,MAAM,MAAM,YAAY,MAAM;IACpC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,QAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAI,WAAW,MAAM;AACnB,SAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,aAAQ,KAAK;;WAET;AACN,WAAO,SAAS,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,KAAK,CAChB;;AAEH,OAAI;IACF,MAAM,SAAS,MAAM,QAAQ,aAAa,UAAU;KAClD;KACA,QAAQ,KAAK;KACd,CAAC;AACF,QAAI,CAAC,UAAU,OAAO,OAAO,OAAO,YAAY,CAAC,OAAO,GAAG,MAAM,CAC/D,QAAO,SAAS,KACd,E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elligenceRuntime","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n if (isIntelligenceRuntime(runtime)) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\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 const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAeA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG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,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,KAAK,CAChB;AAEH,mBAAe,OAAO;YACf,OAAO;IACd,MAAM,SAASG,kDAAuB,MAAM;AAC5C,WAAO,SAAS,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,UAAU,UAAU,OAAO,SAAS,MAAM,SAAS,KAAK,CACnE;;;AAKL,MAAI,EAFW,MAAMC,gCAAc,QAAQ,QAAQ,QAAQ,EAE/C,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAQH,MAAI,CALY,MAAM,QAAQ,OAAO,KAAK;GACxC,UAAU;GACV,GAAI,UAAU,SAAY,EAAE,GAAG,EAAE,OAAO;GACzC,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -6,29 +6,33 @@ import { resolveIntelligenceUser } from "./shared/resolve-intelligence-user.mjs"
6
6
  import { EventType } from "@ag-ui/client";
7
7
 
8
8
  //#region src/v2/runtime/handlers/handle-stop.ts
9
+ /** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */
10
+ async function parseStopScope(request) {
11
+ try {
12
+ const raw = await request.text();
13
+ const body = raw.trim() ? JSON.parse(raw) : {};
14
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return Response.json({ error: "Invalid stop request" }, { status: 400 });
15
+ if (Object.keys(body).some((key) => key !== "runId")) return Response.json({ error: "Invalid stop request" }, { status: 400 });
16
+ if (!("runId" in body)) return {};
17
+ if (typeof body.runId !== "string" || !body.runId.trim()) return Response.json({ error: "Invalid runId" }, { status: 400 });
18
+ return { runId: body.runId };
19
+ } catch {
20
+ return Response.json({ error: "Invalid stop request" }, { status: 400 });
21
+ }
22
+ }
9
23
  /** Stop an active run after applying the runtime's application identity policy. */
10
24
  async function handleStopAgent({ runtime, request, agentId, threadId }) {
11
25
  try {
26
+ const scope = await parseStopScope(request.clone());
27
+ if (isHandlerResponse(scope)) return scope;
28
+ const { runId } = scope;
12
29
  let stopThreadId = threadId;
13
- let runId;
14
30
  if (isIntelligenceRuntime(runtime)) {
15
- const bodyRequest = request.clone();
16
31
  const user = await resolveIntelligenceUser({
17
32
  runtime,
18
33
  request
19
34
  });
20
35
  if (isHandlerResponse(user)) return user;
21
- try {
22
- const raw = await bodyRequest.text();
23
- const body = raw.trim() ? JSON.parse(raw) : {};
24
- if (typeof body !== "object" || body === null || Array.isArray(body)) return Response.json({ error: "Invalid stop request" }, { status: 400 });
25
- if ("runId" in body) {
26
- if (typeof body.runId !== "string" || !body.runId.trim()) return Response.json({ error: "Invalid runId" }, { status: 400 });
27
- runId = body.runId;
28
- }
29
- } catch {
30
- return Response.json({ error: "Invalid stop request" }, { status: 400 });
31
- }
32
36
  try {
33
37
  const thread = await runtime.intelligence.getThread({
34
38
  threadId,
@@ -54,7 +58,7 @@ async function handleStopAgent({ runtime, request, agentId, threadId }) {
54
58
  ...runId === void 0 ? {} : { runId }
55
59
  })) return new Response(JSON.stringify({
56
60
  stopped: false,
57
- message: `No active run for thread '${threadId}'.`
61
+ message: runId === void 0 ? `No active run for thread '${threadId}'.` : `Run '${runId}' is not the active run for thread '${threadId}'.`
58
62
  }), {
59
63
  status: 200,
60
64
  headers: { "Content-Type": "application/json" }
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n let stopThreadId = threadId;\n let runId: string | undefined;\n if (isIntelligenceRuntime(runtime)) {\n const bodyRequest = request.clone();\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const raw = await bodyRequest.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json(\n { error: \"Invalid stop request\" },\n { status: 400 },\n );\n }\n if (\"runId\" in body) {\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n runId = body.runId;\n }\n } catch {\n return Response.json(\n { error: \"Invalid stop request\" },\n { status: 400 },\n );\n }\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\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 const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message: `No active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAeA,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EACF,IAAI,eAAe;EACnB,IAAI;AACJ,MAAI,sBAAsB,QAAQ,EAAE;GAClC,MAAM,cAAc,QAAQ,OAAO;GACnC,MAAM,OAAO,MAAM,wBAAwB;IAAE;IAAS;IAAS,CAAC;AAChE,OAAI,kBAAkB,KAAK,CAAE,QAAO;AACpC,OAAI;IACF,MAAM,MAAM,MAAM,YAAY,MAAM;IACpC,MAAM,OAAgB,IAAI,MAAM,GAAG,KA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,EAAE,GAAG,EAAE,OAAO;GACzC,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SAAS,6BAA6B,SAAS;GAChD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-stop.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n if (isIntelligenceRuntime(runtime)) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\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 const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAeA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,OAAO;SACtB;AACN,SAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;;;;AAK5E,eAAsB,gBAAgB,EACpC,SACA,SACA,SACA,YACyC;AACzC,KAAI;EAIF,MAAM,QAAQ,MA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AS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAM,UAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -3,7 +3,6 @@ const require_runtime = require('../../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_header_utils = require('../header-utils.cjs');
4
4
  const require_runtime$1 = require('../../core/runtime.cjs');
5
5
  const require_client = require('../../intelligence-platform/client.cjs');
6
- const require_open_generative_ui_middleware = require('../../open-generative-ui-middleware.cjs');
7
6
  const require_mcp_apps_servers = require('./mcp-apps-servers.cjs');
8
7
  const require_json_response = require('./json-response.cjs');
9
8
  const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
@@ -11,7 +10,7 @@ const require_memory_policy = require('./memory-policy.cjs');
11
10
  let _copilotkit_shared = require("@copilotkit/shared");
12
11
  let _ag_ui_client = require("@ag-ui/client");
13
12
  let _ag_ui_mcp_middleware = require("@ag-ui/mcp-middleware");
14
- let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
13
+ let _copilotkit_shared_event_transforms = require("@copilotkit/shared/event-transforms");
15
14
  let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
16
15
 
17
16
  //#region src/v2/runtime/handlers/shared/agent-utils.ts
@@ -48,7 +47,7 @@ function configureAgentForRequest(params) {
48
47
  const a2uiEnabledByCatalog = !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;
49
48
  if (require_runtime$1.isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {
50
49
  const { agents: targetAgents, enabled: _enabled, injectA2UITool, ...a2uiOptions } = runtime.a2ui ?? {};
51
- if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _ag_ui_a2ui_middleware.A2UIMiddleware({
50
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _copilotkit_shared_event_transforms.A2UIMiddleware({
52
51
  ...a2uiOptions,
53
52
  injectA2UITool: injectA2UITool ?? (providerA2UIHasCatalog ? true : void 0)
54
53
  }));
@@ -66,7 +65,7 @@ function configureAgentForRequest(params) {
66
65
  if (runtime.openGenerativeUI) {
67
66
  const config = runtime.openGenerativeUI;
68
67
  const targetAgents = typeof config === "object" ? config.agents : void 0;
69
- if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new require_open_generative_ui_middleware.OpenGenerativeUIMiddleware());
68
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _copilotkit_shared_event_transforms.OpenGenerativeUIMiddleware());
70
69
  }
71
70
  agent.headers = require_header_utils.mergeForwardableHeaders(agent.headers, request, runtime.forwardHeadersPolicy ?? require_header_utils.resolveForwardHeadersPolicy(void 0));
72
71
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","isIntelligenceRuntime","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","errorResponse","resolveIntelligenceUser","resolveWebMemory","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,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,QAchC;CACP,MAAM,EACJ,SACA,SACA,SACA,wBACA,sBACE;CACJ,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ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AO,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","mergeForwardableHeaders","resolveForwardHeadersPolicy","errorResponse","resolveIntelligenceUser","resolveWebMemory","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport {\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 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 { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,QAchC;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,mDAAe;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,MAAM,aAAaD,+CA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AAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,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,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -2,7 +2,6 @@ import "reflect-metadata";
2
2
  import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "../header-utils.mjs";
3
3
  import { isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "../../core/runtime.mjs";
4
4
  import { INTELLIGENCE_MEMORY_GRANT_HEADER, INTELLIGENCE_USER_ID_HEADER } from "../../intelligence-platform/client.mjs";
5
- import { OpenGenerativeUIMiddleware } from "../../open-generative-ui-middleware.mjs";
6
5
  import { resolveMcpAppsServers } from "./mcp-apps-servers.mjs";
7
6
  import { errorResponse } from "./json-response.mjs";
8
7
  import { resolveIntelligenceUser } from "./resolve-intelligence-user.mjs";
@@ -10,7 +9,7 @@ import { resolveWebMemory } from "./memory-policy.mjs";
10
9
  import { logger } from "@copilotkit/shared";
11
10
  import { RunAgentInputSchema } from "@ag-ui/client";
12
11
  import { MCPMiddleware } from "@ag-ui/mcp-middleware";
13
- import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
12
+ import { A2UIMiddleware, OpenGenerativeUIMiddleware } from "@copilotkit/shared/event-transforms";
14
13
  import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
15
14
 
16
15
  //#region src/v2/runtime/handlers/shared/agent-utils.ts
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instance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ACtC,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,oBAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport {\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 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 { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAchC;CACP,MAAM,EACJ,SACA,SACA,SACA,wBACA,sBACE;CACJ,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAI,cAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAI,eAAe;GACjB,GAAG;GAIH,gBACE,mBAAmB,yBAAyB,OAAO;GACtD,CAAC,CACH;;AAIL,KAAI,sBAAsB,QAAQ,IAAI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ACN,KAAK,GAAG,QAAQ,aAAa,YAAY,CAAC;EAC1C,UAAU;EACV,SAAS;GACP,eAAe,UAAU,QAAQ,aAAa,YAAY;IACzD,8BAA8B,WAAW;GAC1C,GAAI,QAAQ,SACR,GACG,mCAAmC,KAAK,UACvC,OAAO,MACR,EACF,GACD,EAAE;GACP;EACF,CACF,CAAC,CACH;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAO,oBAAoB,MAAM,YAAY;UACtC,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,oBAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -6,17 +6,17 @@ import "./intelligence-platform/index.cjs";
6
6
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
7
7
  import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.cjs";
8
8
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
9
- import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
10
- import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
9
+ import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
10
+ import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
11
+ import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.cjs";
11
12
  import { ChannelStatus, ChannelsControl } from "./core/channel-manager.cjs";
12
- import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.cjs";
13
- import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.cjs";
13
+ import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
14
14
  import { CopilotExpressEndpointParams, CopilotExpressRouter, createCopilotExpressHandler } from "./endpoints/express.cjs";
15
15
  import { createCopilotEndpointSingleRouteExpress } from "./endpoints/express-single.cjs";
16
+ import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
17
+ import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.cjs";
18
+ import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.cjs";
16
19
  import "./endpoints/index.cjs";
17
- import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
18
- import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
19
- import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.cjs";
20
20
  import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.cjs";
21
21
  import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
22
22
 
@@ -6,17 +6,17 @@ import "./intelligence-platform/index.mjs";
6
6
  import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
7
7
  import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, LearningContainerSelectorInput } from "./core/learning.mjs";
8
8
  import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
9
- import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
10
- import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
9
+ import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
10
+ import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
11
+ import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.mjs";
11
12
  import { ChannelStatus, ChannelsControl } from "./core/channel-manager.mjs";
12
- import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.mjs";
13
- import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.mjs";
13
+ import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
14
14
  import { CopilotExpressEndpointParams, CopilotExpressRouter, createCopilotExpressHandler } from "./endpoints/express.mjs";
15
15
  import { createCopilotEndpointSingleRouteExpress } from "./endpoints/express-single.mjs";
16
+ import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
17
+ import { CopilotEndpointCorsConfig, CopilotHonoApp, createCopilotEndpoint, createCopilotHonoHandler, toFetchCorsConfig } from "./endpoints/hono.mjs";
18
+ import { createCopilotEndpointSingleRoute } from "./endpoints/hono-single.mjs";
16
19
  import "./endpoints/index.mjs";
17
- import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
18
- import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
19
- import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.mjs";
20
20
  import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.mjs";
21
21
  import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
22
22
 
@@ -2,8 +2,8 @@ require("reflect-metadata");
2
2
  const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
3
3
  const require_learned_skills = require('./learned-skills.cjs');
4
4
  let _copilotkit_shared = require("@copilotkit/shared");
5
- let crypto = require("crypto");
6
5
  let zod = require("zod");
6
+ let crypto = require("crypto");
7
7
 
8
8
  //#region src/v2/runtime/intelligence-platform/client.ts
9
9
  /** Let a confirmed HTTP denial survive an error body that never completes. */
@@ -1,8 +1,8 @@
1
1
  import "reflect-metadata";
2
2
  import { LearnedSkillsError, learnedSkillsResponseError } from "./learned-skills.mjs";
3
3
  import { logger, parseInspectorLearningSnapshotV1, parseInspectorMetadataV1 } from "@copilotkit/shared";
4
- import { randomUUID as randomUUID$1 } from "crypto";
5
4
  import { z } from "zod";
5
+ import { randomUUID as randomUUID$1 } from "crypto";
6
6
 
7
7
  //#region src/v2/runtime/intelligence-platform/client.ts
8
8
  /** Let a confirmed HTTP denial survive an error body that never completes. */