@copilotkit/runtime 2.0.0-rc.6 → 2.0.0-rc.61

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 (417) hide show
  1. package/README.md +29 -4
  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 +17 -4
  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 +202 -30
  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 +202 -29
  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 +23 -28
  63. package/dist/index.d.cts +14 -14
  64. package/dist/index.d.mts +14 -14
  65. package/dist/index.mjs +8 -8
  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 +2 -3
  69. package/dist/node.d.cts +3 -3
  70. package/dist/node.d.mts +3 -3
  71. package/dist/node.mjs +3 -3
  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-cors.cjs.map +1 -1
  87. package/dist/runtime/core/fetch-cors.d.cts +2 -2
  88. package/dist/runtime/core/fetch-cors.d.cts.map +1 -1
  89. package/dist/runtime/core/fetch-cors.d.mts +2 -2
  90. package/dist/runtime/core/fetch-cors.d.mts.map +1 -1
  91. package/dist/runtime/core/fetch-cors.mjs.map +1 -1
  92. package/dist/runtime/core/fetch-handler.cjs +17 -14
  93. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  94. package/dist/runtime/core/fetch-handler.d.cts +22 -14
  95. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  96. package/dist/runtime/core/fetch-handler.d.mts +22 -14
  97. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  98. package/dist/runtime/core/fetch-handler.mjs +9 -5
  99. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  100. package/dist/runtime/core/hooks.cjs.map +1 -1
  101. package/dist/runtime/core/hooks.d.cts +5 -5
  102. package/dist/runtime/core/hooks.d.cts.map +1 -1
  103. package/dist/runtime/core/hooks.d.mts +5 -5
  104. package/dist/runtime/core/hooks.d.mts.map +1 -1
  105. package/dist/runtime/core/hooks.mjs.map +1 -1
  106. package/dist/runtime/core/learning.cjs.map +1 -1
  107. package/dist/runtime/core/learning.d.cts +9 -9
  108. package/dist/runtime/core/learning.d.cts.map +1 -1
  109. package/dist/runtime/core/learning.d.mts +8 -8
  110. package/dist/runtime/core/learning.d.mts.map +1 -1
  111. package/dist/runtime/core/learning.mjs.map +1 -1
  112. package/dist/runtime/core/logger.cjs +105 -14
  113. package/dist/runtime/core/logger.cjs.map +1 -1
  114. package/dist/runtime/core/logger.d.cts +26 -9
  115. package/dist/runtime/core/logger.d.cts.map +1 -1
  116. package/dist/runtime/core/logger.d.mts +26 -9
  117. package/dist/runtime/core/logger.d.mts.map +1 -1
  118. package/dist/runtime/core/logger.mjs +105 -12
  119. package/dist/runtime/core/logger.mjs.map +1 -1
  120. package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
  121. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  122. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  123. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  124. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  125. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  126. package/dist/runtime/core/middleware.cjs +5 -5
  127. package/dist/runtime/core/middleware.cjs.map +1 -1
  128. package/dist/runtime/core/middleware.d.cts +3 -3
  129. package/dist/runtime/core/middleware.d.cts.map +1 -1
  130. package/dist/runtime/core/middleware.d.mts +3 -3
  131. package/dist/runtime/core/middleware.d.mts.map +1 -1
  132. package/dist/runtime/core/middleware.mjs +4 -3
  133. package/dist/runtime/core/middleware.mjs.map +1 -1
  134. package/dist/runtime/core/package-info.cjs +1 -1
  135. package/dist/runtime/core/package-info.mjs +1 -1
  136. package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -1
  137. package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -1
  138. package/dist/runtime/core/runtime.cjs +44 -46
  139. package/dist/runtime/core/runtime.cjs.map +1 -1
  140. package/dist/runtime/core/runtime.d.cts +178 -91
  141. package/dist/runtime/core/runtime.d.cts.map +1 -1
  142. package/dist/runtime/core/runtime.d.mts +178 -91
  143. package/dist/runtime/core/runtime.d.mts.map +1 -1
  144. package/dist/runtime/core/runtime.mjs +42 -42
  145. package/dist/runtime/core/runtime.mjs.map +1 -1
  146. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
  147. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  148. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  149. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  150. package/dist/runtime/endpoints/node-fetch-handler.cjs +4 -8
  151. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  152. package/dist/runtime/endpoints/node-fetch-handler.d.cts +4 -5
  153. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  154. package/dist/runtime/endpoints/node-fetch-handler.d.mts +4 -5
  155. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  156. package/dist/runtime/endpoints/node-fetch-handler.mjs +3 -5
  157. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  158. package/dist/runtime/endpoints/node.cjs +7 -5
  159. package/dist/runtime/endpoints/node.cjs.map +1 -1
  160. package/dist/runtime/endpoints/node.d.cts +16 -16
  161. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  162. package/dist/runtime/endpoints/node.d.mts +16 -16
  163. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  164. package/dist/runtime/endpoints/node.mjs +9 -7
  165. package/dist/runtime/endpoints/node.mjs.map +1 -1
  166. package/dist/runtime/event-transforms/index.d.cts +4 -0
  167. package/dist/runtime/event-transforms/index.d.mts +4 -0
  168. package/dist/runtime/event-transforms/index.mjs +5 -0
  169. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  170. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  171. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  172. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  173. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  174. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  175. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  176. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  177. package/dist/runtime/event-transforms/recorded-events.cjs +68 -0
  178. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  179. package/dist/runtime/event-transforms/recorded-events.d.cts +27 -0
  180. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  181. package/dist/runtime/event-transforms/recorded-events.d.mts +27 -0
  182. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  183. package/dist/runtime/event-transforms/recorded-events.mjs +68 -0
  184. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  185. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  186. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  187. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  188. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  189. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs +106 -0
  190. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs.map +1 -0
  191. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs +106 -0
  192. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs.map +1 -0
  193. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs +422 -0
  194. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs.map +1 -0
  195. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs +422 -0
  196. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs.map +1 -0
  197. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs +84 -0
  198. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -0
  199. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts +41 -0
  200. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts.map +1 -0
  201. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts +41 -0
  202. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts.map +1 -0
  203. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs +83 -0
  204. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -0
  205. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs +694 -0
  206. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs.map +1 -0
  207. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs +694 -0
  208. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs.map +1 -0
  209. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  210. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  211. package/dist/runtime/generative-ui/index.d.cts +1 -0
  212. package/dist/runtime/generative-ui/index.d.mts +1 -0
  213. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  214. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  215. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  216. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  217. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  218. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  219. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  220. package/dist/runtime/handlers/get-runtime-info.cjs +24 -6
  221. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  222. package/dist/runtime/handlers/get-runtime-info.mjs +25 -7
  223. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  224. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  225. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  226. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  227. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  228. package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -1
  229. package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -1
  230. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  231. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  232. package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -1
  233. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  234. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  235. package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -1
  236. package/dist/runtime/handlers/handle-run.cjs +11 -16
  237. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  238. package/dist/runtime/handlers/handle-run.mjs +8 -12
  239. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  240. package/dist/runtime/handlers/handle-stop.cjs +5 -5
  241. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  242. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  243. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  244. package/dist/runtime/handlers/handle-suggest.cjs +6 -3
  245. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  246. package/dist/runtime/handlers/handle-suggest.mjs +6 -2
  247. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  248. package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -1
  249. package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -1
  250. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  251. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  252. package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -1
  253. package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
  254. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  255. package/dist/runtime/handlers/intelligence/annotate.mjs +5 -4
  256. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  257. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  258. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  259. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  260. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  261. package/dist/runtime/handlers/intelligence/memories.cjs +28 -23
  262. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  263. package/dist/runtime/handlers/intelligence/memories.mjs +12 -6
  264. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  265. package/dist/runtime/handlers/intelligence/run.cjs +38 -30
  266. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  267. package/dist/runtime/handlers/intelligence/run.mjs +37 -28
  268. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  269. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
  270. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  271. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  272. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  273. package/dist/runtime/handlers/intelligence/threads.cjs +40 -31
  274. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  275. package/dist/runtime/handlers/intelligence/threads.mjs +18 -8
  276. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  277. package/dist/runtime/handlers/shared/agent-utils.cjs +50 -46
  278. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  279. package/dist/runtime/handlers/shared/agent-utils.mjs +47 -42
  280. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  281. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  282. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  283. package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -1
  284. package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -1
  285. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
  286. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  287. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
  288. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  289. package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
  290. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  291. package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
  292. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  293. package/dist/runtime/handlers/shared/thread-access.cjs +4 -3
  294. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  295. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  296. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  297. package/dist/runtime/handlers/shared/thread-access.mjs +4 -3
  298. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  299. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  300. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  301. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  302. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  303. package/dist/runtime/handlers/sse/run.cjs +5 -2
  304. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  305. package/dist/runtime/handlers/sse/run.mjs +5 -2
  306. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  307. package/dist/runtime/index.d.cts +13 -18
  308. package/dist/runtime/index.d.mts +13 -18
  309. package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
  310. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
  311. package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
  312. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
  313. package/dist/runtime/intelligence-platform/client.cjs +30 -4
  314. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  315. package/dist/runtime/intelligence-platform/client.d.cts +25 -2
  316. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  317. package/dist/runtime/intelligence-platform/client.d.mts +25 -2
  318. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  319. package/dist/runtime/intelligence-platform/client.mjs +30 -3
  320. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  321. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  322. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  323. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  324. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  325. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  326. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  327. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  328. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  329. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  330. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  331. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  332. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  333. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  334. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  335. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  336. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  337. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
  338. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  339. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  340. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  341. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
  342. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  343. package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
  344. package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
  345. package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
  346. package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
  347. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
  348. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  349. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  350. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  351. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  352. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  353. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  354. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  355. package/dist/runtime/node.d.cts +2 -2
  356. package/dist/runtime/node.d.mts +2 -2
  357. package/dist/runtime/runner/agent-runner.cjs +0 -1
  358. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  359. package/dist/runtime/runner/agent-runner.d.cts +9 -0
  360. package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
  361. package/dist/runtime/runner/agent-runner.d.mts +9 -0
  362. package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
  363. package/dist/runtime/runner/agent-runner.mjs.map +1 -1
  364. package/dist/runtime/runner/in-memory.cjs +0 -1
  365. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  366. package/dist/runtime/runner/index.d.cts +1 -1
  367. package/dist/runtime/runner/index.d.mts +1 -1
  368. package/dist/runtime/runner/index.mjs +1 -1
  369. package/dist/runtime/runner/intelligence.cjs +55 -9
  370. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  371. package/dist/runtime/runner/intelligence.d.cts +12 -1
  372. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  373. package/dist/runtime/runner/intelligence.d.mts +12 -1
  374. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  375. package/dist/runtime/runner/intelligence.mjs +56 -10
  376. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  377. package/dist/runtime/telemetry/disclosure.cjs +2 -3
  378. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  379. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  380. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  381. package/dist/runtime/telemetry/events.d.cts +1 -1
  382. package/dist/runtime/telemetry/events.d.mts +1 -1
  383. package/dist/runtime/telemetry/instance-created.cjs +33 -12
  384. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  385. package/dist/runtime/telemetry/instance-created.mjs +33 -12
  386. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  387. package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
  388. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  389. package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
  390. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  391. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  392. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  393. package/dist/v2/index.d.cts +242 -0
  394. package/dist/v2/index.d.mts +242 -0
  395. package/dist/v2/node.d.cts +18 -0
  396. package/dist/v2/node.d.mts +18 -0
  397. package/package.json +84 -29
  398. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  399. package/dist/agent/converters/index.d.mts +0 -2
  400. package/dist/agent/index.cjs +0 -1328
  401. package/dist/agent/index.cjs.map +0 -1
  402. package/dist/agent/index.d.cts +0 -467
  403. package/dist/agent/index.d.cts.map +0 -1
  404. package/dist/agent/index.d.mts +0 -468
  405. package/dist/agent/index.d.mts.map +0 -1
  406. package/dist/agent/index.mjs +0 -1318
  407. package/dist/agent/index.mjs.map +0 -1
  408. package/dist/agent/mcp-tool-names.cjs +0 -82
  409. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  410. package/dist/agent/mcp-tool-names.mjs +0 -80
  411. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  412. package/dist/agent/url-download.cjs.map +0 -1
  413. package/dist/agent/url-download.d.cts.map +0 -1
  414. package/dist/agent/url-download.d.mts.map +0 -1
  415. package/dist/agent/url-download.mjs.map +0 -1
  416. package/dist/runtime/index.d.cts.map +0 -1
  417. package/dist/runtime/index.d.mts.map +0 -1
