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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (357) hide show
  1. package/README.md +28 -3
  2. package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -76
  3. package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
  4. package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
  5. package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
  6. package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
  7. package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
  8. package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
  9. package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
  10. package/dist/agent/ai-sdk.cjs +425 -0
  11. package/dist/agent/ai-sdk.cjs.map +1 -0
  12. package/dist/agent/ai-sdk.d.cts +119 -0
  13. package/dist/agent/ai-sdk.d.cts.map +1 -0
  14. package/dist/agent/ai-sdk.d.mts +119 -0
  15. package/dist/agent/ai-sdk.d.mts.map +1 -0
  16. package/dist/agent/ai-sdk.mjs +419 -0
  17. package/dist/agent/ai-sdk.mjs.map +1 -0
  18. package/dist/agent/classic-tools.cjs +185 -0
  19. package/dist/agent/classic-tools.cjs.map +1 -0
  20. package/dist/agent/classic-tools.mjs +183 -0
  21. package/dist/agent/classic-tools.mjs.map +1 -0
  22. package/dist/agent/converters/aisdk.cjs +16 -3
  23. package/dist/agent/converters/aisdk.cjs.map +1 -1
  24. package/dist/agent/converters/aisdk.d.cts.map +1 -1
  25. package/dist/agent/converters/aisdk.d.mts.map +1 -1
  26. package/dist/agent/converters/aisdk.mjs +18 -2
  27. package/dist/agent/converters/aisdk.mjs.map +1 -1
  28. package/dist/agent/converters/tanstack.cjs +201 -29
  29. package/dist/agent/converters/tanstack.cjs.map +1 -1
  30. package/dist/agent/converters/tanstack.d.cts +90 -6
  31. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  32. package/dist/agent/converters/tanstack.d.mts +90 -6
  33. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  34. package/dist/agent/converters/tanstack.mjs +201 -28
  35. package/dist/agent/converters/tanstack.mjs.map +1 -1
  36. package/dist/agent/learned-skills.cjs +15 -17
  37. package/dist/agent/learned-skills.cjs.map +1 -1
  38. package/dist/agent/learned-skills.d.cts +9 -3
  39. package/dist/agent/learned-skills.d.cts.map +1 -1
  40. package/dist/agent/learned-skills.d.mts +9 -3
  41. package/dist/agent/learned-skills.d.mts.map +1 -1
  42. package/dist/agent/learned-skills.mjs +15 -16
  43. package/dist/agent/learned-skills.mjs.map +1 -1
  44. package/dist/agent/model.cjs +42 -0
  45. package/dist/agent/model.cjs.map +1 -0
  46. package/dist/agent/model.d.cts +19 -0
  47. package/dist/agent/model.d.cts.map +1 -0
  48. package/dist/agent/model.d.mts +19 -0
  49. package/dist/agent/model.d.mts.map +1 -0
  50. package/dist/agent/model.mjs +41 -0
  51. package/dist/agent/model.mjs.map +1 -0
  52. package/dist/agent/state-delta.cjs +0 -1
  53. package/dist/agent/state-delta.cjs.map +1 -1
  54. package/dist/agent.cjs +558 -0
  55. package/dist/agent.cjs.map +1 -0
  56. package/dist/agent.d.cts +455 -0
  57. package/dist/agent.d.cts.map +1 -0
  58. package/dist/agent.d.mts +455 -0
  59. package/dist/agent.d.mts.map +1 -0
  60. package/dist/agent.mjs +551 -0
  61. package/dist/agent.mjs.map +1 -0
  62. package/dist/index.cjs +21 -27
  63. package/dist/index.d.cts +10 -11
  64. package/dist/index.d.mts +10 -11
  65. package/dist/index.mjs +5 -6
  66. package/dist/internal/learned-skills.d.cts +1 -1
  67. package/dist/internal/learned-skills.d.mts +1 -1
  68. package/dist/node.cjs +1 -2
  69. package/dist/node.d.cts +2 -2
  70. package/dist/node.d.mts +2 -2
  71. package/dist/node.mjs +2 -2
  72. package/dist/runtime/core/channel-manager.cjs +10 -2
  73. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  74. package/dist/runtime/core/channel-manager.d.cts +1 -1
  75. package/dist/runtime/core/channel-manager.d.mts +1 -1
  76. package/dist/runtime/core/channel-manager.mjs +10 -1
  77. package/dist/runtime/core/channel-manager.mjs.map +1 -1
  78. package/dist/runtime/core/debug-event-bus.cjs +4 -3
  79. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  80. package/dist/runtime/core/debug-event-bus.d.cts +5 -1
  81. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  82. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  83. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  84. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  85. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  86. package/dist/runtime/core/fetch-handler.cjs +15 -12
  87. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  88. package/dist/runtime/core/fetch-handler.d.cts +8 -0
  89. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  90. package/dist/runtime/core/fetch-handler.d.mts +8 -0
  91. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  92. package/dist/runtime/core/fetch-handler.mjs +7 -3
  93. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  94. package/dist/runtime/core/learning.d.cts +1 -1
  95. package/dist/runtime/core/logger.cjs +105 -14
  96. package/dist/runtime/core/logger.cjs.map +1 -1
  97. package/dist/runtime/core/logger.d.cts +25 -8
  98. package/dist/runtime/core/logger.d.cts.map +1 -1
  99. package/dist/runtime/core/logger.d.mts +25 -8
  100. package/dist/runtime/core/logger.d.mts.map +1 -1
  101. package/dist/runtime/core/logger.mjs +105 -12
  102. package/dist/runtime/core/logger.mjs.map +1 -1
  103. package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
  104. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  105. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  106. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  107. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  108. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  109. package/dist/runtime/core/middleware.cjs +5 -5
  110. package/dist/runtime/core/middleware.cjs.map +1 -1
  111. package/dist/runtime/core/middleware.mjs +4 -3
  112. package/dist/runtime/core/middleware.mjs.map +1 -1
  113. package/dist/runtime/core/package-info.cjs +1 -1
  114. package/dist/runtime/core/package-info.mjs +1 -1
  115. package/dist/runtime/core/runtime.cjs +11 -10
  116. package/dist/runtime/core/runtime.cjs.map +1 -1
  117. package/dist/runtime/core/runtime.d.cts +22 -4
  118. package/dist/runtime/core/runtime.d.cts.map +1 -1
  119. package/dist/runtime/core/runtime.d.mts +22 -4
  120. package/dist/runtime/core/runtime.d.mts.map +1 -1
  121. package/dist/runtime/core/runtime.mjs +11 -9
  122. package/dist/runtime/core/runtime.mjs.map +1 -1
  123. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
  124. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  125. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  126. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  127. package/dist/runtime/endpoints/node-fetch-handler.cjs +3 -7
  128. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  129. package/dist/runtime/endpoints/node-fetch-handler.d.cts +3 -4
  130. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  131. package/dist/runtime/endpoints/node-fetch-handler.d.mts +3 -4
  132. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  133. package/dist/runtime/endpoints/node-fetch-handler.mjs +3 -5
  134. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  135. package/dist/runtime/endpoints/node.cjs +4 -2
  136. package/dist/runtime/endpoints/node.cjs.map +1 -1
  137. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  138. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  139. package/dist/runtime/endpoints/node.mjs +4 -2
  140. package/dist/runtime/endpoints/node.mjs.map +1 -1
  141. package/dist/runtime/event-transforms/index.d.cts +4 -0
  142. package/dist/runtime/event-transforms/index.d.mts +4 -0
  143. package/dist/runtime/event-transforms/index.mjs +5 -0
  144. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  145. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  146. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  147. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  148. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  149. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  150. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  151. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  152. package/dist/runtime/event-transforms/recorded-events.cjs +58 -0
  153. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  154. package/dist/runtime/event-transforms/recorded-events.d.cts +23 -0
  155. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  156. package/dist/runtime/event-transforms/recorded-events.d.mts +23 -0
  157. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  158. package/dist/runtime/event-transforms/recorded-events.mjs +58 -0
  159. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  160. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  161. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  162. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  163. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  164. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  165. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  166. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  167. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  168. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  169. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  170. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  171. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  172. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  173. package/dist/runtime/handlers/get-runtime-info.cjs +5 -1
  174. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  175. package/dist/runtime/handlers/get-runtime-info.mjs +5 -1
  176. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  177. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  178. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  179. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  180. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  181. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  182. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  183. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  184. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  185. package/dist/runtime/handlers/handle-run.cjs +11 -14
  186. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  187. package/dist/runtime/handlers/handle-run.mjs +8 -10
  188. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  189. package/dist/runtime/handlers/handle-stop.cjs +5 -5
  190. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  191. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  192. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  193. package/dist/runtime/handlers/handle-suggest.cjs +6 -3
  194. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  195. package/dist/runtime/handlers/handle-suggest.mjs +6 -2
  196. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  197. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  198. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  199. package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
  200. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  201. package/dist/runtime/handlers/intelligence/annotate.mjs +4 -3
  202. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  203. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  204. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  205. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  206. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  207. package/dist/runtime/handlers/intelligence/memories.cjs +27 -22
  208. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  209. package/dist/runtime/handlers/intelligence/memories.mjs +11 -5
  210. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  211. package/dist/runtime/handlers/intelligence/run.cjs +38 -30
  212. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  213. package/dist/runtime/handlers/intelligence/run.mjs +37 -28
  214. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  215. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
  216. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  217. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  218. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  219. package/dist/runtime/handlers/intelligence/threads.cjs +36 -27
  220. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  221. package/dist/runtime/handlers/intelligence/threads.mjs +13 -3
  222. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  223. package/dist/runtime/handlers/shared/agent-utils.cjs +35 -34
  224. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  225. package/dist/runtime/handlers/shared/agent-utils.mjs +29 -27
  226. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  227. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  228. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  229. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
  230. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  231. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
  232. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  233. package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
  234. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  235. package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
  236. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  237. package/dist/runtime/handlers/shared/thread-access.cjs +3 -2
  238. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  239. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  240. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  241. package/dist/runtime/handlers/shared/thread-access.mjs +3 -2
  242. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  243. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  244. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  245. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  246. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  247. package/dist/runtime/handlers/sse/run.cjs +5 -2
  248. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  249. package/dist/runtime/handlers/sse/run.mjs +5 -2
  250. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  251. package/dist/runtime/index.d.cts +9 -15
  252. package/dist/runtime/index.d.mts +9 -15
  253. package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
  254. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
  255. package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
  256. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
  257. package/dist/runtime/intelligence-platform/client.cjs +27 -1
  258. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  259. package/dist/runtime/intelligence-platform/client.d.cts +24 -1
  260. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  261. package/dist/runtime/intelligence-platform/client.d.mts +24 -1
  262. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  263. package/dist/runtime/intelligence-platform/client.mjs +27 -0
  264. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  265. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  266. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  267. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  268. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  269. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  270. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  271. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  272. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  273. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  274. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  275. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  276. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  277. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  278. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  279. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  280. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  281. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
  282. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  283. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  284. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  285. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
  286. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  287. package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
  288. package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
  289. package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
  290. package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
  291. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
  292. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  293. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  294. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  295. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  296. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  297. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  298. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  299. package/dist/runtime/node.d.cts +1 -1
  300. package/dist/runtime/node.d.mts +1 -1
  301. package/dist/runtime/runner/agent-runner.cjs +0 -1
  302. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  303. package/dist/runtime/runner/agent-runner.d.cts +9 -0
  304. package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
  305. package/dist/runtime/runner/agent-runner.d.mts +9 -0
  306. package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
  307. package/dist/runtime/runner/agent-runner.mjs.map +1 -1
  308. package/dist/runtime/runner/in-memory.cjs +0 -1
  309. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  310. package/dist/runtime/runner/index.d.cts +1 -1
  311. package/dist/runtime/runner/index.d.mts +1 -1
  312. package/dist/runtime/runner/index.mjs +1 -1
  313. package/dist/runtime/runner/intelligence.cjs +55 -9
  314. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  315. package/dist/runtime/runner/intelligence.d.cts +12 -1
  316. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  317. package/dist/runtime/runner/intelligence.d.mts +12 -1
  318. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  319. package/dist/runtime/runner/intelligence.mjs +56 -10
  320. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  321. package/dist/runtime/telemetry/disclosure.cjs +2 -3
  322. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  323. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  324. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  325. package/dist/runtime/telemetry/events.d.cts +1 -1
  326. package/dist/runtime/telemetry/events.d.mts +1 -1
  327. package/dist/runtime/telemetry/instance-created.cjs +33 -12
  328. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  329. package/dist/runtime/telemetry/instance-created.mjs +33 -12
  330. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  331. package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
  332. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  333. package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
  334. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  335. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  336. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  337. package/package.json +55 -30
  338. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  339. package/dist/agent/converters/index.d.mts +0 -2
  340. package/dist/agent/index.cjs +0 -1328
  341. package/dist/agent/index.cjs.map +0 -1
  342. package/dist/agent/index.d.cts +0 -467
  343. package/dist/agent/index.d.cts.map +0 -1
  344. package/dist/agent/index.d.mts +0 -468
  345. package/dist/agent/index.d.mts.map +0 -1
  346. package/dist/agent/index.mjs +0 -1318
  347. package/dist/agent/index.mjs.map +0 -1
  348. package/dist/agent/mcp-tool-names.cjs +0 -82
  349. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  350. package/dist/agent/mcp-tool-names.mjs +0 -80
  351. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  352. package/dist/agent/url-download.cjs.map +0 -1
  353. package/dist/agent/url-download.d.cts.map +0 -1
  354. package/dist/agent/url-download.d.mts.map +0 -1
  355. package/dist/agent/url-download.mjs.map +0 -1
  356. package/dist/runtime/index.d.cts.map +0 -1
  357. package/dist/runtime/index.d.mts.map +0 -1
