@copilotkit/runtime 2.0.0-rc.4 → 2.0.0-rc.40

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 (300) hide show
  1. package/README.md +28 -3
  2. package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -76
  3. package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
  4. package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
  5. package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
  6. package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
  7. package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
  8. package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
  9. package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
  10. package/dist/agent/ai-sdk.cjs +425 -0
  11. package/dist/agent/ai-sdk.cjs.map +1 -0
  12. package/dist/agent/ai-sdk.d.cts +119 -0
  13. package/dist/agent/ai-sdk.d.cts.map +1 -0
  14. package/dist/agent/ai-sdk.d.mts +119 -0
  15. package/dist/agent/ai-sdk.d.mts.map +1 -0
  16. package/dist/agent/ai-sdk.mjs +419 -0
  17. package/dist/agent/ai-sdk.mjs.map +1 -0
  18. package/dist/agent/classic-tools.cjs +185 -0
  19. package/dist/agent/classic-tools.cjs.map +1 -0
  20. package/dist/agent/classic-tools.mjs +183 -0
  21. package/dist/agent/classic-tools.mjs.map +1 -0
  22. package/dist/agent/converters/aisdk.cjs +16 -3
  23. package/dist/agent/converters/aisdk.cjs.map +1 -1
  24. package/dist/agent/converters/aisdk.d.cts.map +1 -1
  25. package/dist/agent/converters/aisdk.d.mts.map +1 -1
  26. package/dist/agent/converters/aisdk.mjs +18 -2
  27. package/dist/agent/converters/aisdk.mjs.map +1 -1
  28. package/dist/agent/converters/tanstack.cjs +201 -29
  29. package/dist/agent/converters/tanstack.cjs.map +1 -1
  30. package/dist/agent/converters/tanstack.d.cts +90 -6
  31. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  32. package/dist/agent/converters/tanstack.d.mts +90 -6
  33. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  34. package/dist/agent/converters/tanstack.mjs +201 -28
  35. package/dist/agent/converters/tanstack.mjs.map +1 -1
  36. package/dist/agent/learned-skills.cjs +15 -17
  37. package/dist/agent/learned-skills.cjs.map +1 -1
  38. package/dist/agent/learned-skills.d.cts +9 -3
  39. package/dist/agent/learned-skills.d.cts.map +1 -1
  40. package/dist/agent/learned-skills.d.mts +9 -3
  41. package/dist/agent/learned-skills.d.mts.map +1 -1
  42. package/dist/agent/learned-skills.mjs +15 -16
  43. package/dist/agent/learned-skills.mjs.map +1 -1
  44. package/dist/agent/model.cjs +42 -0
  45. package/dist/agent/model.cjs.map +1 -0
  46. package/dist/agent/model.d.cts +19 -0
  47. package/dist/agent/model.d.cts.map +1 -0
  48. package/dist/agent/model.d.mts +19 -0
  49. package/dist/agent/model.d.mts.map +1 -0
  50. package/dist/agent/model.mjs +41 -0
  51. package/dist/agent/model.mjs.map +1 -0
  52. package/dist/agent/state-delta.cjs +0 -1
  53. package/dist/agent/state-delta.cjs.map +1 -1
  54. package/dist/agent.cjs +558 -0
  55. package/dist/agent.cjs.map +1 -0
  56. package/dist/agent.d.cts +455 -0
  57. package/dist/agent.d.cts.map +1 -0
  58. package/dist/agent.d.mts +455 -0
  59. package/dist/agent.d.mts.map +1 -0
  60. package/dist/agent.mjs +551 -0
  61. package/dist/agent.mjs.map +1 -0
  62. package/dist/index.cjs +21 -27
  63. package/dist/index.d.cts +9 -11
  64. package/dist/index.d.mts +9 -11
  65. package/dist/index.mjs +5 -6
  66. package/dist/internal/learned-skills.d.cts +1 -1
  67. package/dist/internal/learned-skills.d.mts +1 -1
  68. package/dist/node.cjs +1 -2
  69. package/dist/node.d.cts +2 -2
  70. package/dist/node.d.mts +2 -2
  71. package/dist/node.mjs +2 -2
  72. package/dist/runtime/core/channel-manager.cjs +10 -2
  73. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  74. package/dist/runtime/core/channel-manager.d.cts +1 -1
  75. package/dist/runtime/core/channel-manager.d.mts +1 -1
  76. package/dist/runtime/core/channel-manager.mjs +10 -1
  77. package/dist/runtime/core/channel-manager.mjs.map +1 -1
  78. package/dist/runtime/core/debug-event-bus.cjs +0 -1
  79. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  80. package/dist/runtime/core/debug-event-bus.d.cts +1 -1
  81. package/dist/runtime/core/fetch-handler.cjs +7 -5
  82. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  83. package/dist/runtime/core/fetch-handler.d.cts +8 -0
  84. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  85. package/dist/runtime/core/fetch-handler.d.mts +8 -0
  86. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  87. package/dist/runtime/core/fetch-handler.mjs +4 -1
  88. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  89. package/dist/runtime/core/learning.d.cts +1 -1
  90. package/dist/runtime/core/logger.cjs +85 -13
  91. package/dist/runtime/core/logger.cjs.map +1 -1
  92. package/dist/runtime/core/logger.d.cts +21 -8
  93. package/dist/runtime/core/logger.d.cts.map +1 -1
  94. package/dist/runtime/core/logger.d.mts +21 -8
  95. package/dist/runtime/core/logger.d.mts.map +1 -1
  96. package/dist/runtime/core/logger.mjs +85 -10
  97. package/dist/runtime/core/logger.mjs.map +1 -1
  98. package/dist/runtime/core/middleware-sse-parser.cjs +0 -1
  99. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  100. package/dist/runtime/core/middleware.cjs +0 -1
  101. package/dist/runtime/core/middleware.cjs.map +1 -1
  102. package/dist/runtime/core/package-info.cjs +1 -1
  103. package/dist/runtime/core/package-info.mjs +1 -1
  104. package/dist/runtime/core/runtime.cjs +0 -1
  105. package/dist/runtime/core/runtime.cjs.map +1 -1
  106. package/dist/runtime/core/runtime.d.cts +3 -3
  107. package/dist/runtime/core/runtime.d.mts +3 -3
  108. package/dist/runtime/endpoints/auto-start-channels.cjs +0 -1
  109. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  110. package/dist/runtime/endpoints/node-fetch-handler.cjs +0 -4
  111. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  112. package/dist/runtime/endpoints/node-fetch-handler.d.cts +1 -3
  113. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  114. package/dist/runtime/endpoints/node-fetch-handler.d.mts +1 -3
  115. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  116. package/dist/runtime/endpoints/node-fetch-handler.mjs +1 -3
  117. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  118. package/dist/runtime/event-transforms/index.d.cts +4 -0
  119. package/dist/runtime/event-transforms/index.d.mts +4 -0
  120. package/dist/runtime/event-transforms/index.mjs +5 -0
  121. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  122. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  123. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  124. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  125. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  126. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  127. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  128. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  129. package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
  130. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  131. package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
  132. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  133. package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
  134. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  135. package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
  136. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  137. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  138. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  139. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  140. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  141. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  142. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  143. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  144. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  145. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  146. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  147. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  148. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  149. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  150. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  151. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  152. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  153. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  154. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  155. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  156. package/dist/runtime/handlers/handle-run.cjs +8 -6
  157. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  158. package/dist/runtime/handlers/handle-run.mjs +5 -2
  159. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  160. package/dist/runtime/handlers/handle-stop.cjs +3 -4
  161. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  162. package/dist/runtime/handlers/handle-suggest.cjs +4 -3
  163. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  164. package/dist/runtime/handlers/handle-suggest.mjs +4 -2
  165. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  166. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  167. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  168. package/dist/runtime/handlers/intelligence/annotate.cjs +2 -3
  169. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  170. package/dist/runtime/handlers/intelligence/memories.cjs +7 -8
  171. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  172. package/dist/runtime/handlers/intelligence/run.cjs +24 -18
  173. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  174. package/dist/runtime/handlers/intelligence/run.mjs +24 -17
  175. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  176. package/dist/runtime/handlers/intelligence/thread-names.cjs +0 -1
  177. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  178. package/dist/runtime/handlers/intelligence/threads.cjs +6 -7
  179. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  180. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  181. package/dist/runtime/handlers/shared/agent-utils.cjs +9 -9
  182. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  183. package/dist/runtime/handlers/shared/agent-utils.mjs +2 -1
  184. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  185. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  186. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  187. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +1 -1
  188. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  189. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +1 -1
  190. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  191. package/dist/runtime/handlers/shared/sse-response.cjs +72 -64
  192. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  193. package/dist/runtime/handlers/shared/sse-response.mjs +72 -63
  194. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  195. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  196. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  197. package/dist/runtime/index.d.cts +8 -15
  198. package/dist/runtime/index.d.mts +8 -15
  199. package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
  200. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
  201. package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
  202. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
  203. package/dist/runtime/intelligence-platform/client.cjs +27 -1
  204. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  205. package/dist/runtime/intelligence-platform/client.d.cts +24 -1
  206. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  207. package/dist/runtime/intelligence-platform/client.d.mts +24 -1
  208. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  209. package/dist/runtime/intelligence-platform/client.mjs +27 -0
  210. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  211. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  212. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  213. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  214. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  215. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  216. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  217. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  218. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  219. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  220. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  221. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  222. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  223. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  224. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  225. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  226. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  227. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
  228. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  229. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  230. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  231. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
  232. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  233. package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
  234. package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
  235. package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
  236. package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
  237. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +0 -1
  238. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  239. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  240. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  241. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  242. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  243. package/dist/runtime/node.d.cts +1 -1
  244. package/dist/runtime/node.d.mts +1 -1
  245. package/dist/runtime/runner/agent-runner.cjs +0 -1
  246. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  247. package/dist/runtime/runner/agent-runner.d.cts +9 -0
  248. package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
  249. package/dist/runtime/runner/agent-runner.d.mts +9 -0
  250. package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
  251. package/dist/runtime/runner/agent-runner.mjs.map +1 -1
  252. package/dist/runtime/runner/in-memory.cjs +0 -1
  253. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  254. package/dist/runtime/runner/index.d.cts +1 -1
  255. package/dist/runtime/runner/index.d.mts +1 -1
  256. package/dist/runtime/runner/index.mjs +1 -1
  257. package/dist/runtime/runner/intelligence.cjs +50 -6
  258. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  259. package/dist/runtime/runner/intelligence.d.cts +8 -1
  260. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  261. package/dist/runtime/runner/intelligence.d.mts +8 -1
  262. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  263. package/dist/runtime/runner/intelligence.mjs +50 -6
  264. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  265. package/dist/runtime/telemetry/disclosure.cjs +0 -1
  266. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  267. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  268. package/dist/runtime/telemetry/events.d.cts +1 -1
  269. package/dist/runtime/telemetry/events.d.mts +1 -1
  270. package/dist/runtime/telemetry/instance-created.cjs +33 -12
  271. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  272. package/dist/runtime/telemetry/instance-created.mjs +33 -12
  273. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  274. package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
  275. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  276. package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
  277. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  278. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  279. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  280. package/package.json +56 -27
  281. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  282. package/dist/agent/converters/index.d.mts +0 -2
  283. package/dist/agent/index.cjs +0 -1328
  284. package/dist/agent/index.cjs.map +0 -1
  285. package/dist/agent/index.d.cts +0 -467
  286. package/dist/agent/index.d.cts.map +0 -1
  287. package/dist/agent/index.d.mts +0 -468
  288. package/dist/agent/index.d.mts.map +0 -1
  289. package/dist/agent/index.mjs +0 -1318
  290. package/dist/agent/index.mjs.map +0 -1
  291. package/dist/agent/mcp-tool-names.cjs +0 -82
  292. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  293. package/dist/agent/mcp-tool-names.mjs +0 -80
  294. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  295. package/dist/agent/url-download.cjs.map +0 -1
  296. package/dist/agent/url-download.d.cts.map +0 -1
  297. package/dist/agent/url-download.d.mts.map +0 -1
  298. package/dist/agent/url-download.mjs.map +0 -1
  299. package/dist/runtime/index.d.cts.map +0 -1
  300. package/dist/runtime/index.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../src/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MAAI,OAAO,KAAK,KAAK,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CAClD,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAE1E,MAAI,EAAE,WAAW,MAAO,QAAO,EAAE;AACjC,MAAI,OAAO,KAAK,UAAU,YAAY,CAAC,KAAK,MAAM,MAAM,CACtD,QAAO,SAAS,KAAK,EAAE,OAAO,iBAAiB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAEnE,SAAO,EAAE,OAAO,KAAK,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F;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AASH,MAAI,CANY,MAAM,QAAQ,OAAO,KAAK;GACxC,UAAU;GACV,GAAI,UAAU,SAAY,EAAE,GAAG,EAAE,OAAO;GACxC,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"handle-stop.cjs","names":["isHandlerResponse","isIntelligenceRuntime","resolveLocalThreadOwner","resolveIntelligenceUser","getPlatformErrorStatus","resolveAgents","EventType"],"sources":["../../../src/runtime/handlers/handle-stop.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport { isIntelligenceRuntime, resolveAgents } from \"../core/runtime\";\nimport { EventType } from \"@ag-ui/client\";\nimport { resolveIntelligenceUser } from \"./shared/resolve-intelligence-user\";\nimport { isHandlerResponse } from \"./shared/json-response\";\nimport { getPlatformErrorStatus } from \"./shared/intelligence-utils\";\nimport { resolveLocalThreadOwner } from \"./shared/thread-access\";\n\ninterface StopAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n threadId: string;\n}\n\n/** Read `{ runId? }` from a stop request body; a 400 Response when the body is not a valid scope. */\nasync function parseStopScope(\n request: Request,\n): Promise<{ runId?: string } | Response> {\n try {\n const raw = await request.text();\n const body: unknown = raw.trim() ? JSON.parse(raw) : {};\n if (typeof body !== \"object\" || body === null || Array.isArray(body)) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n // Only `runId` is allowed. A misspelt key must not fall through to a\n // thread-wide stop, because a stop cannot be undone.\n if (Object.keys(body).some((key) => key !== \"runId\")) {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n if (!(\"runId\" in body)) return {};\n if (typeof body.runId !== \"string\" || !body.runId.trim()) {\n return Response.json({ error: \"Invalid runId\" }, { status: 400 });\n }\n return { runId: body.runId };\n } catch {\n return Response.json({ error: \"Invalid stop request\" }, { status: 400 });\n }\n}\n\n/** Stop an active run after applying the runtime's application identity policy. */\nexport async function handleStopAgent({\n runtime,\n request,\n agentId,\n threadId,\n}: StopAgentParameters): Promise<Response> {\n try {\n // Parse the optional run scope for every runtime kind, from a clone so an\n // identity callback can still read the original body. No body or `{}`\n // keeps the thread-wide stop existing clients rely on.\n const scope = await parseStopScope(request.clone());\n if (isHandlerResponse(scope)) return scope;\n const { runId } = scope;\n let stopThreadId = threadId;\n let ownerId: string | undefined;\n if (!isIntelligenceRuntime(runtime)) {\n // A run on another identity's thread reports \"no active run\".\n const owner = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"stop\",\n });\n if (isHandlerResponse(owner)) return owner;\n ownerId = owner;\n } else {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n try {\n const thread = await runtime.intelligence.getThread({\n threadId,\n userId: user.id,\n });\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n return Response.json(\n { error: \"Invalid thread response\" },\n { status: 502 },\n );\n }\n if (thread.agentId !== undefined && thread.agentId !== agentId) {\n return Response.json(\n { error: \"Thread access denied\" },\n { status: 403 },\n );\n }\n stopThreadId = thread.id;\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n return Response.json(\n { error: \"Thread access denied\" },\n { status: status && status >= 400 && status < 500 ? status : 502 },\n );\n }\n }\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n const stopped = await runtime.runner.stop({\n threadId: stopThreadId,\n ...(runId === undefined ? {} : { runId }),\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n\n if (!stopped) {\n return new Response(\n JSON.stringify({\n stopped: false,\n message:\n runId === undefined\n ? `No active run for thread '${threadId}'.`\n : `Run '${runId}' is not the active run for thread '${threadId}'.`,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return new Response(\n JSON.stringify({\n stopped: true,\n interrupt: {\n type: EventType.RUN_ERROR,\n message: \"Run stopped by user\",\n code: \"STOPPED\",\n },\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n console.error(\"Error stopping agent run:\", error);\n\n return new Response(\n JSON.stringify({\n error: \"Failed to stop agent\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,eAAe,eACb,SACwC;AACxC,KAAI;EACF,MAAM,MAAM,MAAM,QAAQ,MAAM;EAChC,MAAM,OAAgB,IAAI,MAAM,GAAG,KAAK,MAAM,IAAI,GAAG,EAAE;AACvD,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,MAAM,QAAQ,KAAK,CAClE,QAAO,SAAS,KAAK,EAAE,OAAO,wBAAwB,EAAE,EAAE,QAAQ,KAAK,CAAC;AAI1E,MA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,QAAQ,KAAK,CAChB;AAEH,mBAAe,OAAO;YACf,OAAO;IACd,MAAM,SAASI,kDAAuB,MAAM;AAC5C,WAAO,SAAS,KACd,EAAE,OAAO,wBAAwB,EACjC,EAAE,QAAQ,UAAU,UAAU,OAAO,SAAS,MAAM,SAAS,KAAK,CACnE;;;AAKL,MAAI,EAFW,MAAMC,8BAAc,QAAQ,QAAQ,QAAQ,EAE/C,SACV,QAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,UAAU,QAAQ;GAC5B,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AASH,MAAI,CANY,MAAM,QAAQ,OAAO,KAAK;GACxC,UAAU;GACV,GAAI,UAAU,SAAY,EAAE,GAAG,EAAE,OAAO;GACxC,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC,CAGA,QAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,SACE,UAAU,SACN,6BAA6B,SAAS,MACtC,QAAQ,MAAM,sCAAsC,SAAS;GACpE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;AAGH,SAAO,IAAI,SACT,KAAK,UAAU;GACb,SAAS;GACT,WAAW;IACT,MAAMC,wBAAU;IAChB,SAAS;IACT,MAAM;IACP;GACF,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AACd,UAAQ,MAAM,6BAA6B,MAAM;AAEjD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU;GACnD,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -1,5 +1,5 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_header_utils = require('./header-utils.cjs');
2
+ const require_analytics_context = require('../intelligence-platform/analytics-context.cjs');
3
3
  const require_agent_utils = require('./shared/agent-utils.cjs');
4
4
  const require_sse_response = require('./shared/sse-response.cjs');
5
5
  let _copilotkit_shared = require("@copilotkit/shared");
@@ -43,8 +43,9 @@ async function handleSuggestAgent({ runtime, request, agentId }) {
43
43
  const agent = await require_agent_utils.cloneAgentForRequest(runtime, agentId, request);
44
44
  if (agent instanceof Response) return agent;
45
45
  agent.agentId = agentId;
46
- const input = await require_agent_utils.parseRunRequest(request);
47
- if (input instanceof Response) return input;
46
+ const parsed = await require_agent_utils.parseRunRequest(request);
47
+ if (parsed instanceof Response) return parsed;
48
+ const { input } = require_analytics_context.takeAnalyticsContext(parsed);
48
49
  const headerCarryingAgent = agent;
49
50
  headerCarryingAgent.headers = require_header_utils.mergeForwardableHeaders(headerCarryingAgent.headers, request, runtime.forwardHeadersPolicy ?? require_header_utils.resolveForwardHeadersPolicy(void 0));
50
51
  agent.setMessages(input.messages);
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAMC,oCAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.cjs","names":["cloneAgentForRequest","parseRunRequest","takeAnalyticsContext","mergeForwardableHeaders","resolveForwardHeadersPolicy","createSseEventResponse","Observable"],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const parsed = await parseRunRequest(request);\n if (parsed instanceof Response) {\n return parsed;\n }\n // Suggestions are not Intelligence runs, so an app's analytics context goes\n // nowhere from here; it is only kept away from the agent.\n const { input } = takeAnalyticsContext(parsed);\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAMA,yCAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,SAAS,MAAMC,oCAAgB,QAAQ;AAC7C,KAAI,kBAAkB,SACpB,QAAO;CAIT,MAAM,EAAE,UAAUC,+CAAqB,OAAO;CAc9C,MAAM,sBAAsB;AAG5B,qBAAoB,UAAUC,6CAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwBC,iDAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAOC,4CAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAIC,iBAAuB,eAAe;GAMxC,MAAM,6DAAqC;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "./header-utils.mjs";
2
+ import { takeAnalyticsContext } from "../intelligence-platform/analytics-context.mjs";
2
3
  import { cloneAgentForRequest, parseRunRequest } from "./shared/agent-utils.mjs";
3
4
  import { createSseEventResponse } from "./shared/sse-response.mjs";
4
5
  import { createRunEventFinalizer } from "@copilotkit/shared";
@@ -42,8 +43,9 @@ async function handleSuggestAgent({ runtime, request, agentId }) {
42
43
  const agent = await cloneAgentForRequest(runtime, agentId, request);
43
44
  if (agent instanceof Response) return agent;
44
45
  agent.agentId = agentId;
45
- const input = await parseRunRequest(request);
46
- if (input instanceof Response) return input;
46
+ const parsed = await parseRunRequest(request);
47
+ if (parsed instanceof Response) return parsed;
48
+ const { input } = takeAnalyticsContext(parsed);
47
49
  const headerCarryingAgent = agent;
48
50
  headerCarryingAgent.headers = mergeForwardableHeaders(headerCarryingAgent.headers, request, runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(void 0));
49
51
  agent.setMessages(input.messages);
@@ -1 +1 @@
1
- {"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const input = await parseRunRequest(request);\n if (input instanceof Response) {\n return input;\n }\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,QAAQ,MAAM,gBAAgB,QAAQ;AAC5C,KAAI,iBAAiB,SACnB,QAAO;CAeT,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAI,YAAuB,eAAe;GAMxC,MAAM,YAAY,yBAAyB;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
1
+ {"version":3,"file":"handle-suggest.mjs","names":[],"sources":["../../../src/runtime/handlers/handle-suggest.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent } from \"@ag-ui/client\";\nimport { createRunEventFinalizer } from \"@copilotkit/shared\";\nimport { Observable } from \"rxjs\";\nimport type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"./header-utils\";\nimport { cloneAgentForRequest, parseRunRequest } from \"./shared/agent-utils\";\nimport { createSseEventResponse } from \"./shared/sse-response\";\nimport { takeAnalyticsContext } from \"../intelligence-platform/analytics-context\";\n\n/**\n * Parameters for {@link handleSuggestAgent}.\n */\ninterface SuggestAgentParameters {\n /** The runtime whose registry the agent is resolved from. */\n runtime: CopilotRuntimeLike;\n /** The incoming `POST /agent/:agentId/suggest` request. */\n request: Request;\n /** The route-resolved agent id to run. */\n agentId: string;\n}\n\n/**\n * Stateless suggestion run.\n *\n * Executes the provider agent **directly** and streams its AG-UI events back as\n * SSE — the same wire format as `/agent/:id/run`, so the client consumes it with\n * the stock `HttpAgent` transport and chips fill in as the provider emits them.\n * It deliberately does not go through `runtime.runner`: the runner's\n * `run()` writes to a module-level store keyed by threadId (backing the SSE\n * runtime's local thread endpoints), which would leak the throwaway suggestion\n * thread. This handler runs the agent's event pipeline **without** that\n * persistence — no thread, lock, gateway, name-gen, or run telemetry — so\n * dynamic suggestions are side-effect-free in every runtime mode.\n *\n * The only per-request configuration it applies is forwarding the request's\n * allowlisted headers (`authorization` + `x-*`) onto the agent clone. It does\n * **not** attach any request middleware — no A2UI, no MCPApps, no\n * OpenGenerativeUI, no Intelligence enterprise-learning tools. The **client**\n * (the core suggestion engine) forces `toolChoice: copilotkitSuggest` in the\n * request body; this handler does not set tool choice itself and relies on it\n * being present in the incoming `input`. Given that forced tool choice, any\n * middleware-injected tools are dead weight, and MCPApps setup can incur a\n * `listTools` network round-trip per suggestion under `available: \"always\"` — a\n * side effect this path must never pay.\n *\n * When the client aborts the HTTP request (via its `AbortController`), the\n * server-side run is cancelled best-effort so an aborted suggestion does not\n * keep running a provider call to completion.\n *\n * @param params - The runtime, request, and resolved agent id.\n * @returns A `text/event-stream` `Response` of the provider agent's AG-UI events\n * on success, or the resolution `Response` (e.g. 404/400) when agent/body\n * resolution fails before streaming begins.\n */\nexport async function handleSuggestAgent({\n runtime,\n request,\n agentId,\n}: SuggestAgentParameters): Promise<Response> {\n const agent = await cloneAgentForRequest(runtime, agentId, request);\n if (agent instanceof Response) {\n return agent;\n }\n\n // Carry the registry key onto the clone so any framework relying on it during\n // the run sees the correct agentId.\n agent.agentId = agentId;\n\n const parsed = await parseRunRequest(request);\n if (parsed instanceof Response) {\n return parsed;\n }\n // Suggestions are not Intelligence runs, so an app's analytics context goes\n // nowhere from here; it is only kept away from the agent.\n const { input } = takeAnalyticsContext(parsed);\n\n // Forward eligible inbound headers onto the clone under the runtime's resolved\n // forwarding policy (same helper the run handler uses: `authorization` /\n // custom `x-*`, infra/proxy/platform headers denylisted, server-set headers\n // winning on collision — #5712). Unlike a full agent run, the suggest path\n // intentionally attaches no middleware (see the handler docblock): the forced\n // `copilotkitSuggest` tool choice makes any middleware-injected tools dead\n // weight, and MCPApps setup can trigger a `listTools` network round-trip we\n // must never incur per suggestion.\n //\n // `AbstractAgent` doesn't declare `headers` on its base type (concrete\n // framework agents add it), so narrow to the header-carrying shape rather\n // than casting to `any`.\n const headerCarryingAgent = agent as AbstractAgent & {\n headers?: Record<string, string>;\n };\n headerCarryingAgent.headers = mergeForwardableHeaders(\n headerCarryingAgent.headers,\n request,\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n\n agent.setMessages(input.messages);\n agent.setState(input.state);\n agent.threadId = input.threadId;\n\n // Stream the provider agent's events over SSE without persistence. This is\n // the runner's event pipeline (`agent.runAgent({ onEvent })` + terminal-event\n // finalization) minus the `GLOBAL_STORE` writes that would leak a thread.\n // `captureTelemetry: false` keeps suggestions out of run telemetry; omitting\n // `debugEventBus` keeps them out of the inspector's run trace.\n return createSseEventResponse({\n request,\n agentId,\n captureTelemetry: false,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n new Observable<BaseEvent>((subscriber) => {\n // Tracks open message/tool lifecycles so the missing terminal events\n // (an unclosed message/tool call, or a `RUN_FINISHED`) can be appended\n // — the same closure the runner applies — so the client sees a\n // well-formed AG-UI sequence. Nothing is persisted here, so only the\n // open ids are kept, never the streamed events themselves.\n const finalizer = createRunEventFinalizer();\n let settled = false;\n\n void agent\n .runAgent(input, {\n onEvent: ({ event }) => {\n finalizer.observe(event);\n subscriber.next(event);\n },\n })\n .then(() => {\n for (const event of finalizer.finalize({ stopRequested: false })) {\n subscriber.next(event);\n }\n settled = true;\n subscriber.complete();\n })\n .catch((error: unknown) => {\n settled = true;\n subscriber.error(error);\n });\n\n // Teardown fires when the response stream is torn down (client abort /\n // disconnect). Cancel the still-running provider call best-effort.\n return () => {\n if (!settled && typeof agent.abortRun === \"function\") {\n try {\n agent.abortRun();\n } catch {\n // best-effort — nothing actionable if aborting the run fails.\n }\n }\n };\n }),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,mBAAmB,EACvC,SACA,SACA,WAC4C;CAC5C,MAAM,QAAQ,MAAM,qBAAqB,SAAS,SAAS,QAAQ;AACnE,KAAI,iBAAiB,SACnB,QAAO;AAKT,OAAM,UAAU;CAEhB,MAAM,SAAS,MAAM,gBAAgB,QAAQ;AAC7C,KAAI,kBAAkB,SACpB,QAAO;CAIT,MAAM,EAAE,UAAU,qBAAqB,OAAO;CAc9C,MAAM,sBAAsB;AAG5B,qBAAoB,UAAU,wBAC5B,oBAAoB,SACpB,SACA,QAAQ,wBAAwB,4BAA4B,OAAU,CACvE;AAED,OAAM,YAAY,MAAM,SAAS;AACjC,OAAM,SAAS,MAAM,MAAM;AAC3B,OAAM,WAAW,MAAM;AAOvB,QAAO,uBAAuB;EAC5B;EACA;EACA,kBAAkB;EAClB,0BAA0B,QAAQ;EAClC,yBACE,IAAI,YAAuB,eAAe;GAMxC,MAAM,YAAY,yBAAyB;GAC3C,IAAI,UAAU;AAEd,GAAK,MACF,SAAS,OAAO,EACf,UAAU,EAAE,YAAY;AACtB,cAAU,QAAQ,MAAM;AACxB,eAAW,KAAK,MAAM;MAEzB,CAAC,CACD,WAAW;AACV,SAAK,MAAM,SAAS,UAAU,SAAS,EAAE,eAAe,OAAO,CAAC,CAC9D,YAAW,KAAK,MAAM;AAExB,cAAU;AACV,eAAW,UAAU;KACrB,CACD,OAAO,UAAmB;AACzB,cAAU;AACV,eAAW,MAAM,MAAM;KACvB;AAIJ,gBAAa;AACX,QAAI,CAAC,WAAW,OAAO,MAAM,aAAa,WACxC,KAAI;AACF,WAAM,UAAU;YACV;;IAKZ;EACL,CAAC"}
@@ -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/handle-transcribe.ts
@@ -1 +1 @@
1
- {"version":3,"file":"handle-transcribe.cjs","names":["TranscriptionErrorCode","TranscriptionErrors"],"sources":["../../../src/runtime/handlers/handle-transcribe.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n} from \"@copilotkit/shared\";\nimport type { TranscriptionErrorResponse } from \"@copilotkit/shared\";\n\n/**\n * HTTP status codes for transcription error codes\n */\nconst ERROR_STATUS_CODES: Record<TranscriptionErrorCode, number> = {\n [TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,\n [TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,\n [TranscriptionErrorCode.RATE_LIMITED]: 429,\n [TranscriptionErrorCode.AUTH_FAILED]: 401,\n [TranscriptionErrorCode.PROVIDER_ERROR]: 500,\n [TranscriptionErrorCode.NETWORK_ERROR]: 502,\n [TranscriptionErrorCode.INVALID_REQUEST]: 400,\n};\n\ninterface HandleTranscribeParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface Base64AudioInput {\n audio: string; // base64-encoded audio data\n mimeType: string;\n filename?: string;\n}\n\nconst VALID_AUDIO_TYPES = [\n \"audio/mpeg\",\n \"audio/mp3\",\n \"audio/mp4\",\n \"audio/wav\",\n \"audio/webm\",\n \"audio/ogg\",\n \"audio/flac\",\n \"audio/aac\",\n];\n\nfunction isValidAudioType(type: string): boolean {\n // Extract base MIME type (before semicolon) to handle types like \"audio/webm; codecs=opus\"\n const baseType = type.split(\";\")[0]?.trim() ?? \"\";\n return (\n VALID_AUDIO_TYPES.includes(baseType) ||\n baseType === \"\" ||\n baseType === \"application/octet-stream\"\n );\n}\n\nfunction createErrorResponse(\n errorResponse: TranscriptionErrorResponse,\n): Response {\n const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;\n return new Response(JSON.stringify(errorResponse), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction base64ToFile(\n base64: string,\n mimeType: string,\n filename: string,\n): File {\n // Remove data URL prefix if present (e.g., \"data:audio/webm;base64,\")\n const base64Data = base64.includes(\",\")\n ? (base64.split(\",\")[1] ?? base64)\n : base64;\n\n // Decode base64 to binary\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n // Create File object\n return new File([bytes], filename, { type: mimeType });\n}\n\nasync function extractAudioFromFormData(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n const formData = await request.formData();\n let audioFile = formData.get(\"audio\") as File | null;\n\n if (!audioFile || !(audioFile instanceof File)) {\n const err = TranscriptionErrors.invalidRequest(\n \"No audio file found in form data. Please include an 'audio' field.\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(audioFile.type)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n audioFile.type,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n // Browser MediaRecorder Blobs often arrive at the server with their\n // `type` field empty (and `application/octet-stream` is also accepted by\n // isValidAudioType for compatibility). OpenAI Whisper rejects files\n // without a recognizable MIME / extension with a 502 \"Invalid file\n // format\" — even though the bytes themselves are valid WebM Opus.\n // Stamp `audio/webm` (the standard MediaRecorder default in Chromium /\n // Firefox / Safari) so Whisper can pick the right decoder.\n if (!audioFile.type || audioFile.type === \"application/octet-stream\") {\n audioFile = new File([audioFile], audioFile.name || \"recording.webm\", {\n type: \"audio/webm\",\n });\n }\n\n return { file: audioFile };\n}\n\nasync function extractAudioFromJson(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n let body: Base64AudioInput;\n\n try {\n body = await request.json();\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Request body must be valid JSON\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.audio || typeof body.audio !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'audio' field with base64-encoded audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.mimeType || typeof body.mimeType !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'mimeType' field (e.g., 'audio/webm')\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(body.mimeType)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n body.mimeType,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n try {\n const filename = body.filename || \"recording.webm\";\n const file = base64ToFile(body.audio, body.mimeType, filename);\n return { file };\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Failed to decode base64 audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n}\n\n/**\n * Categorize provider errors into appropriate transcription error responses.\n */\nfunction categorizeProviderError(error: unknown): TranscriptionErrorResponse {\n const message =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n const errorStr = String(error).toLowerCase();\n\n // Check for rate limiting\n if (\n errorStr.includes(\"rate\") ||\n errorStr.includes(\"429\") ||\n errorStr.includes(\"too many\")\n ) {\n return TranscriptionErrors.rateLimited();\n }\n\n // Check for auth errors\n if (\n errorStr.includes(\"auth\") ||\n errorStr.includes(\"401\") ||\n errorStr.includes(\"api key\") ||\n errorStr.includes(\"unauthorized\")\n ) {\n return TranscriptionErrors.authFailed();\n }\n\n // Check for audio too long\n if (\n errorStr.includes(\"too long\") ||\n errorStr.includes(\"duration\") ||\n errorStr.includes(\"length\")\n ) {\n return TranscriptionErrors.audioTooLong();\n }\n\n // Default to provider error\n return TranscriptionErrors.providerError(message);\n}\n\nexport async function handleTranscribe({\n runtime,\n request,\n}: HandleTranscribeParameters) {\n try {\n // Check if transcription service is configured\n if (!runtime.transcriptionService) {\n const err = TranscriptionErrors.serviceNotConfigured();\n return createErrorResponse(err);\n }\n\n // Determine input type based on content-type header\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n let extractResult: { file: File } | { error: Response };\n\n if (contentType.includes(\"multipart/form-data\")) {\n // Handle multipart/form-data (REST mode)\n extractResult = await extractAudioFromFormData(request);\n } else if (contentType.includes(\"application/json\")) {\n // Handle JSON with base64 audio (single-endpoint mode)\n extractResult = await extractAudioFromJson(request);\n } else {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must be multipart/form-data or application/json with base64 audio\",\n );\n return createErrorResponse(err);\n }\n\n // Check for extraction errors\n if (\"error\" in extractResult) {\n return extractResult.error;\n }\n\n const audioFile = extractResult.file;\n\n // Transcribe the audio file\n const transcription = await runtime.transcriptionService.transcribeFile({\n audioFile,\n mimeType: audioFile.type,\n size: audioFile.size,\n });\n\n return new Response(\n JSON.stringify({\n text: transcription,\n size: audioFile.size,\n type: audioFile.type,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n // Categorize the error for better client-side handling\n return createErrorResponse(categorizeProviderError(error));\n }\n}\n"],"mappings":";;;;;;;AAUA,MAAM,qBAA6D;EAChEA,0CAAuB,yBAAyB;EAChDA,0CAAuB,uBAAuB;EAC9CA,0CAAuB,iBAAiB;EACxCA,0CAAuB,kBAAkB;EACzCA,0CAAuB,eAAe;EACtCA,0CAAuB,cAAc;EACrCA,0CAAuB,iBAAiB;EACxCA,0CAAuB,gBAAgB;EACvCA,0CAAuB,kBAAkB;CAC3C;AAaD,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAS,iBAAiB,MAAuB;CAE/C,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI;AAC/C,QACE,kBAAkB,SAAS,SAAS,IACpC,aAAa,MACb,aAAa;;AAIjB,SAAS,oBACP,eACU;CACV,MAAM,SAAS,mBAAmB,cAAc,UAAU;AAC1D,QAAO,IAAI,SAAS,KAAK,UAAU,cAAc,EAAE;EACjD;EACA,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CAAC;;AAGJ,SAAS,aACP,QACA,UACA,UACM;CAEN,MAAM,aAAa,OAAO,SAAS,IAAI,GAClC,OAAO,MAAM,IAAI,CAAC,MAAM,SACzB;CAGJ,MAAM,eAAe,KAAK,WAAW;CACrC,MAAM,QAAQ,IAAI,WAAW,aAAa,O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AC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AAEd,SAAO,oBAAoB,wBAAwB,MAAM,CAAC"}
1
+ {"version":3,"file":"handle-transcribe.cjs","names":["TranscriptionErrorCode","TranscriptionErrors"],"sources":["../../../src/runtime/handlers/handle-transcribe.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../core/runtime\";\nimport {\n TranscriptionErrorCode,\n TranscriptionErrors,\n} from \"@copilotkit/shared\";\nimport type { TranscriptionErrorResponse } from \"@copilotkit/shared\";\n\n/**\n * HTTP status codes for transcription error codes\n */\nconst ERROR_STATUS_CODES: Record<TranscriptionErrorCode, number> = {\n [TranscriptionErrorCode.SERVICE_NOT_CONFIGURED]: 503,\n [TranscriptionErrorCode.INVALID_AUDIO_FORMAT]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_LONG]: 400,\n [TranscriptionErrorCode.AUDIO_TOO_SHORT]: 400,\n [TranscriptionErrorCode.RATE_LIMITED]: 429,\n [TranscriptionErrorCode.AUTH_FAILED]: 401,\n [TranscriptionErrorCode.PROVIDER_ERROR]: 500,\n [TranscriptionErrorCode.NETWORK_ERROR]: 502,\n [TranscriptionErrorCode.INVALID_REQUEST]: 400,\n};\n\ninterface HandleTranscribeParameters {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface Base64AudioInput {\n audio: string; // base64-encoded audio data\n mimeType: string;\n filename?: string;\n}\n\nconst VALID_AUDIO_TYPES = [\n \"audio/mpeg\",\n \"audio/mp3\",\n \"audio/mp4\",\n \"audio/wav\",\n \"audio/webm\",\n \"audio/ogg\",\n \"audio/flac\",\n \"audio/aac\",\n];\n\nfunction isValidAudioType(type: string): boolean {\n // Extract base MIME type (before semicolon) to handle types like \"audio/webm; codecs=opus\"\n const baseType = type.split(\";\")[0]?.trim() ?? \"\";\n return (\n VALID_AUDIO_TYPES.includes(baseType) ||\n baseType === \"\" ||\n baseType === \"application/octet-stream\"\n );\n}\n\nfunction createErrorResponse(\n errorResponse: TranscriptionErrorResponse,\n): Response {\n const status = ERROR_STATUS_CODES[errorResponse.error] ?? 500;\n return new Response(JSON.stringify(errorResponse), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction base64ToFile(\n base64: string,\n mimeType: string,\n filename: string,\n): File {\n // Remove data URL prefix if present (e.g., \"data:audio/webm;base64,\")\n const base64Data = base64.includes(\",\")\n ? (base64.split(\",\")[1] ?? base64)\n : base64;\n\n // Decode base64 to binary\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n // Create File object\n return new File([bytes], filename, { type: mimeType });\n}\n\nasync function extractAudioFromFormData(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n const formData = await request.formData();\n let audioFile = formData.get(\"audio\") as File | null;\n\n if (!audioFile || !(audioFile instanceof File)) {\n const err = TranscriptionErrors.invalidRequest(\n \"No audio file found in form data. Please include an 'audio' field.\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(audioFile.type)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n audioFile.type,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n // Browser MediaRecorder Blobs often arrive at the server with their\n // `type` field empty (and `application/octet-stream` is also accepted by\n // isValidAudioType for compatibility). OpenAI Whisper rejects files\n // without a recognizable MIME / extension with a 502 \"Invalid file\n // format\" — even though the bytes themselves are valid WebM Opus.\n // Stamp `audio/webm` (the standard MediaRecorder default in Chromium /\n // Firefox / Safari) so Whisper can pick the right decoder.\n if (!audioFile.type || audioFile.type === \"application/octet-stream\") {\n audioFile = new File([audioFile], audioFile.name || \"recording.webm\", {\n type: \"audio/webm\",\n });\n }\n\n return { file: audioFile };\n}\n\nasync function extractAudioFromJson(\n request: Request,\n): Promise<{ file: File } | { error: Response }> {\n let body: Base64AudioInput;\n\n try {\n body = await request.json();\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Request body must be valid JSON\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.audio || typeof body.audio !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'audio' field with base64-encoded audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!body.mimeType || typeof body.mimeType !== \"string\") {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must include 'mimeType' field (e.g., 'audio/webm')\",\n );\n return { error: createErrorResponse(err) };\n }\n\n if (!isValidAudioType(body.mimeType)) {\n const err = TranscriptionErrors.invalidAudioFormat(\n body.mimeType,\n VALID_AUDIO_TYPES,\n );\n return { error: createErrorResponse(err) };\n }\n\n try {\n const filename = body.filename || \"recording.webm\";\n const file = base64ToFile(body.audio, body.mimeType, filename);\n return { file };\n } catch {\n const err = TranscriptionErrors.invalidRequest(\n \"Failed to decode base64 audio data\",\n );\n return { error: createErrorResponse(err) };\n }\n}\n\n/**\n * Categorize provider errors into appropriate transcription error responses.\n */\nfunction categorizeProviderError(error: unknown): TranscriptionErrorResponse {\n const message =\n error instanceof Error ? error.message : \"Unknown error occurred\";\n const errorStr = String(error).toLowerCase();\n\n // Check for rate limiting\n if (\n errorStr.includes(\"rate\") ||\n errorStr.includes(\"429\") ||\n errorStr.includes(\"too many\")\n ) {\n return TranscriptionErrors.rateLimited();\n }\n\n // Check for auth errors\n if (\n errorStr.includes(\"auth\") ||\n errorStr.includes(\"401\") ||\n errorStr.includes(\"api key\") ||\n errorStr.includes(\"unauthorized\")\n ) {\n return TranscriptionErrors.authFailed();\n }\n\n // Check for audio too long\n if (\n errorStr.includes(\"too long\") ||\n errorStr.includes(\"duration\") ||\n errorStr.includes(\"length\")\n ) {\n return TranscriptionErrors.audioTooLong();\n }\n\n // Default to provider error\n return TranscriptionErrors.providerError(message);\n}\n\nexport async function handleTranscribe({\n runtime,\n request,\n}: HandleTranscribeParameters) {\n try {\n // Check if transcription service is configured\n if (!runtime.transcriptionService) {\n const err = TranscriptionErrors.serviceNotConfigured();\n return createErrorResponse(err);\n }\n\n // Determine input type based on content-type header\n const contentType = request.headers.get(\"content-type\") || \"\";\n\n let extractResult: { file: File } | { error: Response };\n\n if (contentType.includes(\"multipart/form-data\")) {\n // Handle multipart/form-data (REST mode)\n extractResult = await extractAudioFromFormData(request);\n } else if (contentType.includes(\"application/json\")) {\n // Handle JSON with base64 audio (single-endpoint mode)\n extractResult = await extractAudioFromJson(request);\n } else {\n const err = TranscriptionErrors.invalidRequest(\n \"Request must be multipart/form-data or application/json with base64 audio\",\n );\n return createErrorResponse(err);\n }\n\n // Check for extraction errors\n if (\"error\" in extractResult) {\n return extractResult.error;\n }\n\n const audioFile = extractResult.file;\n\n // Transcribe the audio file\n const transcription = await runtime.transcriptionService.transcribeFile({\n audioFile,\n mimeType: audioFile.type,\n size: audioFile.size,\n });\n\n return new Response(\n JSON.stringify({\n text: transcription,\n size: audioFile.size,\n type: audioFile.type,\n }),\n {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n } catch (error) {\n // Categorize the error for better client-side handling\n return createErrorResponse(categorizeProviderError(error));\n }\n}\n"],"mappings":";;;;;;AAUA,MAAM,qBAA6D;EAChEA,0CAAuB,yBAAyB;EAChDA,0CAAuB,uBAAuB;EAC9CA,0CAAuB,iBAAiB;EACxCA,0CAAuB,kBAAkB;EACzCA,0CAAuB,eAAe;EACtCA,0CAAuB,cAAc;EACrCA,0CAAuB,iBAAiB;EACxCA,0CAAuB,gBAAgB;EACvCA,0CAAuB,kBAAkB;CAC3C;AAaD,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,SAAS,iBAAiB,MAAuB;CAE/C,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI;AAC/C,QACE,kBAAkB,SAAS,SAAS,IACpC,aAAa,MACb,aAAa;;AAIjB,SAAS,oBACP,eACU;CACV,MAA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,QAAQ;MAKnD,QAAO,oBAHKA,uCAAoB,eAC9B,4EACD,CAC8B;AAIjC,MAAI,WAAW,cACb,QAAO,cAAc;EAGvB,MAAM,YAAY,cAAc;EAGhC,MAAM,gBAAgB,MAAM,QAAQ,qBAAqB,eAAe;GACtE;GACA,UAAU,UAAU;GACpB,MAAM,UAAU;GACjB,CAAC;AAEF,SAAO,IAAI,SACT,KAAK,UAAU;GACb,MAAM;GACN,MAAM,UAAU;GAChB,MAAM,UAAU;GACjB,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;UACM,OAAO;AAEd,SAAO,oBAAoB,wBAAwB,MAAM,CAAC"}
@@ -1,8 +1,7 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_json_response = require('../shared/json-response.cjs');
3
2
  const require_client = require('../../intelligence-platform/client.cjs');
4
3
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
5
- const require_runtime$1 = require('../../core/runtime.cjs');
4
+ const require_runtime = require('../../core/runtime.cjs');
6
5
  let _copilotkit_shared = require("@copilotkit/shared");
7
6
 
8
7
  //#region src/runtime/handlers/intelligence/annotate.ts
@@ -15,7 +14,7 @@ async function parseJsonBody(request) {
15
14
  }
16
15
  }
17
16
  function requireIntelligenceRuntime(runtime) {
18
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
17
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
19
18
  return runtime;
20
19
  }
21
20
  function isNonEmptyString(value) {
@@ -1 +1 @@
1
- {"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\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 annotate 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. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;U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B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
1
+ {"version":3,"file":"annotate.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","PlatformRequestError"],"sources":["../../../../src/runtime/handlers/intelligence/annotate.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\n\ninterface AnnotateHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface AnnotateBody {\n /** Discriminator identifying the annotation type (e.g. `\"user_action\"`). */\n type: string;\n /** Type-specific payload. Shape varies by `type`. */\n payload?: unknown;\n /** The thread the annotation is associated with. */\n threadId: string;\n /** Caller-supplied idempotency key. Optional — platform auto-generates one when absent. */\n clientEventId?: string;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\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 annotate 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. annotate requires a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n return runtime;\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\n/**\n * `POST /annotate` handler.\n *\n * Three-tier flow:\n * recordAnnotation() (frontend lib; called by useLearnFromUserAction)\n * → POST ${runtimeUrl}/annotate\n * → this handler resolves the Intel user from BFF auth\n * → intelligence.annotate(...)\n * → PUT ${apiUrl}/connector/annotate/:clientEventId\n *\n * The frontend hook may auto-generate a UUID `clientEventId` per call\n * so retries are idempotent end-to-end (the platform collapses to the\n * original row).\n */\nexport async function handleAnnotate({\n runtime,\n request,\n}: AnnotateHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;\n\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const parsed = parseAnnotateBody(body);\n if (isHandlerResponse(parsed)) return parsed;\n\n try {\n const result = await intelligenceRuntime.intelligence.annotate({\n userId: user.id,\n threadId: parsed.threadId,\n type: parsed.type,\n payload: parsed.payload,\n clientEventId: parsed.clientEventId,\n occurredAt: parsed.occurredAt,\n });\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n } catch (err) {\n logger.error({ err }, \"annotate: platform call failed\");\n // Forward the platform's HTTP status when it's a client error\n // (4xx) so the SDK author sees an actionable response instead of\n // a generic 502. 5xx and non-platform errors collapse to 502\n // (\"Bad Gateway\") because the upstream is genuinely at fault.\n if (\n err instanceof PlatformRequestError &&\n err.status >= 400 &&\n err.status < 500\n ) {\n return errorResponse(err.message, err.status);\n }\n return errorResponse(\"Failed to annotate\", 502);\n }\n}\n\nfunction parseAnnotateBody(\n body: Record<string, unknown>,\n): AnnotateBody | Response {\n if (!isNonEmptyString(body.threadId)) {\n return errorResponse(\"Valid threadId is required\", 400);\n }\n if (!isNonEmptyString(body.type)) {\n return errorResponse(\"Valid type is required\", 400);\n }\n return {\n type: body.type,\n payload: body.payload,\n threadId: body.threadId,\n clientEventId: isNonEmptyString(body.clientEventId)\n ? body.clientEventId\n : undefined,\n occurredAt: isNonEmptyString(body.occurredAt) ? body.occurredAt : undefined,\n };\n}\n"],"mappings":";;;;;;;AA4BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,kCAAkC;AAC/D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAOD,oCACL,+IACA,IACD;AAEH,QAAO;;AAGT,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;;;;;;;AAiBrD,eAAsB,eAAe,EACnC,SACA,WAC2C;CAC3C,MAAM,sBAAsB,2BAA2B,QAAQ;AAC/D,KAAIE,wCAAkB,oBAAoB,CAAE,QAAO;CAEnD,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIA,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EACzC,SAAS;EACT;EACD,CAAC;AACF,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,SAAS,kBAAkB,KAAK;AACtC,KAAIA,wCAAkB,OAAO,CAAE,QAAO;AAEtC,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,aAAa,SAAS;GAC7D,QAAQ,KAAK;GACb,UAAU,OAAO;GACjB,MAAM,OAAO;GACb,SAAS,OAAO;GAChB,eAAe,OAAO;GACtB,YAAY,OAAO;GACpB,CAAC;AACF,SAAO,IAAI,SAAS,KAAK,UAAU,OAAO,EAAE;GAC1C,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CAAC;UACK,KAAK;AACZ,4BAAO,MAAM,EAAE,KAAK,EAAE,iCAAiC;AAKvD,MACE,eAAeE,uCACf,IAAI,UAAU,OACd,IAAI,SAAS,IAEb,QAAOJ,oCAAc,IAAI,SAAS,IAAI,OAAO;AAE/C,SAAOA,oCAAc,sBAAsB,IAAI;;;AAInD,SAAS,kBACP,MACyB;AACzB,KAAI,CAAC,iBAAiB,KAAK,SAAS,CAClC,QAAOA,oCAAc,8BAA8B,IAAI;AAEzD,KAAI,CAAC,iBAAiB,KAAK,KAAK,CAC9B,QAAOA,oCAAc,0BAA0B,IAAI;AAErD,QAAO;EACL,MAAM,KAAK;EACX,SAAS,KAAK;EACd,UAAU,KAAK;EACf,eAAe,iBAAiB,KAAK,cAAc,GAC/C,KAAK,gBACL;EACJ,YAAY,iBAAiB,KAAK,WAAW,GAAG,KAAK,aAAa;EACnE"}
@@ -1,7 +1,6 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_json_response = require('../shared/json-response.cjs');
3
2
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
4
- const require_runtime$1 = require('../../core/runtime.cjs');
3
+ const require_runtime = require('../../core/runtime.cjs');
5
4
  const require_memory_policy = require('../shared/memory-policy.cjs');
6
5
  const require_platform_error = require('../shared/platform-error.cjs');
7
6
  let _copilotkit_shared = require("@copilotkit/shared");
@@ -92,7 +91,7 @@ function parseRecallBody(body) {
92
91
  * consumes directly.
93
92
  */
94
93
  async function handleListMemories({ runtime, request }) {
95
- if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
94
+ if (require_runtime.isIntelligenceRuntime(runtime)) try {
96
95
  const includeInvalidated = new URL(request.url).searchParams.get("includeInvalidated") === "true";
97
96
  const access = await resolveClientMemory(runtime, request);
98
97
  if (require_json_response.isHandlerResponse(access)) return access;
@@ -121,7 +120,7 @@ async function handleListMemories({ runtime, request }) {
121
120
  * each optionally carrying `score`.
122
121
  */
123
122
  async function handleRecallMemories({ runtime, request }) {
124
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
123
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
125
124
  try {
126
125
  const body = await parseJsonBody(request);
127
126
  if (require_json_response.isHandlerResponse(body)) return body;
@@ -160,7 +159,7 @@ async function handleRecallMemories({ runtime, request }) {
160
159
  * contract; the client opens only the user channel).
161
160
  */
162
161
  async function handleSubscribeToMemories({ runtime, request }) {
163
- if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
162
+ if (require_runtime.isIntelligenceRuntime(runtime)) try {
164
163
  const access = await resolveClientMemory(runtime, request);
165
164
  if (require_json_response.isHandlerResponse(access)) return access;
166
165
  const credentials = await runtime.intelligence.ɵsubscribeToMemories({
@@ -185,7 +184,7 @@ async function handleSubscribeToMemories({ runtime, request }) {
185
184
  * with the stored memory (the client store applies it server-authoritatively).
186
185
  */
187
186
  async function handleCreateMemory({ runtime, request }) {
188
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
187
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
189
188
  try {
190
189
  const body = await parseJsonBody(request);
191
190
  if (require_json_response.isHandlerResponse(body)) return body;
@@ -209,7 +208,7 @@ async function handleCreateMemory({ runtime, request }) {
209
208
  * inserts the new content atomically; the response carries `retiredId`.
210
209
  */
211
210
  async function handleUpdateMemory({ runtime, request, memoryId }) {
212
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
211
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
213
212
  try {
214
213
  const body = await parseJsonBody(request);
215
214
  if (require_json_response.isHandlerResponse(body)) return body;
@@ -234,7 +233,7 @@ async function handleUpdateMemory({ runtime, request, memoryId }) {
234
233
  * on the platform side; returns 204.
235
234
  */
236
235
  async function handleRemoveMemory({ runtime, request, memoryId }) {
237
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
236
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);
238
237
  try {
239
238
  const access = await resolveClientMemory(runtime, request);
240
239
  if (require_json_response.isHandlerResponse(access)) return access;
@@ -1 +1 @@
1
- {"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","grantAllowsMemory","errorResponse","platformErrorResponse","isIntelligenceRuntime"],"sources":["../../../../src/runtime/handlers/intelligence/memories.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 { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"../shared/memory-policy\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const access = await resolveWebMemory(runtime, request, user, \"client\");\n if (isHandlerResponse(access)) return access;\n // Unlike an agent run — which proceeds without Memory tools when the policy\n // grants nothing — these routes exist ONLY to serve memories. A caller who\n // asked for them and may not have them gets 403; an empty list would imply\n // there are none, which is a different and false claim.\n if (runtime.memory && !grantAllowsMemory(access.grant)) {\n return errorResponse(\"Memory access denied\", 403);\n }\n return access;\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * The reasoning now lives with the implementation in\n * `../shared/platform-error`, which the thread handlers share. This alias is\n * kept so the many call sites below read the same as they always did.\n */\nconst memoryErrorResponse = platformErrorResponse;\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 memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via CopilotKit Intelligence.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;CACpC,MAAM,SAAS,MAAMC,uCAAiB,SAAS,SAAS,MAAM,SAAS;AACvE,KAAID,wCAAkB,OAAO,CAAE,QAAO;AAKtC,K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C,MAAIH,wCAAkB,KAAK,CAAE,QAAO;EACpC,MAAM,SAAS,gBAAgB,KAAK;AACpC,MAAIA,wCAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAIA,wCAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,aAAa;GACnD,QAAQ,OAAO,KAAK;GACpB,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACvD,IAAI;GACJ,GAAG;GACJ,CAAC;AACF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B;;;;;;;AAQhE,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;AAC1C,KAAI,CAACK,wCAAsB,QAAQ,CACjC,QAAOF,oCAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAIH,wCAAkB,OAAO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
1
+ {"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","grantAllowsMemory","errorResponse","platformErrorResponse","isIntelligenceRuntime"],"sources":["../../../../src/runtime/handlers/intelligence/memories.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 { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { grantAllowsMemory, resolveWebMemory } from \"../shared/memory-policy\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const access = await resolveWebMemory(runtime, request, user, \"client\");\n if (isHandlerResponse(access)) return access;\n // Unlike an agent run — which proceeds without Memory tools when the policy\n // grants nothing — these routes exist ONLY to serve memories. A caller who\n // asked for them and may not have them gets 403; an empty list would imply\n // there are none, which is a different and false claim.\n if (runtime.memory && !grantAllowsMemory(access.grant)) {\n return errorResponse(\"Memory access denied\", 403);\n }\n return access;\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * The reasoning now lives with the implementation in\n * `../shared/platform-error`, which the thread handlers share. This alias is\n * kept so the many call sites below read the same as they always did.\n */\nconst memoryErrorResponse = platformErrorResponse;\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 memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via CopilotKit Intelligence.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;CACpC,MAAM,SAAS,MAAMC,uCAAiB,SAAS,SAAS,MAAM,SAAS;AACvE,KAAID,wCAAkB,OAAO,CAAE,QAAO;AAKtC,KAAI,QAAQ,UAAU,CAACE,wCAAkB,OAAO,MAAM,CACpD,QAAOC,oCAAc,wBAAwB,IAAI;AAEnD,QAAO;;AAGT,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;AASvE,MAAM,sBAAsBC;AAE5B,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wCAAwC;AACrE,SAAOD,oCAAc,wBAAwB,IAAI;;;;;;;AAQrD,SAAS,gBAAgB,MAOZ;CACX,MAAM,EAAE,SAAS,MAAM,OAAO,oBAAoB;AAClD,KAAI,OAAO,YAAY,YAAY,OAAO,SAAS,SACjD,QAAOA,oCAAc,+CAA+C,IAAI;AAI1E,KAAI,CAAC,aAAa,IAAI,KAAK,CACzB,QAAOA,oCACL,gEACA,IACD;AAIH,KAAI,UAAU,UAAa,OAAO,UAAU,SAC1C,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AO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
@@ -1,6 +1,6 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
2
1
  const require_json_response = require('../shared/json-response.cjs');
3
2
  const require_learning = require('../../core/learning.cjs');
3
+ const require_analytics_context = require('../../intelligence-platform/analytics-context.cjs');
4
4
  const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
5
5
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
6
6
  const require_telemetry_client = require('../../telemetry/telemetry-client.cjs');
@@ -23,7 +23,7 @@ function buildRealtimeConnectionInfo(params) {
23
23
  function hasRunnerStartupBoundary(runner) {
24
24
  return typeof runner.runWithStartupBoundary === "function" && (Object.prototype.hasOwnProperty.call(runner, "runWithStartupBoundary") || Object.prototype.hasOwnProperty.call(runner, "threads"));
25
25
  }
26
- async function handleIntelligenceRun({ runtime, request, agentId, agent, input, startTime }) {
26
+ async function handleIntelligenceRun({ runtime, request, agentId, agent, input, analyticsContext: forwardedAnalyticsContext, startTime }) {
27
27
  const runtimeTelemetry = runtime.telemetry ?? require_telemetry_client.default;
28
28
  if (!runtime.intelligence) return Response.json({
29
29
  error: "Intelligence not configured",
@@ -39,6 +39,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
39
39
  const isDirectResourceRead = input.forwardedProps?.__copilotkitMcpResourceReadOnly === true && proxyRequest && typeof proxyRequest === "object" && proxyRequest.method === "resources/read";
40
40
  const forwardedRequestId = input.forwardedProps?.__copilotkitRequestId;
41
41
  const requestId = typeof forwardedRequestId === "string" && forwardedRequestId.length > 0 ? forwardedRequestId : void 0;
42
+ const analyticsContext = require_analytics_context.normalizeAnalyticsContext(forwardedAnalyticsContext);
42
43
  let learningContainerId;
43
44
  try {
44
45
  const selector = runtime.intelligence.ɵgetLearningContainerId?.();
@@ -120,6 +121,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
120
121
  agentId,
121
122
  ...learningContainerId !== void 0 ? { learningContainerId } : {},
122
123
  ...requestId !== void 0 ? { requestId } : {},
124
+ ...analyticsContext !== void 0 ? { analyticsContext } : {},
123
125
  ...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {},
124
126
  ttlSeconds: runtime.lockTtlSeconds
125
127
  });
@@ -192,13 +194,25 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
192
194
  };
193
195
  const runStarted = { current: false };
194
196
  let immediateStartupErrorMessage;
195
- let immediateStartupCleanup;
197
+ let lockRelease;
198
+ const releaseLock = (reason) => {
199
+ clearHeartbeat();
200
+ lockRelease ??= cleanupLock(reason);
201
+ return lockRelease;
202
+ };
196
203
  const runRequest = {
197
204
  threadId: canonicalThreadId,
198
205
  ...backendThreadId === void 0 ? {} : { backendThreadId },
199
206
  agent,
200
207
  input: canonicalInput,
201
- ...persistedInputMessages !== void 0 ? { persistedInputMessages } : {}
208
+ ...persistedInputMessages !== void 0 ? { persistedInputMessages } : {},
209
+ recordStop: (signal) => runtime.intelligence.ɵrecordRunStop({
210
+ threadId: canonicalThreadId,
211
+ runId: canonicalRunId,
212
+ userId,
213
+ agentId,
214
+ signal
215
+ })
202
216
  };
203
217
  const runtimeErrorReporter = require_runtime_error_reporter.getRuntimeErrorReporter(runtime);
204
218
  let agentErrorReported = false;
@@ -228,32 +242,24 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
228
242
  if (event.type === _ag_ui_client.EventType.RUN_ERROR) {
229
243
  const message = "message" in event && typeof event.message === "string" ? event.message : "Runner failed before the run started";
230
244
  reportAgentError(new Error(message), runStarted.current ? "intelligence.subscription" : "intelligence.startup");
231
- if (!runStarted.current) {
232
- clearHeartbeat();
233
- immediateStartupErrorMessage = message;
234
- immediateStartupCleanup = cleanupLock("runner-start-failed");
235
- }
245
+ if (!runStarted.current) immediateStartupErrorMessage = message;
236
246
  }
237
247
  },
238
248
  error: (error) => {
239
249
  reportAgentError(error, runStarted.current ? "intelligence.subscription" : "intelligence.startup");
240
- clearHeartbeat();
241
- if (!runStarted.current) {
242
- immediateStartupErrorMessage = error instanceof Error ? error.message : String(error);
243
- immediateStartupCleanup = cleanupLock("runner-start-error");
244
- } else cleanupLock("runner-error");
250
+ if (!runStarted.current) immediateStartupErrorMessage = error instanceof Error ? error.message : String(error);
251
+ releaseLock(runStarted.current ? "runner-error" : "runner-start-error");
245
252
  _copilotkit_shared.logger.error("Error running agent:", error);
246
253
  },
247
254
  complete: () => {
248
- clearHeartbeat();
255
+ releaseLock("run-ended");
249
256
  runtimeTelemetry.capture("oss.runtime.agent_execution_stream_ended", {});
250
257
  }
251
258
  });
252
259
  await runStart.startup;
253
260
  } catch (error) {
254
261
  reportAgentError(error, "intelligence.startup");
255
- clearHeartbeat();
256
- await (immediateStartupCleanup ?? cleanupLock("runner-start-threw"));
262
+ await releaseLock("runner-start-threw");
257
263
  _copilotkit_shared.logger.error("Error starting agent runner:", error);
258
264
  return Response.json({
259
265
  error: "Failed to start runner",
@@ -261,7 +267,7 @@ async function handleIntelligenceRun({ runtime, request, agentId, agent, input,
261
267
  }, { status: 502 });
262
268
  }
263
269
  if (immediateStartupErrorMessage) {
264
- await immediateStartupCleanup;
270
+ await releaseLock("runner-start-failed");
265
271
  return Response.json({
266
272
  error: "Failed to start runner",
267
273
  message: immediateStartupErrorMessage