@copilotkit/runtime 2.0.0-rc.2 → 2.0.0-rc.20

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 (238) hide show
  1. package/README.md +19 -1
  2. package/dist/agent/converters/aisdk.cjs +0 -1
  3. package/dist/agent/converters/aisdk.cjs.map +1 -1
  4. package/dist/agent/converters/tanstack.cjs +1 -2
  5. package/dist/agent/converters/tanstack.cjs.map +1 -1
  6. package/dist/agent/converters/tanstack.mjs +1 -1
  7. package/dist/agent/converters/tanstack.mjs.map +1 -1
  8. package/dist/agent/index.cjs +23 -33
  9. package/dist/agent/index.cjs.map +1 -1
  10. package/dist/agent/index.d.cts +1 -9
  11. package/dist/agent/index.d.cts.map +1 -1
  12. package/dist/agent/index.d.mts +1 -9
  13. package/dist/agent/index.d.mts.map +1 -1
  14. package/dist/agent/index.mjs +25 -33
  15. package/dist/agent/index.mjs.map +1 -1
  16. package/dist/agent/learned-skills.cjs +0 -1
  17. package/dist/agent/learned-skills.cjs.map +1 -1
  18. package/dist/agent/state-delta.cjs +0 -1
  19. package/dist/agent/state-delta.cjs.map +1 -1
  20. package/dist/agent/url-download.cjs +10 -12
  21. package/dist/agent/url-download.cjs.map +1 -1
  22. package/dist/agent/url-download.d.cts.map +1 -1
  23. package/dist/agent/url-download.d.mts.map +1 -1
  24. package/dist/agent/url-download.mjs +10 -11
  25. package/dist/agent/url-download.mjs.map +1 -1
  26. package/dist/index.cjs +20 -10
  27. package/dist/index.d.cts +6 -3
  28. package/dist/index.d.mts +6 -3
  29. package/dist/index.mjs +5 -2
  30. package/dist/node.cjs +1 -2
  31. package/dist/node.d.cts +2 -2
  32. package/dist/node.d.mts +2 -2
  33. package/dist/node.mjs +2 -2
  34. package/dist/runtime/core/channel-manager.cjs +4 -5
  35. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  36. package/dist/runtime/core/channel-manager.mjs +4 -4
  37. package/dist/runtime/core/channel-manager.mjs.map +1 -1
  38. package/dist/runtime/core/debug-event-bus.cjs +2 -1
  39. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  40. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  41. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  42. package/dist/runtime/core/debug-event-bus.mjs +3 -1
  43. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  44. package/dist/runtime/core/fetch-handler.cjs +3 -4
  45. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  46. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  47. package/dist/runtime/core/logger.cjs +86 -13
  48. package/dist/runtime/core/logger.cjs.map +1 -1
  49. package/dist/runtime/core/logger.d.cts +21 -8
  50. package/dist/runtime/core/logger.d.cts.map +1 -1
  51. package/dist/runtime/core/logger.d.mts +21 -8
  52. package/dist/runtime/core/logger.d.mts.map +1 -1
  53. package/dist/runtime/core/logger.mjs +86 -10
  54. package/dist/runtime/core/logger.mjs.map +1 -1
  55. package/dist/runtime/core/middleware-sse-parser.cjs +0 -1
  56. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  57. package/dist/runtime/core/middleware.cjs +0 -1
  58. package/dist/runtime/core/middleware.cjs.map +1 -1
  59. package/dist/runtime/core/package-info.cjs +1 -1
  60. package/dist/runtime/core/package-info.mjs +1 -1
  61. package/dist/runtime/core/runtime.cjs +19 -6
  62. package/dist/runtime/core/runtime.cjs.map +1 -1
  63. package/dist/runtime/core/runtime.d.cts +19 -3
  64. package/dist/runtime/core/runtime.d.cts.map +1 -1
  65. package/dist/runtime/core/runtime.d.mts +20 -4
  66. package/dist/runtime/core/runtime.d.mts.map +1 -1
  67. package/dist/runtime/core/runtime.mjs +20 -6
  68. package/dist/runtime/core/runtime.mjs.map +1 -1
  69. package/dist/runtime/core/web-crypto.cjs +22 -0
  70. package/dist/runtime/core/web-crypto.cjs.map +1 -0
  71. package/dist/runtime/core/web-crypto.mjs +20 -0
  72. package/dist/runtime/core/web-crypto.mjs.map +1 -0
  73. package/dist/runtime/endpoints/auto-start-channels.cjs +0 -1
  74. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  75. package/dist/runtime/endpoints/node-fetch-handler.cjs +0 -4
  76. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  77. package/dist/runtime/endpoints/node-fetch-handler.d.cts +1 -3
  78. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  79. package/dist/runtime/endpoints/node-fetch-handler.d.mts +1 -3
  80. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  81. package/dist/runtime/endpoints/node-fetch-handler.mjs +1 -3
  82. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  83. package/dist/runtime/event-transforms/index.d.cts +4 -0
  84. package/dist/runtime/event-transforms/index.d.mts +4 -0
  85. package/dist/runtime/event-transforms/index.mjs +5 -0
  86. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  87. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  88. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  89. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  90. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  91. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  92. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  93. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  94. package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
  95. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  96. package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
  97. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  98. package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
  99. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  100. package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
  101. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  102. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  103. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  104. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  105. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  106. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  107. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  108. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  109. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  110. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  111. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  112. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  113. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  114. package/dist/runtime/handlers/get-runtime-info.cjs +7 -6
  115. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  116. package/dist/runtime/handlers/get-runtime-info.mjs +7 -6
  117. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  118. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  119. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  120. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  121. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  122. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  123. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  124. package/dist/runtime/handlers/handle-run.cjs +3 -4
  125. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  126. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  127. package/dist/runtime/handlers/handle-stop.cjs +3 -4
  128. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  129. package/dist/runtime/handlers/handle-suggest.cjs +0 -1
  130. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  131. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  132. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  133. package/dist/runtime/handlers/intelligence/annotate.cjs +2 -3
  134. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  135. package/dist/runtime/handlers/intelligence/memories.cjs +7 -8
  136. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  137. package/dist/runtime/handlers/intelligence/run.cjs +0 -1
  138. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  139. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  140. package/dist/runtime/handlers/intelligence/thread-names.cjs +3 -5
  141. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  142. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -4
  143. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  144. package/dist/runtime/handlers/intelligence/threads.cjs +6 -7
  145. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  146. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  147. package/dist/runtime/handlers/shared/agent-utils.cjs +10 -10
  148. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  149. package/dist/runtime/handlers/shared/agent-utils.mjs +4 -3
  150. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  151. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  152. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  153. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +1 -1
  154. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  155. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +1 -1
  156. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  157. package/dist/runtime/handlers/shared/sse-response.cjs +72 -64
  158. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  159. package/dist/runtime/handlers/shared/sse-response.mjs +72 -63
  160. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  161. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  162. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  163. package/dist/runtime/index.d.cts +4 -9
  164. package/dist/runtime/index.d.mts +4 -9
  165. package/dist/runtime/intelligence-platform/client.cjs +1 -3
  166. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  167. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  168. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  169. package/dist/runtime/intelligence-platform/client.mjs +1 -2
  170. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  171. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  172. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  173. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  174. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  175. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  176. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  177. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  178. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  179. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  180. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  181. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  182. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  183. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +2 -1
  184. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  185. package/dist/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -1
  186. package/dist/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -1
  187. package/dist/runtime/intelligence-platform/skill-registry/config.mjs +2 -1
  188. package/dist/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -1
  189. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +26 -24
  190. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  191. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  192. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  193. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +26 -23
  194. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  195. package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs +3 -7
  196. package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -1
  197. package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -1
  198. package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -1
  199. package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs +3 -6
  200. package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -1
  201. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +0 -1
  202. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  203. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  204. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  205. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  206. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  207. package/dist/runtime/node.d.cts +1 -1
  208. package/dist/runtime/node.d.mts +1 -1
  209. package/dist/runtime/runner/agent-runner.cjs +0 -1
  210. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  211. package/dist/runtime/runner/in-memory.cjs +0 -1
  212. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  213. package/dist/runtime/runner/intelligence.cjs +1 -3
  214. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  215. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  216. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  217. package/dist/runtime/runner/intelligence.mjs +1 -2
  218. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  219. package/dist/runtime/telemetry/disclosure.cjs +2 -1
  220. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  221. package/dist/runtime/telemetry/disclosure.mjs +3 -1
  222. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  223. package/dist/runtime/telemetry/instance-created.cjs +7 -9
  224. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  225. package/dist/runtime/telemetry/instance-created.mjs +7 -9
  226. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  227. package/dist/runtime/telemetry/telemetry-client.cjs +2 -7
  228. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  229. package/dist/runtime/telemetry/telemetry-client.d.cts.map +1 -1
  230. package/dist/runtime/telemetry/telemetry-client.d.mts.map +1 -1
  231. package/dist/runtime/telemetry/telemetry-client.mjs +3 -7
  232. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  233. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  234. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  235. package/package.json +10 -18
  236. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  237. package/dist/runtime/index.d.cts.map +0 -1
  238. package/dist/runtime/index.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA+BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SA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AAE,QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe;GACrD,UAAU,OAAO;GACjB,QAAQ,KAAK;GACd,CAAC;EAMF,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,sBAAsB,OAAO,+BAA+B;;AAIvE,KAAI,6BAA6B,QAAQ,OAAO,EAAE;EAChD,MAAM,UAAU,MAAM,wBAAwB;GAC5C;GACA;GACA,WAAW;GACZ,CAAC;AACF,MAAI,kBAAkB,QAAQ,CAAE,QAAO;AACvC,MAAI;GACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,UAAU,EAAE,SAAS,CAAC;AAClE,UAAO,SAAS,KAAK,EAAE,OAAO,CAAC;WACxB,OAAO;AACd,UAAO,MAAM;IAAE,KAAK;IAAO;IAAU,EAAE,8BAA8B;AACrE,UAAO,cAAc,gCAAgC,IAAI;;;AAI7D,QAAO,cACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n case \"activity\":\n case \"developer\":\n case \"reasoning\":\n case \"system\":\n case \"user\":\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA+BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C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,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,sBAAsB,OAAO,+BAA+B;;AAIvE,KAAI,6BAA6B,QAAQ,OAAO,EAAE;EAChD,MAAM,UAAU,MAAM,wBAAwB;GAC5C;GACA;GACA,WAAW;GACZ,CAAC;AACF,MAAI,kBAAkB,QAAQ,CAAE,QAAO;AACvC,MAAI;GACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,UAAU,EAAE,SAAS,CAAC;AAClE,UAAO,SAAS,KAAK,EAAE,OAAO,CAAC;WACxB,OAAO;AACd,UAAO,MAAM;IAAE,KAAK;IAAO;IAAU,EAAE,8BAA8B;AACrE,UAAO,cAAc,gCAAgC,IAAI;;;AAI7D,QAAO,cACL,uJACA,IACD"}