@@ -1,3 +1,4 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_agent_runner = require('../../runner/agent-runner.cjs');
2
3
  const require_json_response = require('./json-response.cjs');
3
4
  const require_resolve_intelligence_user = require('./resolve-intelligence-user.cjs');
@@ -37,7 +38,7 @@ const ANONYMOUS_THREAD_ACCESS = {
37
38
  isRunning: true
38
39
  }
39
40
  };
40
- const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to CopilotRuntime so each user lists and clears only their own threads, or pass `threads: { access: \"open\" }` to let every caller share threads created without identity (insecure for multi-user deployments).";
41
+ const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to CopilotKitRuntime so each user lists and clears only their own threads, or pass `threads: { access: \"open\" }` to let every caller share threads created without identity (insecure for multi-user deployments).";
41
42
  /**
42
43
  * The configuration error for `identifyUser` with a runner that cannot keep
43
44
  * users apart. Every Thread operation is refused rather than served unscoped.
@@ -50,7 +51,7 @@ function threadOwnershipUnsupportedMessage(runner) {
50
51
  * does not enforce thread ownership. Requests then fail with the same message.
51
52
  */
52
53
  function warnIfThreadOwnershipUnenforced(runtime) {
53
- if (require_resolve_intelligence_user.hasIdentifyUser(runtime) && !require_agent_runner.enforcesThreadOwnership(runtime.runner)) console.warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
+ if (require_resolve_intelligence_user.hasIdentifyUser(runtime) && !require_agent_runner.enforcesThreadOwnership(runtime.runner)) require_logger.getRuntimeLogger(runtime).warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
55
  }
55
56
  /**
56
57
  * The access mode `threads` selects. Throws on anything but an object whose
@@ -76,7 +77,7 @@ function warnIfThreadListRefused(runtime) {
76
77
  if (!require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) return;
77
78
  if (isThreadOperationAvailable(runtime, "list")) return;
78
79
  threadListRefusalWarned = true;
79
- console.warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
+ require_logger.getRuntimeLogger(runtime).warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
81
  }
81
82
  /**
82
83
  * True when `operation` can serve requests on this runtime at all: always
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.cjs","names":["hasIdentifyUser","enforcesThreadOwnership","supportsLocalThreadEndpoints","resolveIntelligenceUser","errorResponse"],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n console.warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n console.warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;AAoCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAIA,kDAAgB,QAAQ,IAAI,CAACC,6CAAwB,QAAQ,OAAO,CACtE,SAAQ,KACN,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAmC;AACzE,KAAI,wBAAyB;AAC7B,KAAI,CAACC,kDAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,SAAQ,KACN,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAAIF,kDAAgB,QAAQ,CAC1B,QAAOC,6CAAwB,QAAQ,OAAO;AAEhD,QAAO,wBAAwB,QAAQ,gBAAgB,uBACrD;;;;;;;;;;;;AAcJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAID,kDAAgB,QAAQ,EAAE;AAG5B,MAAI,CAACC,6CAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAOC,oCAAc,oBAAoB,IAAI"}
1
+ {"version":3,"file":"thread-access.cjs","names":["hasIdentifyUser","enforcesThreadOwnership","supportsLocalThreadEndpoints","resolveIntelligenceUser","errorResponse"],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotKitRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotKitRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotKitRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotKitRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAIA,kDAAgB,QAAQ,IAAI,CAACC,6CAAwB,QAAQ,OAAO,CACtE,iCAAiB,QAAQ,CAAC,KACxB,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAsC;AAC5E,KAAI,wBAAyB;AAC7B,KAAI,CAACC,kDAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,iCAAiB,QAAQ,CAAC,KACxB,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAAIF,kDAAgB,QAAQ,CAC1B,QAAOC,6CAAwB,QAAQ,OAAO;AAEhD,QAAO,wBAAwB,QAAQ,gBAAgB,uBACrD;;;;;;;;;;;;AAcJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAID,kDAAgB,QAAQ,EAAE;AAG5B,MAAI,CAACC,6CAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAOC,oCAAc,oBAAoB,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.d.cts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA4BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
1
+ {"version":3,"file":"thread-access.d.cts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA6BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.d.mts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA4BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
1
+ {"version":3,"file":"thread-access.d.mts","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"mappings":";;;;;;AA6BA;;;;;AAEA;;;;;;;;;KAFY,gBAAA;AAAA,UAEK,aAAA;;EAEf,MAAA,GAAS,gBAAA;AAAA"}
@@ -1,3 +1,4 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { enforcesThreadOwnership, supportsLocalThreadEndpoints } from "../../runner/agent-runner.mjs";
2
3
  import { errorResponse } from "./json-response.mjs";
3
4
  import { hasIdentifyUser, resolveIntelligenceUser } from "./resolve-intelligence-user.mjs";
@@ -37,7 +38,7 @@ const ANONYMOUS_THREAD_ACCESS = {
37
38
  isRunning: true
38
39
  }
39
40
  };
40
- const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to CopilotRuntime so each user lists and clears only their own threads, or pass `threads: { access: \"open\" }` to let every caller share threads created without identity (insecure for multi-user deployments).";
41
+ const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE = "Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` to CopilotKitRuntime so each user lists and clears only their own threads, or pass `threads: { access: \"open\" }` to let every caller share threads created without identity (insecure for multi-user deployments).";
41
42
  /**
42
43
  * The configuration error for `identifyUser` with a runner that cannot keep
43
44
  * users apart. Every Thread operation is refused rather than served unscoped.
@@ -50,7 +51,7 @@ function threadOwnershipUnsupportedMessage(runner) {
50
51
  * does not enforce thread ownership. Requests then fail with the same message.
51
52
  */