@@ -1,28 +1,27 @@
1
- const require_runtime = require('../../../_virtual/_rolldown/runtime.cjs');
1
+ const require_logger = require('../../core/logger.cjs');
2
2
  const require_agent_runner = require('../../runner/agent-runner.cjs');
3
3
  const require_json_response = require('../shared/json-response.cjs');
4
4
  const require_intelligence_utils = require('../shared/intelligence-utils.cjs');
5
5
  const require_resolve_intelligence_user = require('../shared/resolve-intelligence-user.cjs');
6
6
  const require_thread_access = require('../shared/thread-access.cjs');
7
- const require_runtime$1 = require('../../core/runtime.cjs');
7
+ const require_runtime = require('../../core/runtime.cjs');
8
8
  const require_platform_error = require('../shared/platform-error.cjs');
9
- let _copilotkit_shared = require("@copilotkit/shared");
10
9
 
11
10
  //#region src/runtime/handlers/intelligence/threads.ts
12
- async function parseJsonBody(request) {
11
+ async function parseJsonBody(request, logger) {
13
12
  try {
14
13
  return await request.json();
15
14
  } catch (error) {
16
- _copilotkit_shared.logger.error({ err: error }, "Malformed JSON in request body");
15
+ logger.error({ err: error }, "Malformed JSON in request body");
17
16
  return require_json_response.errorResponse("Invalid request body", 400);
18
17
  }
19
18
  }
20
19
  function requireIntelligenceRuntime(runtime) {
21
- if (!require_runtime$1.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
20
+ if (!require_runtime.isIntelligenceRuntime(runtime)) return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
22
21
  return runtime;
23
22
  }
24
23
  async function resolveThreadMutationContext(runtime, request) {
25
- const body = await parseJsonBody(request);
24
+ const body = await parseJsonBody(request, require_logger.getRuntimeLogger(runtime));
26
25
  if (require_json_response.isHandlerResponse(body)) return body;
27
26
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
28
27
  runtime,
@@ -49,6 +48,7 @@ async function resolveThreadMutationContext(runtime, request) {
49
48
  * for anything else (logged as an error).
50
49
  */
51
50
  async function requireUserThread(runtime, threadId, userId, failure) {
51
+ const logger = require_logger.getRuntimeLogger(runtime);
52
52
  let thread;
53
53
  try {
54
54
  thread = await runtime.intelligence.getThread({
@@ -57,24 +57,25 @@ async function requireUserThread(runtime, threadId, userId, failure) {
57
57
  });
58
58
  } catch (error) {
59
59
  const status = require_intelligence_utils.getPlatformErrorStatus(error);
60
- if (status !== void 0 && status >= 400 && status < 500 && status !== 401) _copilotkit_shared.logger.warn({
60
+ if (status !== void 0 && status >= 400 && status < 500 && status !== 401) logger.warn({
61
61
  threadId,
62
62
  status
63
63
  }, "Thread not visible to the user");
64
- else _copilotkit_shared.logger.error({
64
+ else logger.error({
65
65
  err: error,
66
66
  threadId
67
67
  }, "Error resolving thread");
68
68
  return require_platform_error.platformErrorResponse(error, failure);
69
69
  }
70
70
  if (!thread || typeof thread.id !== "string" || !thread.id.trim()) {
71
- _copilotkit_shared.logger.error({ threadId }, "Invalid thread response from getThread");
71
+ logger.error({ threadId }, "Invalid thread response from getThread");
72
72
  return require_json_response.errorResponse("Invalid thread response", 502);
73
73
  }
74
74
  return { threadId: thread.id };
75
75
  }
76
76
  async function handleListThreads({ runtime, request }) {
77
- if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
77
+ const logger = require_logger.getRuntimeLogger(runtime);
78
+ if (require_runtime.isIntelligenceRuntime(runtime)) try {
78
79
  const url = new URL(request.url);
79
80
  const agentId = url.searchParams.get("agentId");
80
81
  const includeArchived = url.searchParams.get("includeArchived") === "true";
@@ -95,7 +96,7 @@ async function handleListThreads({ runtime, request }) {
95
96
  });
96
97
  return Response.json(data);
97
98
  } catch (error) {
98
- _copilotkit_shared.logger.error({ err: error }, "Error listing threads");
99
+ logger.error({ err: error }, "Error listing threads");
99
100
  return require_json_response.errorResponse("Failed to list threads", 500);
100
101
  }
101
102
  if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
@@ -114,7 +115,7 @@ async function handleListThreads({ runtime, request }) {
114
115
  nextCursor: null
115
116
  });
116
117
  } catch (error) {
117
- _copilotkit_shared.logger.error({ err: error }, "Error listing threads");
118
+ logger.error({ err: error }, "Error listing threads");
118
119
  return require_json_response.errorResponse("Failed to list threads", 500);
119
120
  }
120
121
  }
@@ -133,6 +134,7 @@ async function handleListThreads({ runtime, request }) {
133
134
  * client-side page load.
134
135
  */
135
136
  async function handleClearThreads({ runtime, request }) {
137
+ const logger = require_logger.getRuntimeLogger(runtime);
136
138
  if (require_agent_runner.supportsLocalThreadEndpoints(runtime.runner)) {
137
139
  const ownerId = await require_thread_access.resolveLocalThreadOwner({
138
140
  runtime,
@@ -143,13 +145,14 @@ async function handleClearThreads({ runtime, request }) {
143
145
  try {
144
146
  runtime.runner.clearThreads({ ownerId });
145
147
  } catch (error) {
146
- _copilotkit_shared.logger.error({ err: error }, "Error clearing threads");
148
+ logger.error({ err: error }, "Error clearing threads");
147
149
  return require_json_response.errorResponse("Failed to clear threads", 500);
148
150
  }
149
151
  }
150
152
  return new Response(null, { status: 204 });
151
153
  }
152
154
  async function handleUpdateThread({ runtime, request, threadId }) {
155
+ const logger = require_logger.getRuntimeLogger(runtime);
153
156
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
154
157
  if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
155
158
  try {
@@ -165,7 +168,7 @@ async function handleUpdateThread({ runtime, request, threadId }) {
165
168
  });
166
169
  return Response.json(thread);
167
170
  } catch (error) {
168
- _copilotkit_shared.logger.error({
171
+ logger.error({
169
172
  err: error,
170
173
  threadId
171
174
  }, "Error updating thread");
@@ -173,6 +176,7 @@ async function handleUpdateThread({ runtime, request, threadId }) {
173
176
  }
174
177
  }
175
178
  async function handleSubscribeToThreads({ runtime, request }) {
179
+ const logger = require_logger.getRuntimeLogger(runtime);
176
180
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
177
181
  if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
178
182
  try {
@@ -184,11 +188,12 @@ async function handleSubscribeToThreads({ runtime, request }) {
184
188
  const credentials = await intelligenceRuntime.intelligence.ɵsubscribeToThreads({ userId: user.id });
185
189
  return Response.json({ joinToken: credentials.joinToken });
186
190
  } catch (error) {
187
- _copilotkit_shared.logger.error({ err: error }, "Error subscribing to threads");
191
+ logger.error({ err: error }, "Error subscribing to threads");
188
192
  return require_json_response.errorResponse("Failed to subscribe to threads", 500);
189
193
  }
190
194
  }
191
195
  async function handleArchiveThread({ runtime, request, threadId }) {
196
+ const logger = require_logger.getRuntimeLogger(runtime);
192
197
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
193
198
  if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
194
199
  try {
@@ -204,7 +209,7 @@ async function handleArchiveThread({ runtime, request, threadId }) {
204
209
  archived: true
205
210
  });
206
211
  } catch (error) {
207
- _copilotkit_shared.logger.error({
212
+ logger.error({
208
213
  err: error,
209
214
  threadId
210
215
  }, "Error archiving thread");
@@ -212,6 +217,7 @@ async function handleArchiveThread({ runtime, request, threadId }) {
212
217
  }
213
218
  }
214
219
  async function handleDeleteThread({ runtime, request, threadId }) {
220
+ const logger = require_logger.getRuntimeLogger(runtime);
215
221
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
216
222
  if (require_json_response.isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
217
223
  try {
@@ -227,7 +233,7 @@ async function handleDeleteThread({ runtime, request, threadId }) {
227
233
  deleted: true
228
234
  });
229
235
  } catch (error) {
230
- _copilotkit_shared.logger.error({
236
+ logger.error({
231
237
  err: error,
232
238
  threadId
233
239
  }, "Error deleting thread");
@@ -235,7 +241,8 @@ async function handleDeleteThread({ runtime, request, threadId }) {
235
241
  }
236
242
  }
237
243
  async function handleGetThreadMessages({ runtime, request, threadId }) {
238
- if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
244
+ const logger = require_logger.getRuntimeLogger(runtime);
245
+ if (require_runtime.isIntelligenceRuntime(runtime)) try {
239
246
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
240
247
  runtime,
241
248
  request
@@ -247,7 +254,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
247
254
  });
248
255
  return Response.json(data);
249
256
  } catch (error) {
250
- _copilotkit_shared.logger.error({
257
+ logger.error({
251
258
  err: error,
252
259
  threadId
253
260
  }, "Error fetching thread messages");
@@ -264,7 +271,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
264
271
  try {
265
272
  messages = runtime.runner.getThreadMessages(threadId, { ownerId });
266
273
  } catch (error) {
267
- _copilotkit_shared.logger.error({
274
+ logger.error({
268
275
  err: error,
269
276
  threadId
270
277
  }, "Error fetching thread messages");
@@ -303,7 +310,8 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
303
310
  return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
304
311
  }
305
312
  async function handleGetThreadEvents({ runtime, request, threadId }) {
306
- if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
313
+ const logger = require_logger.getRuntimeLogger(runtime);
314
+ if (require_runtime.isIntelligenceRuntime(runtime)) try {
307
315
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
308
316
  runtime,
309
317
  request
@@ -317,7 +325,7 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
317
325
  });
318
326
  return Response.json({ events: data.events });
319
327
  } catch (error) {
320
- _copilotkit_shared.logger.error({
328
+ logger.error({
321
329
  err: error,
322
330
  threadId
323
331
  }, "Error fetching thread events");
@@ -334,7 +342,7 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
334
342
  const events = runtime.runner.getThreadEvents(threadId, { ownerId });
335
343
  return Response.json({ events });
336
344
  } catch (error) {
337
- _copilotkit_shared.logger.error({
345
+ logger.error({
338
346
  err: error,
339
347
  threadId
340
348
  }, "Error fetching thread events");
@@ -344,7 +352,8 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
344
352
  return require_json_response.errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
345
353
  }
346
354
  async function handleGetThreadState({ runtime, request, threadId }) {
347
- if (require_runtime$1.isIntelligenceRuntime(runtime)) try {
355
+ const logger = require_logger.getRuntimeLogger(runtime);
356
+ if (require_runtime.isIntelligenceRuntime(runtime)) try {
348
357
  const user = await require_resolve_intelligence_user.resolveIntelligenceUser({
349
358
  runtime,
350
359
  request
@@ -359,7 +368,7 @@ async function handleGetThreadState({ runtime, request, threadId }) {
359
368
  const state = data.kind === "snapshot" ? data.state : null;
360
369
  return Response.json({ state });
361
370
  } catch (error) {
362
- _copilotkit_shared.logger.error({
371
+ logger.error({
363
372
  err: error,
364
373
  threadId
365
374
  }, "Error fetching thread state");
@@ -376,7 +385,7 @@ async function handleGetThreadState({ runtime, request, threadId }) {
376
385
  const state = runtime.runner.getThreadState(threadId, { ownerId });
377
386
  return Response.json({ state });
378
387
  } catch (error) {
379
- _copilotkit_shared.logger.error({
388
+ logger.error({
380
389
  err: error,
381
390
  threadId
382
391
  }, "Error fetching thread state");
@@ -1 +1 @@
1
- {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","getPlatformErrorStatus","platformErrorResponse","supportsLocalThreadEndpoints","resolveLocalThreadOwner"],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\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AI9D,QAAOA,oCACL,uJACA,IACD;;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAIC,wCAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAID,wCAAkB,KAAK,CAAE,QAAO;EACpC,MAAM,SAAS,MAAM,kBACnB,SACA,UACA,KAAK,IACL,+BACD;AACD,MAAIA,wCAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe;GACrD,UAAU,OAAO;GACjB,QAAQ,KAAK;GACd,CAAC;EAMF,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOI,6CAAsB,OAAO,+BAA+B;;AAIvE,KAAIC,kDAA6B,QAAQ,OAAO,EAAE;EAChD,MAAM,UAAU,MAAMC,8CAAwB;GAC5C;GACA;GACA,WAAW;GACZ,CAAC;AACF,MAAIN,wCAAkB,QAAQ,CAAE,QAAO;AACvC,MAAI;GACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,UAAU,EAAE,SAAS,CAAC;AAClE,UAAO,SAAS,KAAK,EAAE,OAAO,CAAC;WACxB,OAAO;AACd,6BAAO,MAAM;IAAE,KAAK;IAAO;IAAU,EAAE,8BAA8B;AACrE,UAAOF,oCAAc,gCAAgC,IAAI;;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","getRuntimeLogger","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","getPlatformErrorStatus","platformErrorResponse","supportsLocalThreadEndpoints","resolveLocalThreadOwner"],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n logger: CopilotRuntimeLogger,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request, getRuntimeLogger(runtime));\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n const logger = getRuntimeLogger(runtime);\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n case \"activity\":\n case \"developer\":\n case \"reasoning\":\n case \"system\":\n case \"user\":\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AAgCA,eAAe,cACb,SACA,QAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,sCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,SAASE,gCAAiB,QAAQ,CAAC;AACpE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAID,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAACE,6CAAkB,QAAQ,CAC7B,QAAOL,oCAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;;;;;;;;;;;;AAcH,eAAe,kBACb,SACA,UACA,QACA,SAC0C;CAC1C,MAAM,SAASE,gCAAiB,QAAQ;CACxC,IAAI;AACJ,KAAI;AACF,WAAS,MA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Q;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOI,6CAAsB,OAAO,+BAA+B;;AAIvE,KAAIC,kDAA6B,QAAQ,OAAO,EAAE;EAChD,MAAM,UAAU,MAAMC,8CAAwB;GAC5C;GACA;GACA,WAAW;GACZ,CAAC;AACF,MAAIN,wCAAkB,QAAQ,CAAE,QAAO;AACvC,MAAI;GACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,UAAU,EAAE,SAAS,CAAC;AAClE,UAAO,SAAS,KAAK,EAAE,OAAO,CAAC;WACxB,OAAO;AACd,UAAO,MAAM;IAAE,KAAK;IAAO;IAAU,EAAE,8BAA8B;AACrE,UAAOH,oCAAc,gCAAgC,IAAI;;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
@@ -1,3 +1,4 @@
1
+ import { getRuntimeLogger } from "../../core/logger.mjs";
1
2
  import { supportsLocalThreadEndpoints } from "../../runner/agent-runner.mjs";
2
3
  import { errorResponse, isHandlerResponse } from "../shared/json-response.mjs";
3
4
  import { getPlatformErrorStatus, isValidIdentifier } from "../shared/intelligence-utils.mjs";
@@ -5,10 +6,9 @@ import { resolveIntelligenceUser } from "../shared/resolve-intelligence-user.mjs
5
6
  import { resolveLocalThreadOwner } from "../shared/thread-access.mjs";
6
7
  import { isIntelligenceRuntime } from "../../core/runtime.mjs";
7
8
  import { platformErrorResponse } from "../shared/platform-error.mjs";
8
- import { logger } from "@copilotkit/shared";
9
9
 
10
10
  //#region src/runtime/handlers/intelligence/threads.ts
11
- async function parseJsonBody(request) {
11
+ async function parseJsonBody(request, logger) {
12
12
  try {
13
13
  return await request.json();
14
14
  } catch (error) {
@@ -21,7 +21,7 @@ function requireIntelligenceRuntime(runtime) {
21
21
  return runtime;
22
22
  }
23
23
  async function resolveThreadMutationContext(runtime, request) {
24
- const body = await parseJsonBody(request);
24
+ const body = await parseJsonBody(request, getRuntimeLogger(runtime));
25
25
  if (isHandlerResponse(body)) return body;
26
26
  const user = await resolveIntelligenceUser({
27
27
  runtime,
@@ -48,6 +48,7 @@ async function resolveThreadMutationContext(runtime, request) {
48
48
  * for anything else (logged as an error).
49
49
  */
50
50
  async function requireUserThread(runtime, threadId, userId, failure) {
51
+ const logger = getRuntimeLogger(runtime);
51
52
  let thread;
52
53
  try {
53
54
  thread = await runtime.intelligence.getThread({
@@ -73,6 +74,7 @@ async function requireUserThread(runtime, threadId, userId, failure) {
73
74
  return { threadId: thread.id };
74
75
  }
75
76
  async function handleListThreads({ runtime, request }) {
77
+ const logger = getRuntimeLogger(runtime);
76
78
  if (isIntelligenceRuntime(runtime)) try {
77
79
  const url = new URL(request.url);
78
80
  const agentId = url.searchParams.get("agentId");
@@ -132,6 +134,7 @@ async function handleListThreads({ runtime, request }) {
132
134
  * client-side page load.
133
135
  */
134
136
  async function handleClearThreads({ runtime, request }) {
137
+ const logger = getRuntimeLogger(runtime);
135
138
  if (supportsLocalThreadEndpoints(runtime.runner)) {
136
139
  const ownerId = await resolveLocalThreadOwner({
137
140
  runtime,
@@ -149,6 +152,7 @@ async function handleClearThreads({ runtime, request }) {
149
152
  return new Response(null, { status: 204 });
150
153
  }
151
154
  async function handleUpdateThread({ runtime, request, threadId }) {
155
+ const logger = getRuntimeLogger(runtime);
152
156
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
153
157
  if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
154
158
  try {
@@ -172,6 +176,7 @@ async function handleUpdateThread({ runtime, request, threadId }) {
172
176
  }
173
177
  }
174
178
  async function handleSubscribeToThreads({ runtime, request }) {
179
+ const logger = getRuntimeLogger(runtime);
175
180
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
176
181
  if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
177
182
  try {
@@ -188,6 +193,7 @@ async function handleSubscribeToThreads({ runtime, request }) {
188
193
  }
189
194
  }
190
195
  async function handleArchiveThread({ runtime, request, threadId }) {
196
+ const logger = getRuntimeLogger(runtime);
191
197
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
192
198
  if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
193
199
  try {
@@ -211,6 +217,7 @@ async function handleArchiveThread({ runtime, request, threadId }) {
211
217
  }
212
218
  }
213
219
  async function handleDeleteThread({ runtime, request, threadId }) {
220
+ const logger = getRuntimeLogger(runtime);
214
221
  const intelligenceRuntime = requireIntelligenceRuntime(runtime);
215
222
  if (isHandlerResponse(intelligenceRuntime)) return intelligenceRuntime;
216
223
  try {
@@ -234,6 +241,7 @@ async function handleDeleteThread({ runtime, request, threadId }) {
234
241
  }
235
242
  }
236
243
  async function handleGetThreadMessages({ runtime, request, threadId }) {
244
+ const logger = getRuntimeLogger(runtime);
237
245
  if (isIntelligenceRuntime(runtime)) try {
238
246
  const user = await resolveIntelligenceUser({
239
247
  runtime,
@@ -302,6 +310,7 @@ async function handleGetThreadMessages({ runtime, request, threadId }) {
302
310
  return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
303
311
  }
304
312
  async function handleGetThreadEvents({ runtime, request, threadId }) {
313
+ const logger = getRuntimeLogger(runtime);
305
314
  if (isIntelligenceRuntime(runtime)) try {
306
315
  const user = await resolveIntelligenceUser({
307
316
  runtime,
@@ -343,6 +352,7 @@ async function handleGetThreadEvents({ runtime, request, threadId }) {
343
352
  return errorResponse("Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.", 422);
344
353
  }
345
354
  async function handleGetThreadState({ runtime, request, threadId }) {
355
+ const logger = getRuntimeLogger(runtime);
346
356
  if (isIntelligenceRuntime(runtime)) try {
347
357
  const user = await resolveIntelligenceUser({
348
358
  runtime,
@@ -1 +1 @@
1
- {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA+BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;;;;;;;;;;;;AAcH,eAAe,kBACb,SACA,UACA,QACA,SAC0C;CAC1C,IAAI;AACJ,KAAI;AACF,WAAS,MAAM,QAAQ,aAAa,UAAU;GAAE;GAAU;GAAQ,CAAC;UAC5D,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;AAC5C,MACE,WAAW,UACX,UAAU,OACV,SAAS,OACT,WAAW,IAEX,QAAO,KAAK;GAAE;GAAU;GAAQ,EAAE,iCAAiC;MAEnE,QAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,yBAAyB;AAElE,SAAO,sBAAsB,OAAO,QAAQ;;AAE9C,KAAI,CAAC,UAAU,OAAO,OAAO,OAAO,YAAY,CAAC,OAAO,GAAG,MAAM,EAAE;AACjE,SAAO,MAAM,EAAE,UAAU,EAAE,yCAAyC;AAC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I9D,QAAO,cACL,uJACA,IACD;;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAI,sBAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CAAE,QAAO;EACpC,MAAM,SAAS,MAAM,kBACnB,SACA,UACA,KAAK,IACL,+BACD;AACD,MAAI,kBAAkB,OAAO,CAAE,QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe;GACrD,UAAU,OAAO;GACjB,QAAQ,KAAK;GACd,CAAC;EAMF,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,sBAAsB,OAAO,+BAA+B;;AAIvE,KAAI,6BAA6B,QAAQ,OAAO,EAAE;EAChD,MAAM,UAAU,MAAM,wBAAwB;GAC5C;GACA;GACA,WAAW;GACZ,CAAC;AACF,MAAI,kBAAkB,QAAQ,CAAE,QAAO;AACvC,MAAI;GACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,UAAU,EAAE,SAAS,CAAC;AAClE,UAAO,SAAS,KAAK,EAAE,OAAO,CAAC;WACxB,OAAO;AACd,UAAO,MAAM;IAAE,KAAK;IAAO;IAAU,EAAE,8BAA8B;AACrE,UAAO,cAAc,gCAAgC,IAAI;;;AAI7D,QAAO,cACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../src/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { getRuntimeLogger } from \"../../core/logger\";\nimport type { CopilotRuntimeLogger } from \"../../core/logger\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport {\n getPlatformErrorStatus,\n isValidIdentifier,\n} from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { platformErrorResponse } from \"../shared/platform-error\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\nimport { resolveLocalThreadOwner } from \"../shared/thread-access\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n logger: CopilotRuntimeLogger,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request, getRuntimeLogger(runtime));\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\n/**\n * The platform's `_inspect` events and state endpoints are scoped by the\n * project key only. Before calling them, confirm the thread is visible to the\n * resolved user through the user-scoped thread lookup, and return its\n * canonical id for the read, so the check and the read name the same thread.\n *\n * Returns the error Response instead when the lookup refuses: the platform's\n * 4xx for a thread the user cannot see (an expected denial, logged as a\n * warning), 502 for a malformed lookup result, and the mapped platform error\n * for anything else (logged as an error).\n */\nasync function requireUserThread(\n runtime: CopilotIntelligenceRuntimeLike,\n threadId: string,\n userId: string,\n failure: string,\n): Promise<{ threadId: string } | Response> {\n const logger = getRuntimeLogger(runtime);\n let thread: Awaited<ReturnType<typeof runtime.intelligence.getThread>>;\n try {\n thread = await runtime.intelligence.getThread({ threadId, userId });\n } catch (error) {\n const status = getPlatformErrorStatus(error);\n if (\n status !== undefined &&\n status >= 400 &&\n status < 500 &&\n status !== 401\n ) {\n logger.warn({ threadId, status }, \"Thread not visible to the user\");\n } else {\n logger.error({ err: error, threadId }, \"Error resolving thread\");\n }\n return platformErrorResponse(error, failure);\n }\n if (!thread || typeof thread.id !== \"string\" || !thread.id.trim()) {\n logger.error({ threadId }, \"Invalid thread response from getThread\");\n return errorResponse(\"Invalid thread response\", 502);\n }\n return { threadId: thread.id };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"list\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads({ ownerId });\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears the caller's in-memory thread history for the local-dev fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Only the caller's own threads are cleared, and a thread whose run is\n * still active is kept. Without `identifyUser`, the access policy refuses it\n * unless `threads: { access: \"open\" }` is set.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport async function handleClearThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"clear\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n runtime.runner.clearThreads({ ownerId });\n } catch (error) {\n logger.error({ err: error }, \"Error clearing threads\");\n return errorResponse(\"Failed to clear threads\", 500);\n }\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n // The public SDK accepts trusted updates; browser fields must be allowlisted.\n const updates: Record<string, unknown> = {};\n for (const key of [\"name\", \"archived\"]) {\n if (Object.prototype.hasOwnProperty.call(mutation.body, key)) {\n updates[key] = mutation.body[key];\n }\n }\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return platformErrorResponse(error, \"Failed to fetch thread messages\");\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n // Another owner's thread reads exactly like an unknown thread.\n let messages: ReturnType<typeof runtime.runner.getThreadMessages>;\n try {\n messages = runtime.runner.getThreadMessages(threadId, { ownerId });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n case \"activity\":\n case \"developer\":\n case \"reasoning\":\n case \"system\":\n case \"user\":\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path. `_inspect` is not user-scoped, so the\n // thread is first checked against the user (see `requireUserThread`).\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread events\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadEvents({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return platformErrorResponse(error, \"Failed to fetch thread events\");\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const events = runtime.runner.getThreadEvents(threadId, { ownerId });\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const logger = getRuntimeLogger(runtime);\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n const thread = await requireUserThread(\n runtime,\n threadId,\n user.id,\n \"Failed to fetch thread state\",\n );\n if (isHandlerResponse(thread)) return thread;\n\n const data = await runtime.intelligence.getThreadState({\n threadId: thread.threadId,\n userId: user.id,\n });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return platformErrorResponse(error, \"Failed to fetch thread state\");\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const ownerId = await resolveLocalThreadOwner({\n runtime,\n request,\n operation: \"read\",\n });\n if (isHandlerResponse(ownerId)) return ownerId;\n try {\n const state = runtime.runner.getThreadState(threadId, { ownerId });\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AAgCA,eAAe,cACb,SACA,QAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,SAAS,iBAAiB,QAAQ,CAAC;AACpE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;;;;;;;;;;;;AAcH,eAAe,kBACb,SACA,UACA,QACA,SAC0C;CAC1C,MAAM,SAAS,iBAAiB,QAAQ;CACxC,IAAI;AACJ,KAAI;AACF,WAAS,MAAM,QAAQ,aAAa,UAAU;GAAE;GAAU;GAAQ,CAAC;UAC5D,OAAO;EACd,MAAM,SAAS,uBAAuB,MAAM;AAC5C,MACE,WAAW,UACX,UAAU,OACV,SAAS,OACT,WAAW,IAEX,QAAO,K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