@@ -1,16 +1,16 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_header_utils = require('../header-utils.cjs');
3
2
  const require_json_response = require('./json-response.cjs');
4
3
  const require_client = require('../../intelligence-platform/client.cjs');
5
4
  const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
6
- const require_runtime$1 = require('../../core/runtime.cjs');
5
+ const require_runtime = require('../../core/runtime.cjs');
7
6
  const require_generative_ui_middleware = require('../../generative-ui/generative-ui-middleware.cjs');
7
+ const require_open_generative_ui_middleware = require('../../event-transforms/open-generative-ui-middleware.cjs');
8
8
  const require_mcp_apps_servers = require('./mcp-apps-servers.cjs');
9
9
  const require_memory_policy = require('./memory-policy.cjs');
10
10
  let _copilotkit_shared = require("@copilotkit/shared");
11
+ let _ag_ui_a2ui_middleware = require("@ag-ui/a2ui-middleware");
11
12
  let _ag_ui_mcp_middleware = require("@ag-ui/mcp-middleware");
12
13
  let _ag_ui_core_schemas = require("@ag-ui/core/schemas");
13
- let _copilotkit_shared_event_transforms = require("@copilotkit/shared/event-transforms");
14
14
  let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
15
15
 
16
16
  //#region src/runtime/handlers/shared/agent-utils.ts
@@ -31,7 +31,7 @@ let _ag_ui_mcp_apps_middleware = require("@ag-ui/mcp-apps-middleware");
31
31
  * untouched.
32
32
  */
