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

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 (357) 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 +10 -11
  64. package/dist/index.d.mts +10 -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 +4 -3
  79. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  80. package/dist/runtime/core/debug-event-bus.d.cts +5 -1
  81. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  82. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  83. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  84. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  85. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  86. package/dist/runtime/core/fetch-handler.cjs +15 -12
  87. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  88. package/dist/runtime/core/fetch-handler.d.cts +8 -0
  89. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  90. package/dist/runtime/core/fetch-handler.d.mts +8 -0
  91. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  92. package/dist/runtime/core/fetch-handler.mjs +7 -3
  93. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  94. package/dist/runtime/core/learning.d.cts +1 -1
  95. package/dist/runtime/core/logger.cjs +105 -14
  96. package/dist/runtime/core/logger.cjs.map +1 -1
  97. package/dist/runtime/core/logger.d.cts +25 -8
  98. package/dist/runtime/core/logger.d.cts.map +1 -1
  99. package/dist/runtime/core/logger.d.mts +25 -8
  100. package/dist/runtime/core/logger.d.mts.map +1 -1
  101. package/dist/runtime/core/logger.mjs +105 -12
  102. package/dist/runtime/core/logger.mjs.map +1 -1
  103. package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
  104. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  105. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  106. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  107. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  108. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  109. package/dist/runtime/core/middleware.cjs +5 -5
  110. package/dist/runtime/core/middleware.cjs.map +1 -1
  111. package/dist/runtime/core/middleware.mjs +4 -3
  112. package/dist/runtime/core/middleware.mjs.map +1 -1
  113. package/dist/runtime/core/package-info.cjs +1 -1
  114. package/dist/runtime/core/package-info.mjs +1 -1
  115. package/dist/runtime/core/runtime.cjs +11 -10
  116. package/dist/runtime/core/runtime.cjs.map +1 -1
  117. package/dist/runtime/core/runtime.d.cts +22 -4
  118. package/dist/runtime/core/runtime.d.cts.map +1 -1
  119. package/dist/runtime/core/runtime.d.mts +22 -4
  120. package/dist/runtime/core/runtime.d.mts.map +1 -1
  121. package/dist/runtime/core/runtime.mjs +11 -9
  122. package/dist/runtime/core/runtime.mjs.map +1 -1
  123. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
  124. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  125. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  126. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  127. package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -7
  128. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  129. package/dist/runtime/endpoints/node-fetch-handler.d.cts +3 -4
  130. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  131. package/dist/runtime/endpoints/node-fetch-handler.d.mts +3 -4
  132. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  133. package/dist/runtime/endpoints/node-fetch-handler.mjs +3 -5
  134. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  135. package/dist/runtime/endpoints/node.cjs +4 -2
  136. package/dist/runtime/endpoints/node.cjs.map +1 -1
  137. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  138. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  139. package/dist/runtime/endpoints/node.mjs +4 -2
  140. package/dist/runtime/endpoints/node.mjs.map +1 -1
  141. package/dist/runtime/event-transforms/index.d.cts +4 -0
  142. package/dist/runtime/event-transforms/index.d.mts +4 -0
  143. package/dist/runtime/event-transforms/index.mjs +5 -0
  144. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  145. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  146. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  147. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  148. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  149. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  150. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  151. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  152. package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
  153. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  154. package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
  155. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  156. package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
  157. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  158. package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
  159. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  160. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  161. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  162. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  163. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  164. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  165. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  166. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  167. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  168. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  169. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  170. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  171. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  172. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  173. package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
  174. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  175. package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
  176. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  177. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  178. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  179. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  180. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  181. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  182. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  183. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  184. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  185. package/dist/runtime/handlers/handle-run.cjs +11 -14
  186. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  187. package/dist/runtime/handlers/handle-run.mjs +8 -10
  188. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  189. package/dist/runtime/handlers/handle-stop.cjs +5 -5
  190. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  191. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  192. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  193. package/dist/runtime/handlers/handle-suggest.cjs +6 -3
  194. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  195. package/dist/runtime/handlers/handle-suggest.mjs +6 -2
  196. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  197. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  198. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  199. package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
  200. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  201. package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
  202. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  203. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  204. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  205. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  206. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  207. package/dist/runtime/handlers/intelligence/memories.cjs +27 -22
  208. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  209. package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
  210. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  211. package/dist/runtime/handlers/intelligence/run.cjs +38 -30
  212. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  213. package/dist/runtime/handlers/intelligence/run.mjs +37 -28
  214. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  215. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
  216. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  217. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  218. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  219. package/dist/runtime/handlers/intelligence/threads.cjs +36 -27
  220. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  221. package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
  222. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  223. package/dist/runtime/handlers/shared/agent-utils.cjs +35 -34
  224. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  225. package/dist/runtime/handlers/shared/agent-utils.mjs +29 -27
  226. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  227. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  228. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  229. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
  230. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  231. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
  232. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  233. package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
  234. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  235. package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
  236. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  237. package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
  238. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  239. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  240. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  241. package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
  242. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  243. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  244. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  245. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  246. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  247. package/dist/runtime/handlers/sse/run.cjs +5 -2
  248. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  249. package/dist/runtime/handlers/sse/run.mjs +5 -2
  250. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  251. package/dist/runtime/index.d.cts +9 -15
  252. package/dist/runtime/index.d.mts +9 -15
  253. package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
  254. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
  255. package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
  256. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
  257. package/dist/runtime/intelligence-platform/client.cjs +27 -1
  258. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  259. package/dist/runtime/intelligence-platform/client.d.cts +24 -1
  260. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  261. package/dist/runtime/intelligence-platform/client.d.mts +24 -1
  262. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  263. package/dist/runtime/intelligence-platform/client.mjs +27 -0
  264. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  265. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  266. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  267. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  268. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  269. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  270. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  271. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  272. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  273. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  274. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  275. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  276. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  277. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  278. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  279. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  280. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  281. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
  282. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  283. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  284. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  285. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
  286. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  287. package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
  288. package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
  289. package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
  290. package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
  291. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
  292. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  293. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  294. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  295. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  296. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  297. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  298. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  299. package/dist/runtime/node.d.cts +1 -1
  300. package/dist/runtime/node.d.mts +1 -1
  301. package/dist/runtime/runner/agent-runner.cjs +0 -1
  302. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  303. package/dist/runtime/runner/agent-runner.d.cts +9 -0
  304. package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
  305. package/dist/runtime/runner/agent-runner.d.mts +9 -0
  306. package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
  307. package/dist/runtime/runner/agent-runner.mjs.map +1 -1
  308. package/dist/runtime/runner/in-memory.cjs +0 -1
  309. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  310. package/dist/runtime/runner/index.d.cts +1 -1
  311. package/dist/runtime/runner/index.d.mts +1 -1
  312. package/dist/runtime/runner/index.mjs +1 -1
  313. package/dist/runtime/runner/intelligence.cjs +55 -9
  314. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  315. package/dist/runtime/runner/intelligence.d.cts +12 -1
  316. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  317. package/dist/runtime/runner/intelligence.d.mts +12 -1
  318. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  319. package/dist/runtime/runner/intelligence.mjs +56 -10
  320. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  321. package/dist/runtime/telemetry/disclosure.cjs +2 -3
  322. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  323. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  324. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  325. package/dist/runtime/telemetry/events.d.cts +1 -1
  326. package/dist/runtime/telemetry/events.d.mts +1 -1
  327. package/dist/runtime/telemetry/instance-created.cjs +33 -12
  328. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  329. package/dist/runtime/telemetry/instance-created.mjs +33 -12
  330. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  331. package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
  332. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  333. package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
  334. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  335. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  336. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  337. package/package.json +55 -30
  338. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  339. package/dist/agent/converters/index.d.mts +0 -2
  340. package/dist/agent/index.cjs +0 -1328
  341. package/dist/agent/index.cjs.map +0 -1
  342. package/dist/agent/index.d.cts +0 -467
  343. package/dist/agent/index.d.cts.map +0 -1
  344. package/dist/agent/index.d.mts +0 -468
  345. package/dist/agent/index.d.mts.map +0 -1
  346. package/dist/agent/index.mjs +0 -1318
  347. package/dist/agent/index.mjs.map +0 -1
  348. package/dist/agent/mcp-tool-names.cjs +0 -82
  349. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  350. package/dist/agent/mcp-tool-names.mjs +0 -80
  351. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  352. package/dist/agent/url-download.cjs.map +0 -1
  353. package/dist/agent/url-download.d.cts.map +0 -1
  354. package/dist/agent/url-download.d.mts.map +0 -1
  355. package/dist/agent/url-download.mjs.map +0 -1
  356. package/dist/runtime/index.d.cts.map +0 -1
  357. package/dist/runtime/index.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"registry.mjs","names":["SkillDeliveryError","#config","#inFlight","#snapshot","#blocked","#lastCheckedAt","#refresh","#lastError","#stale","#debug","#sources","#multiple","#parts"],"sources":["../../../../src/runtime/intelligence-platform/skill-registry/registry.ts"],"sourcesContent":["import type { CopilotKitIntelligence } from \"../client\";\nimport type {\n GetLearnedSkillsSnapshotRequest,\n LearnedSkillsSnapshotResult,\n} from \"../learned-skills\";\nimport { resolveRegistryConfig } from \"./config\";\nimport type { SingleContainerConfig, SkillRegistryOptions } from \"./config\";\nimport { SkillDeliveryError, invalidSnapshot } from \"./errors\";\nimport type { SkillDeliveryErrorCode } from \"./errors\";\nimport { sha256Hex } from \"../../core/web-crypto\";\nimport { validateSnapshot } from \"./snapshot\";\nimport type { VerifiedSnapshot } from \"./snapshot\";\n\nexport interface SkillRegistryStatus {\n /** Present only for the explicit containers interface. */\n readonly containers?: readonly (SkillRegistryStatus & {\n readonly id: string;\n })[];\n readonly initialized: boolean;\n readonly revision?: string;\n readonly mode: \"latest\" | \"pinned\";\n /** ISO 8601 timestamp of the last successful 200 or matching 304 check. */\n readonly lastCheckedAt?: string;\n readonly stale: boolean;\n readonly lastError?: Readonly<{\n code: SkillDeliveryErrorCode;\n message: string;\n retryable: boolean;\n }>;\n}\n\nfunction transient(error: SkillDeliveryError): boolean {\n return [\n \"NETWORK_ERROR\",\n \"TIMEOUT\",\n \"INVALID_SNAPSHOT\",\n \"UNSUPPORTED_SERVER\",\n ].includes(error.code);\n}\nfunction deliveryError(error: unknown): SkillDeliveryError {\n if (error instanceof SkillDeliveryError) return error;\n return new SkillDeliveryError(\n error instanceof Error && error.name === \"TimeoutError\"\n ? \"TIMEOUT\"\n : \"NETWORK_ERROR\",\n true,\n error,\n );\n}\n\n/** Internal registry shared by framework adapters; public API is framework-native. */\nclass SingleContainerRegistry {\n readonly #config: SingleContainerConfig;\n #snapshot?: VerifiedSnapshot;\n #inFlight?: Promise<VerifiedSnapshot>;\n #lastCheckedAt?: number;\n #stale = false;\n #lastError?: SkillDeliveryError;\n #blocked?: SkillDeliveryError;\n\n constructor(\n config: SingleContainerConfig,\n private readonly fetchSnapshot = (\n request: GetLearnedSkillsSnapshotRequest,\n ) => config.client.getLearnedSkillsSnapshot(request),\n ) {\n this.#config = config;\n }\n\n async initialize(): Promise<void> {\n await this.acquireSnapshot();\n }\n\n /** Capture exactly one immutable snapshot before model work begins. */\n acquireSnapshot(): Promise<VerifiedSnapshot> {\n if (this.#inFlight) return this.#inFlight;\n if (\n this.#snapshot &&\n !this.#blocked &&\n this.#lastCheckedAt !== undefined &&\n Date.now() - this.#lastCheckedAt < this.#config.freshnessWindowMs\n ) {\n return Promise.resolve(this.#snapshot);\n }\n // Defer work one microtask so reentrant and concurrent callers observe the\n // same promise before an injected client can start its request.\n this.#inFlight = Promise.resolve()\n .then(() => this.#refresh())\n .finally(() => {\n this.#inFlight = undefined;\n });\n return this.#inFlight;\n }\n\n get status(): SkillRegistryStatus {\n const error = this.#lastError;\n return Object.freeze({\n initialized: this.#snapshot !== undefined,\n ...(this.#snapshot ? { revision: this.#snapshot.revision } : {}),\n mode: this.#config.revision === undefined ? \"latest\" : \"pinned\",\n ...(this.#lastCheckedAt !== undefined\n ? { lastCheckedAt: new Date(this.#lastCheckedAt).toISOString() }\n : {}),\n stale: this.#stale,\n ...(error\n ? {\n lastError: Object.freeze({\n code: error.code,\n message: error.message,\n retryable: error.retryable,\n }),\n }\n : {}),\n });\n }\n\n async #refresh(): Promise<VerifiedSnapshot> {\n const startedAt = Date.now();\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new SkillDeliveryError(\"TIMEOUT\", true);\n controller.abort(error);\n // Give a canonical client that already received denial headers one\n // event-loop turn to report that denial before the watchdog wins.\n timer = setTimeout(() => reject(error), 0);\n }, this.#config.requestTimeoutMs);\n });\n const replacement = async (): Promise<VerifiedSnapshot> => {\n const response = await this.fetchSnapshot({\n containerId: this.#config.containerId,\n ...(this.#config.revision !== undefined\n ? { revision: this.#config.revision }\n : {}),\n ...(this.#snapshot ? { ifNoneMatch: this.#snapshot.etag } : {}),\n signal: controller.signal,\n });\n controller.signal.throwIfAborted();\n if (!response || typeof response !== \"object\") throw invalidSnapshot();\n if (response.status === \"unchanged\") {\n if (\n !this.#snapshot ||\n response.etag !== this.#snapshot.etag ||\n response.revision !== this.#snapshot.revision\n )\n throw invalidSnapshot();\n return this.#snapshot;\n }\n if (\n this.#config.revision !== undefined &&\n response.revision !== this.#config.revision\n )\n throw invalidSnapshot();\n return validateSnapshot(response, controller.signal);\n };\n try {\n const snapshot = await Promise.race([replacement(), deadline]);\n // An abandoned parse never writes registry state: only the winning\n // complete replacement reaches this assignment.\n this.#snapshot = snapshot;\n this.#lastCheckedAt = Date.now();\n this.#stale = false;\n this.#lastError = undefined;\n this.#blocked = undefined;\n this.#debug(\"refresh-success\", startedAt);\n return snapshot;\n } catch (cause) {\n const error = deliveryError(cause);\n if (!transient(error)) {\n this.#blocked = error;\n this.#stale = false;\n this.#lastError = error;\n this.#debug(\"refresh-denied\", startedAt, error.code);\n throw error;\n }\n // A later unreachable server cannot undo an already confirmed denial.\n if (this.#blocked) {\n this.#lastError = this.#blocked;\n this.#debug(\"refresh-failed\", startedAt, error.code);\n throw this.#blocked;\n }\n this.#lastError = error;\n this.#stale = this.#snapshot !== undefined;\n this.#debug(\"refresh-failed\", startedAt, error.code);\n if (this.#snapshot) return this.#snapshot;\n throw error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n #debug(\n event: string,\n startedAt: number,\n errorCode?: SkillDeliveryErrorCode,\n ): void {\n if (!this.#config.debug) return;\n console.debug(\"CopilotKit learned skills\", {\n event,\n containerId: this.#config.containerId,\n revision: this.#snapshot?.revision,\n durationMs: Date.now() - startedAt,\n ...(errorCode ? { errorCode } : {}),\n });\n }\n}\n\n/** Coalesce refreshes from this registry into one request in the next microtask. */\nfunction batchLoader(client: CopilotKitIntelligence) {\n let pending: {\n request: GetLearnedSkillsSnapshotRequest;\n resolve: (value: LearnedSkillsSnapshotResult) => void;\n reject: (error: unknown) => void;\n }[] = [];\n return (\n request: GetLearnedSkillsSnapshotRequest,\n ): Promise<LearnedSkillsSnapshotResult> =>\n new Promise((resolve, reject) => {\n pending.push({ request, resolve, reject });\n if (pending.length !== 1) return;\n queueMicrotask(async () => {\n const batch = pending;\n pending = [];\n try {\n const results = await client.getLearnedSkillsSnapshots({\n containers: batch.map(\n ({ request: { signal: _signal, ...source } }) => source,\n ),\n signal: batch[0].request.signal,\n });\n if (\n !Array.isArray(results) ||\n results.length !== batch.length ||\n results.some(\n (result, index) =>\n result?.containerId !== batch[index].request.containerId,\n )\n )\n throw invalidSnapshot();\n for (let index = 0; index < batch.length; index++) {\n const result = results[index];\n if (result.status === \"error\") batch[index].reject(result.error);\n else batch[index].resolve(result);\n }\n } catch (error) {\n for (const item of batch) item.reject(error);\n }\n });\n });\n}\n\n/** Compose independent container caches into one immutable invocation snapshot. */\nexport class SkillRegistry {\n readonly #sources: readonly {\n readonly id: string;\n readonly registry: SingleContainerRegistry;\n }[];\n readonly #multiple: boolean;\n #snapshot?: VerifiedSnapshot;\n #parts?: readonly VerifiedSnapshot[];\n #inFlight?: Promise<VerifiedSnapshot>;\n\n constructor(options: SkillRegistryOptions = {}) {\n const config = resolveRegistryConfig(options);\n this.#multiple = config.containers !== undefined;\n const fetchBatch = batchLoader(config.client);\n this.#sources =\n config.containers !== undefined\n ? config.containers.map(({ id, revision }) => ({\n id,\n registry: new SingleContainerRegistry(\n Object.freeze({\n client: config.client,\n freshnessWindowMs: config.freshnessWindowMs,\n requestTimeoutMs: config.requestTimeoutMs,\n debug: config.debug,\n containerId: id,\n ...(revision !== undefined ? { revision } : {}),\n }),\n fetchBatch,\n ),\n }))\n : [\n {\n id: config.containerId!,\n registry: new SingleContainerRegistry({\n client: config.client,\n containerId: config.containerId!,\n revision: config.revision,\n freshnessWindowMs: config.freshnessWindowMs,\n requestTimeoutMs: config.requestTimeoutMs,\n debug: config.debug,\n }),\n },\n ];\n }\n\n /** Load every configured container before agent initialization completes. */\n async initialize(): Promise<void> {\n await this.acquireSnapshot();\n }\n\n /** Capture every container once; a failed source cannot yield a partial catalog. */\n acquireSnapshot(): Promise<VerifiedSnapshot> {\n if (!this.#multiple) return this.#sources[0].registry.acquireSnapshot();\n if (this.#inFlight) return this.#inFlight;\n this.#inFlight = Promise.all(\n this.#sources.map(({ registry }) => registry.acquireSnapshot()),\n )\n .then(async (parts) => {\n if (\n this.#snapshot &&\n parts.every((part, index) => part === this.#parts?.[index])\n ) {\n return this.#snapshot;\n }\n const identity = await sha256Hex(\n JSON.stringify(\n parts.map((part, index) => [\n this.#sources[index].id,\n part.revision,\n part.etag,\n ]),\n ),\n );\n const skills = Object.freeze(\n parts.flatMap((part, index) =>\n part.skills.map((skill) =>\n Object.freeze({\n ...skill,\n name: `${encodeURIComponent(this.#sources[index].id)}/${skill.name}`,\n }),\n ),\n ),\n );\n this.#parts = parts;\n this.#snapshot = Object.freeze({\n revision: `multi:${identity}`,\n etag: `\"${identity}\"`,\n skills,\n });\n return this.#snapshot;\n })\n .finally(() => {\n this.#inFlight = undefined;\n });\n return this.#inFlight;\n }\n\n /** Report each container's real revision; no aggregate server revision exists. */\n get status(): SkillRegistryStatus {\n if (!this.#multiple) return this.#sources[0].registry.status;\n const containers = Object.freeze(\n this.#sources.map(({ id, registry }) =>\n Object.freeze({ id, ...registry.status }),\n ),\n );\n const error =\n containers.find(\n (source) => source.lastError && !source.lastError.retryable,\n )?.lastError ?? containers.find((source) => source.lastError)?.lastError;\n const timestamps = containers.map((source) => source.lastCheckedAt);\n return Object.freeze({\n initialized: this.#snapshot !== undefined,\n mode: containers.every((source) => source.mode === \"pinned\")\n ? \"pinned\"\n : \"latest\",\n stale: containers.some((source) => source.stale),\n ...(timestamps.every((timestamp) => timestamp !== undefined)\n ? { lastCheckedAt: [...timestamps].sort()[0] }\n : {}),\n ...(error ? { lastError: error } : {}),\n containers,\n });\n }\n}\n"],"mappings":";;;;;;;AA+BA,SAAS,UAAU,OAAoC;AACrD,QAAO;EACL;EACA;EACA;EACA;EACD,CAAC,SAAS,MAAM,KAAK;;AAExB,SAAS,cAAc,OAAoC;AACzD,KAAI,iBAAiBA,mBAAoB,QAAO;AAChD,QAAO,IAAIA,mBACT,iBAAiB,SAAS,MAAM,SAAS,iBACrC,YACA,iBACJ,MACA,MACD;;;AAIH,IAAM,0BAAN,MAA8B;CAC5B,CAASC;CACT;CACA;CACA;CACA,SAAS;CACT;CACA;CAEA,YACE,QACA,AAAiB,iBACf,YACG,OAAO,OAAO,yBAAyB,QAAQ,EACpD;EAHiB;AAIjB,QAAKA,SAAU;;CAGjB,MAAM,aAA4B;AAChC,QAAM,KAAK,iBAAiB;;;CAI9B,kBAA6C;AAC3C,MAAI,MAAKC,SAAW,QAAO,MAAKA;AAChC,MACE,MAAKC,YACL,CAAC,MAAKC,WACN,MAAKC,kBAAmB,UACxB,KAAK,KAAK,GAAG,MAAKA,gBAAiB,MAAKJ,OAAQ,kBAEhD,QAAO,QAAQ,QAAQ,MAAKE,SAAU;AAIxC,QAAKD,WAAY,QAAQ,SAAS,CAC/B,WAAW,MAAKI,SAAU,CAAC,CAC3B,cAAc;AACb,SAAKJ,WAAY;IACjB;AACJ,SAAO,MAAKA;;CAGd,IAAI,SAA8B;EAChC,MAAM,QAAQ,MAAKK;AACnB,SAAO,OAAO,OAAO;GACnB,aAAa,MAAKJ,aAAc;GAChC,GAAI,MAAKA,WAAY,EAAE,UAAU,MAAKA,SA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,WAAW,OAAO,UAAU,EAAE;EACjE,MAAM,aAAa,WAAW,KAAK,WAAW,OAAO,cAAc;AACnE,SAAO,OAAO,OAAO;GACnB,aAAa,MAAKP,aAAc;GAChC,MAAM,WAAW,OAAO,WAAW,OAAO,SAAS,SAAS,GACxD,WACA;GACJ,OAAO,WAAW,MAAM,WAAW,OAAO,MAAM;GAChD,GAAI,WAAW,OAAO,cAAc,cAAc,OAAU,GACxD,EAAE,eAAe,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,GAC5C,EAAE;GACN,GAAI,QAAQ,EAAE,WAAW,OAAO,GAAG,EAAE;GACrC;GACD,CAAC"}
