@copilotkit/runtime 1.72.1-canary.sp-longthread-perf → 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 (206) hide show
  1. package/dist/agent/index.cjs +49 -9
  2. package/dist/agent/index.cjs.map +1 -1
  3. package/dist/agent/index.d.cts +20 -7
  4. package/dist/agent/index.d.cts.map +1 -1
  5. package/dist/agent/index.d.mts +19 -6
  6. package/dist/agent/index.d.mts.map +1 -1
  7. package/dist/agent/index.mjs +49 -9
  8. package/dist/agent/index.mjs.map +1 -1
  9. package/dist/agent/learned-skills.cjs +77 -0
  10. package/dist/agent/learned-skills.cjs.map +1 -0
  11. package/dist/agent/learned-skills.d.cts +16 -0
  12. package/dist/agent/learned-skills.d.cts.map +1 -0
  13. package/dist/agent/learned-skills.d.mts +16 -0
  14. package/dist/agent/learned-skills.d.mts.map +1 -0
  15. package/dist/agent/learned-skills.mjs +75 -0
  16. package/dist/agent/learned-skills.mjs.map +1 -0
  17. package/dist/index.d.cts +4 -4
  18. package/dist/index.d.mts +4 -4
  19. package/dist/internal/learned-skills.cjs +22 -0
  20. package/dist/internal/learned-skills.d.cts +10 -0
  21. package/dist/internal/learned-skills.d.mts +10 -0
  22. package/dist/internal/learned-skills.mjs +10 -0
  23. package/dist/lib/index.d.cts +2 -2
  24. package/dist/lib/index.d.mts +2 -2
  25. package/dist/lib/integrations/nextjs/app-router.cjs +1 -1
  26. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  27. package/dist/lib/integrations/nextjs/app-router.mjs +1 -1
  28. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  29. package/dist/lib/integrations/node-http/index.cjs +1 -1
  30. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  31. package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
  32. package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
  33. package/dist/lib/integrations/node-http/index.mjs +1 -1
  34. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  35. package/dist/lib/integrations/shared.cjs.map +1 -1
  36. package/dist/lib/integrations/shared.d.cts +1 -1
  37. package/dist/lib/integrations/shared.d.cts.map +1 -1
  38. package/dist/lib/integrations/shared.d.mts +1 -1
  39. package/dist/lib/integrations/shared.d.mts.map +1 -1
  40. package/dist/lib/integrations/shared.mjs.map +1 -1
  41. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts +1 -1
  42. package/dist/lib/runtime/copilot-runtime.cjs +79 -37
  43. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  44. package/dist/lib/runtime/copilot-runtime.d.cts +54 -4
  45. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  46. package/dist/lib/runtime/copilot-runtime.d.mts +56 -6
  47. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  48. package/dist/lib/runtime/copilot-runtime.mjs +79 -37
  49. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  50. package/dist/lib/runtime/mcp-client-cache.cjs +135 -0
  51. package/dist/lib/runtime/mcp-client-cache.cjs.map +1 -0
  52. package/dist/lib/runtime/mcp-client-cache.mjs +132 -0
  53. package/dist/lib/runtime/mcp-client-cache.mjs.map +1 -0
  54. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  55. package/dist/lib/runtime/telemetry-agent-runner.d.cts +1 -1
  56. package/dist/lib/runtime/telemetry-agent-runner.d.mts +1 -1
  57. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  58. package/dist/package.cjs +15 -7
  59. package/dist/package.mjs +15 -7
  60. package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
  61. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
  62. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
  63. package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
  64. package/dist/service-adapters/shared/sdk-client-utils.cjs.map +1 -1
  65. package/dist/service-adapters/shared/sdk-client-utils.d.cts.map +1 -1
  66. package/dist/service-adapters/shared/sdk-client-utils.d.mts.map +1 -1
  67. package/dist/service-adapters/shared/sdk-client-utils.mjs.map +1 -1
  68. package/dist/v2/index.cjs +9 -3
  69. package/dist/v2/index.d.cts +12 -11
  70. package/dist/v2/index.d.mts +12 -11
  71. package/dist/v2/index.mjs +5 -5
  72. package/dist/v2/runtime/core/channel-manager.cjs +1 -1
  73. package/dist/v2/runtime/core/channel-manager.d.cts +1 -1
  74. package/dist/v2/runtime/core/channel-manager.d.mts +1 -1
  75. package/dist/v2/runtime/core/channel-manager.mjs +1 -1
  76. package/dist/v2/runtime/core/fetch-handler.cjs +1 -0
  77. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  78. package/dist/v2/runtime/core/fetch-handler.d.cts +2 -2
  79. package/dist/v2/runtime/core/fetch-handler.d.mts +2 -2
  80. package/dist/v2/runtime/core/fetch-handler.mjs +1 -0
  81. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  82. package/dist/v2/runtime/core/runtime.cjs +5 -0
  83. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  84. package/dist/v2/runtime/core/runtime.d.cts +18 -3
  85. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  86. package/dist/v2/runtime/core/runtime.d.mts +17 -2
  87. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  88. package/dist/v2/runtime/core/runtime.mjs +5 -0
  89. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  90. package/dist/v2/runtime/endpoints/express-single.cjs.map +1 -1
  91. package/dist/v2/runtime/endpoints/express-single.d.cts +2 -2
  92. package/dist/v2/runtime/endpoints/express-single.d.cts.map +1 -1
  93. package/dist/v2/runtime/endpoints/express-single.d.mts +2 -2
  94. package/dist/v2/runtime/endpoints/express-single.d.mts.map +1 -1
  95. package/dist/v2/runtime/endpoints/express-single.mjs.map +1 -1
  96. package/dist/v2/runtime/endpoints/express.cjs +2 -3
  97. package/dist/v2/runtime/endpoints/express.cjs.map +1 -1
  98. package/dist/v2/runtime/endpoints/express.d.cts +26 -7
  99. package/dist/v2/runtime/endpoints/express.d.cts.map +1 -1
  100. package/dist/v2/runtime/endpoints/express.d.mts +26 -7
  101. package/dist/v2/runtime/endpoints/express.d.mts.map +1 -1
  102. package/dist/v2/runtime/endpoints/express.mjs +2 -2
  103. package/dist/v2/runtime/endpoints/express.mjs.map +1 -1
  104. package/dist/v2/runtime/endpoints/hono.d.cts +2 -2
  105. package/dist/v2/runtime/endpoints/hono.d.mts +2 -2
  106. package/dist/v2/runtime/endpoints/index.d.cts +3 -3
  107. package/dist/v2/runtime/endpoints/index.d.mts +3 -3
  108. package/dist/v2/runtime/endpoints/load-express.cjs +36 -0
  109. package/dist/v2/runtime/endpoints/load-express.cjs.map +1 -0
  110. package/dist/v2/runtime/endpoints/load-express.mjs +35 -0
  111. package/dist/v2/runtime/endpoints/load-express.mjs.map +1 -0
  112. package/dist/v2/runtime/handlers/handle-stop.cjs +18 -14
  113. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -1
  114. package/dist/v2/runtime/handlers/handle-stop.mjs +18 -14
  115. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -1
  116. package/dist/v2/runtime/handlers/handle-suggest.cjs +4 -3
  117. package/dist/v2/runtime/handlers/handle-suggest.cjs.map +1 -1
  118. package/dist/v2/runtime/handlers/handle-suggest.mjs +5 -4
  119. package/dist/v2/runtime/handlers/handle-suggest.mjs.map +1 -1
  120. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +3 -4
  121. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  122. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +1 -2
  123. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  124. package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs +69 -0
  125. package/dist/v2/runtime/handlers/shared/sse-keep-alive.cjs.map +1 -0
  126. package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs +67 -0
  127. package/dist/v2/runtime/handlers/shared/sse-keep-alive.mjs.map +1 -0
  128. package/dist/v2/runtime/handlers/shared/sse-response.cjs +5 -2
  129. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  130. package/dist/v2/runtime/handlers/shared/sse-response.mjs +5 -2
  131. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  132. package/dist/v2/runtime/handlers/sse/connect.cjs +1 -0
  133. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -1
  134. package/dist/v2/runtime/handlers/sse/connect.mjs +1 -0
  135. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -1
  136. package/dist/v2/runtime/handlers/sse/run.cjs +1 -0
  137. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  138. package/dist/v2/runtime/handlers/sse/run.mjs +1 -0
  139. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  140. package/dist/v2/runtime/index.d.cts +9 -9
  141. package/dist/v2/runtime/index.d.mts +9 -9
  142. package/dist/v2/runtime/intelligence-platform/client.cjs +1 -1
  143. package/dist/v2/runtime/intelligence-platform/client.d.cts +1 -1
  144. package/dist/v2/runtime/intelligence-platform/client.d.mts +1 -1
  145. package/dist/v2/runtime/intelligence-platform/client.mjs +1 -1
  146. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs +132 -0
  147. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -0
  148. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts +11 -0
  149. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -0
  150. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts +11 -0
  151. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -0
  152. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs +128 -0
  153. package/dist/v2/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -0
  154. package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs +48 -0
  155. package/dist/v2/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -0
  156. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts +27 -0
  157. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -0
  158. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts +27 -0
  159. package/dist/v2/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -0
  160. package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs +48 -0
  161. package/dist/v2/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -0
  162. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs +11 -0
  163. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.cjs.map +1 -0
  164. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts +8 -0
  165. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.cts.map +1 -0
  166. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts +8 -0
  167. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.d.mts.map +1 -0
  168. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs +11 -0
  169. package/dist/v2/runtime/intelligence-platform/skill-registry/errors.mjs.map +1 -0
  170. package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.cts +8 -0
  171. package/dist/v2/runtime/intelligence-platform/skill-registry/index.d.mts +8 -0
  172. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs +132 -0
  173. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -0
  174. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts +31 -0
  175. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -0
  176. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts +31 -0
  177. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -0
  178. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs +132 -0
  179. package/dist/v2/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -0
  180. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs +42 -0
  181. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.cjs.map +1 -0
  182. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts +13 -0
  183. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.cts.map +1 -0
  184. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts +13 -0
  185. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.d.mts.map +1 -0
  186. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs +39 -0
  187. package/dist/v2/runtime/intelligence-platform/skill-registry/skill-content.mjs.map +1 -0
  188. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs +93 -0
  189. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -0
  190. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts +28 -0
  191. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -0
  192. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts +28 -0
  193. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -0
  194. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs +92 -0
  195. package/dist/v2/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -0
  196. package/dist/v2/runtime/runner/agent-runner.d.cts +1 -1
  197. package/dist/v2/runtime/runner/in-memory.d.cts +1 -1
  198. package/dist/v2/runtime/runner/index.d.cts +2 -2
  199. package/dist/v2/runtime/runner/index.d.mts +2 -2
  200. package/dist/v2/runtime/runner/index.mjs +2 -2
  201. package/dist/v2/runtime/runner/intelligence.d.cts +1 -1
  202. package/package.json +17 -7
  203. package/dist/v2/runtime/open-generative-ui-middleware.cjs +0 -286
  204. package/dist/v2/runtime/open-generative-ui-middleware.cjs.map +0 -1
  205. package/dist/v2/runtime/open-generative-ui-middleware.mjs +0 -284
  206. package/dist/v2/runtime/open-generative-ui-middleware.mjs.map +0 -1