52
53
  function warnIfThreadOwnershipUnenforced(runtime) {
53
- if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) console.warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
+ if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) getRuntimeLogger(runtime).warn(`[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`);
54
55
  }
55
56
  /**
56
57
  * The access mode `threads` selects. Throws on anything but an object whose
@@ -76,7 +77,7 @@ function warnIfThreadListRefused(runtime) {
76
77
  if (!supportsLocalThreadEndpoints(runtime.runner)) return;
77
78
  if (isThreadOperationAvailable(runtime, "list")) return;
78
79
  threadListRefusalWarned = true;
79
- console.warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
+ getRuntimeLogger(runtime).warn(`[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, GET /threads and POST /threads/clear return HTTP 403.`);
80
81
  }
81
82
  /**
82
83
  * True when `operation` can serve requests on this runtime at all: always
@@ -1 +1 @@
1
- {"version":3,"file":"thread-access.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n console.warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n console.warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;AAoCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAI,gBAAgB,QAAQ,IAAI,CAAC,wBAAwB,QAAQ,OAAO,CACtE,SAAQ,KACN,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAmC;AACzE,KAAI,wBAAyB;AAC7B,KAAI,CAAC,6BAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,SAAQ,KACN,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAAI,gBAAgB,QAAQ,CAC1B,QAAO,wBAAwB,QAAQ,OAAO;AAEhD,QAAO,wBAAwB,QAAQ,gBAAgB,uBACrD;;;;;;;;;;;;AAcJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAI,gBAAgB,QAAQ,EAAE;AAG5B,MAAI,CAAC,wBAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAO,cAAc,oBAAoB,IAAI"}
1
+ {"version":3,"file":"thread-access.mjs","names":[],"sources":["../../../../src/runtime/handlers/shared/thread-access.ts"],"sourcesContent":["import { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport type { AgentRunner } from \"../../runner/agent-runner\";\nimport {\n enforcesThreadOwnership,\n supportsLocalThreadEndpoints,\n} from \"../../runner/agent-runner\";\nimport { errorResponse } from \"./json-response\";\nimport {\n hasIdentifyUser,\n resolveIntelligenceUser,\n} from \"./resolve-intelligence-user\";\n\n/**\n * How local (non-Intelligence) Threads are shared among callers that\n * `identifyUser` does not identify. The full policy is\n * {@link ANONYMOUS_THREAD_ACCESS}.\n *\n * - `\"owner\"` (default): a Thread created without identity is a capability.\n * Whoever holds its id may read, connect to, continue and stop it, but\n * nobody may list or bulk-clear such Threads.\n * - `\"open\"`: every caller without identity shares those Threads, list and\n * clear included, as in earlier releases. Insecure for any deployment that\n * more than one person can reach.\n *\n * Neither mode loosens identity: with `identifyUser`, every operation reaches\n * only the caller's own Threads, and a Thread that an identified user created\n * is never reachable by an anonymous caller or another identity.\n */\nexport type ThreadAccessMode = \"owner\" | \"open\";\n\nexport interface ThreadsConfig {\n /** @default \"owner\" */\n access?: ThreadAccessMode;\n}\n\n/** The one place that sets the default Thread access mode. */\nexport const DEFAULT_THREAD_ACCESS: ThreadAccessMode = \"owner\";\n\n/** Owner id of a Thread created without identity. */\nexport const ANONYMOUS_THREAD_OWNER = \"\";\n\n/**\n * Every operation on a local Thread. `read` covers\n * `/threads/:id/{messages,events,state}`; `stop` covers a stop by Thread and a\n * stop by run id. `isRunning` has no route; runners check it the same way.\n */\nexport type ThreadOperation =\n | \"list\"\n | \"clear\"\n | \"read\"\n | \"connect\"\n | \"run\"\n | \"stop\"\n | \"isRunning\";\n\n/**\n * THE anonymous-Thread policy: which operations a caller without identity\n * (no `identifyUser`) may perform, per access mode. Every such operation\n * still reaches only anonymous Threads, never a Thread an identified user\n * owns. To tighten the default, change the `owner` row; nothing else encodes\n * this policy.\n *\n * Callers identified by `identifyUser` are not in this table: every operation\n * is allowed and reaches only their own Threads.\n */\nexport const ANONYMOUS_THREAD_ACCESS: Readonly<\n Record<ThreadAccessMode, Readonly<Record<ThreadOperation, boolean>>>\n> = {\n // A Thread id works as a capability for the Thread it names. Enumerating or\n // wiping every anonymous Thread needs identity or an explicit opt-in.\n owner: {\n list: false,\n clear: false,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n open: {\n list: true,\n clear: true,\n read: true,\n connect: true,\n run: true,\n stop: true,\n isRunning: true,\n },\n};\n\nexport const THREAD_ACCESS_NOT_CONFIGURED_MESSAGE =\n \"Listing and clearing threads need a caller identity. Pass `identifyUser: (request) => ({ id, name })` \" +\n \"to CopilotKitRuntime so each user lists and clears only their own threads, or pass \" +\n '`threads: { access: \"open\" }` to let every caller share threads created without identity ' +\n \"(insecure for multi-user deployments).\";\n\n/**\n * The configuration error for `identifyUser` with a runner that cannot keep\n * users apart. Every Thread operation is refused rather than served unscoped.\n */\nexport function threadOwnershipUnsupportedMessage(runner: AgentRunner): string {\n const name = runner.constructor?.name || \"the configured runner\";\n return (\n `identifyUser is set, but the runner ${name} does not enforce thread ownership: ` +\n \"it has no isThreadAccessible method. Thread routes, run, connect and stop are refused \" +\n \"so that no user can reach another user's threads. Use InMemoryAgentRunner or \" +\n \"SqliteAgentRunner, or implement isThreadAccessible and honor ownerId in run, connect, \" +\n \"stop and isRunning.\"\n );\n}\n\n/**\n * Log once, at runtime construction, when `identifyUser` is set but the runner\n * does not enforce thread ownership. Requests then fail with the same message.\n */\nexport function warnIfThreadOwnershipUnenforced(\n runtime: CopilotKitRuntimeLike,\n): void {\n if (hasIdentifyUser(runtime) && !enforcesThreadOwnership(runtime.runner)) {\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${threadOwnershipUnsupportedMessage(runtime.runner)}`,\n );\n }\n}\n\n/**\n * The access mode `threads` selects. Throws on anything but an object whose\n * `access` is `\"owner\"`, `\"open\"` or omitted: a typo must not silently fall\n * back to the default.\n */\nexport function resolveThreadAccessMode(\n config: ThreadsConfig | undefined,\n): ThreadAccessMode {\n if (config === undefined) return DEFAULT_THREAD_ACCESS;\n if (typeof config !== \"object\" || config === null) {\n throw new Error(\n '`threads` must be an object, such as `{ access: \"owner\" }`; got ' +\n JSON.stringify(config),\n );\n }\n const access: unknown = config.access;\n if (access === undefined) return DEFAULT_THREAD_ACCESS;\n if (access !== \"owner\" && access !== \"open\") {\n throw new Error(\n `threads.access must be \"owner\" or \"open\"; got ${JSON.stringify(access)}`,\n );\n }\n return access;\n}\n\nlet threadListRefusalWarned = false;\n\n/** Re-arm the once-per-process startup warnings. Internal: for tests. */\nexport function ɵresetThreadAccessWarnings(): void {\n threadListRefusalWarned = false;\n}\n\n/**\n * Log once per process, at runtime construction, when the configuration\n * refuses the Thread list and clear routes, so operators see why those\n * requests get 403.\n */\nexport function warnIfThreadListRefused(runtime: CopilotKitRuntimeLike): void {\n if (threadListRefusalWarned) return;\n if (!supportsLocalThreadEndpoints(runtime.runner)) return;\n if (isThreadOperationAvailable(runtime, \"list\")) return;\n threadListRefusalWarned = true;\n getRuntimeLogger(runtime).warn(\n `[CopilotKit] ${THREAD_ACCESS_NOT_CONFIGURED_MESSAGE} Until then, ` +\n \"GET /threads and POST /threads/clear return HTTP 403.\",\n );\n}\n\n/**\n * True when `operation` can serve requests on this runtime at all: always\n * with `identifyUser` (scoped to the caller), otherwise per\n * {@link ANONYMOUS_THREAD_ACCESS}.\n */\nexport function isThreadOperationAvailable(\n runtime: CopilotKitRuntimeLike,\n operation: ThreadOperation,\n): boolean {\n // The same identity test as resolveLocalThreadOwner, so a non-function\n // value is no identity everywhere and never opens list or clear.\n if (hasIdentifyUser(runtime)) {\n return enforcesThreadOwnership(runtime.runner);\n }\n return ANONYMOUS_THREAD_ACCESS[runtime.threadAccess ?? DEFAULT_THREAD_ACCESS][\n operation\n ];\n}\n\n/**\n * Resolves the owner id that a local Thread request acts as, or the error\n * Response that refuses it. Every local Thread handler goes through here.\n *\n * - With `identifyUser`: the identified user's id. Refused when the runner\n * cannot enforce owners, or when identification fails.\n * - Without it: the anonymous owner, when {@link ANONYMOUS_THREAD_ACCESS}\n * allows `operation` in the configured mode; otherwise a 403 that names the\n * options to set.\n */\nexport async function resolveLocalThreadOwner(params: {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n operation: ThreadOperation;\n}): Promise<string | Response> {\n const { runtime, request, operation } = params;\n if (hasIdentifyUser(runtime)) {\n // Never serve an identified request through a runner that cannot keep\n // users apart: refuse it with the configuration error instead.\n if (!enforcesThreadOwnership(runtime.runner)) {\n return Response.json(\n {\n error: \"thread_ownership_unsupported\",\n message: threadOwnershipUnsupportedMessage(runtime.runner),\n },\n { status: 500 },\n );\n }\n const user = await resolveIntelligenceUser({ runtime, request });\n return user instanceof Response ? user : user.id;\n }\n if (!isThreadOperationAvailable(runtime, operation)) {\n return Response.json(\n {\n error: \"thread_access_not_configured\",\n message: THREAD_ACCESS_NOT_CONFIGURED_MESSAGE,\n },\n { status: 403 },\n );\n }\n return ANONYMOUS_THREAD_OWNER;\n}\n\n/**\n * The response to a run on a Thread that another identity owns, whether the\n * handler's check or the runner refused it. It is the same 404 and body as an\n * unknown Thread on the inspect routes, so it does not say that the Thread\n * belongs to someone. A run on an unknown Thread id creates the Thread, so a\n * refusal still shows that the id is taken; it never shows by whom.\n */\nexport function threadAccessDeniedResponse(): Response {\n return errorResponse(\"Thread not found\", 404);\n}\n"],"mappings":";;;;;;;AAqCA,MAAa,wBAA0C;;AAGvD,MAAa,yBAAyB;;;;;;;;;;;AA0BtC,MAAa,0BAET;CAGF,OAAO;EACL,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACD,MAAM;EACJ,MAAM;EACN,OAAO;EACP,MAAM;EACN,SAAS;EACT,KAAK;EACL,MAAM;EACN,WAAW;EACZ;CACF;AAED,MAAa,uCACX;;;;;AASF,SAAgB,kCAAkC,QAA6B;AAE7E,QACE,uCAFW,OAAO,aAAa,QAAQ,wBAEK;;;;;;AAYhD,SAAgB,gCACd,SACM;AACN,KAAI,gBAAgB,QAAQ,IAAI,CAAC,wBAAwB,QAAQ,OAAO,CACtE,kBAAiB,QAAQ,CAAC,KACxB,gBAAgB,kCAAkC,QAAQ,OAAO,GAClE;;;;;;;AASL,SAAgB,wBACd,QACkB;AAClB,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,OAAO,WAAW,YAAY,WAAW,KAC3C,OAAM,IAAI,MACR,uEACE,KAAK,UAAU,OAAO,CACzB;CAEH,MAAM,SAAkB,OAAO;AAC/B,KAAI,WAAW,OAAW,QAAO;AACjC,KAAI,WAAW,WAAW,WAAW,OACnC,OAAM,IAAI,MACR,iDAAiD,KAAK,UAAU,OAAO,GACxE;AAEH,QAAO;;AAGT,IAAI,0BAA0B;;;;;;AAY9B,SAAgB,wBAAwB,SAAsC;AAC5E,KAAI,wBAAyB;AAC7B,KAAI,CAAC,6BAA6B,QAAQ,OAAO,CAAE;AACnD,KAAI,2BAA2B,SAAS,OAAO,CAAE;AACjD,2BAA0B;AAC1B,kBAAiB,QAAQ,CAAC,KACxB,gBAAgB,qCAAqC,oEAEtD;;;;;;;AAQH,SAAgB,2BACd,SACA,WACS;AAGT,KAAI,gBAAgB,QAAQ,CAC1B,QAAO,wBAAwB,QAAQ,OAAO;AAEhD,QAAO,wBAAwB,QAAQ,gBAAgB,uBACrD;;;;;;;;;;;;AAcJ,eAAsB,wBAAwB,QAIf;CAC7B,MAAM,EAAE,SAAS,SAAS,cAAc;AACxC,KAAI,gBAAgB,QAAQ,EAAE;AAG5B,MAAI,CAAC,wBAAwB,QAAQ,OAAO,CAC1C,QAAO,SAAS,KACd;GACE,OAAO;GACP,SAAS,kCAAkC,QAAQ,OAAO;GAC3D,EACD,EAAE,QAAQ,KAAK,CAChB;EAEH,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,SAAO,gBAAgB,WAAW,OAAO,KAAK;;AAEhD,KAAI,CAAC,2BAA2B,SAAS,UAAU,CACjD,QAAO,SAAS,KACd;EACE,OAAO;EACP,SAAS;EACV,EACD,EAAE,QAAQ,KAAK,CAChB;AAEH,QAAO;;;;;;;;;AAUT,SAAgB,6BAAuC;AACrD,QAAO,cAAc,oBAAoB,IAAI"}
@@ -1,4 +1,5 @@
1
1
  const require_header_utils = require('../header-utils.cjs');