33
33
  async function cloneAgentForRequest(runtime, agentId, request) {
34
- const agents = await require_runtime$1.resolveAgents(runtime.agents, request);
34
+ const agents = await require_runtime.resolveAgents(runtime.agents, request);
35
35
  if (!agents[agentId]) return new Response(JSON.stringify({
36
36
  error: "Agent not found",
37
37
  message: `Agent '${agentId}' does not exist`
@@ -45,14 +45,14 @@ function configureAgentForRequest(params) {
45
45
  const { runtime, request, agentId, providerA2UIHasCatalog, isMcpProxyRequest } = params;
46
46
  const agent = params.agent;
47
47
  const a2uiEnabledByCatalog = !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;
48
- if (require_runtime$1.isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {
48
+ if (require_runtime.isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {
49
49
  const { agents: targetAgents, enabled: _enabled, injectA2UITool, ...a2uiOptions } = runtime.a2ui ?? {};
50
- if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _copilotkit_shared_event_transforms.A2UIMiddleware({
50
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _ag_ui_a2ui_middleware.A2UIMiddleware({
51
51
  ...a2uiOptions,
52
52
  injectA2UITool: injectA2UITool ?? (providerA2UIHasCatalog ? true : void 0)
53
53
  }));
54
54
  }
55
- if (require_runtime$1.isIntelligenceRuntime(runtime) && typeof agent.use === "function") {
55
+ if (require_runtime.isIntelligenceRuntime(runtime) && typeof agent.use === "function") {
56
56
  const mcpServers = require_mcp_apps_servers.resolveMcpAppsServers(runtime.mcpApps?.servers ?? [], agentId);
57
57
  if (mcpServers.length > 0 || isMcpProxyRequest) agent.use(new _ag_ui_mcp_apps_middleware.MCPAppsMiddleware({
58
58
  mcpServers,
@@ -65,7 +65,7 @@ function configureAgentForRequest(params) {
65
65
  if (runtime.openGenerativeUI) {
66
66
  const config = runtime.openGenerativeUI;
67
67
  const targetAgents = typeof config === "object" ? config.agents : void 0;
68
- if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new _copilotkit_shared_event_transforms.OpenGenerativeUIMiddleware());
68
+ if ((!targetAgents || targetAgents.includes(agentId)) && typeof agent.use === "function") agent.use(new require_open_generative_ui_middleware.OpenGenerativeUIMiddleware());
69
69
  }
70
70
  const generativeUI = runtime.generativeUI;
71
71
  const transport = params.providerGenerativeUITransport;
@@ -103,7 +103,7 @@ const NO_MIDDLEWARE_WARNING = "CopilotKitIntelligence.enableEnterpriseLearning i
103
103
  async function attachIntelligenceEnterpriseLearning(params) {
104
104
  const { runtime, request } = params;
105
105
  const agent = params.agent;
106
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return;
106
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return;
107
107
  const learningEnabled = runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;
108
108
  if (runtime.memory === void 0 && !learningEnabled) return;
109
109
  if (runtime.memory === void 0 && typeof agent.use !== "function") {
@@ -136,7 +136,7 @@ async function attachIntelligenceEnterpriseLearning(params) {
136
136
  }]));
137
137
  }
138
138
  function warnCompatibility(what, replacement) {
139
- if (typeof process !== "undefined" && typeof process.env !== "undefined" && process.env.SUPPRESS_TRANSFORMATION_WARNINGS) return;
139
+ if (typeof process !== "undefined" && typeof (0, _copilotkit_shared.processEnv)() !== "undefined" && (0, _copilotkit_shared.processEnv)().SUPPRESS_TRANSFORMATION_WARNINGS) return;
140
140
  console.warn(`[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`);
141
141
  }
142
142
  function isRecord(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","isIntelligenceRuntime","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","GenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","resolveIntelligenceUser","resolveWebMemory","grantAllowsMemory","errorResponse","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"sources":["../../../../src/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/core/schemas\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport {\n A2UIMiddleware,\n OpenGenerativeUIMiddleware,\n} from \"@copilotkit/shared/event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\n * The transport of the generative UI envelope that the client sent on this\n * run (`forwardedProps.copilotkit.ui`). Not set when the run has no envelope.\n */\n providerGenerativeUITransport?: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Shared by the two places a run meets a middleware-less agent: before Memory\n * is resolved (nothing left to resolve) and after (Memory resolved to nothing).\n */\nconst NO_MIDDLEWARE_WARNING =\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\";\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (!isIntelligenceRuntime(runtime)) return;\n\n const learningEnabled =\n runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;\n if (runtime.memory === undefined && !learningEnabled) return;\n\n // Nothing here is resolvable for an agent whose framework can't take\n // middleware and whose runtime configures no Memory — bail before paying for\n // `identifyUser`, so an enterprise-learning-only run keeps warning rather\n // than acquiring a new way to fail.\n if (runtime.memory === undefined && typeof agent.use !== \"function\") {\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n const memoryGranted =\n runtime.memory !== undefined && grantAllowsMemory(access.grant);\n\n // A policy that grants no scope means this run gets no Memory — it does NOT\n // mean the run is refused. Attach nothing and let the conversation proceed,\n // exactly as a Channel does when its grant asks for nothing\n // (`hasMemoryAccess` in @copilotkit/channels-core). Returning a 403 here\n // instead fails the whole run, so switching Memory off for one tenant would\n // leave that tenant with no assistant, and the only signal is a run error the\n // chat surface has no reason to render.\n //\n // Enterprise learning rides the SAME MCP server, so \"no Memory\" must not cost\n // an operator the learning tools too. When it is on, attach anyway and let\n // Intelligence filter: it registers one Memory tool per granted scope and\n // none at all for an all-none grant, leaving the learning tools untouched.\n if (!memoryGranted && !learningEnabled) return;\n\n // Whatever is left to attach needs middleware. Failing the run is right only\n // when Memory was actually granted and cannot be delivered; a run that merely\n // wanted learning tools warns and proceeds, as it always has.\n if (typeof agent.use !== \"function\") {\n if (memoryGranted) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\n// Intentional local exception: HTTP request parsing runs before AG-UI's event\n// compatibility boundary. Mirror its historically accepted optional-null rules\n// and its legacy binary-part upgrade here, without depending on a new public\n// AG-UI helper (AG-UI does not export one). Keep these aligned\n// with client/src/middleware/compatibility-boundary.ts and AG-UI's migration guide.\n// Required nulls and nulls within application data must remain untouched.\nfunction warnCompatibility(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof process.env !== \"undefined\" &&\n process.env.SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.warn(\n `[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction omitLegacyNull(\n value: unknown,\n field: string,\n context: string,\n): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\n const { [field]: _null, ...rest } = value;\n return rest;\n}\n\nfunction mapProtocolArray(\n value: unknown,\n field: string,\n normalize: (entry: unknown) => unknown,\n): unknown {\n if (!isRecord(value) || !Array.isArray(value[field])) return value;\n const original = value[field];\n const entries = original.map(normalize);\n return entries.some((entry, index) => entry !== original[index])\n ? { ...value, [field]: entries }\n : value;\n}\n\nfunction mediaTypeFor(\n mimeType: string,\n): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction sameSource(part: unknown, converted: Record<string, unknown>) {\n if (!isRecord(part) || part.type !== converted.type) return false;\n const a = part.source;\n const b = converted.source as Record<string, unknown>;\n return (\n isRecord(a) &&\n a.type === b.type &&\n a.value === b.value &&\n a.mimeType === b.mimeType\n );\n}\n\n/**\n * The 0.x `{ type: \"binary\" }` part, which 1.0 retired and main accepted.\n * Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):\n * data or url becomes the media part its mime type names, and a binary part\n * that only mirrors a modern part already in the message is dropped. A part\n * with only an `id` has no 1.0 form; it is dropped with a warning instead of\n * failing the whole request, which is what BuiltInAgent already did with it.\n */\nfunction upgradeLegacyBinaryParts(content: unknown[]): unknown[] {\n return content.flatMap((part) => {\n if (\n !isRecord(part) ||\n part.type !== \"binary\" ||\n typeof part.mimeType !== \"string\"\n )\n return [part];\n const kind =\n typeof part.data === \"string\"\n ? \"data\"\n : typeof part.url === \"string\"\n ? \"url\"\n : null;\n if (kind === null) {\n console.warn(\n \"[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.\",\n );\n return [];\n }\n warnCompatibility(\"binary input content\", \"the modern media content part\");\n const converted: Record<string, unknown> = {\n type: mediaTypeFor(part.mimeType),\n source: {\n type: kind,\n value: kind === \"data\" ? part.data : part.url,\n mimeType: part.mimeType,\n },\n ...(typeof part.filename === \"string\"\n ? { metadata: { filename: part.filename } }\n : {}),\n };\n return content.some((other) => sameSource(other, converted))\n ? []\n : [converted];\n });\n}\n\nfunction normalizeLegacyMessageContent(message: unknown): unknown {\n const upgraded =\n isRecord(message) &&\n Array.isArray(message.content) &&\n message.content.some((part) => isRecord(part) && part.type === \"binary\")\n ? {\n ...message,\n content: upgradeLegacyBinaryParts(message.content),\n }\n : message;\n return mapProtocolArray(upgraded, \"content\", (part) => {\n if (!isRecord(part)) return part;\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return omitLegacyNull(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): RunAgentInput {\n // With strictNullChecks disabled, Zod infers some required nested fields\n // (such as image.source) as optional. The schema still validates them.\n return RunAgentInputSchema.parse(\n normalizeLegacyRunAgentInput(value),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAmBhC;CACP,MAAM,EACJ,SACA,SACA,SACA,wBACA,sBACE;CACJ,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAIC,mDAAe;GACjB,GAAG;GAIH,gBACE,mBAAmB,yBAAyB,OAAO;GACtD,CAAC,CACH;;AAIL,KAAIC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AMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,YAAY;EAC7C,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","isIntelligenceRuntime","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","GenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","resolveIntelligenceUser","resolveWebMemory","grantAllowsMemory","errorResponse","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"sources":["../../../../src/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/core/schemas\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { OpenGenerativeUIMiddleware } from \"../../event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger, processEnv } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\n * The transport of the generative UI envelope that the client sent on this\n * run (`forwardedProps.copilotkit.ui`). Not set when the run has no envelope.\n */\n providerGenerativeUITransport?: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Shared by the two places a run meets a middleware-less agent: before Memory\n * is resolved (nothing left to resolve) and after (Memory resolved to nothing).\n */\nconst NO_MIDDLEWARE_WARNING =\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\";\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (!isIntelligenceRuntime(runtime)) return;\n\n const learningEnabled =\n runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;\n if (runtime.memory === undefined && !learningEnabled) return;\n\n // Nothing here is resolvable for an agent whose framework can't take\n // middleware and whose runtime configures no Memory — bail before paying for\n // `identifyUser`, so an enterprise-learning-only run keeps warning rather\n // than acquiring a new way to fail.\n if (runtime.memory === undefined && typeof agent.use !== \"function\") {\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n const memoryGranted =\n runtime.memory !== undefined && grantAllowsMemory(access.grant);\n\n // A policy that grants no scope means this run gets no Memory — it does NOT\n // mean the run is refused. Attach nothing and let the conversation proceed,\n // exactly as a Channel does when its grant asks for nothing\n // (`hasMemoryAccess` in @copilotkit/channels-core). Returning a 403 here\n // instead fails the whole run, so switching Memory off for one tenant would\n // leave that tenant with no assistant, and the only signal is a run error the\n // chat surface has no reason to render.\n //\n // Enterprise learning rides the SAME MCP server, so \"no Memory\" must not cost\n // an operator the learning tools too. When it is on, attach anyway and let\n // Intelligence filter: it registers one Memory tool per granted scope and\n // none at all for an all-none grant, leaving the learning tools untouched.\n if (!memoryGranted && !learningEnabled) return;\n\n // Whatever is left to attach needs middleware. Failing the run is right only\n // when Memory was actually granted and cannot be delivered; a run that merely\n // wanted learning tools warns and proceeds, as it always has.\n if (typeof agent.use !== \"function\") {\n if (memoryGranted) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\n// Intentional local exception: HTTP request parsing runs before AG-UI's event\n// compatibility boundary. Mirror its historically accepted optional-null rules\n// and its legacy binary-part upgrade here, without depending on a new public\n// AG-UI helper (AG-UI does not export one). Keep these aligned\n// with client/src/middleware/compatibility-boundary.ts and AG-UI's migration guide.\n// Required nulls and nulls within application data must remain untouched.\nfunction warnCompatibility(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.warn(\n `[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction omitLegacyNull(\n value: unknown,\n field: string,\n context: string,\n): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\n const { [field]: _null, ...rest } = value;\n return rest;\n}\n\nfunction mapProtocolArray(\n value: unknown,\n field: string,\n normalize: (entry: unknown) => unknown,\n): unknown {\n if (!isRecord(value) || !Array.isArray(value[field])) return value;\n const original = value[field];\n const entries = original.map(normalize);\n return entries.some((entry, index) => entry !== original[index])\n ? { ...value, [field]: entries }\n : value;\n}\n\nfunction mediaTypeFor(\n mimeType: string,\n): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction sameSource(part: unknown, converted: Record<string, unknown>) {\n if (!isRecord(part) || part.type !== converted.type) return false;\n const a = part.source;\n const b = converted.source as Record<string, unknown>;\n return (\n isRecord(a) &&\n a.type === b.type &&\n a.value === b.value &&\n a.mimeType === b.mimeType\n );\n}\n\n/**\n * The 0.x `{ type: \"binary\" }` part, which 1.0 retired and main accepted.\n * Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):\n * data or url becomes the media part its mime type names, and a binary part\n * that only mirrors a modern part already in the message is dropped. A part\n * with only an `id` has no 1.0 form; it is dropped with a warning instead of\n * failing the whole request, which is what BuiltInAgent already did with it.\n */\nfunction upgradeLegacyBinaryParts(content: unknown[]): unknown[] {\n return content.flatMap((part) => {\n if (\n !isRecord(part) ||\n part.type !== \"binary\" ||\n typeof part.mimeType !== \"string\"\n )\n return [part];\n const kind =\n typeof part.data === \"string\"\n ? \"data\"\n : typeof part.url === \"string\"\n ? \"url\"\n : null;\n if (kind === null) {\n console.warn(\n \"[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.\",\n );\n return [];\n }\n warnCompatibility(\"binary input content\", \"the modern media content part\");\n const converted: Record<string, unknown> = {\n type: mediaTypeFor(part.mimeType),\n source: {\n type: kind,\n value: kind === \"data\" ? part.data : part.url,\n mimeType: part.mimeType,\n },\n ...(typeof part.filename === \"string\"\n ? { metadata: { filename: part.filename } }\n : {}),\n };\n return content.some((other) => sameSource(other, converted))\n ? []\n : [converted];\n });\n}\n\nfunction normalizeLegacyMessageContent(message: unknown): unknown {\n const upgraded =\n isRecord(message) &&\n Array.isArray(message.content) &&\n message.content.some((part) => isRecord(part) && part.type === \"binary\")\n ? {\n ...message,\n content: upgradeLegacyBinaryParts(message.content),\n }\n : message;\n return mapProtocolArray(upgraded, \"content\", (part) => {\n if (!isRecord(part)) return part;\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return omitLegacyNull(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): RunAgentInput {\n // With strictNullChecks disabled, Zod infers some required nested fields\n // (such as image.source) as optional. The schema still validates them.\n return RunAgentInputSchema.parse(\n normalizeLegacyRunAgentInput(value),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,8BAAc,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,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Ac,CAChD;AACD,QAAO,iBACL,YACA,YACA,8BACD;;AAGH,SAAS,mBAAmB,OAA+B;AAGzD,QAAOC,wCAAoB,MACzB,6BAA6B,MAAM,CACpC;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;AAEF,SAAO,mBADa,MAAM,QAAQ,MAAM,CACF;UAC/B,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,YAAY;EAC7C,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -4,12 +4,13 @@ import { INTELLIGENCE_MEMORY_GRANT_HEADER, INTELLIGENCE_USER_ID_HEADER } from ".
4
4
  import { resolveIntelligenceUser } from "./resolve-intelligence-user.mjs";
5
5
  import { isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "../../core/runtime.mjs";
6
6
  import { GenerativeUIMiddleware } from "../../generative-ui/generative-ui-middleware.mjs";
7
+ import { OpenGenerativeUIMiddleware } from "../../event-transforms/open-generative-ui-middleware.mjs";
7
8
  import { resolveMcpAppsServers } from "./mcp-apps-servers.mjs";
8
9
  import { grantAllowsMemory, resolveWebMemory } from "./memory-policy.mjs";
9
- import { logger } from "@copilotkit/shared";
10
+ import { logger, processEnv } from "@copilotkit/shared";
11
+ import { A2UIMiddleware } from "@ag-ui/a2ui-middleware";
10
12
  import { MCPMiddleware } from "@ag-ui/mcp-middleware";
11
13
  import { RunAgentInputSchema } from "@ag-ui/core/schemas";
12
- import { A2UIMiddleware, OpenGenerativeUIMiddleware } from "@copilotkit/shared/event-transforms";
13
14
  import { MCPAppsMiddleware } from "@ag-ui/mcp-apps-middleware";
14
15
 
15
16
  //#region src/runtime/handlers/shared/agent-utils.ts
@@ -135,7 +136,7 @@ async function attachIntelligenceEnterpriseLearning(params) {
135
136
  }]));
136
137
  }
137
138
  function warnCompatibility(what, replacement) {
138
- if (typeof process !== "undefined" && typeof process.env !== "undefined" && process.env.SUPPRESS_TRANSFORMATION_WARNINGS) return;
139
+ if (typeof process !== "undefined" && typeof processEnv() !== "undefined" && processEnv().SUPPRESS_TRANSFORMATION_WARNINGS) return;
139
140
  console.warn(`[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`);
140
141
  }
141
142
  function isRecord(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/core/schemas\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport {\n A2UIMiddleware,\n OpenGenerativeUIMiddleware,\n} from \"@copilotkit/shared/event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\n * The transport of the generative UI envelope that the client sent on this\n * run (`forwardedProps.copilotkit.ui`). Not set when the run has no envelope.\n */\n providerGenerativeUITransport?: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Shared by the two places a run meets a middleware-less agent: before Memory\n * is resolved (nothing left to resolve) and after (Memory resolved to nothing).\n */\nconst NO_MIDDLEWARE_WARNING =\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\";\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (!isIntelligenceRuntime(runtime)) return;\n\n const learningEnabled =\n runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;\n if (runtime.memory === undefined && !learningEnabled) return;\n\n // Nothing here is resolvable for an agent whose framework can't take\n // middleware and whose runtime configures no Memory — bail before paying for\n // `identifyUser`, so an enterprise-learning-only run keeps warning rather\n // than acquiring a new way to fail.\n if (runtime.memory === undefined && typeof agent.use !== \"function\") {\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n const memoryGranted =\n runtime.memory !== undefined && grantAllowsMemory(access.grant);\n\n // A policy that grants no scope means this run gets no Memory — it does NOT\n // mean the run is refused. Attach nothing and let the conversation proceed,\n // exactly as a Channel does when its grant asks for nothing\n // (`hasMemoryAccess` in @copilotkit/channels-core). Returning a 403 here\n // instead fails the whole run, so switching Memory off for one tenant would\n // leave that tenant with no assistant, and the only signal is a run error the\n // chat surface has no reason to render.\n //\n // Enterprise learning rides the SAME MCP server, so \"no Memory\" must not cost\n // an operator the learning tools too. When it is on, attach anyway and let\n // Intelligence filter: it registers one Memory tool per granted scope and\n // none at all for an all-none grant, leaving the learning tools untouched.\n if (!memoryGranted && !learningEnabled) return;\n\n // Whatever is left to attach needs middleware. Failing the run is right only\n // when Memory was actually granted and cannot be delivered; a run that merely\n // wanted learning tools warns and proceeds, as it always has.\n if (typeof agent.use !== \"function\") {\n if (memoryGranted) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\n// Intentional local exception: HTTP request parsing runs before AG-UI's event\n// compatibility boundary. Mirror its historically accepted optional-null rules\n// and its legacy binary-part upgrade here, without depending on a new public\n// AG-UI helper (AG-UI does not export one). Keep these aligned\n// with client/src/middleware/compatibility-boundary.ts and AG-UI's migration guide.\n// Required nulls and nulls within application data must remain untouched.\nfunction warnCompatibility(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof process.env !== \"undefined\" &&\n process.env.SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.warn(\n `[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction omitLegacyNull(\n value: unknown,\n field: string,\n context: string,\n): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\n const { [field]: _null, ...rest } = value;\n return rest;\n}\n\nfunction mapProtocolArray(\n value: unknown,\n field: string,\n normalize: (entry: unknown) => unknown,\n): unknown {\n if (!isRecord(value) || !Array.isArray(value[field])) return value;\n const original = value[field];\n const entries = original.map(normalize);\n return entries.some((entry, index) => entry !== original[index])\n ? { ...value, [field]: entries }\n : value;\n}\n\nfunction mediaTypeFor(\n mimeType: string,\n): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction sameSource(part: unknown, converted: Record<string, unknown>) {\n if (!isRecord(part) || part.type !== converted.type) return false;\n const a = part.source;\n const b = converted.source as Record<string, unknown>;\n return (\n isRecord(a) &&\n a.type === b.type &&\n a.value === b.value &&\n a.mimeType === b.mimeType\n );\n}\n\n/**\n * The 0.x `{ type: \"binary\" }` part, which 1.0 retired and main accepted.\n * Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):\n * data or url becomes the media part its mime type names, and a binary part\n * that only mirrors a modern part already in the message is dropped. A part\n * with only an `id` has no 1.0 form; it is dropped with a warning instead of\n * failing the whole request, which is what BuiltInAgent already did with it.\n */\nfunction upgradeLegacyBinaryParts(content: unknown[]): unknown[] {\n return content.flatMap((part) => {\n if (\n !isRecord(part) ||\n part.type !== \"binary\" ||\n typeof part.mimeType !== \"string\"\n )\n return [part];\n const kind =\n typeof part.data === \"string\"\n ? \"data\"\n : typeof part.url === \"string\"\n ? \"url\"\n : null;\n if (kind === null) {\n console.warn(\n \"[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.\",\n );\n return [];\n }\n warnCompatibility(\"binary input content\", \"the modern media content part\");\n const converted: Record<string, unknown> = {\n type: mediaTypeFor(part.mimeType),\n source: {\n type: kind,\n value: kind === \"data\" ? part.data : part.url,\n mimeType: part.mimeType,\n },\n ...(typeof part.filename === \"string\"\n ? { metadata: { filename: part.filename } }\n : {}),\n };\n return content.some((other) => sameSource(other, converted))\n ? []\n : [converted];\n });\n}\n\nfunction normalizeLegacyMessageContent(message: unknown): unknown {\n const upgraded =\n isRecord(message) &&\n Array.isArray(message.content) &&\n message.content.some((part) => isRecord(part) && part.type === \"binary\")\n ? {\n ...message,\n content: upgradeLegacyBinaryParts(message.content),\n }\n : message;\n return mapProtocolArray(upgraded, \"content\", (part) => {\n if (!isRecord(part)) return part;\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return omitLegacyNull(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): RunAgentInput {\n // With strictNullChecks disabled, Zod infers some required nested fields\n // (such as image.source) as optional. The schema still validates them.\n return RunAgentInputSchema.parse(\n normalizeLegacyRunAgentInput(value),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB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cAAa,iBAAiB,YAAY,WAAW,UACnD,eAAe,OAAO,WAAW,cAAc,CAChD;AACD,QAAO,iBACL,YACA,YACA,8BACD;;AAGH,SAAS,mBAAmB,OAA+B;AAGzD,QAAO,oBAAoB,MACzB,6BAA6B,MAAM,CACpC;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;AAEF,SAAO,mBADa,MAAM,QAAQ,MAAM,CACF;UAC/B,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,YAAY;EAC7C,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/core/schemas\";\nimport type { CopilotKitUIEnvelope } from \"@copilotkit/shared\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { OpenGenerativeUIMiddleware } from \"../../event-transforms\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport { GenerativeUIMiddleware } from \"../../generative-ui\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger, processEnv } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n /**\n * The transport of the generative UI envelope that the client sent on this\n * run (`forwardedProps.copilotkit.ui`). Not set when the run has no envelope.\n */\n providerGenerativeUITransport?: CopilotKitUIEnvelope[\"metadata\"][\"extensions\"][\"copilotkit_transport\"];\n /** Retain proxy rejection even when no server is available to this agent. */\n isMcpProxyRequest?: boolean;\n}): void {\n const {\n runtime,\n request,\n agentId,\n providerA2UIHasCatalog,\n isMcpProxyRequest,\n } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (isIntelligenceRuntime(runtime) && typeof agent.use === \"function\") {\n // Ordinary runs need no middleware without selected servers. Proxy requests\n // still need the upstream guard so they cannot fall through to the model.\n const mcpServers = resolveMcpAppsServers(\n runtime.mcpApps?.servers ?? [],\n agentId,\n );\n if (mcpServers.length > 0 || isMcpProxyRequest) {\n agent.use(\n new MCPAppsMiddleware({ mcpServers, discoveryFailureMode: \"throw\" }),\n );\n }\n } else if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // A \"markdown\" envelope means the model writes ```a2ui fences, so the run\n // gets no render tool, even when the runtime turns generative UI on.\n const generativeUI = runtime.generativeUI;\n const transport = params.providerGenerativeUITransport;\n const isGenerativeUIRun =\n transport === \"tool\" || (transport !== \"markdown\" && !!generativeUI);\n if (\n isGenerativeUIRun &&\n generativeUI !== false &&\n typeof agent.use === \"function\"\n ) {\n const targetAgents =\n typeof generativeUI === \"object\" ? generativeUI.agents : undefined;\n if (!targetAgents || targetAgents.includes(agentId)) {\n agent.use(new GenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Shared by the two places a run meets a middleware-less agent: before Memory\n * is resolved (nothing left to resolve) and after (Memory resolved to nothing).\n */\nconst NO_MIDDLEWARE_WARNING =\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\";\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (!isIntelligenceRuntime(runtime)) return;\n\n const learningEnabled =\n runtime.intelligence?.ɵisEnterpriseLearningEnabled?.() === true;\n if (runtime.memory === undefined && !learningEnabled) return;\n\n // Nothing here is resolvable for an agent whose framework can't take\n // middleware and whose runtime configures no Memory — bail before paying for\n // `identifyUser`, so an enterprise-learning-only run keeps warning rather\n // than acquiring a new way to fail.\n if (runtime.memory === undefined && typeof agent.use !== \"function\") {\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n const memoryGranted =\n runtime.memory !== undefined && grantAllowsMemory(access.grant);\n\n // A policy that grants no scope means this run gets no Memory — it does NOT\n // mean the run is refused. Attach nothing and let the conversation proceed,\n // exactly as a Channel does when its grant asks for nothing\n // (`hasMemoryAccess` in @copilotkit/channels-core). Returning a 403 here\n // instead fails the whole run, so switching Memory off for one tenant would\n // leave that tenant with no assistant, and the only signal is a run error the\n // chat surface has no reason to render.\n //\n // Enterprise learning rides the SAME MCP server, so \"no Memory\" must not cost\n // an operator the learning tools too. When it is on, attach anyway and let\n // Intelligence filter: it registers one Memory tool per granted scope and\n // none at all for an all-none grant, leaving the learning tools untouched.\n if (!memoryGranted && !learningEnabled) return;\n\n // Whatever is left to attach needs middleware. Failing the run is right only\n // when Memory was actually granted and cannot be delivered; a run that merely\n // wanted learning tools warns and proceeds, as it always has.\n if (typeof agent.use !== \"function\") {\n if (memoryGranted) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(NO_MIDDLEWARE_WARNING);\n return;\n }\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\n// Intentional local exception: HTTP request parsing runs before AG-UI's event\n// compatibility boundary. Mirror its historically accepted optional-null rules\n// and its legacy binary-part upgrade here, without depending on a new public\n// AG-UI helper (AG-UI does not export one). Keep these aligned\n// with client/src/middleware/compatibility-boundary.ts and AG-UI's migration guide.\n// Required nulls and nulls within application data must remain untouched.\nfunction warnCompatibility(what: string, replacement: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof processEnv() !== \"undefined\" &&\n processEnv().SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.warn(\n `[ag-ui][compat] Converting deprecated ${what} to ${replacement}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction omitLegacyNull(\n value: unknown,\n field: string,\n context: string,\n): unknown {\n if (!isRecord(value) || value[field] !== null) return value;\n warnCompatibility(`${context}.${field}: null`, \"an absent field\");\n const { [field]: _null, ...rest } = value;\n return rest;\n}\n\nfunction mapProtocolArray(\n value: unknown,\n field: string,\n normalize: (entry: unknown) => unknown,\n): unknown {\n if (!isRecord(value) || !Array.isArray(value[field])) return value;\n const original = value[field];\n const entries = original.map(normalize);\n return entries.some((entry, index) => entry !== original[index])\n ? { ...value, [field]: entries }\n : value;\n}\n\nfunction mediaTypeFor(\n mimeType: string,\n): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction sameSource(part: unknown, converted: Record<string, unknown>) {\n if (!isRecord(part) || part.type !== converted.type) return false;\n const a = part.source;\n const b = converted.source as Record<string, unknown>;\n return (\n isRecord(a) &&\n a.type === b.type &&\n a.value === b.value &&\n a.mimeType === b.mimeType\n );\n}\n\n/**\n * The 0.x `{ type: \"binary\" }` part, which 1.0 retired and main accepted.\n * Mirrors AG-UI's outgoing upgrade (client/src/middleware/legacy-content.ts):\n * data or url becomes the media part its mime type names, and a binary part\n * that only mirrors a modern part already in the message is dropped. A part\n * with only an `id` has no 1.0 form; it is dropped with a warning instead of\n * failing the whole request, which is what BuiltInAgent already did with it.\n */\nfunction upgradeLegacyBinaryParts(content: unknown[]): unknown[] {\n return content.flatMap((part) => {\n if (\n !isRecord(part) ||\n part.type !== \"binary\" ||\n typeof part.mimeType !== \"string\"\n )\n return [part];\n const kind =\n typeof part.data === \"string\"\n ? \"data\"\n : typeof part.url === \"string\"\n ? \"url\"\n : null;\n if (kind === null) {\n console.warn(\n \"[CopilotKit] Dropping a legacy binary content part that has no data or url; AG-UI 1.0 has no equivalent for it.\",\n );\n return [];\n }\n warnCompatibility(\"binary input content\", \"the modern media content part\");\n const converted: Record<string, unknown> = {\n type: mediaTypeFor(part.mimeType),\n source: {\n type: kind,\n value: kind === \"data\" ? part.data : part.url,\n mimeType: part.mimeType,\n },\n ...(typeof part.filename === \"string\"\n ? { metadata: { filename: part.filename } }\n : {}),\n };\n return content.some((other) => sameSource(other, converted))\n ? []\n : [converted];\n });\n}\n\nfunction normalizeLegacyMessageContent(message: unknown): unknown {\n const upgraded =\n isRecord(message) &&\n Array.isArray(message.content) &&\n message.content.some((part) => isRecord(part) && part.type === \"binary\")\n ? {\n ...message,\n content: upgradeLegacyBinaryParts(message.content),\n }\n : message;\n return mapProtocolArray(upgraded, \"content\", (part) => {\n if (!isRecord(part)) return part;\n switch (part.type) {\n case \"image\":\n case \"audio\":\n case \"video\":\n case \"document\":\n return omitLegacyNull(part, \"metadata\", `${part.type} input content`);\n default:\n return part;\n }\n });\n}\n\nfunction normalizeLegacyRunAgentInput(input: unknown): unknown {\n let normalized = omitLegacyNull(input, \"forwardedProps\", \"RunAgentInput\");\n normalized = mapProtocolArray(normalized, \"tools\", (tool) =>\n omitLegacyNull(tool, \"parameters\", \"Tool\"),\n );\n normalized = mapProtocolArray(normalized, \"resume\", (entry) =>\n omitLegacyNull(entry, \"payload\", \"ResumeEntry\"),\n );\n return mapProtocolArray(\n normalized,\n \"messages\",\n normalizeLegacyMessageContent,\n );\n}\n\nfunction parseRunAgentInput(value: unknown): RunAgentInput {\n // With strictNullChecks disabled, Zod infers some required nested fields\n // (such as image.source) as optional. The schema still validates them.\n return RunAgentInputSchema.parse(\n normalizeLegacyRunAgentInput(value),\n ) as RunAgentInput;\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return parseRunAgentInput(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = parseRunAgentInput(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAM,cAAc,QAAQ,QAAQ,QA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J,SAAS,6BAA6B,OAAyB;CAC7D,IAAI,aAAa,eAAe,OAAO,kBAAkB,gBAAgB;AACzE,cAAa,iBAAiB,YAAY,UAAU,SAClD,eAAe,MAAM,cAAc,OAAO,CAC3C;AACD,cAAa,iBAAiB,YAAY,WAAW,UACnD,eAAe,OAAO,WAAW,cAAc,CAChD;AACD,QAAO,iBACL,YACA,YACA,8BACD;;AAGH,SAAS,mBAAmB,OAA+B;AAGzD,QAAO,oBAAoB,MACzB,6BAA6B,MAAM,CACpC;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;AAEF,SAAO,mBADa,MAAM,QAAQ,MAAM,CACF;UAC/B,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQ,mBAAmB,YAAY;EAC7C,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,SAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,4 +1,3 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
2
1
  let _copilotkit_shared = require("@copilotkit/shared");
3
2
 
4
3
  //#region src/runtime/handlers/shared/cloud-telemetry.ts
@@ -1 +1 @@
1
- {"version":3,"file":"cloud-telemetry.cjs","names":[],"sources":["../../../../src/runtime/handlers/shared/cloud-telemetry.ts"],"sourcesContent":["// The CopilotCloud guardrails flag on `oss.runtime.copilot_request_created`.\n//\n// It lives here because the v1 entrypoint used to compute it in its own\n// middleware and emit a second copy of the event. That copy is gone; this is\n// what it carried and the v2 handlers did not.\n//\n// The v1 copy also carried `cloud.base_url`, which is deliberately not\n// ported. The cross-language conformance suite pins this event to exactly\n// requestType, cloud.guardrails.enabled and cloud.api_key_provided\n// (`tools/runtime-conformance/telemetry-cases.mjs`), and the four native\n// runtimes send nothing else. A near-constant read off an env var is not\n// worth diverging the canonical event shape for.\n\nimport { readBody } from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/client\";\n\n/**\n * Whether the caller forwarded CopilotCloud guardrails configuration.\n *\n * Guardrails reach a runtime as `forwardedProps.cloud.guardrails`. An earlier\n * version read the body only when the CopilotCloud key header was present,\n * because in principle only a CopilotCloud client sends guardrails and that\n * client always sends its key. Production does not hold to that: of 112\n * guardrails-enabled requests over 90 days, 2 carried no key, and they\n * undercounted as `false`. The signal is rare enough — 13 people across 9\n * Cloud keys in a year — that losing 2% of it to save a body clone is a bad\n * trade, so the body is now always read.\n *\n * `readBody` clones rather than consuming, so the handler can still parse the\n * request afterwards.\n */\nexport async function readGuardrailsEnabled(\n request: Request,\n): Promise<boolean> {\n try {\n const body = (await readBody(request)) as RunAgentInput | undefined;\n const forwardedProps = body?.forwardedProps as\n | { cloud?: { guardrails?: unknown } }\n | undefined;\n return forwardedProps?.cloud?.guardrails !== undefined;\n } catch {\n // Telemetry must never decide whether a request is served.\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,eAAsB,sBACpB,SACkB;AAClB,KAAI;AAKF,WAJc,uCAAe,QAAQ,GACR,iBAGN,OAAO,eAAe;SACvC;AAEN,SAAO"}
1
+ {"version":3,"file":"cloud-telemetry.cjs","names":[],"sources":["../../../../src/runtime/handlers/shared/cloud-telemetry.ts"],"sourcesContent":["// The CopilotCloud guardrails flag on `oss.runtime.copilot_request_created`.\n//\n// It lives here because the v1 entrypoint used to compute it in its own\n// middleware and emit a second copy of the event. That copy is gone; this is\n// what it carried and the v2 handlers did not.\n//\n// The v1 copy also carried `cloud.base_url`, which is deliberately not\n// ported. The cross-language conformance suite pins this event to exactly\n// requestType, cloud.guardrails.enabled and cloud.api_key_provided\n// (`tools/runtime-conformance/telemetry-cases.mjs`), and the four native\n// runtimes send nothing else. A near-constant read off an env var is not\n// worth diverging the canonical event shape for.\n\nimport { readBody } from \"@copilotkit/shared\";\nimport type { RunAgentInput } from \"@ag-ui/client\";\n\n/**\n * Whether the caller forwarded CopilotCloud guardrails configuration.\n *\n * Guardrails reach a runtime as `forwardedProps.cloud.guardrails`. An earlier\n * version read the body only when the CopilotCloud key header was present,\n * because in principle only a CopilotCloud client sends guardrails and that\n * client always sends its key. Production does not hold to that: of 112\n * guardrails-enabled requests over 90 days, 2 carried no key, and they\n * undercounted as `false`. The signal is rare enough — 13 people across 9\n * Cloud keys in a year — that losing 2% of it to save a body clone is a bad\n * trade, so the body is now always read.\n *\n * `readBody` clones rather than consuming, so the handler can still parse the\n * request afterwards.\n */\nexport async function readGuardrailsEnabled(\n request: Request,\n): Promise<boolean> {\n try {\n const body = (await readBody(request)) as RunAgentInput | undefined;\n const forwardedProps = body?.forwardedProps as\n | { cloud?: { guardrails?: unknown } }\n | undefined;\n return forwardedProps?.cloud?.guardrails !== undefined;\n } catch {\n // Telemetry must never decide whether a request is served.\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+BA,eAAsB,sBACpB,SACkB;AAClB,KAAI;AAKF,WAJc,uCAAe,QAAQ,GACR,iBAGN,OAAO,eAAe;SACvC;AAEN,SAAO"}
@@ -19,7 +19,7 @@ const resolvedUsers = /* @__PURE__ */ new WeakMap();
19
19
  async function resolveIntelligenceUser(params) {
20
20
  const { runtime, request } = params;
21
21
  const existing = resolvedUsers.get(request);
22
- if (existing) return existing;
22
+ if (existing !== void 0) return existing;
23
23
  const resolution = resolveUser(runtime, request);
24
24
  resolvedUsers.set(request, resolution);
25
25
  return resolution;
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-intelligence-user.cjs","names":["errorResponse","isValidIdentifier","isIntelligenceRuntime"],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n CopilotRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n console.error(\"Error identifying user: identifyUser is not configured\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n console.error(\"Error identifying user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;AAgBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,SAAU,QAAO;CAErB,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,UAAQ,MAAM,yDAAyD;AACvE,SAAOA,oCAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAACC,6CAAkB,MAAM,GAAG,CAC9B,QAAOD,oCAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAWE,sCAAsB,QAAQ,CAC5C,QAAOF,oCAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,UAAQ,MAAM,2BAA2B,MAAM;AAC/C,SAAOA,oCAAc,2BAA2B,IAAI"}
1
+ {"version":3,"file":"resolve-intelligence-user.cjs","names":["errorResponse","isValidIdentifier","isIntelligenceRuntime"],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n CopilotRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing !== undefined) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n console.error(\"Error identifying user: identifyUser is not configured\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n console.error(\"Error identifying user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;AAgBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,aAAa,OAAW,QAAO;CAEnC,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,UAAQ,MAAM,yDAAyD;AACvE,SAAOA,oCAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAACC,6CAAkB,MAAM,GAAG,CAC9B,QAAOD,oCAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAWE,sCAAsB,QAAQ,CAC5C,QAAOF,oCAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,UAAQ,MAAM,2BAA2B,MAAM;AAC/C,SAAOA,oCAAc,2BAA2B,IAAI"}
@@ -19,7 +19,7 @@ const resolvedUsers = /* @__PURE__ */ new WeakMap();
19
19
  async function resolveIntelligenceUser(params) {
20
20
  const { runtime, request } = params;
21
21
  const existing = resolvedUsers.get(request);
22
- if (existing) return existing;
22
+ if (existing !== void 0) return existing;
23
23
  const resolution = resolveUser(runtime, request);
24
24
  resolvedUsers.set(request, resolution);
25
25
  return resolution;
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n CopilotRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n console.error(\"Error identifying user: identifyUser is not configured\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n console.error(\"Error identifying user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;AAgBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,SAAU,QAAO;CAErB,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,UAAQ,MAAM,yDAAyD;AACvE,SAAO,cAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAW,sBAAsB,QAAQ,CAC5C,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,UAAQ,MAAM,2BAA2B,MAAM;AAC/C,SAAO,cAAc,2BAA2B,IAAI"}
1
+ {"version":3,"file":"resolve-intelligence-user.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/resolve-intelligence-user.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n CopilotRuntimeUser,\n IdentifyUserCallback,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { errorResponse } from \"./json-response\";\nimport { isValidIdentifier } from \"./intelligence-utils\";\n\n/** A runtime whose `identifyUser` is known to be set. */\nexport type IdentifiedRuntimeLike = CopilotRuntimeLike & {\n identifyUser: IdentifyUserCallback;\n};\n\n/** Narrows a runtime to one that has `identifyUser`. */\nexport function hasIdentifyUser(\n runtime: CopilotRuntimeLike,\n): runtime is IdentifiedRuntimeLike {\n return typeof runtime.identifyUser === \"function\";\n}\n\nconst resolvedUsers = new WeakMap<\n Request,\n Promise<CopilotRuntimeUser | Response>\n>();\n\n/**\n * Resolves the request's user through `identifyUser`, once per request, for\n * both runtime kinds: the Intelligence runtime and an SSE runtime with\n * `identifyUser` (local Thread ownership). Only the Intelligence runtime\n * needs the user's `name`; an SSE runtime needs the `id` alone.\n *\n * A callback that throws gets a 500 on every route.\n */\nexport async function resolveIntelligenceUser(params: {\n runtime: CopilotIntelligenceRuntimeLike | IdentifiedRuntimeLike;\n request: Request;\n}): Promise<CopilotRuntimeUser | Response> {\n const { runtime, request } = params;\n\n const existing = resolvedUsers.get(request);\n if (existing !== undefined) return existing;\n\n const resolution = resolveUser(runtime, request);\n resolvedUsers.set(request, resolution);\n return resolution;\n}\n\nasync function resolveUser(\n runtime: CopilotRuntimeLike,\n request: Request,\n): Promise<CopilotRuntimeUser | Response> {\n if (!hasIdentifyUser(runtime)) {\n console.error(\"Error identifying user: identifyUser is not configured\");\n return errorResponse(\"Failed to identify user\", 500);\n }\n try {\n const user = await runtime.identifyUser(request);\n if (!isValidIdentifier(user?.id)) {\n return errorResponse(\"identifyUser must return a valid user id\", 400);\n }\n const hasName =\n typeof user?.name === \"string\" && user.name.trim().length > 0;\n if (!hasName && isIntelligenceRuntime(runtime)) {\n return errorResponse(\"identifyUser must return a valid user name\", 400);\n }\n\n return { id: user.id, name: hasName ? user.name : user.id };\n } catch (error) {\n console.error(\"Error identifying user:\", error);\n return errorResponse(\"Failed to identify user\", 500);\n }\n}\n"],"mappings":";;;;;;AAgBA,SAAgB,gBACd,SACkC;AAClC,QAAO,OAAO,QAAQ,iBAAiB;;AAGzC,MAAM,gCAAgB,IAAI,SAGvB;;;;;;;;;AAUH,eAAsB,wBAAwB,QAGH;CACzC,MAAM,EAAE,SAAS,YAAY;CAE7B,MAAM,WAAW,cAAc,IAAI,QAAQ;AAC3C,KAAI,aAAa,OAAW,QAAO;CAEnC,MAAM,aAAa,YAAY,SAAS,QAAQ;AAChD,eAAc,IAAI,SAAS,WAAW;AACtC,QAAO;;AAGT,eAAe,YACb,SACA,SACwC;AACxC,KAAI,CAAC,gBAAgB,QAAQ,EAAE;AAC7B,UAAQ,MAAM,yDAAyD;AACvE,SAAO,cAAc,2BAA2B,IAAI;;AAEtD,KAAI;EACF,MAAM,OAAO,MAAM,QAAQ,aAAa,QAAQ;AAChD,MAAI,CAAC,kBAAkB,MAAM,GAAG,CAC9B,QAAO,cAAc,4CAA4C,IAAI;EAEvE,MAAM,UACJ,OAAO,MAAM,SAAS,YAAY,KAAK,KAAK,MAAM,CAAC,SAAS;AAC9D,MAAI,CAAC,WAAW,sBAAsB,QAAQ,CAC5C,QAAO,cAAc,8CAA8C,IAAI;AAGzE,SAAO;GAAE,IAAI,KAAK;GAAI,MAAM,UAAU,KAAK,OAAO,KAAK;GAAI;UACpD,OAAO;AACd,UAAQ,MAAM,2BAA2B,MAAM;AAC/C,SAAO,cAAc,2BAA2B,IAAI"}