@@ -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;A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AQ,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,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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AAM,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,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"}
@@ -55,14 +55,15 @@ async function handleSuggestAgent({ runtime, request, agentId }) {
55
55
  request,
56
56
  agentId,
57
57
  captureTelemetry: false,
58
+ keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
58
59
  observableFactory: () => new rxjs.Observable((subscriber) => {
59
- const collected = [];
60
+ const finalizer = (0, _copilotkit_shared.createRunEventFinalizer)();
60
61
  let settled = false;
61
62
  agent.runAgent(input, { onEvent: ({ event }) => {
62
- collected.push(event);
63
+ finalizer.observe(event);
63
64
  subscriber.next(event);
64
65
  } }).then(() => {
65
- for (const event of (0, _copilotkit_shared.finalizeRunEvents)(collected, { stopRequested: false })) subscriber.next(event);
66
+ for (const event of finalizer.finalize({ stopRequested: false })) subscriber.next(event);
66
67
  settled = true;
67
68
  subscriber.complete();
68
69
  }).catch((error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../../src/v2/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { finalizeRunEvents } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Collected so `finalizeRunEvents` can append any missing terminal\n // events (e.g. an unclosed message/tool call, or a `RUN_FINISHED`) —\n // the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence.\n const collected: BaseEvent[] = [];\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n collected.push(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizeRunEvents(collected, {\n stopRequested: false,\n })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,yBACE,IAAIC,iBAAuB,eAAe;GAKxC,MAAM,YAAyB,EAAE;GACjC,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,KAAK,MAAM;AACrB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,mDAA2B,WAAW,EAC/C,eAAe,OAChB,CAAC,CACA,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../../src/v2/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -2,7 +2,7 @@ import "reflect-metadata";
2
2
  import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "./header-utils.mjs";
3
3
  import { cloneAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
4
4
  import { createSseEventResponse } from "./shared/sse-response.mjs";
5
- import { finalizeRunEvents } from "@copilotkit/shared";
5
+ import { createRunEventFinalizer } from "@copilotkit/shared";
6
6
  import { Observable } from "rxjs";
7
7
 
8
8
  //#region src/v2/runtime/handlers/handle-suggest.ts
@@ -54,14 +54,15 @@ async function handleSuggestAgent({ runtime, request, agentId }) {
54
54
  request,
55
55
  agentId,
56
56
  captureTelemetry: false,
57
+ keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
57
58
  observableFactory: () => new Observable((subscriber) => {
58
- const collected = [];
59
+ const finalizer = createRunEventFinalizer();
59
60
  let settled = false;
60
61
  agent.runAgent(input, { onEvent: ({ event }) => {
61
- collected.push(event);
62
+ finalizer.observe(event);
62
63
  subscriber.next(event);
63
64
  } }).then(() => {
64
- for (const event of finalizeRunEvents(collected, { stopRequested: false })) subscriber.next(event);
65
+ for (const event of finalizer.finalize({ stopRequested: false })) subscriber.next(event);
65
66
  settled = true;
66
67
  subscriber.complete();
67
68
  }).catch((error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { finalizeRunEvents } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Collected so `finalizeRunEvents` can append any missing terminal\n // events (e.g. an unclosed message/tool call, or a `RUN_FINISHED`) —\n // the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence.\n const collected: BaseEvent[] = [];\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n collected.push(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizeRunEvents(collected, {\n stopRequested: false,\n })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,yBACE,IAAI,YAAuB,eAAe;GAKxC,MAAM,YAAyB,EAAE;GACjC,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,KAAK,MAAM;AACrB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,kBAAkB,WAAW,EAC/C,eAAe,OAChB,CAAC,CACA,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../../src/v2/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAI,YAAuB,eAAe;GAMxC,MAAM,YAAY,yBAAyB;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -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,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAIC,sCAAe;GACjB,GAAG;GAIH,gBACE,mBAAmB,yBAAyB,OAAO;GACtD,CAAC,CACH;;AAIL,KAAIC,wCAAsB,QAAQ,IAAI,OAAO,MAAM,QAAQ,YAAY;EAGrE,MAAM,aAAaC,+CACjB,QAAQ,SAAS,WAAW,EAAE,EAC9B,QACD;AACD,MAAI,WAAW,SAAS,KAAK,kBAC3B,OAAM,IACJ,IAAIC,6CAAkB;GAAE;GAAY,sBAAsB;GAAS,CAAC,CACrE;YAEM,QAAQ,SAAS,SAAS,QAAQ;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CACF,CAAC,CACH;;AAGH,eAAsB,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"}
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,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,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 instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAchC;CACP,MAAM,EACJ,SACA,SACA,SACA,wBACA,sBACE;CACJ,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAI,cAAc,QAAQ,KAA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M,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,UA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c,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"}
@@ -0,0 +1,69 @@
1
+ require("reflect-metadata");
2
+
3
+ //#region src/v2/runtime/handlers/shared/sse-keep-alive.ts
4
+ /**
5
+ * Default silence, in seconds, before an SSE response carries a keep-alive
6
+ * comment. Sits under the tightest common proxy idle timeouts (55–60 s) and
7
+ * beside `lockHeartbeatIntervalSeconds`, which shares the unit and default.
8
+ */
9
+ const DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS = 15;
10
+ /**
11
+ * Longest interval the timer can honour. Timers take a signed 32-bit
12
+ * millisecond delay; Node silently replaces anything larger with 1 ms, which
13
+ * would turn a keep-alive into a flood.
14
+ */
15
+ const MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS = (2 ** 31 - 1) / 1e3;
16
+ /**
17
+ * Resolves the `sseKeepAliveIntervalSeconds` runtime option once, at
18
+ * construction, so every SSE call site reads one validated value.
19
+ * `undefined` takes the default; `0` disables the keep-alive.
20
+ */
21
+ function resolveSseKeepAliveIntervalSeconds(value) {
22
+ const seconds = value ?? DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS;
23
+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS) throw new RangeError(`sseKeepAliveIntervalSeconds must be between 0 and ${MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS}, got ${String(value)}`);
24
+ return seconds;
25
+ }
26
+ /**
27
+ * SSE comment frame. Parsers drop comment lines, so no AG-UI event is
28
+ * invented and the verifier, history and middleware never see it.
29
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes
30
+ */
31
+ const KEEP_ALIVE_FRAME = new TextEncoder().encode(": keep-alive\n\n");
32
+ /**
33
+ * Keeps a quiet SSE body open by writing a comment after `idleMs` of silence.
34
+ *
35
+ * Any byte from `source` resets the clock, so an active stream adds nothing
36
+ * to the wire. A back-pressured reader skips the tick instead of queueing
37
+ * frames. The timer stops when the pipe settles, which covers both the source
38
+ * completing and the reader cancelling, on every supported Node version.
39
+ */
40
+ function keepAliveSse(source, idleMs) {
41
+ let timer;
42
+ const stop = () => {
43
+ if (timer !== void 0) clearTimeout(timer);
44
+ timer = void 0;
45
+ };
46
+ const arm = (controller) => {
47
+ stop();
48
+ timer = setTimeout(() => {
49
+ if (controller.desiredSize === 1) controller.enqueue(KEEP_ALIVE_FRAME);
50
+ arm(controller);
51
+ }, idleMs);
52
+ timer.unref?.();
53
+ };
54
+ const transform = new TransformStream({
55
+ start: arm,
56
+ transform(chunk, controller) {
57
+ controller.enqueue(chunk);
58
+ arm(controller);
59
+ },
60
+ flush: stop
61
+ }, void 0, { highWaterMark: 1 });
62
+ source.pipeTo(transform.writable).catch(() => {}).finally(stop);
63
+ return transform.readable;
64
+ }
65
+
66
+ //#endregion
67
+ exports.keepAliveSse = keepAliveSse;
68
+ exports.resolveSseKeepAliveIntervalSeconds = resolveSseKeepAliveIntervalSeconds;
69
+ //# sourceMappingURL=sse-keep-alive.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse-keep-alive.cjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-keep-alive.ts"],"sourcesContent":["/**\n * Default silence, in seconds, before an SSE response carries a keep-alive\n * comment. Sits under the tightest common proxy idle timeouts (55–60 s) and\n * beside `lockHeartbeatIntervalSeconds`, which shares the unit and default.\n */\nexport const DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS = 15;\n\n/**\n * Longest interval the timer can honour. Timers take a signed 32-bit\n * millisecond delay; Node silently replaces anything larger with 1 ms, which\n * would turn a keep-alive into a flood.\n */\nexport const MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS = (2 ** 31 - 1) / 1000;\n\n/**\n * Resolves the `sseKeepAliveIntervalSeconds` runtime option once, at\n * construction, so every SSE call site reads one validated value.\n * `undefined` takes the default; `0` disables the keep-alive.\n */\nexport function resolveSseKeepAliveIntervalSeconds(\n value: number | undefined,\n): number {\n const seconds = value ?? DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS;\n if (\n !Number.isFinite(seconds) ||\n seconds < 0 ||\n seconds > MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS\n ) {\n throw new RangeError(\n `sseKeepAliveIntervalSeconds must be between 0 and ${MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS}, got ${String(value)}`,\n );\n }\n return seconds;\n}\n\n/**\n * SSE comment frame. Parsers drop comment lines, so no AG-UI event is\n * invented and the verifier, history and middleware never see it.\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes\n */\nconst KEEP_ALIVE_FRAME = new TextEncoder().encode(\": keep-alive\\n\\n\");\n\n/**\n * Keeps a quiet SSE body open by writing a comment after `idleMs` of silence.\n *\n * Any byte from `source` resets the clock, so an active stream adds nothing\n * to the wire. A back-pressured reader skips the tick instead of queueing\n * frames. The timer stops when the pipe settles, which covers both the source\n * completing and the reader cancelling, on every supported Node version.\n */\nexport function keepAliveSse(\n source: ReadableStream<Uint8Array>,\n idleMs: number,\n): ReadableStream<Uint8Array> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const stop = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n };\n const arm = (controller: TransformStreamDefaultController<Uint8Array>) => {\n stop();\n timer = setTimeout(() => {\n // `desiredSize` is 1 only while the readable queue is empty; 0 means a\n // slow reader still holds the previous chunk, null means it went away.\n if (controller.desiredSize === 1) controller.enqueue(KEEP_ALIVE_FRAME);\n arm(controller);\n }, idleMs);\n timer.unref?.();\n };\n const transform = new TransformStream<Uint8Array, Uint8Array>(\n {\n start: arm,\n transform(chunk, controller) {\n controller.enqueue(chunk);\n arm(controller);\n },\n flush: stop,\n },\n undefined,\n { highWaterMark: 1 },\n );\n // `flush` stops the timer when the source completes. The pipe settling\n // covers the reader cancelling, on every supported Node version; the source\n // writer surfaces that cancellation to the caller.\n void source\n .pipeTo(transform.writable)\n .catch(() => {})\n .finally(stop);\n return transform.readable;\n}\n"],"mappings":";;;;;;;;AAKA,MAAa,0CAA0C;;;;;;AAOvD,MAAa,uCAAuC,KAAK,KAAK,KAAK;;;;;;AAOnE,SAAgB,mCACd,OACQ;CACR,MAAM,UAAU,SAAS;AACzB,KACE,CAAC,OAAO,SAAS,QAAQ,IACzB,UAAU,KACV,UAAU,oCAEV,OAAM,IAAI,WACR,qDAAqD,oCAAoC,QAAQ,OAAO,MAAM,GAC/G;AAEH,QAAO;;;;;;;AAQT,MAAM,mBAAmB,IAAI,aAAa,CAAC,OAAO,mBAAmB;;;;;;;;;AAUrE,SAAgB,aACd,QACA,QAC4B;CAC5B,IAAI;CACJ,MAAM,aAAa;AACjB,MAAI,UAAU,OAAW,cAAa,MAAM;AAC5C,UAAQ;;CAEV,MAAM,OAAO,eAA6D;AACxE,QAAM;AACN,UAAQ,iBAAiB;AAGvB,OAAI,WAAW,gBAAgB,EAAG,YAAW,QAAQ,iBAAiB;AACtE,OAAI,WAAW;KACd,OAAO;AACV,QAAM,SAAS;;CAEjB,MAAM,YAAY,IAAI,gBACpB;EACE,OAAO;EACP,UAAU,OAAO,YAAY;AAC3B,cAAW,QAAQ,MAAM;AACzB,OAAI,WAAW;;EAEjB,OAAO;EACR,EACD,QACA,EAAE,eAAe,GAAG,CACrB;AAID,CAAK,OACF,OAAO,UAAU,SAAS,CAC1B,YAAY,GAAG,CACf,QAAQ,KAAK;AAChB,QAAO,UAAU"}
@@ -0,0 +1,67 @@
1
+ import "reflect-metadata";
2
+ //#region src/v2/runtime/handlers/shared/sse-keep-alive.ts
3
+ /**
4
+ * Default silence, in seconds, before an SSE response carries a keep-alive
5
+ * comment. Sits under the tightest common proxy idle timeouts (55–60 s) and
6
+ * beside `lockHeartbeatIntervalSeconds`, which shares the unit and default.
7
+ */
8
+ const DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS = 15;
9
+ /**
10
+ * Longest interval the timer can honour. Timers take a signed 32-bit
11
+ * millisecond delay; Node silently replaces anything larger with 1 ms, which
12
+ * would turn a keep-alive into a flood.
13
+ */
14
+ const MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS = (2 ** 31 - 1) / 1e3;
15
+ /**
16
+ * Resolves the `sseKeepAliveIntervalSeconds` runtime option once, at
17
+ * construction, so every SSE call site reads one validated value.
18
+ * `undefined` takes the default; `0` disables the keep-alive.
19
+ */
20
+ function resolveSseKeepAliveIntervalSeconds(value) {
21
+ const seconds = value ?? DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS;
22
+ if (!Number.isFinite(seconds) || seconds < 0 || seconds > MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS) throw new RangeError(`sseKeepAliveIntervalSeconds must be between 0 and ${MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS}, got ${String(value)}`);
23
+ return seconds;
24
+ }
25
+ /**
26
+ * SSE comment frame. Parsers drop comment lines, so no AG-UI event is
27
+ * invented and the verifier, history and middleware never see it.
28
+ * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes
29
+ */
30
+ const KEEP_ALIVE_FRAME = new TextEncoder().encode(": keep-alive\n\n");
31
+ /**
32
+ * Keeps a quiet SSE body open by writing a comment after `idleMs` of silence.
33
+ *
34
+ * Any byte from `source` resets the clock, so an active stream adds nothing
35
+ * to the wire. A back-pressured reader skips the tick instead of queueing
36
+ * frames. The timer stops when the pipe settles, which covers both the source
37
+ * completing and the reader cancelling, on every supported Node version.
38
+ */
39
+ function keepAliveSse(source, idleMs) {
40
+ let timer;
41
+ const stop = () => {
42
+ if (timer !== void 0) clearTimeout(timer);
43
+ timer = void 0;
44
+ };
45
+ const arm = (controller) => {
46
+ stop();
47
+ timer = setTimeout(() => {
48
+ if (controller.desiredSize === 1) controller.enqueue(KEEP_ALIVE_FRAME);
49
+ arm(controller);
50
+ }, idleMs);
51
+ timer.unref?.();
52
+ };
53
+ const transform = new TransformStream({
54
+ start: arm,
55
+ transform(chunk, controller) {
56
+ controller.enqueue(chunk);
57
+ arm(controller);
58
+ },
59
+ flush: stop
60
+ }, void 0, { highWaterMark: 1 });
61
+ source.pipeTo(transform.writable).catch(() => {}).finally(stop);
62
+ return transform.readable;
63
+ }
64
+
65
+ //#endregion
66
+ export { keepAliveSse, resolveSseKeepAliveIntervalSeconds };
67
+ //# sourceMappingURL=sse-keep-alive.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse-keep-alive.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/shared/sse-keep-alive.ts"],"sourcesContent":["/**\n * Default silence, in seconds, before an SSE response carries a keep-alive\n * comment. Sits under the tightest common proxy idle timeouts (55–60 s) and\n * beside `lockHeartbeatIntervalSeconds`, which shares the unit and default.\n */\nexport const DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS = 15;\n\n/**\n * Longest interval the timer can honour. Timers take a signed 32-bit\n * millisecond delay; Node silently replaces anything larger with 1 ms, which\n * would turn a keep-alive into a flood.\n */\nexport const MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS = (2 ** 31 - 1) / 1000;\n\n/**\n * Resolves the `sseKeepAliveIntervalSeconds` runtime option once, at\n * construction, so every SSE call site reads one validated value.\n * `undefined` takes the default; `0` disables the keep-alive.\n */\nexport function resolveSseKeepAliveIntervalSeconds(\n value: number | undefined,\n): number {\n const seconds = value ?? DEFAULT_SSE_KEEP_ALIVE_INTERVAL_SECONDS;\n if (\n !Number.isFinite(seconds) ||\n seconds < 0 ||\n seconds > MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS\n ) {\n throw new RangeError(\n `sseKeepAliveIntervalSeconds must be between 0 and ${MAX_SSE_KEEP_ALIVE_INTERVAL_SECONDS}, got ${String(value)}`,\n );\n }\n return seconds;\n}\n\n/**\n * SSE comment frame. Parsers drop comment lines, so no AG-UI event is\n * invented and the verifier, history and middleware never see it.\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#authoring-notes\n */\nconst KEEP_ALIVE_FRAME = new TextEncoder().encode(\": keep-alive\\n\\n\");\n\n/**\n * Keeps a quiet SSE body open by writing a comment after `idleMs` of silence.\n *\n * Any byte from `source` resets the clock, so an active stream adds nothing\n * to the wire. A back-pressured reader skips the tick instead of queueing\n * frames. The timer stops when the pipe settles, which covers both the source\n * completing and the reader cancelling, on every supported Node version.\n */\nexport function keepAliveSse(\n source: ReadableStream<Uint8Array>,\n idleMs: number,\n): ReadableStream<Uint8Array> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const stop = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n };\n const arm = (controller: TransformStreamDefaultController<Uint8Array>) => {\n stop();\n timer = setTimeout(() => {\n // `desiredSize` is 1 only while the readable queue is empty; 0 means a\n // slow reader still holds the previous chunk, null means it went away.\n if (controller.desiredSize === 1) controller.enqueue(KEEP_ALIVE_FRAME);\n arm(controller);\n }, idleMs);\n timer.unref?.();\n };\n const transform = new TransformStream<Uint8Array, Uint8Array>(\n {\n start: arm,\n transform(chunk, controller) {\n controller.enqueue(chunk);\n arm(controller);\n },\n flush: stop,\n },\n undefined,\n { highWaterMark: 1 },\n );\n // `flush` stops the timer when the source completes. The pipe settling\n // covers the reader cancelling, on every supported Node version; the source\n // writer surfaces that cancellation to the caller.\n void source\n .pipeTo(transform.writable)\n .catch(() => {})\n .finally(stop);\n return transform.readable;\n}\n"],"mappings":";;;;;;;AAKA,MAAa,0CAA0C;;;;;;AAOvD,MAAa,uCAAuC,KAAK,KAAK,KAAK;;;;;;AAOnE,SAAgB,mCACd,OACQ;CACR,MAAM,UAAU,SAAS;AACzB,KACE,CAAC,OAAO,SAAS,QAAQ,IACzB,UAAU,KACV,UAAU,oCAEV,OAAM,IAAI,WACR,qDAAqD,oCAAoC,QAAQ,OAAO,MAAM,GAC/G;AAEH,QAAO;;;;;;;AAQT,MAAM,mBAAmB,IAAI,aAAa,CAAC,OAAO,mBAAmB;;;;;;;;;AAUrE,SAAgB,aACd,QACA,QAC4B;CAC5B,IAAI;CACJ,MAAM,aAAa;AACjB,MAAI,UAAU,OAAW,cAAa,MAAM;AAC5C,UAAQ;;CAEV,MAAM,OAAO,eAA6D;AACxE,QAAM;AACN,UAAQ,iBAAiB;AAGvB,OAAI,WAAW,gBAAgB,EAAG,YAAW,QAAQ,iBAAiB;AACtE,OAAI,WAAW;KACd,OAAO;AACV,QAAM,SAAS;;CAEjB,MAAM,YAAY,IAAI,gBACpB;EACE,OAAO;EACP,UAAU,OAAO,YAAY;AAC3B,cAAW,QAAQ,MAAM;AACzB,OAAI,WAAW;;EAEjB,OAAO;EACR,EACD,QACA,EAAE,eAAe,GAAG,CACrB;AAID,CAAK,OACF,OAAO,UAAU,SAAS,CAC1B,YAAY,GAAG,CACf,QAAQ,KAAK;AAChB,QAAO,UAAU"}