2
+ const require_logger = require('../../core/logger.cjs');
2
3
  const require_sse_response = require('../shared/sse-response.cjs');
3
4
 
4
5
  //#region src/runtime/handlers/sse/connect.ts
@@ -8,6 +9,7 @@ function handleSseConnect({ runtime, request, agentId, threadId, agent, ownerId
8
9
  debugEventBus: runtime.debugEventBus,
9
10
  agentId,
10
11
  telemetry: runtime.telemetry,
12
+ logger: require_logger.getRuntimeLogger(runtime),
11
13
  keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
12
14
  observableFactory: () => runtime.runner.connect({
13
15
  threadId,
@@ -1 +1 @@
1
- {"version":3,"file":"connect.cjs","names":["createSseEventResponse","mergeForwardableHeaders","resolveForwardHeadersPolicy"],"sources":["../../../../src/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n ...(ownerId === undefined ? {} : { ownerId }),\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) ignores it.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;AAkCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAASC,6CACP,OAAO,SACP,SAIA,QAAQ,wBACNC,iDAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.cjs","names":["createSseEventResponse","getRuntimeLogger","mergeForwardableHeaders","resolveForwardHeadersPolicy"],"sources":["../../../../src/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n logger: getRuntimeLogger(runtime),\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n ...(ownerId === undefined ? {} : { ownerId }),\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) ignores it.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotKitRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;;AAmCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAOA,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,QAAQC,gCAAiB,QAAQ;EACjC,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAASC,6CACP,OAAO,SACP,SAIA,QAAQ,wBACNC,iDAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { mergeForwardableHeaders, resolveForwardHeadersPolicy } from "../header-utils.mjs";
2
+ import { getRuntimeLogger } from "../../core/logger.mjs";
2
3
  import { createSseEventResponse } from "../shared/sse-response.mjs";
3
4
 
4
5
  //#region src/runtime/handlers/sse/connect.ts
@@ -8,6 +9,7 @@ function handleSseConnect({ runtime, request, agentId, threadId, agent, ownerId
8
9
  debugEventBus: runtime.debugEventBus,
9
10
  agentId,
10
11
  telemetry: runtime.telemetry,
12
+ logger: getRuntimeLogger(runtime),
11
13
  keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,
12
14
  observableFactory: () => runtime.runner.connect({
13
15
  threadId,
@@ -1 +1 @@
1
- {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n ...(ownerId === undefined ? {} : { ownerId }),\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) ignores it.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;AAkCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAAS,wBACP,OAAO,SACP,SAIA,QAAQ,wBACN,4BAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"connect.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/connect.ts"],"sourcesContent":["import type { AbstractAgent } from \"@ag-ui/client\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\n\n/**\n * `headers` lives on the HTTP-backed agent configs (e.g. `HttpAgent`), not on\n * the base `AbstractAgent`. Mirror the runtime's own optional-headers shape so\n * we can read server-configured headers off the per-request clone without a\n * cast. See `agent-utils.ts`.\n */\ntype AgentWithHeaders = AbstractAgent & {\n headers?: Record<string, string>;\n};\n\ninterface HandleSseConnectParams {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n agentId: string;\n threadId: string;\n /**\n * The per-request agent clone, carrying any server-configured `agent.headers`\n * (e.g. service-to-service auth). Used only to compute the merged header set\n * threaded into `runner.connect` below — see the note there for why that\n * merge is forward-looking plumbing rather than active outbound auth today.\n */\n agent?: AgentWithHeaders;\n /** Caller identity; the runner hides threads owned by anyone else. */\n ownerId?: string;\n}\n\nexport function handleSseConnect({\n runtime,\n request,\n agentId,\n threadId,\n agent,\n ownerId,\n}: HandleSseConnectParams): Response {\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n // Forward the real agentId so debug envelopes reflect the agent the\n // route resolved to — not the literal string \"connect\".\n agentId,\n telemetry: runtime.telemetry,\n logger: getRuntimeLogger(runtime),\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n observableFactory: () =>\n runtime.runner.connect({\n threadId,\n agentId,\n ...(ownerId === undefined ? {} : { ownerId }),\n // Forward-looking plumbing: we compute the merged header set (server\n // `agent.headers` win on collision, case-insensitively; non-colliding\n // inbound headers still forward — see `mergeForwardableHeaders`, #5712)\n // and thread it into `runner.connect`. NO shipped runner consumes the\n // `headers` field of `AgentRunnerConnectRequest` today — every runner\n // (in-memory, intelligence, telemetry, sqlite) ignores it.\n // The real outbound header forwarding is the /run path, where\n // `cloneAgentForRequest` mutates `agent.headers` directly\n // (agent-utils.ts). This wiring exists so a future outbound-connecting\n // runner can pick the merged headers up without a route change; the\n // collision precedence noted here is purely about that merge, not about\n // middleware/mutation parity with /run.\n headers: mergeForwardableHeaders(\n agent?.headers,\n request,\n // Optional on `CopilotKitRuntimeLike` (non-breaking minor release);\n // coalesce a policy-less external implementor to the default resolved\n // policy (default-on denylist) instead of dereffing undefined.\n runtime.forwardHeadersPolicy ??\n resolveForwardHeadersPolicy(undefined),\n ),\n }),\n });\n}\n"],"mappings":";;;;;AAmCA,SAAgB,iBAAiB,EAC/B,SACA,SACA,SACA,UACA,OACA,WACmC;AACnC,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EAGvB;EACA,WAAW,QAAQ;EACnB,QAAQ,iBAAiB,QAAQ;EACjC,0BAA0B,QAAQ;EAClC,yBACE,QAAQ,OAAO,QAAQ;GACrB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAa5C,SAAS,wBACP,OAAO,SACP,SAIA,QAAQ,wBACN,4BAA4B,OAAU,CACzC;GACF,CAAC;EACL,CAAC"}
@@ -1,10 +1,12 @@
1
+ const require_logger = require('../../core/logger.cjs');
1
2
  const require_agent_runner = require('../../runner/agent-runner.cjs');
2
3
  const require_thread_access = require('../shared/thread-access.cjs');
3
4
  const require_runtime_error_reporter = require('../../core/runtime-error-reporter.cjs');
4
5
  const require_sse_response = require('../shared/sse-response.cjs');
5
6
 
6
7
  //#region src/runtime/handlers/sse/run.ts
7
- function handleSseRun({ runtime, request, agent, input, agentId, debug, logger, startTime, ownerId }) {
8
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, debugLogger, startTime, ownerId }) {
9
+ const logger = require_logger.getRuntimeLogger(runtime);
8
10
  let started;
9
11
  let startError;
10
12
  try {
@@ -16,7 +18,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
16
18
  });
17
19
  } catch (error) {
18
20
  if (require_agent_runner.isThreadAccessDeniedError(error)) {
19
- console.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
21
+ logger.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
20
22
  return require_thread_access.threadAccessDeniedResponse();
21
23
  }
22
24
  startError = error;
@@ -26,6 +28,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
26
28
  debugEventBus: runtime.debugEventBus,
27
29
  agentId,
28
30
  debug,
31
+ debugLogger,
29
32
  logger,
30
33
  runtimeErrorReporter: require_runtime_error_reporter.getRuntimeErrorReporter(runtime),
31
34
  startTime,
@@ -1 +1 @@
1
- {"version":3,"file":"run.cjs","names":["isThreadAccessDeniedError","threadAccessDeniedResponse","createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;AAwBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,WACA,WAC+B;CAM/B,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAIA,+CAA0B,MAAM,EAAE;AACpC,WAAQ,KACN,oEACD;AACD,UAAOC,kDAA4B;;AAErC,eAAa;;AAGf,QAAOC,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"run.cjs","names":["getRuntimeLogger","isThreadAccessDeniedError","threadAccessDeniedResponse","createSseEventResponse","getRuntimeErrorReporter"],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created debug logger, so a request does not create its own. */\n debugLogger?: CopilotKitRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n debugLogger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n const logger = getRuntimeLogger(runtime);\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n logger.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n debugLogger,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;;AAyBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,aACA,WACA,WAC+B;CAC/B,MAAM,SAASA,gCAAiB,QAAQ;CAMxC,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAIC,+CAA0B,MAAM,EAAE;AACpC,UAAO,KACL,oEACD;AACD,UAAOC,kDAA4B;;AAErC,eAAa;;AAGf,QAAOC,4CAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA;EACA,sBAAsBC,uDAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
@@ -1,10 +1,12 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { isThreadAccessDeniedError } from "../../runner/agent-runner.mjs";
2
3
  import { threadAccessDeniedResponse } from "../shared/thread-access.mjs";
3
4
  import { getRuntimeErrorReporter } from "../../core/runtime-error-reporter.mjs";
4
5
  import { createSseEventResponse } from "../shared/sse-response.mjs";
5
6
 
6
7
  //#region src/runtime/handlers/sse/run.ts
7
- function handleSseRun({ runtime, request, agent, input, agentId, debug, logger, startTime, ownerId }) {
8
+ function handleSseRun({ runtime, request, agent, input, agentId, debug, debugLogger, startTime, ownerId }) {
9
+ const logger = getRuntimeLogger(runtime);
8
10
  let started;
9
11
  let startError;
10
12
  try {
@@ -16,7 +18,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
16
18
  });
17
19
  } catch (error) {
18
20
  if (isThreadAccessDeniedError(error)) {
19
- console.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
21
+ logger.warn("[CopilotKit] Run refused: the thread belongs to another identity.");
20
22
  return threadAccessDeniedResponse();
21
23
  }
22
24
  startError = error;
@@ -26,6 +28,7 @@ function handleSseRun({ runtime, request, agent, input, agentId, debug, logger,
26
28
  debugEventBus: runtime.debugEventBus,
27
29
  agentId,
28
30
  debug,
31
+ debugLogger,
29
32
  logger,
30
33
  runtimeErrorReporter: getRuntimeErrorReporter(runtime),
31
34
  startTime,
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created logger instance to avoid creating a new pino logger per request. */\n logger?: CopilotRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n logger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n console.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;AAwBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,QACA,WACA,WAC+B;CAM/B,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAI,0BAA0B,MAAM,EAAE;AACpC,WAAQ,KACN,oEACD;AACD,UAAO,4BAA4B;;AAErC,eAAa;;AAGf,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
1
+ {"version":3,"file":"run.mjs","names":[],"sources":["../../../../src/runtime/handlers/sse/run.ts"],"sourcesContent":["import type { AbstractAgent, BaseEvent, RunAgentInput } from \"@ag-ui/client\";\nimport type { Observable } from \"rxjs\";\nimport { isThreadAccessDeniedError } from \"../../runner/agent-runner\";\nimport { threadAccessDeniedResponse } from \"../shared/thread-access\";\nimport type { ResolvedDebugConfig, ModelHostClass } from \"@copilotkit/shared\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotKitRuntimeLike } from \"../../core/runtime\";\nimport { getRuntimeErrorReporter } from \"../../core/runtime-error-reporter\";\nimport { createSseEventResponse } from \"../shared/sse-response\";\n\ninterface HandleSseRunParams {\n runtime: CopilotKitRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n input: RunAgentInput;\n agentId: string;\n debug?: ResolvedDebugConfig;\n /** Pre-created debug logger, so a request does not create its own. */\n debugLogger?: CopilotKitRuntimeLogger;\n startTime?: number;\n /** Identity the run acts as; the runner records it as the thread owner. */\n ownerId?: string;\n}\n\nexport function handleSseRun({\n runtime,\n request,\n agent,\n input,\n agentId,\n debug,\n debugLogger,\n startTime,\n ownerId,\n}: HandleSseRunParams): Response {\n const logger = getRuntimeLogger(runtime);\n // Start the run before the stream opens. When another identity claimed the\n // thread after the handler's owner check, the runner refuses at once, and\n // that refusal becomes the same HTTP error as the check's, not a streamed\n // agent failure. Any other start error still reaches the client as a\n // RUN_ERROR on the stream, as before.\n let started: Observable<BaseEvent> | undefined;\n let startError: unknown;\n try {\n started = runtime.runner.run({\n threadId: input.threadId,\n agent,\n input,\n ...(ownerId === undefined ? {} : { ownerId }),\n });\n } catch (error) {\n if (isThreadAccessDeniedError(error)) {\n logger.warn(\n \"[CopilotKit] Run refused: the thread belongs to another identity.\",\n );\n return threadAccessDeniedResponse();\n }\n startError = error;\n }\n\n return createSseEventResponse({\n request,\n debugEventBus: runtime.debugEventBus,\n agentId,\n debug,\n debugLogger,\n logger,\n runtimeErrorReporter: getRuntimeErrorReporter(runtime),\n startTime,\n telemetry: runtime.telemetry,\n keepAliveIntervalSeconds: runtime.sseKeepAliveIntervalSeconds,\n // Read structurally rather than via `instanceof BuiltInAgent`, which would\n // pull the agent module into this handler. Any agent can opt in by\n // exposing the same property.\n executionSeed: {\n llmHostClass:\n (agent as { modelHostClass?: ModelHostClass }).modelHostClass ??\n \"unknown\",\n },\n observableFactory: () => {\n if (started === undefined) throw startError;\n return started;\n },\n });\n}\n"],"mappings":";;;;;;;AAyBA,SAAgB,aAAa,EAC3B,SACA,SACA,OACA,OACA,SACA,OACA,aACA,WACA,WAC+B;CAC/B,MAAM,SAAS,iBAAiB,QAAQ;CAMxC,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,YAAU,QAAQ,OAAO,IAAI;GAC3B,UAAU,MAAM;GAChB;GACA;GACA,GAAI,YAAY,SAAY,EAAE,GAAG,EAAE,SAAS;GAC7C,CAAC;UACK,OAAO;AACd,MAAI,0BAA0B,MAAM,EAAE;AACpC,UAAO,KACL,oEACD;AACD,UAAO,4BAA4B;;AAErC,eAAa;;AAGf,QAAO,uBAAuB;EAC5B;EACA,eAAe,QAAQ;EACvB;EACA;EACA;EACA;EACA,sBAAsB,wBAAwB,QAAQ;EACtD;EACA,WAAW,QAAQ;EACnB,0BAA0B,QAAQ;EAIlC,eAAe,EACb,cACG,MAA8C,kBAC/C,WACH;EACD,yBAAyB;AACvB,OAAI,YAAY,OAAW,OAAM;AACjC,UAAO;;EAEV,CAAC"}
@@ -1,29 +1,24 @@
1
+ import { experimental_d_exports } from "./intelligence-platform/experimental.cjs";
1
2
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, LocalThreadEndpointScope, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, ThreadOwnershipRunner, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./runner/agent-runner.cjs";
2
3
  import { ThreadAccessMode, ThreadsConfig } from "./handlers/shared/thread-access.cjs";
4
+ import { CopilotKitRuntimeLogger } from "./core/logger.cjs";
3
5
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.cjs";
4
- import { experimental_d_exports } from "./intelligence-platform/experimental.cjs";
5
- import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, GetTrajectoryLearningContainerIds, LearningContainerSelectorInput, TrajectoryLearningContainerSelectorInput } from "./core/learning.cjs";
6
6
  import { GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.cjs";
7
- import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, PlatformRequestError, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
8
7
  import "./intelligence-platform/index.cjs";
9
- import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
8
+ import { A2UIVersion, AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotKitIntelligenceRuntime, CopilotKitIntelligenceRuntimeLike, CopilotKitIntelligenceRuntimeOptions, CopilotKitRuntime, CopilotKitRuntimeConstructor, CopilotKitRuntimeLike, CopilotKitRuntimeMemoryConfig, CopilotKitRuntimeOptions, CopilotKitSseRuntime, CopilotKitSseRuntimeLike, CopilotKitSseRuntimeOptions, GenerativeUIOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isIntelligenceRuntime, resolveAgents } from "./core/runtime.cjs";
9
+ import { CopilotKitRuntimeLearningConfig, CopilotKitRuntimeLearningContext, CopilotKitRuntimeUser, GetLearningContainerId, GetTrajectoryLearningContainerIds, LearningContainerSelectorInput, TrajectoryLearningContainerSelectorInput } from "./core/learning.cjs";
10
+ import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, PlatformRequestError, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.cjs";
10
11
  import { GenerativeUIMiddleware } from "./generative-ui/generative-ui-middleware.cjs";
12
+ import { A2UIV09BridgeMiddleware } from "./generative-ui/a2ui-v09-middleware.cjs";
11
13
  import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./generative-ui/surface-writer.cjs";
12
14
  import "./generative-ui/index.cjs";
15
+ import { ArgsParser, GenerateSandboxedUIParams, OnParamEvent, OpenGenerativeUIMiddleware } from "./event-transforms/open-generative-ui-middleware.cjs";
16
+ import { RecordedEventTransformOptions, transformRecordedEvents } from "./event-transforms/recorded-events.cjs";
17
+ import { A2UIMiddleware, A2UIMiddlewareConfig } from "./event-transforms/index.cjs";
13
18
  import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.cjs";
14
- import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.cjs";
19
+ import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary, STOP_RECORD_DEADLINE_MS } from "./runner/intelligence.cjs";
15
20
  import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.cjs";
16
21
  import { ChannelStatus, ChannelsControl } from "./core/channel-manager.cjs";
17
- import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
18
- import { CopilotCorsConfig } from "./core/fetch-cors.cjs";
19
- import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.cjs";
20
- import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
21
-
22
- //#region src/runtime/index.d.ts
23
- /** @deprecated Use `CopilotRuntimeFetchHandler` instead. Note: the new type takes `Request` directly, not `{ request: Request }`. */
24
- type CopilotKitRequestHandler = (params: {
25
- request: Request;
26
- }) => Promise<Response>;
27
- //#endregion
28
- export { CopilotKitRequestHandler, type MCPClient, type MCPTransport };
29
- //# sourceMappingURL=index.d.cts.map
22
+ import { CopilotKitRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.cjs";
23
+ import { CopilotKitCorsConfig } from "./core/fetch-cors.cjs";
24
+ import { CopilotKitRuntimeFetchHandler, CopilotKitRuntimeFetchHandlerWithChannels, CopilotKitRuntimeHandlerOptions, createCopilotKitRuntimeHandler } from "./core/fetch-handler.cjs";
@@ -1,29 +1,24 @@
1
+ import { experimental_d_exports } from "./intelligence-platform/experimental.mjs";
1
2
  import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest, LocalThreadEndpointRecord, LocalThreadEndpointRunner, LocalThreadEndpointScope, THREAD_ACCESS_DENIED_ERROR_CODE, ThreadAccessDeniedError, ThreadAlreadyRunningError, ThreadOwnershipRunner, enforcesThreadOwnership, isThreadAccessDeniedError, supportsLocalThreadEndpoints, ɵSERVER_THREAD_OWNER, ɵresolveThreadOwner } from "./runner/agent-runner.mjs";
2
3
  import { ThreadAccessMode, ThreadsConfig } from "./handlers/shared/thread-access.mjs";
4
+ import { CopilotKitRuntimeLogger } from "./core/logger.mjs";
3
5
  import { TranscribeFileOptions, TranscriptionService } from "./transcription-service/transcription-service.mjs";
4
- import { experimental_d_exports } from "./intelligence-platform/experimental.mjs";
5
- import { CopilotRuntimeLearningConfig, CopilotRuntimeLearningContext, CopilotRuntimeUser, GetLearningContainerId, GetTrajectoryLearningContainerIds, LearningContainerSelectorInput, TrajectoryLearningContainerSelectorInput } from "./core/learning.mjs";
6
6
  import { GetLearnedSkillsSnapshotRequest, GetLearnedSkillsSnapshotsRequest, LearnedSkillsBatchResult, LearnedSkillsError, LearnedSkillsErrorCode, LearnedSkillsSnapshotResult } from "./intelligence-platform/learned-skills.mjs";
7
- import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, PlatformRequestError, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
8
7
  import "./intelligence-platform/index.mjs";
9
- import { AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeConstructor, CopilotRuntimeLike, CopilotRuntimeMemoryConfig, CopilotRuntimeOptions, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isA2UIEnabled, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
8
+ import { A2UIVersion, AgentFactoryContext, AgentsConfig, AgentsFactory, CopilotKitIntelligenceRuntime, CopilotKitIntelligenceRuntimeLike, CopilotKitIntelligenceRuntimeOptions, CopilotKitRuntime, CopilotKitRuntimeConstructor, CopilotKitRuntimeLike, CopilotKitRuntimeMemoryConfig, CopilotKitRuntimeOptions, CopilotKitSseRuntime, CopilotKitSseRuntimeLike, CopilotKitSseRuntimeOptions, GenerativeUIOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, MemoryAccess, MemoryConsumer, MemoryGrant, OpenGenerativeUIConfig, OpenGenerativeUIOptions, RuntimeWithDeclaredChannels, VERSION, isIntelligenceRuntime, resolveAgents } from "./core/runtime.mjs";
9
+ import { CopilotKitRuntimeLearningConfig, CopilotKitRuntimeLearningContext, CopilotKitRuntimeUser, GetLearningContainerId, GetTrajectoryLearningContainerIds, LearningContainerSelectorInput, TrajectoryLearningContainerSelectorInput } from "./core/learning.mjs";
10
+ import { CopilotKitIntelligence, CopilotKitIntelligenceConfig, CreateThreadRequest, ListThreadsResponse, PlatformRequestError, SubscribeToThreadsRequest, SubscribeToThreadsResponse, ThreadSummary, UpdateThreadRequest } from "./intelligence-platform/client.mjs";
10
11
  import { GenerativeUIMiddleware } from "./generative-ui/generative-ui-middleware.mjs";
12
+ import { A2UIV09BridgeMiddleware } from "./generative-ui/a2ui-v09-middleware.mjs";
11
13
  import { GenerativeUISurfaceWriter, createSurfaceWriter } from "./generative-ui/surface-writer.mjs";
12
14
  import "./generative-ui/index.mjs";
15
+ import { ArgsParser, GenerateSandboxedUIParams, OnParamEvent, OpenGenerativeUIMiddleware } from "./event-transforms/open-generative-ui-middleware.mjs";
16
+ import { RecordedEventTransformOptions, transformRecordedEvents } from "./event-transforms/recorded-events.mjs";
17
+ import { A2UIMiddleware, A2UIMiddlewareConfig } from "./event-transforms/index.mjs";
13
18
  import { InMemoryAgentRunner, InMemoryAgentRunnerOptions, InMemoryLimits, InMemoryThread, ɵBoundedThreadStore, ɵGLOBAL_STORE, ɵINMEMORY_DEFAULTS, ɵOWNER_RETENTION_DEFAULTS, ɵOwnerRetention, ɵestimateBytes, ɵnormalizeLimits } from "./runner/in-memory.mjs";
14
- import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary } from "./runner/intelligence.mjs";
19
+ import { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions, RunnerStartupBoundary, STOP_RECORD_DEADLINE_MS } from "./runner/intelligence.mjs";
15
20
  import { FinalizeRunOptions, RunEventFinalizer, createRunEventFinalizer, finalizeRunEvents } from "./runner/index.mjs";
16
21
  import { ChannelStatus, ChannelsControl } from "./core/channel-manager.mjs";
17
- import { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
18
- import { CopilotCorsConfig } from "./core/fetch-cors.mjs";
19
- import { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler } from "./core/fetch-handler.mjs";
20
- import { MCPClient, MCPTransport } from "@ai-sdk/mcp";
21
-
22
- //#region src/runtime/index.d.ts
23
- /** @deprecated Use `CopilotRuntimeFetchHandler` instead. Note: the new type takes `Request` directly, not `{ request: Request }`. */
24
- type CopilotKitRequestHandler = (params: {
25
- request: Request;
26
- }) => Promise<Response>;
27
- //#endregion
28
- export { CopilotKitRequestHandler, type MCPClient, type MCPTransport };
29
- //# sourceMappingURL=index.d.mts.map
22
+ import { CopilotKitRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo } from "./core/hooks.mjs";
23
+ import { CopilotKitCorsConfig } from "./core/fetch-cors.mjs";
24
+ import { CopilotKitRuntimeFetchHandler, CopilotKitRuntimeFetchHandlerWithChannels, CopilotKitRuntimeHandlerOptions, createCopilotKitRuntimeHandler } from "./core/fetch-handler.mjs";
@@ -0,0 +1,84 @@
1
+ const require_logger = require('../core/logger.cjs');
2
+
3
+ //#region src/runtime/intelligence-platform/analytics-context.ts
4
+ /**
5
+ * The `forwardedProps` key an app uses to hand the runtime its analytics
6
+ * context for one run.
7
+ */
8
+ const ANALYTICS_CONTEXT_FORWARDED_PROP = "__copilotkitAnalyticsContext";
9
+ /** The largest analytics context the runtime forwards, in UTF-8 bytes of JSON. */
10
+ const MAX_ANALYTICS_CONTEXT_BYTES = 4096;
11
+ /**
12
+ * Splits an app's analytics context off a run's input.
13
+ *
14
+ * The returned input no longer carries the context, so it never reaches the
15
+ * agent or the run's stored events. The caller forwards it on the thread lock
16
+ * request alone. The context is returned as the app sent it; check it with
17
+ * {@link normalizeAnalyticsContext} before sending it anywhere.
18
+ */
19
+ function takeAnalyticsContext(input) {
20
+ const forwardedProps = input.forwardedProps;
21
+ if (typeof forwardedProps !== "object" || forwardedProps === null || !Object.prototype.hasOwnProperty.call(forwardedProps, ANALYTICS_CONTEXT_FORWARDED_PROP)) return {
22
+ input,
23
+ analyticsContext: void 0
24
+ };
25
+ const { [ANALYTICS_CONTEXT_FORWARDED_PROP]: analyticsContext, ...agentForwardedProps } = forwardedProps;
26
+ return {
27
+ input: {
28
+ ...input,
29
+ forwardedProps: agentForwardedProps
30
+ },
31
+ analyticsContext
32
+ };
33
+ }
34
+ /**
35
+ * Returns a JSON copy of an app's analytics context when it has the shape the
36
+ * lock request carries, and `undefined` otherwise.
37
+ *
38
+ * The runtime does not know what the context means. It checks only that the
39
+ * value is a plain object that serializes to JSON without losing anything (no
40
+ * functions, symbols, BigInts, cycles or non-finite numbers) in at most
41
+ * {@link MAX_ANALYTICS_CONTEXT_BYTES}. Intelligence validates the fields.
42
+ *
43
+ * A missing context (`undefined` or `null`) is dropped silently. A malformed
44
+ * one is dropped with a warning that names the problem but never the content.
45
+ * Neither ever fails the run.
46
+ */
47
+ function normalizeAnalyticsContext(value, logger = require_logger.getRuntimeLogger()) {
48
+ if (value === void 0 || value === null) return void 0;
49
+ const result = serializeAnalyticsContext(value);
50
+ if ("problem" in result) {
51
+ logger.warn({ problem: result.problem }, "Dropped the run's analytics context; the run continues without it");
52
+ return;
53
+ }
54
+ return JSON.parse(result.json);
55
+ }
56
+ function serializeAnalyticsContext(value) {
57
+ if (!isPlainObject(value)) return { problem: "not a plain object" };
58
+ let lossy;
59
+ let json;
60
+ try {
61
+ json = JSON.stringify(value, (_key, entry) => {
62
+ if (typeof entry === "function") lossy ??= "contains a function";
63
+ else if (typeof entry === "symbol") lossy ??= "contains a symbol";
64
+ else if (typeof entry === "number" && !Number.isFinite(entry)) lossy ??= "contains a non-finite number";
65
+ return entry;
66
+ });
67
+ } catch {
68
+ return { problem: "not serializable as JSON" };
69
+ }
70
+ if (lossy) return { problem: lossy };
71
+ const bytes = new TextEncoder().encode(json).byteLength;
72
+ if (bytes > MAX_ANALYTICS_CONTEXT_BYTES) return { problem: `larger than ${MAX_ANALYTICS_CONTEXT_BYTES} bytes (${bytes})` };
73
+ return { json };
74
+ }
75
+ function isPlainObject(value) {
76
+ if (typeof value !== "object" || value === null) return false;
77
+ const prototype = Object.getPrototypeOf(value);
78
+ return prototype === Object.prototype || prototype === null;
79
+ }
80
+
81
+ //#endregion
82
+ exports.normalizeAnalyticsContext = normalizeAnalyticsContext;
83
+ exports.takeAnalyticsContext = takeAnalyticsContext;
84
+ //# sourceMappingURL=analytics-context.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analytics-context.cjs","names":["getRuntimeLogger"],"sources":["../../../src/runtime/intelligence-platform/analytics-context.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport { getRuntimeLogger } from \"../core/logger\";\nimport type { CopilotKitRuntimeLogger } from \"../core/logger\";\n\n/**\n * The `forwardedProps` key an app uses to hand the runtime its analytics\n * context for one run.\n */\nexport const ANALYTICS_CONTEXT_FORWARDED_PROP = \"__copilotkitAnalyticsContext\";\n\n/** The largest analytics context the runtime forwards, in UTF-8 bytes of JSON. */\nexport const MAX_ANALYTICS_CONTEXT_BYTES = 4096;\n\n/**\n * Splits an app's analytics context off a run's input.\n *\n * The returned input no longer carries the context, so it never reaches the\n * agent or the run's stored events. The caller forwards it on the thread lock\n * request alone. The context is returned as the app sent it; check it with\n * {@link normalizeAnalyticsContext} before sending it anywhere.\n */\nexport function takeAnalyticsContext(input: RunAgentInput): {\n input: RunAgentInput;\n analyticsContext: unknown;\n} {\n const forwardedProps: unknown = input.forwardedProps;\n if (\n typeof forwardedProps !== \"object\" ||\n forwardedProps === null ||\n !Object.prototype.hasOwnProperty.call(\n forwardedProps,\n ANALYTICS_CONTEXT_FORWARDED_PROP,\n )\n ) {\n return { input, analyticsContext: undefined };\n }\n const {\n [ANALYTICS_CONTEXT_FORWARDED_PROP]: analyticsContext,\n ...agentForwardedProps\n } = forwardedProps as Record<string, unknown>;\n return {\n input: { ...input, forwardedProps: agentForwardedProps },\n analyticsContext,\n };\n}\n\n/**\n * Returns a JSON copy of an app's analytics context when it has the shape the\n * lock request carries, and `undefined` otherwise.\n *\n * The runtime does not know what the context means. It checks only that the\n * value is a plain object that serializes to JSON without losing anything (no\n * functions, symbols, BigInts, cycles or non-finite numbers) in at most\n * {@link MAX_ANALYTICS_CONTEXT_BYTES}. Intelligence validates the fields.\n *\n * A missing context (`undefined` or `null`) is dropped silently. A malformed\n * one is dropped with a warning that names the problem but never the content.\n * Neither ever fails the run.\n */\nexport function normalizeAnalyticsContext(\n value: unknown,\n logger: CopilotKitRuntimeLogger = getRuntimeLogger(),\n): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n const result = serializeAnalyticsContext(value);\n if (\"problem\" in result) {\n logger.warn(\n { problem: result.problem },\n \"Dropped the run's analytics context; the run continues without it\",\n );\n return undefined;\n }\n return JSON.parse(result.json) as Record<string, unknown>;\n}\n\nfunction serializeAnalyticsContext(\n value: unknown,\n): { json: string } | { problem: string } {\n if (!isPlainObject(value)) {\n return { problem: \"not a plain object\" };\n }\n let lossy: string | undefined;\n let json: string;\n try {\n json = JSON.stringify(value, (_key, entry: unknown) => {\n if (typeof entry === \"function\") lossy ??= \"contains a function\";\n else if (typeof entry === \"symbol\") lossy ??= \"contains a symbol\";\n else if (typeof entry === \"number\" && !Number.isFinite(entry))\n lossy ??= \"contains a non-finite number\";\n return entry;\n });\n } catch {\n // JSON.stringify throws on cycles and BigInts.\n return { problem: \"not serializable as JSON\" };\n }\n if (lossy) return { problem: lossy };\n const bytes = new TextEncoder().encode(json).byteLength;\n if (bytes > MAX_ANALYTICS_CONTEXT_BYTES) {\n return {\n problem: `larger than ${MAX_ANALYTICS_CONTEXT_BYTES} bytes (${bytes})`,\n };\n }\n return { json };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;;;;;AAQA,MAAa,mCAAmC;;AAGhD,MAAa,8BAA8B;;;;;;;;;AAU3C,SAAgB,qBAAqB,OAGnC;CACA,MAAM,iBAA0B,MAAM;AACtC,KACE,OAAO,mBAAmB,YAC1B,mBAAmB,QACnB,CAAC,OAAO,UAAU,eAAe,KAC/B,gBACA,iCACD,CAED,QAAO;EAAE;EAAO,kBAAkB;EAAW;CAE/C,MAAM,GACH,mCAAmC,kBACpC,GAAG,wBACD;AACJ,QAAO;EACL,OAAO;GAAE,GAAG;GAAO,gBAAgB;GAAqB;EACxD;EACD;;;;;;;;;;;;;;;AAgBH,SAAgB,0BACd,OACA,SAAkCA,iCAAkB,EACf;AACrC,KAAI,UAAU,UAAa,UAAU,KAAM,QAAO;CAClD,MAAM,SAAS,0BAA0B,MAAM;AAC/C,KAAI,aAAa,QAAQ;AACvB,SAAO,KACL,EAAE,SAAS,OAAO,SAAS,EAC3B,oEACD;AACD;;AAEF,QAAO,KAAK,MAAM,OAAO,KAAK;;AAGhC,SAAS,0BACP,OACwC;AACxC,KAAI,CAAC,cAAc,MAAM,CACvB,QAAO,EAAE,SAAS,sBAAsB;CAE1C,IAAI;CACJ,IAAI;AACJ,KAAI;AACF,SAAO,KAAK,UAAU,QAAQ,MAAM,UAAmB;AACrD,OAAI,OAAO,UAAU,WAAY,WAAU;YAClC,OAAO,UAAU,SAAU,WAAU;YACrC,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,MAAM,CAC3D,WAAU;AACZ,UAAO;IACP;SACI;AAEN,SAAO,EAAE,SAAS,4BAA4B;;AAEhD,KAAI,MAAO,QAAO,EAAE,SAAS,OAAO;CACpC,MAAM,QAAQ,IAAI,aAAa,CAAC,OAAO,KAAK,CAAC;AAC7C,KAAI,QAAQ,4BACV,QAAO,EACL,SAAS,eAAe,4BAA4B,UAAU,MAAM,IACrE;AAEH,QAAO,EAAE,MAAM;;AAGjB,SAAS,cAAc,OAAkD;AACvE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,YAAqB,OAAO,eAAe,MAAM;AACvD,QAAO,cAAc,OAAO,aAAa,cAAc"}