1
+ {"version":3,"file":"registry.mjs","names":["SkillDeliveryError","#config","#inFlight","#snapshot","#blocked","#lastCheckedAt","#refresh","#lastError","#stale","#debug","#sources","#multiple","#parts"],"sources":["../../../../src/runtime/intelligence-platform/skill-registry/registry.ts"],"sourcesContent":["import type { CopilotKitIntelligence } from \"../client\";\nimport type {\n GetLearnedSkillsSnapshotRequest,\n LearnedSkillsSnapshotResult,\n} from \"../learned-skills\";\nimport { resolveRegistryConfig } from \"./config\";\nimport type { SingleContainerConfig, SkillRegistryOptions } from \"./config\";\nimport { SkillDeliveryError, invalidSnapshot } from \"./errors\";\nimport type { SkillDeliveryErrorCode } from \"./errors\";\nimport { sha256Hex } from \"../../core/web-crypto\";\nimport { validateSnapshot } from \"./snapshot\";\nimport type { VerifiedSnapshot } from \"./snapshot\";\n\nexport interface SkillRegistryStatus {\n /** Present only for the explicit containers interface. */\n readonly containers?: readonly (SkillRegistryStatus & {\n readonly id: string;\n })[];\n readonly initialized: boolean;\n readonly revision?: string;\n readonly mode: \"latest\" | \"pinned\";\n /** ISO 8601 timestamp of the last successful 200 or matching 304 check. */\n readonly lastCheckedAt?: string;\n readonly stale: boolean;\n readonly lastError?: Readonly<{\n code: SkillDeliveryErrorCode;\n message: string;\n retryable: boolean;\n }>;\n}\n\nfunction transient(error: SkillDeliveryError): boolean {\n return [\n \"NETWORK_ERROR\",\n \"TIMEOUT\",\n \"INVALID_SNAPSHOT\",\n \"UNSUPPORTED_SERVER\",\n ].includes(error.code);\n}\nfunction deliveryError(error: unknown): SkillDeliveryError {\n if (error instanceof SkillDeliveryError) return error;\n return new SkillDeliveryError(\n error instanceof Error && error.name === \"TimeoutError\"\n ? \"TIMEOUT\"\n : \"NETWORK_ERROR\",\n true,\n error,\n );\n}\n\n/** Internal registry shared by framework adapters; public API is framework-native. */\nclass SingleContainerRegistry {\n readonly #config: SingleContainerConfig;\n #snapshot?: VerifiedSnapshot;\n #inFlight?: Promise<VerifiedSnapshot>;\n #lastCheckedAt?: number;\n #stale = false;\n #lastError?: SkillDeliveryError;\n #blocked?: SkillDeliveryError;\n\n constructor(\n config: SingleContainerConfig,\n private readonly fetchSnapshot = (\n request: GetLearnedSkillsSnapshotRequest,\n ) => config.client.getLearnedSkillsSnapshot(request),\n ) {\n this.#config = config;\n }\n\n async initialize(): Promise<void> {\n await this.acquireSnapshot();\n }\n\n /** Capture exactly one immutable snapshot before model work begins. */\n acquireSnapshot(): Promise<VerifiedSnapshot> {\n if (this.#inFlight !== undefined) return this.#inFlight;\n if (\n this.#snapshot &&\n !this.#blocked &&\n this.#lastCheckedAt !== undefined &&\n Date.now() - this.#lastCheckedAt < this.#config.freshnessWindowMs\n ) {\n return Promise.resolve(this.#snapshot);\n }\n // Defer work one microtask so reentrant and concurrent callers observe the\n // same promise before an injected client can start its request.\n this.#inFlight = Promise.resolve()\n .then(() => this.#refresh())\n .finally(() => {\n this.#inFlight = undefined;\n });\n return this.#inFlight;\n }\n\n get status(): SkillRegistryStatus {\n const error = this.#lastError;\n return Object.freeze({\n initialized: this.#snapshot !== undefined,\n ...(this.#snapshot ? { revision: this.#snapshot.revision } : {}),\n mode: this.#config.revision === undefined ? \"latest\" : \"pinned\",\n ...(this.#lastCheckedAt !== undefined\n ? { lastCheckedAt: new Date(this.#lastCheckedAt).toISOString() }\n : {}),\n stale: this.#stale,\n ...(error\n ? {\n lastError: Object.freeze({\n code: error.code,\n message: error.message,\n retryable: error.retryable,\n }),\n }\n : {}),\n });\n }\n\n async #refresh(): Promise<VerifiedSnapshot> {\n const startedAt = Date.now();\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const error = new SkillDeliveryError(\"TIMEOUT\", true);\n controller.abort(error);\n // Give a canonical client that already received denial headers one\n // event-loop turn to report that denial before the watchdog wins.\n timer = setTimeout(() => reject(error), 0);\n }, this.#config.requestTimeoutMs);\n });\n const replacement = async (): Promise<VerifiedSnapshot> => {\n const response = await this.fetchSnapshot({\n containerId: this.#config.containerId,\n ...(this.#config.revision !== undefined\n ? { revision: this.#config.revision }\n : {}),\n ...(this.#snapshot ? { ifNoneMatch: this.#snapshot.etag } : {}),\n signal: controller.signal,\n });\n controller.signal.throwIfAborted();\n if (!response || typeof response !== \"object\") throw invalidSnapshot();\n if (response.status === \"unchanged\") {\n if (\n !this.#snapshot ||\n response.etag !== this.#snapshot.etag ||\n response.revision !== this.#snapshot.revision\n )\n throw invalidSnapshot();\n return this.#snapshot;\n }\n if (\n this.#config.revision !== undefined &&\n response.revision !== this.#config.revision\n )\n throw invalidSnapshot();\n return validateSnapshot(response, controller.signal);\n };\n try {\n const snapshot = await Promise.race([replacement(), deadline]);\n // An abandoned parse never writes registry state: only the winning\n // complete replacement reaches this assignment.\n this.#snapshot = snapshot;\n this.#lastCheckedAt = Date.now();\n this.#stale = false;\n this.#lastError = undefined;\n this.#blocked = undefined;\n this.#debug(\"refresh-success\", startedAt);\n return snapshot;\n } catch (cause) {\n const error = deliveryError(cause);\n if (!transient(error)) {\n this.#blocked = error;\n this.#stale = false;\n this.#lastError = error;\n this.#debug(\"refresh-denied\", startedAt, error.code);\n throw error;\n }\n // A later unreachable server cannot undo an already confirmed denial.\n if (this.#blocked) {\n this.#lastError = this.#blocked;\n this.#debug(\"refresh-failed\", startedAt, error.code);\n throw this.#blocked;\n }\n this.#lastError = error;\n this.#stale = this.#snapshot !== undefined;\n this.#debug(\"refresh-failed\", startedAt, error.code);\n if (this.#snapshot) return this.#snapshot;\n throw error;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n #debug(\n event: string,\n startedAt: number,\n errorCode?: SkillDeliveryErrorCode,\n ): void {\n if (!this.#config.debug) return;\n console.debug(\"CopilotKit learned skills\", {\n event,\n containerId: this.#config.containerId,\n revision: this.#snapshot?.revision,\n durationMs: Date.now() - startedAt,\n ...(errorCode ? { errorCode } : {}),\n });\n }\n}\n\n/** Coalesce refreshes from this registry into one request in the next microtask. */\nfunction batchLoader(client: CopilotKitIntelligence) {\n let pending: {\n request: GetLearnedSkillsSnapshotRequest;\n resolve: (value: LearnedSkillsSnapshotResult) => void;\n reject: (error: unknown) => void;\n }[] = [];\n // Rejects each pending request itself, so it never rejects.\n const flush = async () => {\n const batch = pending;\n pending = [];\n try {\n const results = await client.getLearnedSkillsSnapshots({\n containers: batch.map(\n ({ request: { signal: _signal, ...source } }) => source,\n ),\n signal: batch[0].request.signal,\n });\n if (\n !Array.isArray(results) ||\n results.length !== batch.length ||\n results.some(\n (result, index) =>\n result?.containerId !== batch[index].request.containerId,\n )\n )\n throw invalidSnapshot();\n for (let index = 0; index < batch.length; index++) {\n const result = results[index];\n if (result.status === \"error\") batch[index].reject(result.error);\n else batch[index].resolve(result);\n }\n } catch (error) {\n for (const item of batch) item.reject(error);\n }\n };\n return (\n request: GetLearnedSkillsSnapshotRequest,\n ): Promise<LearnedSkillsSnapshotResult> =>\n new Promise((resolve, reject) => {\n pending.push({ request, resolve, reject });\n if (pending.length !== 1) return;\n queueMicrotask(() => {\n void flush();\n });\n });\n}\n\n/** Compose independent container caches into one immutable invocation snapshot. */\nexport class SkillRegistry {\n readonly #sources: readonly {\n readonly id: string;\n readonly registry: SingleContainerRegistry;\n }[];\n readonly #multiple: boolean;\n #snapshot?: VerifiedSnapshot;\n #parts?: readonly VerifiedSnapshot[];\n #inFlight?: Promise<VerifiedSnapshot>;\n\n constructor(options: SkillRegistryOptions = {}) {\n const config = resolveRegistryConfig(options);\n this.#multiple = config.containers !== undefined;\n const fetchBatch = batchLoader(config.client);\n this.#sources =\n config.containers !== undefined\n ? config.containers.map(({ id, revision }) => ({\n id,\n registry: new SingleContainerRegistry(\n Object.freeze({\n client: config.client,\n freshnessWindowMs: config.freshnessWindowMs,\n requestTimeoutMs: config.requestTimeoutMs,\n debug: config.debug,\n containerId: id,\n ...(revision !== undefined ? { revision } : {}),\n }),\n fetchBatch,\n ),\n }))\n : [\n {\n id: config.containerId!,\n registry: new SingleContainerRegistry({\n client: config.client,\n containerId: config.containerId!,\n revision: config.revision,\n freshnessWindowMs: config.freshnessWindowMs,\n requestTimeoutMs: config.requestTimeoutMs,\n debug: config.debug,\n }),\n },\n ];\n }\n\n /** Load every configured container before agent initialization completes. */\n async initialize(): Promise<void> {\n await this.acquireSnapshot();\n }\n\n /** Capture every container once; a failed source cannot yield a partial catalog. */\n acquireSnapshot(): Promise<VerifiedSnapshot> {\n if (!this.#multiple) return this.#sources[0].registry.acquireSnapshot();\n if (this.#inFlight !== undefined) return this.#inFlight;\n this.#inFlight = Promise.all(\n this.#sources.map(({ registry }) => registry.acquireSnapshot()),\n )\n .then(async (parts) => {\n if (\n this.#snapshot &&\n parts.every((part, index) => part === this.#parts?.[index])\n ) {\n return this.#snapshot;\n }\n const identity = await sha256Hex(\n JSON.stringify(\n parts.map((part, index) => [\n this.#sources[index].id,\n part.revision,\n part.etag,\n ]),\n ),\n );\n const skills = Object.freeze(\n parts.flatMap((part, index) =>\n part.skills.map((skill) =>\n Object.freeze({\n ...skill,\n name: `${encodeURIComponent(this.#sources[index].id)}/${skill.name}`,\n }),\n ),\n ),\n );\n this.#parts = parts;\n this.#snapshot = Object.freeze({\n revision: `multi:${identity}`,\n etag: `\"${identity}\"`,\n skills,\n });\n return this.#snapshot;\n })\n .finally(() => {\n this.#inFlight = undefined;\n });\n return this.#inFlight;\n }\n\n /** Report each container's real revision; no aggregate server revision exists. */\n get status(): SkillRegistryStatus {\n if (!this.#multiple) return this.#sources[0].registry.status;\n const containers = Object.freeze(\n this.#sources.map(({ id, registry }) =>\n Object.freeze({ id, ...registry.status }),\n ),\n );\n const error =\n containers.find(\n (source) => source.lastError && !source.lastError.retryable,\n )?.lastError ?? containers.find((source) => source.lastError)?.lastError;\n const timestamps = containers.map((source) => source.lastCheckedAt);\n return Object.freeze({\n initialized: this.#snapshot !== undefined,\n mode: containers.every((source) => source.mode === \"pinned\")\n ? \"pinned\"\n : \"latest\",\n stale: containers.some((source) => source.stale),\n ...(timestamps.every((timestamp) => timestamp !== undefined)\n ? { lastCheckedAt: [...timestamps].sort()[0] }\n : {}),\n ...(error ? { lastError: error } : {}),\n containers,\n });\n }\n}\n"],"mappings":";;;;;;;AA+BA,SAAS,UAAU,OAAoC;AACrD,QAAO;EACL;EACA;EACA;EACA;EACD,CAAC,SAAS,MAAM,KAAK;;AAExB,SAAS,cAAc,OAAoC;AACzD,KAAI,iBAAiBA,mBAAoB,QAAO;AAChD,QAAO,IAAIA,mBACT,iBAAiB,SAAS,MAAM,SAAS,iBACrC,YACA,iBACJ,MACA,MACD;;;AAIH,IAAM,0BAAN,MAA8B;CAC5B,CAASC;CACT;CACA;CACA;CACA,SAAS;CACT;CACA;CAEA,YACE,QACA,AAAiB,iBACf,YACG,OAAO,OAAO,yBAAyB,QAAQ,EACpD;EAHiB;AAIjB,QAAKA,SAAU;;CAGjB,MAAM,aAA4B;AAChC,QAAM,KAAK,iBAAiB;;;CAI9B,kBAA6C;AAC3C,MAAI,MAAKC,aAAc,OAAW,QAAO,MAAKA;AAC9C,MACE,MAAKC,YACL,CAAC,MAAKC,WACN,MAAKC,kBAAmB,UACxB,KAAK,KAAK,GAAG,MAAKA,gBAAiB,MAAKJ,OAAQ,kBAEhD,QAAO,QAAQ,QAAQ,MAAKE,SAAU;AAIxC,QAAKD,WAAY,QAAQ,SAAS,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ChC,MAAI,CAAC,MAAKS,SAAW,QAAO,MAAKD,QAAS,GAAG,SAAS;EACtD,MAAM,aAAa,OAAO,OACxB,MAAKA,QAAS,KAAK,EAAE,IAAI,eACvB,OAAO,OAAO;GAAE;GAAI,GAAG,SAAS;GAAQ,CAAC,CAC1C,CACF;EACD,MAAM,QACJ,WAAW,MACR,WAAW,OAAO,aAAa,CAAC,OAAO,UAAU,UACnD,EAAE,aAAa,WAAW,MAAM,WAAW,OAAO,UAAU,EAAE;EACjE,MAAM,aAAa,WAAW,KAAK,WAAW,OAAO,cAAc;AACnE,SAAO,OAAO,OAAO;GACnB,aAAa,MAAKP,aAAc;GAChC,MAAM,WAAW,OAAO,WAAW,OAAO,SAAS,SAAS,GACxD,WACA;GACJ,OAAO,WAAW,MAAM,WAAW,OAAO,MAAM;GAChD,GAAI,WAAW,OAAO,cAAc,cAAc,OAAU,GACxD,EAAE,eAAe,CAAC,GAAG,WAAW,CAAC,MAAM,CAAC,IAAI,GAC5C,EAAE;GACN,GAAI,QAAQ,EAAE,WAAW,OAAO,GAAG,EAAE;GACrC;GACD,CAAC"}
@@ -0,0 +1,50 @@
1
+ let phoenix = require("phoenix");
2
+
3
+ //#region src/runtime/intelligence-platform/stop-run.ts
4
+ /** The thread channel command a browser's Stop sends. */
5
+ const STOP_RUN_EVENT = "stop_run";
6
+ /**
7
+ * Sends `stop_run` for one run on its thread's client channel, the message a
8
+ * browser's Stop sends, and resolves once Intelligence acknowledges it.
9
+ *
10
+ * Intelligence answers by storing the stop for the run and relaying it to the
11
+ * run's runner. The join token is single use, so the socket is closed after
12
+ * the one command and never reconnects.
13
+ *
14
+ * @throws when the socket, the join or the command is refused or unanswered,
15
+ * or when `signal` aborts.
16
+ */
17
+ function sendStopRun(params) {
18
+ return new Promise((resolve, reject) => {
19
+ if (params.signal?.aborted) {
20
+ reject(/* @__PURE__ */ new Error("Stopped before the stop could be sent"));
21
+ return;
22
+ }
23
+ const socket = new phoenix.Socket(params.url, { params: { join_token: params.joinToken } });
24
+ const channel = socket.channel(`thread:${params.threadId}`, {
25
+ stream_mode: "run",
26
+ run_id: params.runId
27
+ });
28
+ let settled = false;
29
+ const finish = (error) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ params.signal?.removeEventListener("abort", onAbort);
33
+ channel.leave();
34
+ socket.disconnect();
35
+ if (error) reject(error);
36
+ else resolve();
37
+ };
38
+ const onAbort = () => finish(/* @__PURE__ */ new Error("Stopped waiting for Intelligence to record the stop"));
39
+ params.signal?.addEventListener("abort", onAbort, { once: true });
40
+ socket.onError(() => finish(/* @__PURE__ */ new Error("Could not reach Intelligence to record the stop")));
41
+ channel.join().receive("ok", () => {
42
+ channel.push(STOP_RUN_EVENT, { run_id: params.runId }).receive("ok", () => finish()).receive("error", () => finish(/* @__PURE__ */ new Error("Intelligence refused the stop"))).receive("timeout", () => finish(/* @__PURE__ */ new Error("Intelligence did not answer the stop")));
43
+ }).receive("error", () => finish(/* @__PURE__ */ new Error("Intelligence refused the thread channel"))).receive("timeout", () => finish(/* @__PURE__ */ new Error("Intelligence did not answer the thread channel")));
44
+ socket.connect();
45
+ });
46
+ }
47
+
48
+ //#endregion
49
+ exports.sendStopRun = sendStopRun;
50
+ //# sourceMappingURL=stop-run.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stop-run.cjs","names":["Socket"],"sources":["../../../src/runtime/intelligence-platform/stop-run.ts"],"sourcesContent":["import { Socket } from \"phoenix\";\n\n/** The thread channel command a browser's Stop sends. */\nconst STOP_RUN_EVENT = \"stop_run\";\n\n/**\n * Sends `stop_run` for one run on its thread's client channel, the message a\n * browser's Stop sends, and resolves once Intelligence acknowledges it.\n *\n * Intelligence answers by storing the stop for the run and relaying it to the\n * run's runner. The join token is single use, so the socket is closed after\n * the one command and never reconnects.\n *\n * @throws when the socket, the join or the command is refused or unanswered,\n * or when `signal` aborts.\n */\nexport function sendStopRun(params: {\n /** The Intelligence client websocket URL (`.../client`). */\n url: string;\n /** A fresh thread join token, as `POST /api/threads/:id/connect` mints it. */\n joinToken: string;\n threadId: string;\n runId: string;\n signal?: AbortSignal;\n}): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (params.signal?.aborted) {\n reject(new Error(\"Stopped before the stop could be sent\"));\n return;\n }\n const socket = new Socket(params.url, {\n params: { join_token: params.joinToken },\n });\n const channel = socket.channel(`thread:${params.threadId}`, {\n stream_mode: \"run\",\n run_id: params.runId,\n });\n\n let settled = false;\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n params.signal?.removeEventListener(\"abort\", onAbort);\n channel.leave();\n socket.disconnect();\n if (error) reject(error);\n else resolve();\n };\n const onAbort = () =>\n finish(new Error(\"Stopped waiting for Intelligence to record the stop\"));\n params.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n socket.onError(() =>\n finish(new Error(\"Could not reach Intelligence to record the stop\")),\n );\n channel\n .join()\n .receive(\"ok\", () => {\n channel\n .push(STOP_RUN_EVENT, { run_id: params.runId })\n .receive(\"ok\", () => finish())\n .receive(\"error\", () =>\n finish(new Error(\"Intelligence refused the stop\")),\n )\n .receive(\"timeout\", () =>\n finish(new Error(\"Intelligence did not answer the stop\")),\n );\n })\n .receive(\"error\", () =>\n finish(new Error(\"Intelligence refused the thread channel\")),\n )\n .receive(\"timeout\", () =>\n finish(new Error(\"Intelligence did not answer the thread channel\")),\n );\n socket.connect();\n });\n}\n"],"mappings":";;;;AAGA,MAAM,iBAAiB;;;;;;;;;;;;AAavB,SAAgB,YAAY,QAQV;AAChB,QAAO,IAAI,SAAe,SAAS,WAAW;AAC5C,MAAI,OAAO,QAAQ,SAAS;AAC1B,0BAAO,IAAI,MAAM,wCAAwC,CAAC;AAC1D;;EAEF,MAAM,SAAS,IAAIA,eAAO,OAAO,KAAK,EACpC,QAAQ,EAAE,YAAY,OAAO,WAAW,EACzC,CAAC;EACF,MAAM,UAAU,OAAO,QAAQ,UAAU,OAAO,YAAY;GAC1D,aAAa;GACb,QAAQ,OAAO;GAChB,CAAC;EAEF,IAAI,UAAU;EACd,MAAM,UAAU,UAAkB;AAChC,OAAI,QAAS;AACb,aAAU;AACV,UAAO,QAAQ,oBAAoB,SAAS,QAAQ;AACpD,WAAQ,OAAO;AACf,UAAO,YAAY;AACnB,OAAI,MAAO,QAAO,MAAM;OACnB,UAAS;;EAEhB,MAAM,gBACJ,uBAAO,IAAI,MAAM,sDAAsD,CAAC;AAC1E,SAAO,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjE,SAAO,cACL,uBAAO,IAAI,MAAM,kDAAkD,CAAC,CACrE;AACD,UACG,MAAM,CACN,QAAQ,YAAY;AACnB,WACG,KAAK,gBAAgB,EAAE,QAAQ,OAAO,OAAO,CAAC,CAC9C,QAAQ,YAAY,QAAQ,CAAC,CAC7B,QAAQ,eACP,uBAAO,IAAI,MAAM,gCAAgC,CAAC,CACnD,CACA,QAAQ,iBACP,uBAAO,IAAI,MAAM,uCAAuC,CAAC,CAC1D;IACH,CACD,QAAQ,eACP,uBAAO,IAAI,MAAM,0CAA0C,CAAC,CAC7D,CACA,QAAQ,iBACP,uBAAO,IAAI,MAAM,iDAAiD,CAAC,CACpE;AACH,SAAO,SAAS;GAChB"}
@@ -0,0 +1,50 @@
1
+ import { Socket } from "phoenix";
2
+
3
+ //#region src/runtime/intelligence-platform/stop-run.ts
4
+ /** The thread channel command a browser's Stop sends. */
5
+ const STOP_RUN_EVENT = "stop_run";
6
+ /**
7
+ * Sends `stop_run` for one run on its thread's client channel, the message a
8
+ * browser's Stop sends, and resolves once Intelligence acknowledges it.
9
+ *
10
+ * Intelligence answers by storing the stop for the run and relaying it to the
11
+ * run's runner. The join token is single use, so the socket is closed after
12
+ * the one command and never reconnects.
13
+ *
14
+ * @throws when the socket, the join or the command is refused or unanswered,
15
+ * or when `signal` aborts.
16
+ */
17
+ function sendStopRun(params) {
18
+ return new Promise((resolve, reject) => {
19
+ if (params.signal?.aborted) {
20
+ reject(/* @__PURE__ */ new Error("Stopped before the stop could be sent"));
21
+ return;
22
+ }
23
+ const socket = new Socket(params.url, { params: { join_token: params.joinToken } });
24
+ const channel = socket.channel(`thread:${params.threadId}`, {
25
+ stream_mode: "run",
26
+ run_id: params.runId
27
+ });
28
+ let settled = false;
29
+ const finish = (error) => {
30
+ if (settled) return;
31
+ settled = true;
32
+ params.signal?.removeEventListener("abort", onAbort);
33
+ channel.leave();
34
+ socket.disconnect();
35
+ if (error) reject(error);
36
+ else resolve();
37
+ };
38
+ const onAbort = () => finish(/* @__PURE__ */ new Error("Stopped waiting for Intelligence to record the stop"));
39
+ params.signal?.addEventListener("abort", onAbort, { once: true });
40
+ socket.onError(() => finish(/* @__PURE__ */ new Error("Could not reach Intelligence to record the stop")));
41
+ channel.join().receive("ok", () => {
42
+ channel.push(STOP_RUN_EVENT, { run_id: params.runId }).receive("ok", () => finish()).receive("error", () => finish(/* @__PURE__ */ new Error("Intelligence refused the stop"))).receive("timeout", () => finish(/* @__PURE__ */ new Error("Intelligence did not answer the stop")));
43
+ }).receive("error", () => finish(/* @__PURE__ */ new Error("Intelligence refused the thread channel"))).receive("timeout", () => finish(/* @__PURE__ */ new Error("Intelligence did not answer the thread channel")));
44
+ socket.connect();
45
+ });
46
+ }
47
+
48
+ //#endregion
49
+ export { sendStopRun };
50
+ //# sourceMappingURL=stop-run.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stop-run.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/stop-run.ts"],"sourcesContent":["import { Socket } from \"phoenix\";\n\n/** The thread channel command a browser's Stop sends. */\nconst STOP_RUN_EVENT = \"stop_run\";\n\n/**\n * Sends `stop_run` for one run on its thread's client channel, the message a\n * browser's Stop sends, and resolves once Intelligence acknowledges it.\n *\n * Intelligence answers by storing the stop for the run and relaying it to the\n * run's runner. The join token is single use, so the socket is closed after\n * the one command and never reconnects.\n *\n * @throws when the socket, the join or the command is refused or unanswered,\n * or when `signal` aborts.\n */\nexport function sendStopRun(params: {\n /** The Intelligence client websocket URL (`.../client`). */\n url: string;\n /** A fresh thread join token, as `POST /api/threads/:id/connect` mints it. */\n joinToken: string;\n threadId: string;\n runId: string;\n signal?: AbortSignal;\n}): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (params.signal?.aborted) {\n reject(new Error(\"Stopped before the stop could be sent\"));\n return;\n }\n const socket = new Socket(params.url, {\n params: { join_token: params.joinToken },\n });\n const channel = socket.channel(`thread:${params.threadId}`, {\n stream_mode: \"run\",\n run_id: params.runId,\n });\n\n let settled = false;\n const finish = (error?: Error) => {\n if (settled) return;\n settled = true;\n params.signal?.removeEventListener(\"abort\", onAbort);\n channel.leave();\n socket.disconnect();\n if (error) reject(error);\n else resolve();\n };\n const onAbort = () =>\n finish(new Error(\"Stopped waiting for Intelligence to record the stop\"));\n params.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n socket.onError(() =>\n finish(new Error(\"Could not reach Intelligence to record the stop\")),\n );\n channel\n .join()\n .receive(\"ok\", () => {\n channel\n .push(STOP_RUN_EVENT, { run_id: params.runId })\n .receive(\"ok\", () => finish())\n .receive(\"error\", () =>\n finish(new Error(\"Intelligence refused the stop\")),\n )\n .receive(\"timeout\", () =>\n finish(new Error(\"Intelligence did not answer the stop\")),\n );\n })\n .receive(\"error\", () =>\n finish(new Error(\"Intelligence refused the thread channel\")),\n )\n .receive(\"timeout\", () =>\n finish(new Error(\"Intelligence did not answer the thread channel\")),\n );\n socket.connect();\n });\n}\n"],"mappings":";;;;AAGA,MAAM,iBAAiB;;;;;;;;;;;;AAavB,SAAgB,YAAY,QAQV;AAChB,QAAO,IAAI,SAAe,SAAS,WAAW;AAC5C,MAAI,OAAO,QAAQ,SAAS;AAC1B,0BAAO,IAAI,MAAM,wCAAwC,CAAC;AAC1D;;EAEF,MAAM,SAAS,IAAI,OAAO,OAAO,KAAK,EACpC,QAAQ,EAAE,YAAY,OAAO,WAAW,EACzC,CAAC;EACF,MAAM,UAAU,OAAO,QAAQ,UAAU,OAAO,YAAY;GAC1D,aAAa;GACb,QAAQ,OAAO;GAChB,CAAC;EAEF,IAAI,UAAU;EACd,MAAM,UAAU,UAAkB;AAChC,OAAI,QAAS;AACb,aAAU;AACV,UAAO,QAAQ,oBAAoB,SAAS,QAAQ;AACpD,WAAQ,OAAO;AACf,UAAO,YAAY;AACnB,OAAI,MAAO,QAAO,MAAM;OACnB,UAAS;;EAEhB,MAAM,gBACJ,uBAAO,IAAI,MAAM,sDAAsD,CAAC;AAC1E,SAAO,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjE,SAAO,cACL,uBAAO,IAAI,MAAM,kDAAkD,CAAC,CACrE;AACD,UACG,MAAM,CACN,QAAQ,YAAY;AACnB,WACG,KAAK,gBAAgB,EAAE,QAAQ,OAAO,OAAO,CAAC,CAC9C,QAAQ,YAAY,QAAQ,CAAC,CAC7B,QAAQ,eACP,uBAAO,IAAI,MAAM,gCAAgC,CAAC,CACnD,CACA,QAAQ,iBACP,uBAAO,IAAI,MAAM,uCAAuC,CAAC,CAC1D;IACH,CACD,QAAQ,eACP,uBAAO,IAAI,MAAM,0CAA0C,CAAC,CAC7D,CACA,QAAQ,iBACP,uBAAO,IAAI,MAAM,iDAAiD,CAAC,CACpE;AACH,SAAO,SAAS;GAChB"}
@@ -1,6 +1,5 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
1
+ const require_logger = require('../core/logger.cjs');
2
2
  const require_client = require('./client.cjs');
3
- let _copilotkit_shared = require("@copilotkit/shared");
4
3
 
5
4
  //#region src/runtime/intelligence-platform/thread-lock-heartbeat.ts
6
5
  /** Delay before the first retry of a failed renewal; doubles per attempt. */
@@ -45,6 +44,7 @@ function isRetryableLockRenewalError(error) {
45
44
  */
46
45
  function startThreadLockHeartbeat(options) {
47
46
  const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;
47
+ const logger = options.logger ?? require_logger.getRuntimeLogger();
48
48
  let stopped = false;
49
49
  let timer;
50
50
  const initialTtlSeconds = typeof options.initialTtlSeconds === "number" && Number.isFinite(options.initialTtlSeconds) ? options.initialTtlSeconds : fallbackTtlSeconds;
@@ -109,7 +109,7 @@ function startThreadLockHeartbeat(options) {
109
109
  lose(error);
110
110
  return;
111
111
  }
112
- _copilotkit_shared.logger.warn({
112
+ logger.warn({
113
113
  err: error,
114
114
  attempt: failedAttempts,
115
115
  retryInMs: delayMs,
@@ -1 +1 @@
1
- {"version":3,"file":"thread-lock-heartbeat.cjs","names":["PlatformRequestError"],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;;AAKA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAuClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiBA,qCAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;;AAGzE,QAAO;;;;;;;;;;;;;;;;AAiBT,SAAgB,yBACd,SACqB;CACrB,MAAM,EAAE,OAAO,YAAY,oBAAoB,WAAW;CAC1D,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,oBACJ,OAAO,QAAQ,sBAAsB,YACrC,OAAO,SAAS,QAAQ,kBAAkB,GACtC,QAAQ,oBACR;CACN,IAAI,WAAW,KAAK,KAAK,GAAG,oBAAoB;CAChD,IAAI,iBAAiB;CAErB,MAAM,YAAY,YAA0B;AAC1C,UAAQ,iBAAiB;AACvB,WAAQ;AACR,GAAK,SAAS;KACb,QAAQ;AACX,MAAI,QAAQ,MAAO,OAAM,SAAS;;;CAIpC,MAAM,oBACJ,WAAW,4BAA4B,KAAK,KAAK;CAInD,MAAM,wBAA8B;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AAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
1
+ {"version":3,"file":"thread-lock-heartbeat.cjs","names":["PlatformRequestError","getRuntimeLogger"],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../core/logger\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n /** Where retried renewals are reported. Default: the console. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n const logger = options.logger ?? getRuntimeLogger();\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAyClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiBA,qCAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;;AAGzE,QAAO;;;;;;;;;;;;;;;;AAiBT,SAAgB,yBACd,SACqB;CACrB,MAAM,EAAE,OAAO,YAAY,oBAAoB,WAAW;CAC1D,MAAM,SAAS,QAAQ,UAAUC,iCAAkB;CACnD,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,oBACJ,OAAO,QAAQ,sBAAsB,YACrC,OAAO,SAAS,QAAQ,kBAAkB,GACtC,QAAQ,oBACR;CACN,IAAI,WAAW,KAAK,KAAK,GAAG,oBAAoB;CAChD,IAAI,iBAAiB;CAErB,MAAM,YAAY,YAA0B;AAC1C,UAAQ,iBAAiB;AACvB,WAAQ;AACR,GAAK,SAAS;KACb,QAAQ;AACX,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ACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
@@ -1,5 +1,5 @@
1
+ import { getRuntimeLogger } from "../core/logger.mjs";
1
2
  import { PlatformRequestError } from "./client.mjs";
2
- import { logger } from "@copilotkit/shared";
3
3
 
4
4
  //#region src/runtime/intelligence-platform/thread-lock-heartbeat.ts
5
5
  /** Delay before the first retry of a failed renewal; doubles per attempt. */
@@ -44,6 +44,7 @@ function isRetryableLockRenewalError(error) {
44
44
  */
45
45
  function startThreadLockHeartbeat(options) {
46
46
  const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;
47
+ const logger = options.logger ?? getRuntimeLogger();
47
48
  let stopped = false;
48
49
  let timer;
49
50
  const initialTtlSeconds = typeof options.initialTtlSeconds === "number" && Number.isFinite(options.initialTtlSeconds) ? options.initialTtlSeconds : fallbackTtlSeconds;
@@ -1 +1 @@
1
- {"version":3,"file":"thread-lock-heartbeat.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAKA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAuClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiB,sBAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM;AAChD,SAAO,MAAM,UAAU,OAAO,MAA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2B;AACjC,mBAAiB;;CAGnB,MAAM,iBAAiB,UAAyB;AAC9C,MAAI,CAAC,4BAA4B,MAAM,EAAE;AACvC,QAAK,MAAM;AACX;;EAEF,MAAM,UAAU,KAAK,IACnB,yBAAyB,KAAK,gBAC9B,mBACD;AACD,oBAAkB;EAClB,MAAM,YAAY,aAAa;AAC/B,MAAI,WAAW,WAAW;AACxB,QAAK,MAAM;AACX;;AAEF,SAAO,KACL;GACE,KAAK;GACL,SAAS;GACT,WAAW;GACX,aAAa;GACd,EACD,+DACD;AACD,WAAS,QAAQ;;AAGnB,kBAAiB;AACjB,QAAO,EAAE,MAAM;;AAGjB,SAAS,YACP,SACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
1
+ {"version":3,"file":"thread-lock-heartbeat.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/thread-lock-heartbeat.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../core/logger\";\nimport { PlatformRequestError } from \"./client\";\nimport type { RenewThreadLockResponse } from \"./client\";\n\n/** Delay before the first retry of a failed renewal; doubles per attempt. */\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n/** Upper bound for the delay between renewal retries. */\nconst MAX_RETRY_DELAY_MS = 8_000;\n/** Longest a single renewal may stay in flight before it counts as failed. */\nconst ATTEMPT_TIMEOUT_MS = 10_000;\n/** Stop retrying this long before the lock would expire. */\nconst DEADLINE_SAFETY_MARGIN_MS = 1_000;\n\nexport interface ThreadLockHeartbeatOptions {\n /**\n * Sends one renewal request. The signal aborts when the attempt times out,\n * so an abandoned request never overlaps its retry.\n */\n renew: (signal: AbortSignal) => Promise<RenewThreadLockResponse>;\n /** Delay between successful renewals. */\n intervalMs: number;\n /**\n * Lock lifetime assumed when the platform has not reported one: until the\n * first successful renewal when {@link initialTtlSeconds} is absent, and\n * for renewal responses that omit `ttlSeconds`.\n */\n fallbackTtlSeconds: number;\n /**\n * Remaining lock lifetime when the heartbeat starts, as reported by the\n * platform at acquisition, measured from when the acquire request was sent.\n * Used until the first successful renewal; when absent,\n * {@link fallbackTtlSeconds} applies instead. A value of zero or less means\n * the lock has already expired.\n */\n initialTtlSeconds?: number;\n /**\n * Called once when the lock can no longer be kept: a non-retryable failure,\n * or retryable failures that ran out the lock's remaining lifetime. Never\n * called after {@link ThreadLockHeartbeat.stop}.\n */\n onLost: (error: unknown) => void;\n /** Unref timers so a pending heartbeat never keeps the process alive. */\n unref?: boolean;\n /** Where retried renewals are reported. Default: the console. */\n logger?: CopilotRuntimeLogger;\n}\n\nexport interface ThreadLockHeartbeat {\n /** Cancel the next renewal and any pending retry. Idempotent. */\n stop(): void;\n}\n\nclass RenewalTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Thread lock renewal did not settle within ${timeoutMs}ms`);\n this.name = \"RenewalTimeoutError\";\n }\n}\n\n/**\n * Whether a failed renewal may succeed if retried. A lost lock is a 409 the\n * platform marks `retryable: false`; server failures (5xx), timeouts and\n * network errors are worth retrying while the lock is still valid.\n */\nexport function isRetryableLockRenewalError(error: unknown): boolean {\n if (error instanceof PlatformRequestError) {\n if (error.retryable !== undefined) return error.retryable;\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n // Timeouts, fetch network failures and malformed responses.\n return true;\n}\n\n/**\n * Keep a thread lock alive for a running agent.\n *\n * Renews every `intervalMs` (sooner if that would run past the lock's\n * lifetime), with at most one renewal in flight. A failed renewal is retried\n * with exponential backoff while the lock is still valid: the deadline is when\n * the last successful renewal was *sent* plus the `ttlSeconds` it returned,\n * because the platform starts the TTL when it handles the request (initially\n * start plus `initialTtlSeconds`, or `fallbackTtlSeconds` when the platform\n * reported no lifetime at acquisition). A non-retryable failure, or running\n * out of time before the deadline, calls `onLost`.\n * A `\"completed\"` response means the run already ended on the platform, so\n * the heartbeat stops without calling `onLost`.\n */\nexport function startThreadLockHeartbeat(\n options: ThreadLockHeartbeatOptions,\n): ThreadLockHeartbeat {\n const { renew, intervalMs, fallbackTtlSeconds, onLost } = options;\n const logger = options.logger ?? getRuntimeLogger();\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const initialTtlSeconds =\n typeof options.initialTtlSeconds === \"number\" &&\n Number.isFinite(options.initialTtlSeconds)\n ? options.initialTtlSeconds\n : fallbackTtlSeconds;\n let deadline = Date.now() + initialTtlSeconds * 1_000;\n let failedAttempts = 0;\n\n const schedule = (delayMs: number): void => {\n timer = setTimeout(() => {\n timer = undefined;\n void attempt();\n }, delayMs);\n if (options.unref) timer.unref?.();\n };\n\n /** Time left before the safety cutoff ahead of the lock's expiry. */\n const remainingMs = (): number =>\n deadline - DEADLINE_SAFETY_MARGIN_MS - Date.now();\n\n // Renew on the interval, or right away when waiting that long would run\n // past the cutoff and leave the lock to lapse.\n const scheduleRenewal = (): void => {\n schedule(intervalMs < remainingMs() ? intervalMs : 0);\n };\n\n const stop = (): void => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const lose = (error: unknown): void => {\n stop();\n onLost(error);\n };\n\n const attempt = async (): Promise<void> => {\n // Bound each attempt by the lock's remaining lifetime so a hung request\n // cannot silently outlive the lock; past the cutoff, renewing is too late.\n const timeoutMs = Math.min(ATTEMPT_TIMEOUT_MS, remainingMs());\n if (timeoutMs <= 0) {\n lose(new Error(\"Thread lock expired before it could be renewed\"));\n return;\n }\n const sentAt = Date.now();\n const controller = new AbortController();\n let response: RenewThreadLockResponse;\n try {\n response = await withTimeout(\n renew(controller.signal),\n timeoutMs,\n options.unref,\n () => controller.abort(),\n );\n } catch (error) {\n if (!stopped) handleFailure(error);\n return;\n }\n if (stopped) return;\n\n failedAttempts = 0;\n if (response?.status === \"completed\") {\n stop();\n return;\n }\n const ttlSeconds =\n typeof response?.ttlSeconds === \"number\" && response.ttlSeconds > 0\n ? response.ttlSeconds\n : fallbackTtlSeconds;\n deadline = sentAt + ttlSeconds * 1_000;\n scheduleRenewal();\n };\n\n const handleFailure = (error: unknown): void => {\n if (!isRetryableLockRenewalError(error)) {\n lose(error);\n return;\n }\n const delayMs = Math.min(\n INITIAL_RETRY_DELAY_MS * 2 ** failedAttempts,\n MAX_RETRY_DELAY_MS,\n );\n failedAttempts += 1;\n const remaining = remainingMs();\n if (delayMs >= remaining) {\n lose(error);\n return;\n }\n logger.warn(\n {\n err: error,\n attempt: failedAttempts,\n retryInMs: delayMs,\n remainingMs: remaining,\n },\n \"Thread lock renewal failed; retrying before the lock expires\",\n );\n schedule(delayMs);\n };\n\n scheduleRenewal();\n return { stop };\n}\n\nfunction withTimeout<T>(\n promise: Promise<T>,\n timeoutMs: number,\n unref: boolean | undefined,\n onTimeout: () => void,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => {\n onTimeout();\n reject(new RenewalTimeoutError(timeoutMs));\n }, timeoutMs);\n if (unref) timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timeout);\n reject(error);\n },\n );\n });\n}\n"],"mappings":";;;;;AAMA,MAAM,yBAAyB;;AAE/B,MAAM,qBAAqB;;AAE3B,MAAM,qBAAqB;;AAE3B,MAAM,4BAA4B;AAyClC,IAAM,sBAAN,cAAkC,MAAM;CACtC,YAAY,WAAmB;AAC7B,QAAM,6CAA6C,UAAU,IAAI;AACjE,OAAK,OAAO;;;;;;;;AAShB,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,iBAAiB,sBAAsB;AACzC,MAAI,MAAM,cAAc,OAAW,QAAO,MAAM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MF,aAAW,UAHT,OAAO,UAAU,eAAe,YAAY,SAAS,aAAa,IAC9D,SAAS,aACT,sBAC2B;AACjC,mBAAiB;;CAGnB,MAAM,iBAAiB,UAAyB;AAC9C,MAAI,CAAC,4BAA4B,MAAM,EAAE;AACvC,QAAK,MAAM;AACX;;EAEF,MAAM,UAAU,KAAK,IACnB,yBAAyB,KAAK,gBAC9B,mBACD;AACD,oBAAkB;EAClB,MAAM,YAAY,aAAa;AAC/B,MAAI,WAAW,WAAW;AACxB,QAAK,MAAM;AACX;;AAEF,SAAO,KACL;GACE,KAAK;GACL,SAAS;GACT,WAAW;GACX,aAAa;GACd,EACD,+DACD;AACD,WAAS,QAAQ;;AAGnB,kBAAiB;AACjB,QAAO,EAAE,MAAM;;AAGjB,SAAS,YACP,SACA,WACA,OACA,WACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,UAAU,iBAAiB;AAC/B,cAAW;AACX,UAAO,IAAI,oBAAoB,UAAU,CAAC;KACzC,UAAU;AACb,MAAI,MAAO,SAAQ,SAAS;AAC5B,UAAQ,MACL,UAAU;AACT,gBAAa,QAAQ;AACrB,WAAQ,MAAM;MAEf,UAAmB;AAClB,gBAAa,QAAQ;AACrB,UAAO,MAAM;IAEhB;GACD"}
@@ -1,9 +1,8 @@
1
- const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
1
  let _copilotkit_shared = require("@copilotkit/shared");
3
2
  let zod = require("zod");
4
3
 
5
4
  //#region src/runtime/intelligence-platform/trajectories.ts
6
- const trajectoryIdSchema = zod.z.string().uuid();
5
+ const trajectoryIdSchema = zod.z.guid();
7
6
  function isValidTrajectoryId(value) {
8
7
  return trajectoryIdSchema.safeParse(value).success;
9
8
  }
@@ -14,7 +13,7 @@ const joinResponseSchema = zod.z.object({
14
13
  const grantSchema = zod.z.object({
15
14
  joinToken: zod.z.string().refine((value) => value.trim().length > 0),
16
15
  realtime: zod.z.object({
17
- clientUrl: zod.z.string().url().refine((value) => {
16
+ clientUrl: zod.z.url().refine((value) => {
18
17
  const url = new URL(value);
19
18
  return (url.protocol === "wss:" || url.protocol === "ws:") && !url.username && !url.password;
20
19
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"trajectories.cjs","names":["z"],"sources":["../../../src/runtime/intelligence-platform/trajectories.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { z } from \"zod\";\n\nexport interface TrajectoryConnectionGrant {\n joinToken: string;\n realtime: { clientUrl: string; topic: string };\n}\n\nconst trajectoryIdSchema = z.string().uuid();\n\nexport function isValidTrajectoryId(value: unknown): value is string {\n return trajectoryIdSchema.safeParse(value).success;\n}\n\nconst joinResponseSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n trajectoryId: trajectoryIdSchema,\n});\n\nconst grantSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n realtime: z.object({\n clientUrl: z\n .string()\n .url()\n .refine((value) => {\n const url = new URL(value);\n return (\n (url.protocol === \"wss:\" || url.protocol === \"ws:\") &&\n !url.username &&\n !url.password\n );\n }),\n topic: z\n .string()\n .refine((value) => value.trim().length > 0 && !/\\p{Cc}/u.test(value)),\n }),\n});\n\nconst runtimeConfigurationErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"AUTH_UNAUTHENTICATED\",\n \"API_KEY_NOT_FOUND\",\n \"ORG_NOT_FOUND\",\n \"PROJECT_NOT_FOUND\",\n ]),\n }),\n});\n\nconst contractErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"VALIDATION_ERROR\",\n \"TRAJECTORY_APP_USER_CONFLICT\",\n \"LEARNING_CONTAINER_NOT_FOUND\",\n \"RATE_LIMIT_EXCEEDED\",\n \"INTERNAL_SERVER_ERROR\",\n \"MARKETPLACE_LICENSE_REQUIRED\",\n \"TRAJECTORIES_NOT_ENABLED\",\n ]),\n message: z.string().trim().min(1).max(512),\n }),\n});\n\nexport class TrajectoryConnectionError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly status: number,\n ) {\n super(message);\n this.name = \"TrajectoryConnectionError\";\n }\n}\n\nexport function parseTrajectoryConnectionGrant(\n value: unknown,\n trajectoryId: string,\n clientUrl: string,\n): TrajectoryConnectionGrant {\n const join = joinResponseSchema.safeParse(value);\n const result = grantSchema.safeParse(\n join.success && join.data.trajectoryId === trajectoryId\n ? {\n joinToken: join.data.joinToken,\n realtime: { clientUrl, topic: `trajectory:${trajectoryId}` },\n }\n : undefined,\n );\n if (!result.success) {\n const joinValid = join.success && join.data.trajectoryId === trajectoryId;\n logger.warn(\n { trajectoryIdMatches: joinValid },\n joinValid\n ? \"Intelligence returned a Trajectory join token, but the Gateway URL is invalid; check the Intelligence wsUrl\"\n : \"Intelligence returned an invalid Trajectory join response\",\n );\n throw new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence returned an invalid trajectory connection grant\",\n 502,\n );\n }\n return {\n joinToken: result.data.joinToken,\n realtime: {\n clientUrl: result.data.realtime.clientUrl,\n topic: result.data.realtime.topic,\n },\n };\n}\n\n// Intelligence answers with this code when Trajectory capture is switched off\n// for the deployment, because the join route is then not registered.\nconst routeNotFoundSchema = z.object({\n error: z.object({ code: z.literal(\"ROUTE_NOT_FOUND\") }),\n});\n\nconst upstreamCodeSchema = z.object({\n error: z.object({ code: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/) }),\n});\n\n/** Forward only the public contract, never raw platform errors or credentials. */\nexport function trajectoryResponseError(\n value: unknown,\n status: number,\n apiKey: string,\n): TrajectoryConnectionError {\n const result = contractErrorSchema.safeParse(value);\n if (result.success && !result.data.error.message.includes(apiKey)) {\n return new TrajectoryConnectionError(\n result.data.error.code,\n result.data.error.message,\n status,\n );\n }\n if (status === 404 && routeNotFoundSchema.safeParse(value).success) {\n logger.warn(\n { status },\n \"Intelligence does not serve Trajectory capture; enable Trajectories for this deployment\",\n );\n return new TrajectoryConnectionError(\n \"TRAJECTORIES_UNAVAILABLE\",\n \"This Intelligence deployment does not serve Trajectory capture\",\n 404,\n );\n }\n // The browser only learns that the connection failed. Log the upstream code,\n // never the message, so the cause is visible to the Runtime's operator.\n logger.warn(\n {\n status,\n upstreamCode: upstreamCodeSchema.safeParse(value).data?.error.code,\n },\n \"Intelligence rejected the Trajectory connection request; the browser receives CONNECTION_FAILED\",\n );\n // These failures describe the Runtime's server credentials or tenant setup,\n // not the browser user's identity. Do not expose them as a client auth error.\n if (runtimeConfigurationErrorSchema.safeParse(value).success) {\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence rejected the trajectory connection request\",\n status,\n );\n}\n"],"mappings":";;;;;AAQA,MAAM,qBAAqBA,MAAE,QAAQ,CAAC,MAAM;AAE5C,SAAgB,oBAAoB,OAAiC;AACnE,QAAO,mBAAmB,UAAU,MAAM,CAAC;;AAG7C,MAAM,qBAAqBA,MAAE,OAAO;CAClC,WAAWA,MAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,cAAc;CACf,CAAC;AAEF,MAAM,cAAcA,MAAE,OAAO;CAC3B,WAAWA,MAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,UAAUA,MAAE,OAAO;EACjB,WAAWA,MACR,QAAQ,CACR,KAAK,CACL,QAAQ,UAAU;GACjB,MAAM,MAAM,IAAI,IAAI,MAAM;AAC1B,WACG,IAAI,aAAa,UAAU,IAAI,aAAa,UAC7C,CAAC,IAAI,YACL,CAAC,IAAI;IAEP;EACJ,OAAOA,MACJ,QAAQ,CACR,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,KAAK,CAAC,UAAU,KAAK,MAAM,CAAC;EACxE,CAAC;CACH,CAAC;AAEF,MAAM,kCAAkCA,MAAE,OAAO,EAC/C,OAAOA,MAAE,OAAO,EACd,MAAMA,MAAE,KA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M,SAAS,oBAAoB,UAAU,MAAM;AACnD,KAAI,OAAO,WAAW,CAAC,OAAO,KAAK,MAAM,QAAQ,SAAS,OAAO,CAC/D,QAAO,IAAI,0BACT,OAAO,KAAK,MAAM,MAClB,OAAO,KAAK,MAAM,SAClB,OACD;AAEH,KAAI,WAAW,OAAO,oBAAoB,UAAU,MAAM,CAAC,SAAS;AAClE,4BAAO,KACL,EAAE,QAAQ,EACV,0FACD;AACD,SAAO,IAAI,0BACT,4BACA,kEACA,IACD;;AAIH,2BAAO,KACL;EACE;EACA,cAAc,mBAAmB,UAAU,MAAM,CAAC,MAAM,MAAM;EAC/D,EACD,kGACD;AAGD,KAAI,gCAAgC,UAAU,MAAM,CAAC,QACnD,QAAO,IAAI,0BACT,qBACA,qCACA,IACD;AAEH,QAAO,IAAI,0BACT,qBACA,2DACA,OACD"}
1
+ {"version":3,"file":"trajectories.cjs","names":["z"],"sources":["../../../src/runtime/intelligence-platform/trajectories.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { z } from \"zod\";\n\nexport interface TrajectoryConnectionGrant {\n joinToken: string;\n realtime: { clientUrl: string; topic: string };\n}\n\nconst trajectoryIdSchema = z.guid();\n\nexport function isValidTrajectoryId(value: unknown): value is string {\n return trajectoryIdSchema.safeParse(value).success;\n}\n\nconst joinResponseSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n trajectoryId: trajectoryIdSchema,\n});\n\nconst grantSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n realtime: z.object({\n clientUrl: z.url().refine((value) => {\n const url = new URL(value);\n return (\n (url.protocol === \"wss:\" || url.protocol === \"ws:\") &&\n !url.username &&\n !url.password\n );\n }),\n topic: z\n .string()\n .refine((value) => value.trim().length > 0 && !/\\p{Cc}/u.test(value)),\n }),\n});\n\nconst runtimeConfigurationErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"AUTH_UNAUTHENTICATED\",\n \"API_KEY_NOT_FOUND\",\n \"ORG_NOT_FOUND\",\n \"PROJECT_NOT_FOUND\",\n ]),\n }),\n});\n\nconst contractErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"VALIDATION_ERROR\",\n \"TRAJECTORY_APP_USER_CONFLICT\",\n \"LEARNING_CONTAINER_NOT_FOUND\",\n \"RATE_LIMIT_EXCEEDED\",\n \"INTERNAL_SERVER_ERROR\",\n \"MARKETPLACE_LICENSE_REQUIRED\",\n \"TRAJECTORIES_NOT_ENABLED\",\n ]),\n message: z.string().trim().min(1).max(512),\n }),\n});\n\nexport class TrajectoryConnectionError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly status: number,\n ) {\n super(message);\n this.name = \"TrajectoryConnectionError\";\n }\n}\n\nexport function parseTrajectoryConnectionGrant(\n value: unknown,\n trajectoryId: string,\n clientUrl: string,\n): TrajectoryConnectionGrant {\n const join = joinResponseSchema.safeParse(value);\n const result = grantSchema.safeParse(\n join.success && join.data.trajectoryId === trajectoryId\n ? {\n joinToken: join.data.joinToken,\n realtime: { clientUrl, topic: `trajectory:${trajectoryId}` },\n }\n : undefined,\n );\n if (!result.success) {\n const joinValid = join.success && join.data.trajectoryId === trajectoryId;\n logger.warn(\n { trajectoryIdMatches: joinValid },\n joinValid\n ? \"Intelligence returned a Trajectory join token, but the Gateway URL is invalid; check the Intelligence wsUrl\"\n : \"Intelligence returned an invalid Trajectory join response\",\n );\n throw new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence returned an invalid trajectory connection grant\",\n 502,\n );\n }\n return {\n joinToken: result.data.joinToken,\n realtime: {\n clientUrl: result.data.realtime.clientUrl,\n topic: result.data.realtime.topic,\n },\n };\n}\n\n// Intelligence answers with this code when Trajectory capture is switched off\n// for the deployment, because the join route is then not registered.\nconst routeNotFoundSchema = z.object({\n error: z.object({ code: z.literal(\"ROUTE_NOT_FOUND\") }),\n});\n\nconst upstreamCodeSchema = z.object({\n error: z.object({ code: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/) }),\n});\n\n/** Forward only the public contract, never raw platform errors or credentials. */\nexport function trajectoryResponseError(\n value: unknown,\n status: number,\n apiKey: string,\n): TrajectoryConnectionError {\n const result = contractErrorSchema.safeParse(value);\n if (result.success && !result.data.error.message.includes(apiKey)) {\n return new TrajectoryConnectionError(\n result.data.error.code,\n result.data.error.message,\n status,\n );\n }\n if (status === 404 && routeNotFoundSchema.safeParse(value).success) {\n logger.warn(\n { status },\n \"Intelligence does not serve Trajectory capture; enable Trajectories for this deployment\",\n );\n return new TrajectoryConnectionError(\n \"TRAJECTORIES_UNAVAILABLE\",\n \"This Intelligence deployment does not serve Trajectory capture\",\n 404,\n );\n }\n // The browser only learns that the connection failed. Log the upstream code,\n // never the message, so the cause is visible to the Runtime's operator.\n logger.warn(\n {\n status,\n upstreamCode: upstreamCodeSchema.safeParse(value).data?.error.code,\n },\n \"Intelligence rejected the Trajectory connection request; the browser receives CONNECTION_FAILED\",\n );\n // These failures describe the Runtime's server credentials or tenant setup,\n // not the browser user's identity. Do not expose them as a client auth error.\n if (runtimeConfigurationErrorSchema.safeParse(value).success) {\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence rejected the trajectory connection request\",\n status,\n );\n}\n"],"mappings":";;;;AAQA,MAAM,qBAAqBA,MAAE,MAAM;AAEnC,SAAgB,oBAAoB,OAAiC;AACnE,QAAO,mBAAmB,UAAU,MAAM,CAAC;;AAG7C,MAAM,qBAAqBA,MAAE,OAAO;CAClC,WAAWA,MAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,cAAc;CACf,CAAC;AAEF,MAAM,cAAcA,MAAE,OAAO;CAC3B,WAAWA,MAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,UAAUA,MAAE,OAAO;EACjB,WA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WAAW,OAAO,KAAK,SAAS;GAChC,OAAO,OAAO,KAAK,SAAS;GAC7B;EACF;;AAKH,MAAM,sBAAsBA,MAAE,OAAO,EACnC,OAAOA,MAAE,OAAO,EAAE,MAAMA,MAAE,QAAQ,kBAAkB,EAAE,CAAC,EACxD,CAAC;AAEF,MAAM,qBAAqBA,MAAE,OAAO,EAClC,OAAOA,MAAE,OAAO,EAAE,MAAMA,MAAE,QAAQ,CAAC,MAAM,yBAAyB,EAAE,CAAC,EACtE,CAAC;;AAGF,SAAgB,wBACd,OACA,QACA,QAC2B;CAC3B,MAAM,SAAS,oBAAoB,UAAU,MAAM;AACnD,KAAI,OAAO,WAAW,CAAC,OAAO,KAAK,MAAM,QAAQ,SAAS,OAAO,CAC/D,QAAO,IAAI,0BACT,OAAO,KAAK,MAAM,MAClB,OAAO,KAAK,MAAM,SAClB,OACD;AAEH,KAAI,WAAW,OAAO,oBAAoB,UAAU,MAAM,CAAC,SAAS;AAClE,4BAAO,KACL,EAAE,QAAQ,EACV,0FACD;AACD,SAAO,IAAI,0BACT,4BACA,kEACA,IACD;;AAIH,2BAAO,KACL;EACE;EACA,cAAc,mBAAmB,UAAU,MAAM,CAAC,MAAM,MAAM;EAC/D,EACD,kGACD;AAGD,KAAI,gCAAgC,UAAU,MAAM,CAAC,QACnD,QAAO,IAAI,0BACT,qBACA,qCACA,IACD;AAEH,QAAO,IAAI,0BACT,qBACA,2DACA,OACD"}
@@ -2,7 +2,7 @@ import { logger } from "@copilotkit/shared";
2
2
  import { z } from "zod";
3
3
 
4
4
  //#region src/runtime/intelligence-platform/trajectories.ts
5
- const trajectoryIdSchema = z.string().uuid();
5
+ const trajectoryIdSchema = z.guid();
6
6
  function isValidTrajectoryId(value) {
7
7
  return trajectoryIdSchema.safeParse(value).success;
8
8
  }
@@ -13,7 +13,7 @@ const joinResponseSchema = z.object({
13
13
  const grantSchema = z.object({
14
14
  joinToken: z.string().refine((value) => value.trim().length > 0),
15
15
  realtime: z.object({
16
- clientUrl: z.string().url().refine((value) => {
16
+ clientUrl: z.url().refine((value) => {
17
17
  const url = new URL(value);
18
18
  return (url.protocol === "wss:" || url.protocol === "ws:") && !url.username && !url.password;
19
19
  }),
@@ -1 +1 @@
1
- {"version":3,"file":"trajectories.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/trajectories.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { z } from \"zod\";\n\nexport interface TrajectoryConnectionGrant {\n joinToken: string;\n realtime: { clientUrl: string; topic: string };\n}\n\nconst trajectoryIdSchema = z.string().uuid();\n\nexport function isValidTrajectoryId(value: unknown): value is string {\n return trajectoryIdSchema.safeParse(value).success;\n}\n\nconst joinResponseSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n trajectoryId: trajectoryIdSchema,\n});\n\nconst grantSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n realtime: z.object({\n clientUrl: z\n .string()\n .url()\n .refine((value) => {\n const url = new URL(value);\n return (\n (url.protocol === \"wss:\" || url.protocol === \"ws:\") &&\n !url.username &&\n !url.password\n );\n }),\n topic: z\n .string()\n .refine((value) => value.trim().length > 0 && !/\\p{Cc}/u.test(value)),\n }),\n});\n\nconst runtimeConfigurationErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"AUTH_UNAUTHENTICATED\",\n \"API_KEY_NOT_FOUND\",\n \"ORG_NOT_FOUND\",\n \"PROJECT_NOT_FOUND\",\n ]),\n }),\n});\n\nconst contractErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"VALIDATION_ERROR\",\n \"TRAJECTORY_APP_USER_CONFLICT\",\n \"LEARNING_CONTAINER_NOT_FOUND\",\n \"RATE_LIMIT_EXCEEDED\",\n \"INTERNAL_SERVER_ERROR\",\n \"MARKETPLACE_LICENSE_REQUIRED\",\n \"TRAJECTORIES_NOT_ENABLED\",\n ]),\n message: z.string().trim().min(1).max(512),\n }),\n});\n\nexport class TrajectoryConnectionError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly status: number,\n ) {\n super(message);\n this.name = \"TrajectoryConnectionError\";\n }\n}\n\nexport function parseTrajectoryConnectionGrant(\n value: unknown,\n trajectoryId: string,\n clientUrl: string,\n): TrajectoryConnectionGrant {\n const join = joinResponseSchema.safeParse(value);\n const result = grantSchema.safeParse(\n join.success && join.data.trajectoryId === trajectoryId\n ? {\n joinToken: join.data.joinToken,\n realtime: { clientUrl, topic: `trajectory:${trajectoryId}` },\n }\n : undefined,\n );\n if (!result.success) {\n const joinValid = join.success && join.data.trajectoryId === trajectoryId;\n logger.warn(\n { trajectoryIdMatches: joinValid },\n joinValid\n ? \"Intelligence returned a Trajectory join token, but the Gateway URL is invalid; check the Intelligence wsUrl\"\n : \"Intelligence returned an invalid Trajectory join response\",\n );\n throw new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence returned an invalid trajectory connection grant\",\n 502,\n );\n }\n return {\n joinToken: result.data.joinToken,\n realtime: {\n clientUrl: result.data.realtime.clientUrl,\n topic: result.data.realtime.topic,\n },\n };\n}\n\n// Intelligence answers with this code when Trajectory capture is switched off\n// for the deployment, because the join route is then not registered.\nconst routeNotFoundSchema = z.object({\n error: z.object({ code: z.literal(\"ROUTE_NOT_FOUND\") }),\n});\n\nconst upstreamCodeSchema = z.object({\n error: z.object({ code: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/) }),\n});\n\n/** Forward only the public contract, never raw platform errors or credentials. */\nexport function trajectoryResponseError(\n value: unknown,\n status: number,\n apiKey: string,\n): TrajectoryConnectionError {\n const result = contractErrorSchema.safeParse(value);\n if (result.success && !result.data.error.message.includes(apiKey)) {\n return new TrajectoryConnectionError(\n result.data.error.code,\n result.data.error.message,\n status,\n );\n }\n if (status === 404 && routeNotFoundSchema.safeParse(value).success) {\n logger.warn(\n { status },\n \"Intelligence does not serve Trajectory capture; enable Trajectories for this deployment\",\n );\n return new TrajectoryConnectionError(\n \"TRAJECTORIES_UNAVAILABLE\",\n \"This Intelligence deployment does not serve Trajectory capture\",\n 404,\n );\n }\n // The browser only learns that the connection failed. Log the upstream code,\n // never the message, so the cause is visible to the Runtime's operator.\n logger.warn(\n {\n status,\n upstreamCode: upstreamCodeSchema.safeParse(value).data?.error.code,\n },\n \"Intelligence rejected the Trajectory connection request; the browser receives CONNECTION_FAILED\",\n );\n // These failures describe the Runtime's server credentials or tenant setup,\n // not the browser user's identity. Do not expose them as a client auth error.\n if (runtimeConfigurationErrorSchema.safeParse(value).success) {\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence rejected the trajectory connection request\",\n status,\n );\n}\n"],"mappings":";;;;AAQA,MAAM,qBAAqB,EAAE,QAAQ,CAAC,MAAM;AAE5C,SAAgB,oBAAoB,OAAiC;AACnE,QAAO,mBAAmB,UAAU,MAAM,CAAC;;AAG7C,MAAM,qBAAqB,EAAE,OAAO;CAClC,WAAW,EAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,cAAc;CACf,CAAC;AAEF,MAAM,cAAc,EAAE,OAAO;CAC3B,WAAW,EAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,UAAU,EAAE,OAAO;EACjB,WAAW,EACR,QAAQ,CACR,KAAK,CACL,QAAQ,UAAU;GACjB,MAAM,MAAM,IAAI,IAAI,MAAM;AAC1B,WACG,IAAI,aAAa,UAAU,IAAI,aAAa,UAC7C,CAAC,IAAI,YACL,CAAC,IAAI;IAEP;EACJ,OAAO,EACJ,QAAQ,CACR,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,KAAK,CAAC,UAAU,KAAK,MAAM,CAAC;EACxE,CAAC;CACH,CAAC;AAEF,MAAM,kCAAkC,EAAE,OAAO,EAC/C,OAAO,EAAE,OAAO,EACd,MAAM,EAAE,KA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AoB,UAAU,MAAM;AACnD,KAAI,OAAO,WAAW,CAAC,OAAO,KAAK,MAAM,QAAQ,SAAS,OAAO,CAC/D,QAAO,IAAI,0BACT,OAAO,KAAK,MAAM,MAClB,OAAO,KAAK,MAAM,SAClB,OACD;AAEH,KAAI,WAAW,OAAO,oBAAoB,UAAU,MAAM,CAAC,SAAS;AAClE,SAAO,KACL,EAAE,QAAQ,EACV,0FACD;AACD,SAAO,IAAI,0BACT,4BACA,kEACA,IACD;;AAIH,QAAO,KACL;EACE;EACA,cAAc,mBAAmB,UAAU,MAAM,CAAC,MAAM,MAAM;EAC/D,EACD,kGACD;AAGD,KAAI,gCAAgC,UAAU,MAAM,CAAC,QACnD,QAAO,IAAI,0BACT,qBACA,qCACA,IACD;AAEH,QAAO,IAAI,0BACT,qBACA,2DACA,OACD"}
1
+ {"version":3,"file":"trajectories.mjs","names":[],"sources":["../../../src/runtime/intelligence-platform/trajectories.ts"],"sourcesContent":["import { logger } from \"@copilotkit/shared\";\nimport { z } from \"zod\";\n\nexport interface TrajectoryConnectionGrant {\n joinToken: string;\n realtime: { clientUrl: string; topic: string };\n}\n\nconst trajectoryIdSchema = z.guid();\n\nexport function isValidTrajectoryId(value: unknown): value is string {\n return trajectoryIdSchema.safeParse(value).success;\n}\n\nconst joinResponseSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n trajectoryId: trajectoryIdSchema,\n});\n\nconst grantSchema = z.object({\n joinToken: z.string().refine((value) => value.trim().length > 0),\n realtime: z.object({\n clientUrl: z.url().refine((value) => {\n const url = new URL(value);\n return (\n (url.protocol === \"wss:\" || url.protocol === \"ws:\") &&\n !url.username &&\n !url.password\n );\n }),\n topic: z\n .string()\n .refine((value) => value.trim().length > 0 && !/\\p{Cc}/u.test(value)),\n }),\n});\n\nconst runtimeConfigurationErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"AUTH_UNAUTHENTICATED\",\n \"API_KEY_NOT_FOUND\",\n \"ORG_NOT_FOUND\",\n \"PROJECT_NOT_FOUND\",\n ]),\n }),\n});\n\nconst contractErrorSchema = z.object({\n error: z.object({\n code: z.enum([\n \"VALIDATION_ERROR\",\n \"TRAJECTORY_APP_USER_CONFLICT\",\n \"LEARNING_CONTAINER_NOT_FOUND\",\n \"RATE_LIMIT_EXCEEDED\",\n \"INTERNAL_SERVER_ERROR\",\n \"MARKETPLACE_LICENSE_REQUIRED\",\n \"TRAJECTORIES_NOT_ENABLED\",\n ]),\n message: z.string().trim().min(1).max(512),\n }),\n});\n\nexport class TrajectoryConnectionError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n public readonly status: number,\n ) {\n super(message);\n this.name = \"TrajectoryConnectionError\";\n }\n}\n\nexport function parseTrajectoryConnectionGrant(\n value: unknown,\n trajectoryId: string,\n clientUrl: string,\n): TrajectoryConnectionGrant {\n const join = joinResponseSchema.safeParse(value);\n const result = grantSchema.safeParse(\n join.success && join.data.trajectoryId === trajectoryId\n ? {\n joinToken: join.data.joinToken,\n realtime: { clientUrl, topic: `trajectory:${trajectoryId}` },\n }\n : undefined,\n );\n if (!result.success) {\n const joinValid = join.success && join.data.trajectoryId === trajectoryId;\n logger.warn(\n { trajectoryIdMatches: joinValid },\n joinValid\n ? \"Intelligence returned a Trajectory join token, but the Gateway URL is invalid; check the Intelligence wsUrl\"\n : \"Intelligence returned an invalid Trajectory join response\",\n );\n throw new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence returned an invalid trajectory connection grant\",\n 502,\n );\n }\n return {\n joinToken: result.data.joinToken,\n realtime: {\n clientUrl: result.data.realtime.clientUrl,\n topic: result.data.realtime.topic,\n },\n };\n}\n\n// Intelligence answers with this code when Trajectory capture is switched off\n// for the deployment, because the join route is then not registered.\nconst routeNotFoundSchema = z.object({\n error: z.object({ code: z.literal(\"ROUTE_NOT_FOUND\") }),\n});\n\nconst upstreamCodeSchema = z.object({\n error: z.object({ code: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/) }),\n});\n\n/** Forward only the public contract, never raw platform errors or credentials. */\nexport function trajectoryResponseError(\n value: unknown,\n status: number,\n apiKey: string,\n): TrajectoryConnectionError {\n const result = contractErrorSchema.safeParse(value);\n if (result.success && !result.data.error.message.includes(apiKey)) {\n return new TrajectoryConnectionError(\n result.data.error.code,\n result.data.error.message,\n status,\n );\n }\n if (status === 404 && routeNotFoundSchema.safeParse(value).success) {\n logger.warn(\n { status },\n \"Intelligence does not serve Trajectory capture; enable Trajectories for this deployment\",\n );\n return new TrajectoryConnectionError(\n \"TRAJECTORIES_UNAVAILABLE\",\n \"This Intelligence deployment does not serve Trajectory capture\",\n 404,\n );\n }\n // The browser only learns that the connection failed. Log the upstream code,\n // never the message, so the cause is visible to the Runtime's operator.\n logger.warn(\n {\n status,\n upstreamCode: upstreamCodeSchema.safeParse(value).data?.error.code,\n },\n \"Intelligence rejected the Trajectory connection request; the browser receives CONNECTION_FAILED\",\n );\n // These failures describe the Runtime's server credentials or tenant setup,\n // not the browser user's identity. Do not expose them as a client auth error.\n if (runtimeConfigurationErrorSchema.safeParse(value).success) {\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Could not connect to Intelligence\",\n 502,\n );\n }\n return new TrajectoryConnectionError(\n \"CONNECTION_FAILED\",\n \"Intelligence rejected the trajectory connection request\",\n status,\n );\n}\n"],"mappings":";;;;AAQA,MAAM,qBAAqB,EAAE,MAAM;AAEnC,SAAgB,oBAAoB,OAAiC;AACnE,QAAO,mBAAmB,UAAU,MAAM,CAAC;;AAG7C,MAAM,qBAAqB,EAAE,OAAO;CAClC,WAAW,EAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,cAAc;CACf,CAAC;AAEF,MAAM,cAAc,EAAE,OAAO;CAC3B,WAAW,EAAE,QAAQ,CAAC,QAAQ,UAAU,MAAM,MAAM,CAAC,SAAS,EAAE;CAChE,UAAU,EAAE,OAAO;EACjB,WAAW,EAAE,KAAK,CAAC,QA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,OAAO,KAAK,SAAS;GAC7B;EACF;;AAKH,MAAM,sBAAsB,EAAE,OAAO,EACnC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,kBAAkB,EAAE,CAAC,EACxD,CAAC;AAEF,MAAM,qBAAqB,EAAE,OAAO,EAClC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,yBAAyB,EAAE,CAAC,EACtE,CAAC;;AAGF,SAAgB,wBACd,OACA,QACA,QAC2B;CAC3B,MAAM,SAAS,oBAAoB,UAAU,MAAM;AACnD,KAAI,OAAO,WAAW,CAAC,OAAO,KAAK,MAAM,QAAQ,SAAS,OAAO,CAC/D,QAAO,IAAI,0BACT,OAAO,KAAK,MAAM,MAClB,OAAO,KAAK,MAAM,SAClB,OACD;AAEH,KAAI,WAAW,OAAO,oBAAoB,UAAU,MAAM,CAAC,SAAS;AAClE,SAAO,KACL,EAAE,QAAQ,EACV,0FACD;AACD,SAAO,IAAI,0BACT,4BACA,kEACA,IACD;;AAIH,QAAO,KACL;EACE;EACA,cAAc,mBAAmB,UAAU,MAAM,CAAC,MAAM,MAAM;EAC/D,EACD,kGACD;AAGD,KAAI,gCAAgC,UAAU,MAAM,CAAC,QACnD,QAAO,IAAI,0BACT,qBACA,qCACA,IACD;AAEH,QAAO,IAAI,0BACT,qBACA,2DACA,OACD"}
@@ -1,2 +1,2 @@
1
- import { NodeFetchHandler, createCopilotNodeHandler, createNodeFetchHandler } from "./endpoints/node-fetch-handler.cjs";
1
+ import { NodeFetchHandler, createCopilotNodeHandler } from "./endpoints/node-fetch-handler.cjs";
2
2
  import { NodeCopilotListener, NodeCopilotListenerWithChannels, createCopilotNodeListener } from "./endpoints/node.cjs";
@@ -1,2 +1,2 @@
1
- import { NodeFetchHandler, createCopilotNodeHandler, createNodeFetchHandler } from "./endpoints/node-fetch-handler.mjs";
1
+ import { NodeFetchHandler, createCopilotNodeHandler } from "./endpoints/node-fetch-handler.mjs";
2
2
  import { NodeCopilotListener, NodeCopilotListenerWithChannels, createCopilotNodeListener } from "./endpoints/node.mjs";
@@ -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/runner/agent-runner.ts
@@ -1 +1 @@
1
- {"version":3,"file":"agent-runner.cjs","names":["THREAD_ALREADY_RUNNING_ERROR_CODE"],"sources":["../../../src/runtime/runner/agent-runner.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\n\n/**\n * Thrown by a runner when the thread already has a run in flight. The SSE\n * handler sends it to the client as a `RUN_ERROR` with\n * {@link THREAD_ALREADY_RUNNING_ERROR_CODE}, matched on `code` so a copy of\n * this class from another package version still counts.\n */\nexport class ThreadAlreadyRunningError extends Error {\n readonly code = THREAD_ALREADY_RUNNING_ERROR_CODE;\n\n constructor() {\n super(\"Thread already running\");\n this.name = \"ThreadAlreadyRunningError\";\n }\n}\n\n/** `code` of {@link ThreadAccessDeniedError}, also sent on the SSE `RUN_ERROR`. */\nexport const THREAD_ACCESS_DENIED_ERROR_CODE = \"THREAD_ACCESS_DENIED\";\n\n/**\n * Thrown by a runner when a run targets a Thread that another identity owns.\n *\n * Defense in depth: the run handler checks `isThreadAccessible` first and\n * refuses with an HTTP error, so the runner throws this only when another\n * identity claims the Thread between that check and the run, or for direct\n * runner callers. A synchronous throw from `run()` is still mapped to the\n * HTTP error; a later one reaches the client as a `RUN_ERROR` with\n * {@link THREAD_ACCESS_DENIED_ERROR_CODE}. Neither is reported as an agent\n * failure. Matched on `code`, so a copy of this class from another package\n * version still counts.\n */\nexport class ThreadAccessDeniedError extends Error {\n readonly code = THREAD_ACCESS_DENIED_ERROR_CODE;\n\n constructor() {\n super(\"Thread access denied\");\n this.name = \"ThreadAccessDeniedError\";\n }\n}\n\n/** True for a {@link ThreadAccessDeniedError}, from any package version. */\nexport function isThreadAccessDeniedError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error as { code?: unknown }).code === THREAD_ACCESS_DENIED_ERROR_CODE\n );\n}\n\n/**\n * Owner of a Thread created, or reached, by a runner call that names no owner:\n * a run, connect, stop or isRunning without `ownerId`, or a Thread endpoint call\n * without a scope. Such calls come only from trusted server-side code (for\n * example a Channel listener), and they act as this one server identity.\n *\n * No HTTP caller can act as it: request identities are `\"\"` (anonymous) or an\n * id that `identifyUser` returned, and a valid id cannot hold a NUL character.\n * So an omitted owner never means \"every Thread\", and a Thread created\n * server-side is never reachable by an anonymous caller.\n */\nexport const ɵSERVER_THREAD_OWNER = \"\\u0000server\";\n\n/** The owner a runner call acts as: `ownerId`, or the server owner when omitted. */\nexport function ɵresolveThreadOwner(ownerId: string | undefined): string {\n return ownerId ?? ɵSERVER_THREAD_OWNER;\n}\n\nexport interface AgentRunnerRunRequest {\n threadId: string;\n /** Backend execution ID supplied by Intelligence for imported non-UUID sessions. */\n backendThreadId?: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n persistedInputMessages?: Message[];\n /** Short-lived token scoped to this runner invocation. */\n authToken?: string;\n /**\n * Identity the run acts as. A runner that tracks owners records it on the\n * Thread's first run and refuses a run from any other identity. `\"\"` is the\n * anonymous owner. When omitted, the run acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerConnectRequest {\n threadId: string;\n agentId?: string;\n headers?: Record<string, string>;\n joinCode?: string;\n /**\n * Caller identity. A Thread owned by another identity is treated as unknown.\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerIsRunningRequest {\n threadId: string;\n /**\n * Caller identity. A Thread owned by another identity reports \"not running\".\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerStopRequest {\n threadId: string;\n /** When present, stop only this exact run and never a newer run on the Thread. */\n runId?: string;\n /**\n * Caller identity. A run on a Thread owned by another identity is not\n * stopped. When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface LocalThreadEndpointRecord {\n id: string;\n name: string | null;\n agentId: string;\n organizationId: string;\n createdById: string;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Limits a local Thread endpoint call to the Threads of one owner. `\"\"` is the\n * anonymous owner. A call without a scope acts as\n * {@link ɵSERVER_THREAD_OWNER}: it sees only Threads created server-side, never\n * every Thread.\n */\nexport interface LocalThreadEndpointScope {\n ownerId: string;\n}\n\nexport interface LocalThreadEndpointRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints: true;\n listThreads(scope?: LocalThreadEndpointScope): LocalThreadEndpointRecord[];\n getThreadMessages(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Message[];\n getThreadEvents(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): BaseEvent[];\n getThreadState(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Record<string, unknown> | null;\n clearThreads(scope?: LocalThreadEndpointScope): void;\n /** See {@link ThreadOwnershipRunner.isThreadAccessible}. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean;\n}\n\nexport function supportsLocalThreadEndpoints(\n runner: AgentRunner,\n): runner is LocalThreadEndpointRunner {\n return runner.ɵsupportsLocalThreadEndpoints === true;\n}\n\n/**\n * A runner that records each Thread's owner and enforces it. Implementing\n * `isThreadAccessible` is the promise that `run`, `connect`, `stop` and\n * `isRunning` honor `ownerId` the same way: a call never reaches a Thread that\n * another owner holds.\n */\nexport interface ThreadOwnershipRunner extends AgentRunner {\n /** False when the Thread id is held by an owner other than `scope`'s. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n}\n\n/**\n * True when `runner` enforces Thread owners. Checks the method itself, so a\n * runner built against an older interface (one that sets the endpoint flag\n * but has no `isThreadAccessible`) is not taken to enforce them.\n */\nexport function enforcesThreadOwnership(\n runner: AgentRunner,\n): runner is ThreadOwnershipRunner {\n return typeof runner.isThreadAccessible === \"function\";\n}\n\nexport abstract class AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints?: boolean;\n\n /** See {@link ThreadOwnershipRunner}. Optional: not every runner tracks owners. */\n isThreadAccessible?(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n\n abstract run(request: AgentRunnerRunRequest): Observable<BaseEvent>;\n abstract connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;\n abstract isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;\n abstract stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;\n}\n"],"mappings":";;;;;;;;;;AAeA,IAAa,4BAAb,cAA+C,MAAM;CAGnD,cAAc;AACZ,QAAM,yBAAyB;cAHjBA;AAId,OAAK,OAAO;;;;AAKhB,MAAa,kCAAkC;;;;;;;;;;;;;AAc/C,IAAa,0BAAb,cAA6C,MAAM;CAGjD,cAAc;AACZ,QAAM,uBAAuB;cAHf;AAId,OAAK,OAAO;;;;AAKhB,SAAgB,0BAA0B,OAAyB;AACjE,QACE,iBAAiB,SAChB,MAA6B,SAAS;;;;;;;;;;;;;AAe3C,MAAa,uBAAuB;;AAGpC,SAAgB,oBAAoB,SAAqC;AACvE,QAAO,WAAW;;AAgGpB,SAAgB,6BACd,QACqC;AACrC,QAAO,OAAO,kCAAkC;;;;;;;AAsBlD,SAAgB,wBACd,QACiC;AACjC,QAAO,OAAO,OAAO,uBAAuB;;AAG9C,IAAsB,cAAtB,MAAkC"}
1
+ {"version":3,"file":"agent-runner.cjs","names":["THREAD_ALREADY_RUNNING_ERROR_CODE"],"sources":["../../../src/runtime/runner/agent-runner.ts"],"sourcesContent":["import type {\n AbstractAgent,\n BaseEvent,\n Message,\n RunAgentInput,\n} from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { THREAD_ALREADY_RUNNING_ERROR_CODE } from \"@copilotkit/shared\";\n\n/**\n * Thrown by a runner when the thread already has a run in flight. The SSE\n * handler sends it to the client as a `RUN_ERROR` with\n * {@link THREAD_ALREADY_RUNNING_ERROR_CODE}, matched on `code` so a copy of\n * this class from another package version still counts.\n */\nexport class ThreadAlreadyRunningError extends Error {\n readonly code = THREAD_ALREADY_RUNNING_ERROR_CODE;\n\n constructor() {\n super(\"Thread already running\");\n this.name = \"ThreadAlreadyRunningError\";\n }\n}\n\n/** `code` of {@link ThreadAccessDeniedError}, also sent on the SSE `RUN_ERROR`. */\nexport const THREAD_ACCESS_DENIED_ERROR_CODE = \"THREAD_ACCESS_DENIED\";\n\n/**\n * Thrown by a runner when a run targets a Thread that another identity owns.\n *\n * Defense in depth: the run handler checks `isThreadAccessible` first and\n * refuses with an HTTP error, so the runner throws this only when another\n * identity claims the Thread between that check and the run, or for direct\n * runner callers. A synchronous throw from `run()` is still mapped to the\n * HTTP error; a later one reaches the client as a `RUN_ERROR` with\n * {@link THREAD_ACCESS_DENIED_ERROR_CODE}. Neither is reported as an agent\n * failure. Matched on `code`, so a copy of this class from another package\n * version still counts.\n */\nexport class ThreadAccessDeniedError extends Error {\n readonly code = THREAD_ACCESS_DENIED_ERROR_CODE;\n\n constructor() {\n super(\"Thread access denied\");\n this.name = \"ThreadAccessDeniedError\";\n }\n}\n\n/** True for a {@link ThreadAccessDeniedError}, from any package version. */\nexport function isThreadAccessDeniedError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error as { code?: unknown }).code === THREAD_ACCESS_DENIED_ERROR_CODE\n );\n}\n\n/**\n * Owner of a Thread created, or reached, by a runner call that names no owner:\n * a run, connect, stop or isRunning without `ownerId`, or a Thread endpoint call\n * without a scope. Such calls come only from trusted server-side code (for\n * example a Channel listener), and they act as this one server identity.\n *\n * No HTTP caller can act as it: request identities are `\"\"` (anonymous) or an\n * id that `identifyUser` returned, and a valid id cannot hold a NUL character.\n * So an omitted owner never means \"every Thread\", and a Thread created\n * server-side is never reachable by an anonymous caller.\n */\nexport const ɵSERVER_THREAD_OWNER = \"\\u0000server\";\n\n/** The owner a runner call acts as: `ownerId`, or the server owner when omitted. */\nexport function ɵresolveThreadOwner(ownerId: string | undefined): string {\n return ownerId ?? ɵSERVER_THREAD_OWNER;\n}\n\nexport interface AgentRunnerRunRequest {\n threadId: string;\n /** Backend execution ID supplied by Intelligence for imported non-UUID sessions. */\n backendThreadId?: string;\n agent: AbstractAgent;\n input: RunAgentInput;\n persistedInputMessages?: Message[];\n /** Short-lived token scoped to this runner invocation. */\n authToken?: string;\n /**\n * Identity the run acts as. A runner that tracks owners records it on the\n * Thread's first run and refuses a run from any other identity. `\"\"` is the\n * anonymous owner. When omitted, the run acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n /**\n * Records a stop of this run with Intelligence. An Intelligence runner calls\n * it when the runtime stops the run itself (not when Intelligence relayed\n * the stop), and sends the run's terminal event only once it settles or a\n * short deadline passes, so Intelligence counts the run as cancelled. The\n * signal aborts when that deadline passes. A failure never stops the run\n * from stopping. Runners that do not deliver to Intelligence ignore it.\n */\n recordStop?: (signal: AbortSignal) => Promise<void>;\n}\n\nexport interface AgentRunnerConnectRequest {\n threadId: string;\n agentId?: string;\n headers?: Record<string, string>;\n joinCode?: string;\n /**\n * Caller identity. A Thread owned by another identity is treated as unknown.\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerIsRunningRequest {\n threadId: string;\n /**\n * Caller identity. A Thread owned by another identity reports \"not running\".\n * When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface AgentRunnerStopRequest {\n threadId: string;\n /** When present, stop only this exact run and never a newer run on the Thread. */\n runId?: string;\n /**\n * Caller identity. A run on a Thread owned by another identity is not\n * stopped. When omitted, the call acts as {@link ɵSERVER_THREAD_OWNER}.\n */\n ownerId?: string;\n}\n\nexport interface LocalThreadEndpointRecord {\n id: string;\n name: string | null;\n agentId: string;\n organizationId: string;\n createdById: string;\n archived: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Limits a local Thread endpoint call to the Threads of one owner. `\"\"` is the\n * anonymous owner. A call without a scope acts as\n * {@link ɵSERVER_THREAD_OWNER}: it sees only Threads created server-side, never\n * every Thread.\n */\nexport interface LocalThreadEndpointScope {\n ownerId: string;\n}\n\nexport interface LocalThreadEndpointRunner extends AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints: true;\n listThreads(scope?: LocalThreadEndpointScope): LocalThreadEndpointRecord[];\n getThreadMessages(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Message[];\n getThreadEvents(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): BaseEvent[];\n getThreadState(\n threadId: string,\n scope?: LocalThreadEndpointScope,\n ): Record<string, unknown> | null;\n clearThreads(scope?: LocalThreadEndpointScope): void;\n /** See {@link ThreadOwnershipRunner.isThreadAccessible}. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean;\n}\n\nexport function supportsLocalThreadEndpoints(\n runner: AgentRunner,\n): runner is LocalThreadEndpointRunner {\n return runner.ɵsupportsLocalThreadEndpoints === true;\n}\n\n/**\n * A runner that records each Thread's owner and enforces it. Implementing\n * `isThreadAccessible` is the promise that `run`, `connect`, `stop` and\n * `isRunning` honor `ownerId` the same way: a call never reaches a Thread that\n * another owner holds.\n */\nexport interface ThreadOwnershipRunner extends AgentRunner {\n /** False when the Thread id is held by an owner other than `scope`'s. */\n isThreadAccessible(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n}\n\n/**\n * True when `runner` enforces Thread owners. Checks the method itself, so a\n * runner built against an older interface (one that sets the endpoint flag\n * but has no `isThreadAccessible`) is not taken to enforce them.\n */\nexport function enforcesThreadOwnership(\n runner: AgentRunner,\n): runner is ThreadOwnershipRunner {\n return typeof runner.isThreadAccessible === \"function\";\n}\n\nexport abstract class AgentRunner {\n readonly ɵsupportsLocalThreadEndpoints?: boolean;\n\n /** See {@link ThreadOwnershipRunner}. Optional: not every runner tracks owners. */\n isThreadAccessible?(\n threadId: string,\n scope: LocalThreadEndpointScope,\n ): boolean | Promise<boolean>;\n\n abstract run(request: AgentRunnerRunRequest): Observable<BaseEvent>;\n abstract connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;\n abstract isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;\n abstract stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;\n}\n"],"mappings":";;;;;;;;;AAeA,IAAa,4BAAb,cAA+C,MAAM;CAGnD,cAAc;AACZ,QAAM,yBAAyB;cAHjBA;AAId,OAAK,OAAO;;;;AAKhB,MAAa,kCAAkC;;;;;;;;;;;;;AAc/C,IAAa,0BAAb,cAA6C,MAAM;CAGjD,cAAc;AACZ,QAAM,uBAAuB;cAHf;AAId,OAAK,OAAO;;;;AAKhB,SAAgB,0BAA0B,OAAyB;AACjE,QACE,iBAAiB,SAChB,MAA6B,SAAS;;;;;;;;;;;;;AAe3C,MAAa,uBAAuB;;AAGpC,SAAgB,oBAAoB,SAAqC;AACvE,QAAO,WAAW;;AAyGpB,SAAgB,6BACd,QACqC;AACrC,QAAO,OAAO,kCAAkC;;;;;;;AAsBlD,SAAgB,wBACd,QACiC;AACjC,QAAO,OAAO,OAAO,uBAAuB;;AAG9C,IAAsB,cAAtB,MAAkC"}
@@ -61,6 +61,15 @@ interface AgentRunnerRunRequest {
61
61
  * anonymous owner. When omitted, the run acts as {@link ɵSERVER_THREAD_OWNER}.
62
62
  */
63
63
  ownerId?: string;
64
+ /**
65
+ * Records a stop of this run with Intelligence. An Intelligence runner calls
66
+ * it when the runtime stops the run itself (not when Intelligence relayed
67
+ * the stop), and sends the run's terminal event only once it settles or a
68
+ * short deadline passes, so Intelligence counts the run as cancelled. The
69
+ * signal aborts when that deadline passes. A failure never stops the run
70
+ * from stopping. Runners that do not deliver to Intelligence ignore it.
71
+ */
72
+ recordStop?: (signal: AbortSignal) => Promise<void>;
64
73
  }
65
74
  interface AgentRunnerConnectRequest {
66
75
  threadId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-runner.d.cts","names":[],"sources":["../../../src/runtime/runner/agent-runner.ts"],"mappings":";;;;;;AAeA;;;;cAAa,yBAAA,SAAkC,KAAA;EAAA,SACpC,IAAA;;;;cASE,+BAAA;;;;;AAcb;;;;;;;;cAAa,uBAAA,SAAgC,KAAA;EAAA,SAClC,IAAA;;;;iBASK,yBAAA,CAA0B,KAAA;AAkB1C;;;;;AAGA;;;;;AAIA;AAPA,cAAa,oBAAA;;iBAGG,mBAAA,CAAoB,OAAA;AAAA,UAInB,qBAAA;EACf,QAAA;EAKgC;EAHhC,eAAA;EACA,KAAA,EAAO,aAAA;EACP,KAAA,EAAO,aAAA;EACP,sBAAA,GAAyB,OAAA;EAFlB;EAIP,SAAA;EAHO;;;;;EASP,OAAA;AAAA;AAAA,UAGe,yBAAA;EACf,QAAA;EACA,OAAA;EACA,OAAA,GAAU,MAAA;EACV,QAAA;EAFA;;;;EAOA,OAAA;AAAA;AAAA,UAGe,2BAAA;EACf,QAAA;EAD0C;;;;EAM1C,OAAA;AAAA;AAAA,UAGe,sBAAA;EACf,QAAA;EAAA;EAEA,KAAA;EAKA;;;AAGF;EAHE,OAAA;AAAA;AAAA,UAGe,yBAAA;EACf,EAAA;EACA,IAAA;EACA,OAAA;EACA,cAAA;EACA,WAAA;EACA,QAAA;EACA,SAAA;EACA,SAAA;AAAA;;AASF;;;;;UAAiB,wBAAA;EACf,OAAA;AAAA;AAAA,UAGe,yBAAA,SAAkC,WAAA;EAAA,SACxC,6BAAA;EACT,WAAA,CAAY,KAAA,GAAQ,wBAAA,GAA2B,yBAAA;EAC/C,iBAAA,CACE,QAAA,UACA,KAAA,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A,SACX,6BAAA;EA1CP;EA6CF,kBAAA,CAAA,CACE,QAAA,UACA,KAAA,EAAO,wBAAA,aACI,OAAA;EAAA,SAEJ,GAAA,CAAI,OAAA,EAAS,qBAAA,GAAwB,UAAA,CAAW,SAAA;EAAA,SAChD,OAAA,CAAQ,OAAA,EAAS,yBAAA,GAA4B,UAAA,CAAW,SAAA;EAAA,SACxD,SAAA,CAAU,OAAA,EAAS,2BAAA,GAA8B,OAAA;EAAA,SACjD,IAAA,CAAK,OAAA,EAAS,sBAAA,GAAyB,OAAA;AAAA"}
@@ -61,6 +61,15 @@ interface AgentRunnerRunRequest {
61
61
  * anonymous owner. When omitted, the run acts as {@link ɵSERVER_THREAD_OWNER}.
62
62
  */
63
63
  ownerId?: string;
64
+ /**
65
+ * Records a stop of this run with Intelligence. An Intelligence runner calls
66
+ * it when the runtime stops the run itself (not when Intelligence relayed
67
+ * the stop), and sends the run's terminal event only once it settles or a
68
+ * short deadline passes, so Intelligence counts the run as cancelled. The
69
+ * signal aborts when that deadline passes. A failure never stops the run
70
+ * from stopping. Runners that do not deliver to Intelligence ignore it.
71
+ */
72
+ recordStop?: (signal: AbortSignal) => Promise<void>;
64
73
  }
65
74
  interface AgentRunnerConnectRequest {
66
75
  threadId: string;