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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/README.md +29 -4
  2. package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -76
  3. package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
  4. package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
  5. package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
  6. package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
  7. package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
  8. package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
  9. package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
  10. package/dist/agent/ai-sdk.cjs +425 -0
  11. package/dist/agent/ai-sdk.cjs.map +1 -0
  12. package/dist/agent/ai-sdk.d.cts +119 -0
  13. package/dist/agent/ai-sdk.d.cts.map +1 -0
  14. package/dist/agent/ai-sdk.d.mts +119 -0
  15. package/dist/agent/ai-sdk.d.mts.map +1 -0
  16. package/dist/agent/ai-sdk.mjs +419 -0
  17. package/dist/agent/ai-sdk.mjs.map +1 -0
  18. package/dist/agent/classic-tools.cjs +185 -0
  19. package/dist/agent/classic-tools.cjs.map +1 -0
  20. package/dist/agent/classic-tools.mjs +183 -0
  21. package/dist/agent/classic-tools.mjs.map +1 -0
  22. package/dist/agent/converters/aisdk.cjs +17 -4
  23. package/dist/agent/converters/aisdk.cjs.map +1 -1
  24. package/dist/agent/converters/aisdk.d.cts.map +1 -1
  25. package/dist/agent/converters/aisdk.d.mts.map +1 -1
  26. package/dist/agent/converters/aisdk.mjs +18 -2
  27. package/dist/agent/converters/aisdk.mjs.map +1 -1
  28. package/dist/agent/converters/tanstack.cjs +202 -30
  29. package/dist/agent/converters/tanstack.cjs.map +1 -1
  30. package/dist/agent/converters/tanstack.d.cts +90 -6
  31. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  32. package/dist/agent/converters/tanstack.d.mts +90 -6
  33. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  34. package/dist/agent/converters/tanstack.mjs +202 -29
  35. package/dist/agent/converters/tanstack.mjs.map +1 -1
  36. package/dist/agent/learned-skills.cjs +15 -17
  37. package/dist/agent/learned-skills.cjs.map +1 -1
  38. package/dist/agent/learned-skills.d.cts +9 -3
  39. package/dist/agent/learned-skills.d.cts.map +1 -1
  40. package/dist/agent/learned-skills.d.mts +9 -3
  41. package/dist/agent/learned-skills.d.mts.map +1 -1
  42. package/dist/agent/learned-skills.mjs +15 -16
  43. package/dist/agent/learned-skills.mjs.map +1 -1
  44. package/dist/agent/model.cjs +42 -0
  45. package/dist/agent/model.cjs.map +1 -0
  46. package/dist/agent/model.d.cts +19 -0
  47. package/dist/agent/model.d.cts.map +1 -0
  48. package/dist/agent/model.d.mts +19 -0
  49. package/dist/agent/model.d.mts.map +1 -0
  50. package/dist/agent/model.mjs +41 -0
  51. package/dist/agent/model.mjs.map +1 -0
  52. package/dist/agent/state-delta.cjs +0 -1
  53. package/dist/agent/state-delta.cjs.map +1 -1
  54. package/dist/agent.cjs +558 -0
  55. package/dist/agent.cjs.map +1 -0
  56. package/dist/agent.d.cts +455 -0
  57. package/dist/agent.d.cts.map +1 -0
  58. package/dist/agent.d.mts +455 -0
  59. package/dist/agent.d.mts.map +1 -0
  60. package/dist/agent.mjs +551 -0
  61. package/dist/agent.mjs.map +1 -0
  62. package/dist/index.cjs +23 -28
  63. package/dist/index.d.cts +14 -14
  64. package/dist/index.d.mts +14 -14
  65. package/dist/index.mjs +8 -8
  66. package/dist/internal/learned-skills.d.cts +1 -1
  67. package/dist/internal/learned-skills.d.mts +1 -1
  68. package/dist/node.cjs +2 -3
  69. package/dist/node.d.cts +3 -3
  70. package/dist/node.d.mts +3 -3
  71. package/dist/node.mjs +3 -3
  72. package/dist/runtime/core/channel-manager.cjs +10 -2
  73. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  74. package/dist/runtime/core/channel-manager.d.cts +1 -1
  75. package/dist/runtime/core/channel-manager.d.mts +1 -1
  76. package/dist/runtime/core/channel-manager.mjs +10 -1
  77. package/dist/runtime/core/channel-manager.mjs.map +1 -1
  78. package/dist/runtime/core/debug-event-bus.cjs +4 -3
  79. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  80. package/dist/runtime/core/debug-event-bus.d.cts +5 -1
  81. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  82. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  83. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  84. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  85. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  86. package/dist/runtime/core/fetch-cors.cjs.map +1 -1
  87. package/dist/runtime/core/fetch-cors.d.cts +2 -2
  88. package/dist/runtime/core/fetch-cors.d.cts.map +1 -1
  89. package/dist/runtime/core/fetch-cors.d.mts +2 -2
  90. package/dist/runtime/core/fetch-cors.d.mts.map +1 -1
  91. package/dist/runtime/core/fetch-cors.mjs.map +1 -1
  92. package/dist/runtime/core/fetch-handler.cjs +17 -14
  93. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  94. package/dist/runtime/core/fetch-handler.d.cts +22 -14
  95. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  96. package/dist/runtime/core/fetch-handler.d.mts +22 -14
  97. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  98. package/dist/runtime/core/fetch-handler.mjs +9 -5
  99. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  100. package/dist/runtime/core/hooks.cjs.map +1 -1
  101. package/dist/runtime/core/hooks.d.cts +5 -5
  102. package/dist/runtime/core/hooks.d.cts.map +1 -1
  103. package/dist/runtime/core/hooks.d.mts +5 -5
  104. package/dist/runtime/core/hooks.d.mts.map +1 -1
  105. package/dist/runtime/core/hooks.mjs.map +1 -1
  106. package/dist/runtime/core/learning.cjs.map +1 -1
  107. package/dist/runtime/core/learning.d.cts +9 -9
  108. package/dist/runtime/core/learning.d.cts.map +1 -1
  109. package/dist/runtime/core/learning.d.mts +8 -8
  110. package/dist/runtime/core/learning.d.mts.map +1 -1
  111. package/dist/runtime/core/learning.mjs.map +1 -1
  112. package/dist/runtime/core/logger.cjs +105 -14
  113. package/dist/runtime/core/logger.cjs.map +1 -1
  114. package/dist/runtime/core/logger.d.cts +26 -9
  115. package/dist/runtime/core/logger.d.cts.map +1 -1
  116. package/dist/runtime/core/logger.d.mts +26 -9
  117. package/dist/runtime/core/logger.d.mts.map +1 -1
  118. package/dist/runtime/core/logger.mjs +105 -12
  119. package/dist/runtime/core/logger.mjs.map +1 -1
  120. package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
  121. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  122. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  123. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  124. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  125. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  126. package/dist/runtime/core/middleware.cjs +5 -5
  127. package/dist/runtime/core/middleware.cjs.map +1 -1
  128. package/dist/runtime/core/middleware.d.cts +3 -3
  129. package/dist/runtime/core/middleware.d.cts.map +1 -1
  130. package/dist/runtime/core/middleware.d.mts +3 -3
  131. package/dist/runtime/core/middleware.d.mts.map +1 -1
  132. package/dist/runtime/core/middleware.mjs +4 -3
  133. package/dist/runtime/core/middleware.mjs.map +1 -1
  134. package/dist/runtime/core/package-info.cjs +1 -1
  135. package/dist/runtime/core/package-info.mjs +1 -1
  136. package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -1
  137. package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -1
  138. package/dist/runtime/core/runtime.cjs +44 -46
  139. package/dist/runtime/core/runtime.cjs.map +1 -1
  140. package/dist/runtime/core/runtime.d.cts +178 -91
  141. package/dist/runtime/core/runtime.d.cts.map +1 -1
  142. package/dist/runtime/core/runtime.d.mts +178 -91
  143. package/dist/runtime/core/runtime.d.mts.map +1 -1
  144. package/dist/runtime/core/runtime.mjs +42 -42
  145. package/dist/runtime/core/runtime.mjs.map +1 -1
  146. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
  147. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  148. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  149. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  150. package/dist/runtime/endpoints/node-fetch-handler.cjs +4 -8
  151. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  152. package/dist/runtime/endpoints/node-fetch-handler.d.cts +4 -5
  153. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  154. package/dist/runtime/endpoints/node-fetch-handler.d.mts +4 -5
  155. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  156. package/dist/runtime/endpoints/node-fetch-handler.mjs +3 -5
  157. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  158. package/dist/runtime/endpoints/node.cjs +7 -5
  159. package/dist/runtime/endpoints/node.cjs.map +1 -1
  160. package/dist/runtime/endpoints/node.d.cts +16 -16
  161. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  162. package/dist/runtime/endpoints/node.d.mts +16 -16
  163. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  164. package/dist/runtime/endpoints/node.mjs +9 -7
  165. package/dist/runtime/endpoints/node.mjs.map +1 -1
  166. package/dist/runtime/event-transforms/index.d.cts +4 -0
  167. package/dist/runtime/event-transforms/index.d.mts +4 -0
  168. package/dist/runtime/event-transforms/index.mjs +5 -0
  169. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  170. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  171. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  172. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  173. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  174. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  175. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  176. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  177. package/dist/runtime/event-transforms/recorded-events.cjs +68 -0
  178. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  179. package/dist/runtime/event-transforms/recorded-events.d.cts +27 -0
  180. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  181. package/dist/runtime/event-transforms/recorded-events.d.mts +27 -0
  182. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  183. package/dist/runtime/event-transforms/recorded-events.mjs +68 -0
  184. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  185. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  186. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  187. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  188. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  189. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs +106 -0
  190. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs.map +1 -0
  191. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs +106 -0
  192. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs.map +1 -0
  193. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs +422 -0
  194. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs.map +1 -0
  195. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs +422 -0
  196. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs.map +1 -0
  197. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs +84 -0
  198. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -0
  199. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts +41 -0
  200. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts.map +1 -0
  201. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts +41 -0
  202. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts.map +1 -0
  203. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs +83 -0
  204. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -0
  205. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs +694 -0
  206. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs.map +1 -0
  207. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs +694 -0
  208. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs.map +1 -0
  209. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  210. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  211. package/dist/runtime/generative-ui/index.d.cts +1 -0
  212. package/dist/runtime/generative-ui/index.d.mts +1 -0
  213. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  214. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  215. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  216. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  217. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  218. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  219. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  220. package/dist/runtime/handlers/get-runtime-info.cjs +24 -6
  221. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  222. package/dist/runtime/handlers/get-runtime-info.mjs +25 -7
  223. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  224. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  225. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  226. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  227. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  228. package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -1
  229. package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -1
  230. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  231. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  232. package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -1
  233. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  234. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  235. package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -1
  236. package/dist/runtime/handlers/handle-run.cjs +11 -16
  237. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  238. package/dist/runtime/handlers/handle-run.mjs +8 -12
  239. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  240. package/dist/runtime/handlers/handle-stop.cjs +5 -5
  241. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  242. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  243. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  244. package/dist/runtime/handlers/handle-suggest.cjs +6 -3
  245. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  246. package/dist/runtime/handlers/handle-suggest.mjs +6 -2
  247. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  248. package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -1
  249. package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -1
  250. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  251. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  252. package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -1
  253. package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
  254. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  255. package/dist/runtime/handlers/intelligence/annotate.mjs +5 -4
  256. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  257. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  258. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  259. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  260. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  261. package/dist/runtime/handlers/intelligence/memories.cjs +28 -23
  262. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  263. package/dist/runtime/handlers/intelligence/memories.mjs +12 -6
  264. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  265. package/dist/runtime/handlers/intelligence/run.cjs +38 -30
  266. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  267. package/dist/runtime/handlers/intelligence/run.mjs +37 -28
  268. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  269. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
  270. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  271. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  272. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  273. package/dist/runtime/handlers/intelligence/threads.cjs +40 -31
  274. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  275. package/dist/runtime/handlers/intelligence/threads.mjs +18 -8
  276. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  277. package/dist/runtime/handlers/shared/agent-utils.cjs +50 -46
  278. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  279. package/dist/runtime/handlers/shared/agent-utils.mjs +47 -42
  280. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  281. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  282. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  283. package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -1
  284. package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -1
  285. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
  286. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  287. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
  288. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  289. package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
  290. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  291. package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
  292. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  293. package/dist/runtime/handlers/shared/thread-access.cjs +4 -3
  294. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  295. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  296. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  297. package/dist/runtime/handlers/shared/thread-access.mjs +4 -3
  298. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  299. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  300. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  301. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  302. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  303. package/dist/runtime/handlers/sse/run.cjs +5 -2
  304. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  305. package/dist/runtime/handlers/sse/run.mjs +5 -2
  306. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  307. package/dist/runtime/index.d.cts +13 -18
  308. package/dist/runtime/index.d.mts +13 -18
  309. package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
  310. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
  311. package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
  312. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
  313. package/dist/runtime/intelligence-platform/client.cjs +30 -4
  314. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  315. package/dist/runtime/intelligence-platform/client.d.cts +25 -2
  316. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  317. package/dist/runtime/intelligence-platform/client.d.mts +25 -2
  318. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  319. package/dist/runtime/intelligence-platform/client.mjs +30 -3
  320. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  321. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  322. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  323. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  324. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  325. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  326. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  327. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  328. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  329. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  330. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  331. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  332. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  333. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  334. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  335. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  336. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  337. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
  338. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  339. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  340. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  341. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
  342. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  343. package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
  344. package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
  345. package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
  346. package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
  347. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
  348. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  349. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  350. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  351. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  352. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  353. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  354. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  355. package/dist/runtime/node.d.cts +2 -2
  356. package/dist/runtime/node.d.mts +2 -2
  357. package/dist/runtime/runner/agent-runner.cjs +0 -1
  358. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  359. package/dist/runtime/runner/agent-runner.d.cts +9 -0
  360. package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
  361. package/dist/runtime/runner/agent-runner.d.mts +9 -0
  362. package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
  363. package/dist/runtime/runner/agent-runner.mjs.map +1 -1
  364. package/dist/runtime/runner/in-memory.cjs +0 -1
  365. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  366. package/dist/runtime/runner/index.d.cts +1 -1
  367. package/dist/runtime/runner/index.d.mts +1 -1
  368. package/dist/runtime/runner/index.mjs +1 -1
  369. package/dist/runtime/runner/intelligence.cjs +55 -9
  370. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  371. package/dist/runtime/runner/intelligence.d.cts +12 -1
  372. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  373. package/dist/runtime/runner/intelligence.d.mts +12 -1
  374. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  375. package/dist/runtime/runner/intelligence.mjs +56 -10
  376. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  377. package/dist/runtime/telemetry/disclosure.cjs +2 -3
  378. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  379. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  380. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  381. package/dist/runtime/telemetry/events.d.cts +1 -1
  382. package/dist/runtime/telemetry/events.d.mts +1 -1
  383. package/dist/runtime/telemetry/instance-created.cjs +33 -12
  384. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  385. package/dist/runtime/telemetry/instance-created.mjs +33 -12
  386. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  387. package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
  388. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  389. package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
  390. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  391. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  392. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  393. package/dist/v2/index.d.cts +242 -0
  394. package/dist/v2/index.d.mts +242 -0
  395. package/dist/v2/node.d.cts +18 -0
  396. package/dist/v2/node.d.mts +18 -0
  397. package/package.json +84 -29
  398. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  399. package/dist/agent/converters/index.d.mts +0 -2
  400. package/dist/agent/index.cjs +0 -1328
  401. package/dist/agent/index.cjs.map +0 -1
  402. package/dist/agent/index.d.cts +0 -467
  403. package/dist/agent/index.d.cts.map +0 -1
  404. package/dist/agent/index.d.mts +0 -468
  405. package/dist/agent/index.d.mts.map +0 -1
  406. package/dist/agent/index.mjs +0 -1318
  407. package/dist/agent/index.mjs.map +0 -1
  408. package/dist/agent/mcp-tool-names.cjs +0 -82
  409. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  410. package/dist/agent/mcp-tool-names.mjs +0 -80
  411. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  412. package/dist/agent/url-download.cjs.map +0 -1
  413. package/dist/agent/url-download.d.cts.map +0 -1
  414. package/dist/agent/url-download.d.mts.map +0 -1
  415. package/dist/agent/url-download.mjs.map +0 -1
  416. package/dist/runtime/index.d.cts.map +0 -1
  417. package/dist/runtime/index.d.mts.map +0 -1
@@ -1,11 +1,12 @@
1
- import { CopilotRuntimeLike, RuntimeWithDeclaredChannels } from "./runtime.mjs";
1
+ import { RuntimeInstanceCreatedInfo } from "../telemetry/events.mjs";
2
+ import { CopilotKitRuntimeLike, RuntimeWithDeclaredChannels } from "./runtime.mjs";
2
3
  import { ActivateChannelEngine, ChannelsControl } from "./channel-manager.mjs";
3
- import { CopilotRuntimeHooks } from "./hooks.mjs";
4
- import { CopilotCorsConfig } from "./fetch-cors.mjs";
4
+ import { CopilotKitRuntimeHooks } from "./hooks.mjs";
5
+ import { CopilotKitCorsConfig } from "./fetch-cors.mjs";
5
6
 
6
7
  //#region src/runtime/core/fetch-handler.d.ts
7
- interface CopilotRuntimeHandlerOptions {
8
- runtime: CopilotRuntimeLike;
8
+ interface CopilotKitRuntimeHandlerOptions {
9
+ runtime: CopilotKitRuntimeLike;
9
10
  /**
10
11
  * Optional base path for routing.
11
12
  *
@@ -27,11 +28,11 @@ interface CopilotRuntimeHandlerOptions {
27
28
  * When not provided, no CORS headers are added (let the framework handle it).
28
29
  * Set to true for permissive defaults, or provide an object.
29
30
  */
30
- cors?: boolean | CopilotCorsConfig;
31
+ cors?: boolean | CopilotKitCorsConfig;
31
32
  /**
32
33
  * Lifecycle hooks for request processing.
33
34
  */
34
- hooks?: CopilotRuntimeHooks;
35
+ hooks?: CopilotKitRuntimeHooks;
35
36
  /**
36
37
  * Whether the handler builds the runtime's declared managed-Channel control
37
38
  * surface. Defaults to `true`, which constructs the {@link ChannelManager} and
@@ -52,6 +53,13 @@ interface CopilotRuntimeHandlerOptions {
52
53
  * API and may change or be removed without notice.
53
54
  */
54
55
  __channelEngine?: ActivateChannelEngine;
56
+ /**
57
+ * @internal Payload for the `oss.runtime.instance_created` event, used in
58
+ * place of the v2 defaults. The v1 integration wrappers pass the v1 payload
59
+ * here so that the event fires once, from this factory, with the v1 data.
60
+ * Not part of the public API and may change or be removed without notice.
61
+ */
62
+ __instanceCreatedInfo?: RuntimeInstanceCreatedInfo;
55
63
  }
56
64
  /**
57
65
  * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`
@@ -59,7 +67,7 @@ interface CopilotRuntimeHandlerOptions {
59
67
  * control surface. A plain function is assignable to this type, so existing
60
68
  * call sites that treat it as `(Request) => Promise<Response>` keep working.
61
69
  */
62
- type CopilotRuntimeFetchHandler = ((request: Request) => Promise<Response>) & {
70
+ type CopilotKitRuntimeFetchHandler = ((request: Request) => Promise<Response>) & {
63
71
  /**
64
72
  * Present only when the handler activated managed Channels for an
65
73
  * Intelligence runtime; the lifecycle control surface for those Channels.
@@ -67,13 +75,13 @@ type CopilotRuntimeFetchHandler = ((request: Request) => Promise<Response>) & {
67
75
  channels?: ChannelsControl;
68
76
  };
69
77
  /**
70
- * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is
78
+ * A {@link CopilotKitRuntimeFetchHandler} whose {@link ChannelsControl} surface is
71
79
  * guaranteed present. Returned when the runtime was constructed with at least
72
80
  * one declared Intelligence Channel and activation was not opted out of, so the
73
81
  * documented `handler.channels.ready(...)` call type-checks without a `!` or
74
82
  * `?.` under strict TypeScript.
75
83
  */
76
- type CopilotRuntimeFetchHandlerWithChannels = ((request: Request) => Promise<Response>) & {
84
+ type CopilotKitRuntimeFetchHandlerWithChannels = ((request: Request) => Promise<Response>) & {
77
85
  /** Lifecycle control surface for the runtime's activated managed Channels. */channels: ChannelsControl;
78
86
  };
79
87
  /**
@@ -85,15 +93,15 @@ type CopilotRuntimeFetchHandlerWithChannels = ((request: Request) => Promise<Res
85
93
  * `.channels`) falls through to the optional-shape overload below rather than
86
94
  * dishonestly promising a control surface that will not exist.
87
95
  */
88
- declare function createCopilotRuntimeHandler(options: CopilotRuntimeHandlerOptions & {
96
+ declare function createCopilotKitRuntimeHandler(options: CopilotKitRuntimeHandlerOptions & {
89
97
  runtime: RuntimeWithDeclaredChannels;
90
98
  activateChannels?: true | undefined;
91
- }): CopilotRuntimeFetchHandlerWithChannels;
99
+ }): CopilotKitRuntimeFetchHandlerWithChannels;
92
100
  /**
93
101
  * Overload: every other runtime (SSE, Intelligence without channels, or with
94
102
  * activation disabled) yields a handler whose `.channels` is optional.
95
103
  */
96
- declare function createCopilotRuntimeHandler(options: CopilotRuntimeHandlerOptions): CopilotRuntimeFetchHandler;
104
+ declare function createCopilotKitRuntimeHandler(options: CopilotKitRuntimeHandlerOptions): CopilotKitRuntimeFetchHandler;
97
105
  //#endregion
98
- export { CopilotRuntimeFetchHandler, CopilotRuntimeFetchHandlerWithChannels, CopilotRuntimeHandlerOptions, createCopilotRuntimeHandler };
106
+ export { CopilotKitRuntimeFetchHandler, CopilotKitRuntimeFetchHandlerWithChannels, CopilotKitRuntimeHandlerOptions, createCopilotKitRuntimeHandler };
99
107
  //# sourceMappingURL=fetch-handler.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../src/runtime/core/fetch-handler.ts"],"mappings":";;;;;;UA8IiB,4BAAA;EACf,OAAA,EAAS,kBAAA;EAuKK;;;;;;;;;EA5Jd,QAAA;EA8JW;;;;;EAvJX,IAAA;EA+Jc;;;;;EAxJd,IAAA,aAAiB,iBAAA;EA0JhB;;;EArJD,KAAA,GAAQ,mBAAA;;;;;;;;;;;;;;EAeR,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;AAAA;;;;;;;KASR,0BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,sCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBAqFI,2BAAA,CACd,OAAA,EAAS,4BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,sCAAA;;;;;iBAKa,2BAAA,CACd,OAAA,EAAS,4BAAA,GACR,0BAAA"}
1
+ {"version":3,"file":"fetch-handler.d.mts","names":[],"sources":["../../../src/runtime/core/fetch-handler.ts"],"mappings":";;;;;;;UA+IiB,+BAAA;EACf,OAAA,EAAS,qBAAA;EA0FC;;;AAwFZ;;;;;;EAvKE,QAAA;EA4K0C;;;;;EArK1C,IAAA;EAqKC;;;AAKH;;EAnKE,IAAA,aAAiB,oBAAA;EAqKa;;;EAhK9B,KAAA,GAAQ,sBAAA;EAgKsB;;;;;;;;;;;;;EAjJ9B,gBAAA;;;;;;EAOA,eAAA,GAAkB,qBAAA;;;;;;;EAQlB,qBAAA,GAAwB,0BAAA;AAAA;;;;;;;KASd,6BAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;;;;;EAKX,QAAA,GAAW,eAAA;AAAA;;;;;;;;KAUD,yCAAA,KACV,OAAA,EAAS,OAAA,KACN,OAAA,CAAQ,QAAA;gFAEX,QAAA,EAAU,eAAA;AAAA;;;;;;;;;;iBAwFI,8BAAA,CACd,OAAA,EAAS,+BAAA;EACP,OAAA,EAAS,2BAAA;EACT,gBAAA;AAAA,IAED,yCAAA;;;;;iBAKa,8BAAA,CACd,OAAA,EAAS,+BAAA,GACR,6BAAA"}
@@ -1,3 +1,4 @@
1
+ import { getRuntimeLogger } from "./logger.mjs";
1
2
  import { isIntelligenceRuntime } from "./runtime.mjs";
2
3
  import { ChannelManager } from "./channel-manager.mjs";
3
4
  import { runOnBeforeHandler, runOnError, runOnRequest, runOnResponse } from "./hooks.mjs";
@@ -19,7 +20,6 @@ import { handleCreateMemory, handleListMemories, handleRecallMemories, handleRem
19
20
  import { handleAnnotate } from "../handlers/intelligence/annotate.mjs";
20
21
  import { createJsonRequest, createResourceRequest, detectSingleRouteEnvelope, expectString, parseMethodCall } from "../endpoints/single-route-helpers.mjs";
21
22
  import { fireInstanceCreatedTelemetry } from "../telemetry/instance-created.mjs";
22
- import { logger } from "@copilotkit/shared";
23
23
 
24
24
  //#region src/runtime/core/fetch-handler.ts
25
25
  /**
@@ -71,15 +71,19 @@ function getOrCreateChannelManager(runtime, engine) {
71
71
  ...runtime.lockKeyPrefix !== void 0 ? { lockKeyPrefix: runtime.lockKeyPrefix } : {},
72
72
  channels: runtime.channels,
73
73
  telemetry: runtime.telemetry,
74
- log: (msg, meta) => logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),
74
+ log: (msg, meta) => getRuntimeLogger(runtime).warn(meta instanceof Error ? { err: meta } : { meta }, msg),
75
75
  ...engine ? { activateChannel: engine } : {}
76
76
  });
77
77
  channelManagers.set(runtime, manager);
78
78
  return manager;
79
79
  }
80
- function createCopilotRuntimeHandler(options) {
80
+ function createCopilotKitRuntimeHandler(options) {
81
81
  const { runtime, basePath, mode = "multi-route", cors, hooks } = options;
82
- fireInstanceCreatedTelemetry({ runtime });
82
+ const logger = getRuntimeLogger(runtime);
83
+ fireInstanceCreatedTelemetry({
84
+ runtime,
85
+ info: options.__instanceCreatedInfo
86
+ });
83
87
  const corsConfig = resolveCorsConfig(cors);
84
88
  const handler = async (request) => {
85
89
  const path = new URL(request.url, "http://localhost").pathname;
@@ -534,5 +538,5 @@ function jsonResponse(body, status, extraHeaders) {
534
538
  }
535
539
 
536
540
  //#endregion
537
- export { createCopilotRuntimeHandler };
541
+ export { createCopilotKitRuntimeHandler };
538
542
  //# sourceMappingURL=fetch-handler.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../src/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotRuntime, createCopilotRuntimeHandler } from \"@copilotkit/runtime\";\n *\n * const handler = createCopilotRuntimeHandler({\n * runtime: new CopilotRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / a Bun or Deno server),\n * call `await handler.channels.ready()` ONCE at startup to open the listener;\n * the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * This laziness is a property of THIS handler, because it is the one entry point\n * that must stay serverless-safe. The process-owning wrappers do not inherit it:\n * `createCopilotNodeListener` STARTS activation\n * at creation (OSS-641), so `ready()` there is optional and await-and-observe.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotRuntimeLike,\n CopilotIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport {\n handleTrajectoryConnect,\n trajectoryErrorResponse,\n} from \"../handlers/handle-trajectory-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleInspectorMetadata } from \"../handlers/handle-inspector-metadata\";\nimport { handleInspectorLearning } from \"../handlers/handle-inspector-learning\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n createResourceRequest,\n expectString,\n detectSingleRouteEnvelope,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { logger } from \"@copilotkit/shared\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\n\n/**\n * Emitted when a single-route client's JSON envelope reaches a runtime mounted\n * in multi-route mode. Named so callers can branch on the cause rather than\n * string-matching the prose.\n */\nconst SINGLE_ROUTE_ENVELOPE_CODE =\n \"single_route_envelope_against_multi_route_runtime\";\n\nconst SINGLE_ROUTE_ENVELOPE_MESSAGE =\n 'Received a single-route request envelope ({ method: \"...\" }) but this ' +\n \"runtime is mounted in multi-route mode, so the request matched no route. \" +\n \"Either drop useSingleEndpoint from the frontend provider so it negotiates \" +\n 'the transport, or mount the runtime with mode: \"single-route\" to serve ' +\n \"this envelope.\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHandlerOptions {\n runtime: CopilotRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n *\n * The process-owning Node listener also starts activation when this is left on,\n * so `false` is the opt-out that keeps a mounted listener socket-free in a test\n * or a short-lived script.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n ...(runtime.learning !== undefined ? { learning: runtime.learning } : {}),\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n telemetry: runtime.telemetry,\n // Bridge the manager's diagnostic sink to the shared logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n logger.warn(meta instanceof Error ? { err: meta } : { meta }, msg),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler;\nexport function createCopilotRuntimeHandler(\n options: CopilotRuntimeHandlerOptions,\n): CopilotRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n\n fireInstanceCreatedTelemetry({ runtime });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n let handlerPath = path;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(\n request,\n basePath,\n path,\n runtime.exposeMemoryRoutes === true,\n );\n route = resolved.route;\n request = resolved.request;\n handlerPath = resolved.path;\n const { methodCall } = resolved;\n if (methodCall.method === \"resource/request\") {\n const methodError = validateHttpMethod(request.method, route);\n if (methodError) {\n throw methodError;\n }\n }\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path: handlerPath,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n } else if (route.method === \"agent/stop\") {\n request = createJsonRequest(\n request,\n methodCall.body === undefined ? {} : methodCall.body,\n );\n } else if (route.method === \"inspector/learning\") {\n const learningUrl = new URL(request.url);\n for (const key of [\n \"agentId\",\n \"skillsPage\",\n \"insightsPage\",\n ] as const) {\n const value = methodCall.params?.[key];\n if (typeof value === \"string\" || typeof value === \"number\") {\n learningUrl.searchParams.set(key, String(value));\n }\n }\n request = new Request(learningUrl, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: methodCall.method === \"resource/request\",\n singleRouteResourceOperationsEnabled: true,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n // A single-endpoint client POSTing `{ method }` at the base path\n // matches no route here. Say so, rather than leaving the developer\n // with a bare 404 and no way to tell a transport mismatch from a\n // wrong `basePath` (issue OSS-882).\n const envelopeMethod = await detectSingleRouteEnvelope(request);\n if (envelopeMethod) {\n logger.warn(\n { url: request.url, path, method: envelopeMethod },\n SINGLE_ROUTE_ENVELOPE_MESSAGE,\n );\n throw jsonResponse(\n {\n error: \"Not found\",\n code: SINGLE_ROUTE_ENVELOPE_CODE,\n message: SINGLE_ROUTE_ENVELOPE_MESSAGE,\n },\n 404,\n );\n }\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n singleRouteResourceOperationsEnabled: false,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path: handlerPath,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client. Only clone when\n // middleware is set: an unread clone still buffers every streamed chunk\n // until the response ends.\n if (runtime.afterRequestMiddleware) {\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path: handlerPath,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path: handlerPath },\n \"Error running after request middleware\",\n );\n });\n }\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path: handlerPath,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path: handlerPath,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n {\n err: hookError,\n originalErr: error,\n url: request.url,\n path: handlerPath,\n },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path: handlerPath },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: {\n threadEndpointsEnabled: boolean;\n singleRouteResourceOperationsEnabled: boolean;\n },\n): Promise<Response> {\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.identifyUser === undefined &&\n route.method !== \"info\" &&\n route.method !== \"trajectory/connect\"\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"trajectory/connect\":\n return handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId: route.trajectoryId,\n });\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n singleRouteResourceOperationsEnabled:\n options.singleRouteResourceOperationsEnabled,\n });\n case \"inspector/metadata\":\n return handleInspectorMetadata({ runtime, request });\n case \"inspector/learning\":\n return handleInspectorLearning({\n runtime,\n request,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return handleClearThreads({ runtime, request });\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n request: Request;\n path: string;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n memoryRoutesExposed: boolean,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n // Same boundary rule as multi-route matchRoute: \"/\" matches everything;\n // otherwise the character after basePath must be \"/\" or end of string.\n if (normalizedBase !== \"/\") {\n const afterBase = pathname.slice(normalizedBase.length);\n if (\n !pathname.startsWith(normalizedBase) ||\n (afterBase.length > 0 && !afterBase.startsWith(\"/\"))\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"trajectory/connect\": {\n const trajectoryId = methodCall.params?.trajectoryId;\n if (typeof trajectoryId !== \"string\") {\n throw trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n route = { method: \"trajectory/connect\", trajectoryId };\n break;\n }\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"inspector/metadata\":\n route = { method: \"inspector/metadata\" };\n break;\n case \"inspector/learning\":\n route = { method: \"inspector/learning\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n case \"resource/request\": {\n const resourceRequest = createResourceRequest(\n request,\n expectString(methodCall.params, \"path\"),\n expectString(methodCall.params, \"httpMethod\"),\n methodCall.body,\n );\n const resourceUrl = new URL(resourceRequest.url);\n const resourceRoute = matchRoute(resourceUrl.pathname, pathname);\n if (!resourceRoute || !isSingleRouteResourceRoute(resourceRoute)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n if (\n resourceRoute.method.startsWith(\"memories/\") &&\n !memoryRoutesExposed\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n return {\n route: resourceRoute,\n methodCall,\n request: resourceRequest,\n path: resourceUrl.pathname,\n };\n }\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall, request, path: pathname };\n}\n\n/** Limits the generic envelope bridge to the Runtime's resource APIs. */\nfunction isSingleRouteResourceRoute(route: RouteInfo): boolean {\n switch (route.method) {\n case \"threads/list\":\n case \"threads/subscribe\":\n case \"threads/update\":\n case \"threads/archive\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"threads/clear\":\n case \"memories/list\":\n case \"memories/recall\":\n case \"memories/subscribe\":\n case \"memories/mutate\":\n case \"annotate\":\n return true;\n default:\n return false;\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"inspector/metadata\":\n case \"inspector/learning\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotCorsConfig | undefined,\n): CopilotCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgIA,MAAM,6BACJ;AAEF,MAAM,gCACJ;;;;;;;AAsGF,MAAM,kCAAkB,IAAI,SAAiC;;;;;;;;;;;;;;;;;;;;;;;;AAyB7D,SAAS,0BACP,SACA,QACgB;CAChB,MAAM,WAAW,gBAAgB,IAAI,QAAQ;AAC7C,KAAI,SACF,QAAO;CAET,MAAM,UAAU,IAAI,eAAe;EACjC,cAAc,QAAQ;EACtB,QAAQ,QAAQ;EAChB,GAAI,QAAQ,aAAa,SAAY,EAAE,UAAU,QAAQ,UAAU,GAAG,EAAE;EACxE,gBAAgB,QAAQ;EACxB,8BAA8B,QAAQ;EACtC,GAAI,QAAQ,kBAAkB,SAC1B,EAAE,eAAe,QAAQ,eAAe,GACxC,EAAE;EACN,UAAU,QAAQ;EAClB,WAAW,QAAQ;EAYnB,MAAM,KAAK,SACT,OAAO,KAAK,gBAAgB,QAAQ,EAAE,KAAK,MAAM,GAAG,EAAE,MAAM,EAAE,IAAI;EACpE,GAAI,SAAS,EAAE,iBAAiB,QAAQ,GAAG,EAAE;EAC9C,CAAC;AACF,iBAAgB,IAAI,SAAS,QAAQ;AACrC,QAAO;;AA6BT,SAAgB,4BACd,SAC4B;CAC5B,MAAM,EAAE,SAAS,UAAU,OAAO,eAAe,MAAM,UAAU;AAEjE,8BAA6B,EAAE,SAAS,CAAC;CAEzC,MAAM,aAAa,kBAAkB,KAAK;CAE1C,MAAM,UAAsC,OAC1C,YACsB;EAEtB,MAAM,OADM,IAAI,IAAI,QAAQ,KAAK,mBAAmB,CACnC;EACjB,IAAI,cAAc;EAClB,MAAM,gBAAgB,QAAQ,QAAQ,IAAI,SAAS;EAG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QAAO,IAAI,SAAS,KAAK,UAAU,KAAK,EAAE;EACxC;EACA,SAAS;GAAE,gBAAgB;GAAoB,GAAG;GAAc;EACjE,CAAC"}
1
+ {"version":3,"file":"fetch-handler.mjs","names":[],"sources":["../../../src/runtime/core/fetch-handler.ts"],"sourcesContent":["/**\n * Framework-agnostic CopilotKit runtime handler.\n *\n * Returns a pure `(Request) => Promise<Response>` function that can be used\n * directly with Bun, Deno, Cloudflare Workers, Next.js App Router, or any\n * Fetch-native runtime — no framework dependency required.\n *\n * @example\n * ```typescript\n * import { CopilotKitRuntime, createCopilotKitRuntimeHandler } from \"@copilotkit/runtime\";\n *\n * const handler = createCopilotKitRuntimeHandler({\n * runtime: new CopilotKitRuntime({ agents: { ... } }),\n * basePath: \"/api/copilotkit\",\n * cors: true,\n * });\n *\n * // Bun\n * Bun.serve({ fetch: handler });\n *\n * // Deno\n * Deno.serve(handler);\n *\n * // Cloudflare Workers\n * export default { fetch: handler };\n * ```\n *\n * ## Managed Channels lifecycle (serverless-safe)\n *\n * When the runtime declares managed Channels, the returned handler carries a\n * `handler.channels` control surface — but creating the handler opens NO\n * network connection. Activation (which opens a persistent gateway WebSocket)\n * is LAZY: it is triggered by the first `await handler.channels.ready()` and\n * never before — not at handler creation, not on the first HTTP request.\n *\n * - On a LONG-RUNNING host (a Node server / container / a Bun or Deno server),\n * call `await handler.channels.ready()` ONCE at startup to open the listener;\n * the process owns it for its lifetime.\n * - On a SERVERLESS / EDGE host (Cloudflare Workers, Next.js App Router), do NOT\n * call `ready()` — those hosts freeze/recycle per-request isolates and cannot\n * own a persistent listener, and separate cold starts would mint conflicting\n * listeners. The generic Fetch handler stays a pure request/response function\n * there, exactly as documented above.\n *\n * This laziness is a property of THIS handler, because it is the one entry point\n * that must stay serverless-safe. The process-owning wrappers do not inherit it:\n * `createCopilotKitNodeListener` STARTS activation\n * at creation (OSS-641), so `ready()` there is optional and await-and-observe.\n *\n * @example\n * ```typescript\n * // Long-running host: open the managed-Channel listener once at startup.\n * const handler = createCopilotKitRuntimeHandler({ runtime });\n * await handler.channels.ready();\n * ```\n */\n\nimport type {\n CopilotKitRuntimeLike,\n CopilotKitIntelligenceRuntimeLike,\n RuntimeWithDeclaredChannels,\n} from \"./runtime\";\nimport { isIntelligenceRuntime } from \"./runtime\";\nimport { ChannelManager } from \"./channel-manager\";\nimport type { ChannelsControl, ActivateChannelEngine } from \"./channel-manager\";\nimport type { CopilotKitRuntimeHooks, RouteInfo, HookContext } from \"./hooks\";\nimport {\n runOnRequest,\n runOnBeforeHandler,\n runOnResponse,\n runOnError,\n} from \"./hooks\";\nimport type { CopilotKitCorsConfig } from \"./fetch-cors\";\nimport { handleCors, addCorsHeaders } from \"./fetch-cors\";\nimport { matchRoute } from \"./fetch-router\";\nimport {\n callBeforeRequestMiddleware,\n callAfterRequestMiddleware,\n} from \"./middleware\";\nimport { handleRunAgent } from \"../handlers/handle-run\";\nimport { handleSuggestAgent } from \"../handlers/handle-suggest\";\nimport { handleConnectAgent } from \"../handlers/handle-connect\";\nimport {\n handleTrajectoryConnect,\n trajectoryErrorResponse,\n} from \"../handlers/handle-trajectory-connect\";\nimport { handleStopAgent } from \"../handlers/handle-stop\";\nimport { handleGetRuntimeInfo } from \"../handlers/get-runtime-info\";\nimport { handleInspectorMetadata } from \"../handlers/handle-inspector-metadata\";\nimport { handleInspectorLearning } from \"../handlers/handle-inspector-learning\";\nimport { handleTranscribe } from \"../handlers/handle-transcribe\";\nimport { handleDebugEvents } from \"../handlers/handle-debug-events\";\nimport {\n handleClearThreads,\n handleListThreads,\n handleSubscribeToThreads,\n handleUpdateThread,\n handleArchiveThread,\n handleDeleteThread,\n handleGetThreadMessages,\n handleGetThreadEvents,\n handleGetThreadState,\n} from \"../handlers/handle-threads\";\nimport {\n handleListMemories,\n handleRecallMemories,\n handleSubscribeToMemories,\n handleCreateMemory,\n handleUpdateMemory,\n handleRemoveMemory,\n} from \"../handlers/handle-memories\";\nimport { handleAnnotate } from \"../handlers/handle-user-actions\";\nimport {\n parseMethodCall,\n createJsonRequest,\n createResourceRequest,\n expectString,\n detectSingleRouteEnvelope,\n} from \"../endpoints/single-route-helpers\";\nimport type { MethodCall } from \"../endpoints/single-route-helpers\";\nimport { getRuntimeLogger } from \"./logger\";\nimport { fireInstanceCreatedTelemetry } from \"../telemetry/instance-created\";\nimport type { RuntimeInstanceCreatedInfo } from \"../telemetry/events\";\n\n/**\n * Emitted when a single-route client's JSON envelope reaches a runtime mounted\n * in multi-route mode. Named so callers can branch on the cause rather than\n * string-matching the prose.\n */\nconst SINGLE_ROUTE_ENVELOPE_CODE =\n \"single_route_envelope_against_multi_route_runtime\";\n\nconst SINGLE_ROUTE_ENVELOPE_MESSAGE =\n 'Received a single-route request envelope ({ method: \"...\" }) but this ' +\n \"runtime is mounted in multi-route mode, so the request matched no route. \" +\n \"Either drop useSingleEndpoint from the frontend provider so it negotiates \" +\n 'the transport, or mount the runtime with mode: \"single-route\" to serve ' +\n \"this envelope.\";\n\n/* ------------------------------------------------------------------------------------------------\n * Public types\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotKitRuntimeHandlerOptions {\n runtime: CopilotKitRuntimeLike;\n\n /**\n * Optional base path for routing.\n *\n * When provided: strict prefix stripping. The handler strips this prefix from the\n * URL pathname and matches the remainder against known routes.\n *\n * When omitted: suffix matching. The handler matches known route patterns as\n * suffixes of the URL pathname.\n */\n basePath?: string;\n\n /**\n * Endpoint mode:\n * - \"multi-route\" (default): Routes like POST /agent/:agentId/run, GET /info, etc.\n * - \"single-route\": Single POST endpoint with JSON envelope { method, params, body }\n */\n mode?: \"multi-route\" | \"single-route\";\n\n /**\n * Optional CORS configuration.\n * When not provided, no CORS headers are added (let the framework handle it).\n * Set to true for permissive defaults, or provide an object.\n */\n cors?: boolean | CopilotKitCorsConfig;\n\n /**\n * Lifecycle hooks for request processing.\n */\n hooks?: CopilotKitRuntimeHooks;\n\n /**\n * Whether the handler builds the runtime's declared managed-Channel control\n * surface. Defaults to `true`, which constructs the {@link ChannelManager} and\n * exposes `handler.channels` — but does NOT open any connection: activation is\n * lazy and triggered by the first `handler.channels.ready()` (see the factory\n * TSDoc). Set `false` to opt out entirely: no {@link ChannelManager} is\n * constructed and the returned handler has no `.channels`. Non-intelligence or\n * channel-less runtimes never build a control surface regardless of this flag.\n *\n * The process-owning Node listener also starts activation when this is left on,\n * so `false` is the opt-out that keeps a mounted listener socket-free in a test\n * or a short-lived script.\n */\n activateChannels?: boolean;\n\n /**\n * @internal Test seam: inject a fake Channel activation engine so channel\n * activation runs without opening a real transport. Not part of the public\n * API and may change or be removed without notice.\n */\n __channelEngine?: ActivateChannelEngine;\n\n /**\n * @internal Payload for the `oss.runtime.instance_created` event, used in\n * place of the v2 defaults. The v1 integration wrappers pass the v1 payload\n * here so that the event fires once, from this factory, with the v1 data.\n * Not part of the public API and may change or be removed without notice.\n */\n __instanceCreatedInfo?: RuntimeInstanceCreatedInfo;\n}\n\n/**\n * A framework-agnostic runtime handler: a `(Request) => Promise<Response>`\n * function that is also a callable object carrying an optional {@link channels}\n * control surface. A plain function is assignable to this type, so existing\n * call sites that treat it as `(Request) => Promise<Response>` keep working.\n */\nexport type CopilotKitRuntimeFetchHandler = ((\n request: Request,\n) => Promise<Response>) & {\n /**\n * Present only when the handler activated managed Channels for an\n * Intelligence runtime; the lifecycle control surface for those Channels.\n */\n channels?: ChannelsControl;\n};\n\n/**\n * A {@link CopilotKitRuntimeFetchHandler} whose {@link ChannelsControl} surface is\n * guaranteed present. Returned when the runtime was constructed with at least\n * one declared Intelligence Channel and activation was not opted out of, so the\n * documented `handler.channels.ready(...)` call type-checks without a `!` or\n * `?.` under strict TypeScript.\n */\nexport type CopilotKitRuntimeFetchHandlerWithChannels = ((\n request: Request,\n) => Promise<Response>) & {\n /** Lifecycle control surface for the runtime's activated managed Channels. */\n channels: ChannelsControl;\n};\n\n/**\n * Managed Channel managers keyed by runtime instance. Guarantees a single\n * manager (and thus a single activation) per runtime: creating the handler more\n * than once for the same runtime reuses the existing manager instead of\n * constructing a second one.\n */\nconst channelManagers = new WeakMap<object, ChannelManager>();\n\n/**\n * Look up (or lazily CREATE) the {@link ChannelManager} for an Intelligence\n * runtime. First creation constructs the manager and caches it; subsequent\n * lookups reuse the cached instance so there is exactly one manager per runtime.\n *\n * Activation is NOT triggered here. Constructing the manager opens no\n * transport — the persistent gateway socket is opened lazily on the first\n * {@link ChannelManager.ready} call (see the factory TSDoc). This keeps the\n * generic Fetch handler serverless/edge-safe: creating it (e.g. at\n * Cloudflare-Worker module scope or per Next.js App Router isolate) never\n * performs network I/O and never mints a listener the host cannot own.\n *\n * Caching the un-activated manager is correct: a later `ready()` activates it\n * once (idempotently), and an up-front misconfiguration (duplicate/missing\n * channel names) surfaces as a rejected `ready()` rather than a throw at\n * creation. A manager that has been {@link ChannelManager.stop}ped stays\n * stopped on reuse — its latches short-circuit any later `activate()`/`ready()`.\n *\n * @param runtime - The Intelligence runtime whose Channels the manager drives.\n * @param engine - Optional injected activation engine (test seam); when\n * omitted the manager uses its default Realtime Gateway engine.\n * @returns The runtime's (un-activated) Channel manager.\n */\nfunction getOrCreateChannelManager(\n runtime: CopilotKitIntelligenceRuntimeLike,\n engine: ActivateChannelEngine | undefined,\n): ChannelManager {\n const existing = channelManagers.get(runtime);\n if (existing) {\n return existing;\n }\n const manager = new ChannelManager({\n intelligence: runtime.intelligence,\n runner: runtime.runner,\n ...(runtime.learning !== undefined ? { learning: runtime.learning } : {}),\n lockTtlSeconds: runtime.lockTtlSeconds,\n lockHeartbeatIntervalSeconds: runtime.lockHeartbeatIntervalSeconds,\n ...(runtime.lockKeyPrefix !== undefined\n ? { lockKeyPrefix: runtime.lockKeyPrefix }\n : {}),\n channels: runtime.channels,\n telemetry: runtime.telemetry,\n // Bridge the manager's diagnostic sink to the runtime's logger. Without this\n // every `this.log?.(...)` breadcrumb in the manager (setup_required,\n // failed-to-activate, dropped-session, teardown-stop failures) is a no-op,\n // so a channel that fails to activate is permanently dead with zero output.\n // Mirror the `logger.<level>(context, message)` call shape used elsewhere in\n // this file; a failed activation is a degraded-but-recoverable condition, so\n // `warn` is the appropriate level. The manager passes an `Error` as `meta`\n // for failure breadcrumbs, but pino only serializes an Error (its\n // non-enumerable message/stack) under the `err` key — under any other key it\n // renders as `{}` and the cause is lost. Route an Error to `err` and keep the\n // `meta` key for everything else (`meta` is typed `unknown`).\n log: (msg, meta) =>\n getRuntimeLogger(runtime).warn(\n meta instanceof Error ? { err: meta } : { meta },\n msg,\n ),\n ...(engine ? { activateChannel: engine } : {}),\n });\n channelManagers.set(runtime, manager);\n return manager;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Handler factory\n * --------------------------------------------------------------------------------------------- */\n\n/**\n * Overload: a runtime constructed with at least one declared Intelligence\n * Channel (a {@link RuntimeWithDeclaredChannels}-branded runtime), when\n * activation is not disabled, yields a handler with a **non-optional**\n * {@link ChannelsControl}. `activateChannels` is constrained to `true | undefined`\n * here so passing `activateChannels: false` (which skips activation and leaves no\n * `.channels`) falls through to the optional-shape overload below rather than\n * dishonestly promising a control surface that will not exist.\n */\nexport function createCopilotKitRuntimeHandler(\n options: CopilotKitRuntimeHandlerOptions & {\n runtime: RuntimeWithDeclaredChannels;\n activateChannels?: true | undefined;\n },\n): CopilotKitRuntimeFetchHandlerWithChannels;\n/**\n * Overload: every other runtime (SSE, Intelligence without channels, or with\n * activation disabled) yields a handler whose `.channels` is optional.\n */\nexport function createCopilotKitRuntimeHandler(\n options: CopilotKitRuntimeHandlerOptions,\n): CopilotKitRuntimeFetchHandler;\nexport function createCopilotKitRuntimeHandler(\n options: CopilotKitRuntimeHandlerOptions,\n): CopilotKitRuntimeFetchHandler {\n const { runtime, basePath, mode = \"multi-route\", cors, hooks } = options;\n const logger = getRuntimeLogger(runtime);\n\n fireInstanceCreatedTelemetry({\n runtime,\n info: options.__instanceCreatedInfo,\n });\n\n const corsConfig = resolveCorsConfig(cors);\n\n const handler: CopilotKitRuntimeFetchHandler = async (\n request: Request,\n ): Promise<Response> => {\n const url = new URL(request.url, \"http://localhost\");\n const path = url.pathname;\n let handlerPath = path;\n const requestOrigin = request.headers.get(\"origin\");\n\n // Base hook context (route not yet known)\n const baseCtx: HookContext = { request, path, runtime };\n\n let route: RouteInfo | undefined;\n\n try {\n // 1. CORS preflight\n if (corsConfig) {\n const preflight = handleCors(request, corsConfig);\n if (preflight) return preflight;\n }\n\n // 2. onRequest hook\n request = await runOnRequest(hooks, { ...baseCtx, request });\n\n // 3. Legacy beforeRequestMiddleware\n try {\n const maybeModified = await callBeforeRequestMiddleware({\n runtime,\n request,\n path,\n });\n if (maybeModified) {\n request = maybeModified;\n }\n } catch (mwError: unknown) {\n logger.error(\n { err: mwError, url: request.url, path },\n \"Error running before request middleware\",\n );\n if (mwError instanceof Response) {\n return maybeAddCors(mwError, corsConfig, requestOrigin);\n }\n throw mwError;\n }\n\n // 4. Route matching\n let response: Response;\n\n if (mode === \"single-route\") {\n const resolved = await resolveSingleRoute(\n request,\n basePath,\n path,\n runtime.exposeMemoryRoutes === true,\n );\n route = resolved.route;\n request = resolved.request;\n handlerPath = resolved.path;\n const { methodCall } = resolved;\n if (methodCall.method === \"resource/request\") {\n const methodError = validateHttpMethod(request.method, route);\n if (methodError) {\n throw methodError;\n }\n }\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path: handlerPath,\n runtime,\n route,\n });\n // 6. Wrap body for methods that need it, then dispatch\n if (\n route.method === \"agent/run\" ||\n route.method === \"agent/suggest\" ||\n route.method === \"agent/connect\" ||\n route.method === \"transcribe\"\n ) {\n request = createJsonRequest(request, methodCall.body);\n } else if (route.method === \"agent/stop\") {\n request = createJsonRequest(\n request,\n methodCall.body === undefined ? {} : methodCall.body,\n );\n } else if (route.method === \"inspector/learning\") {\n const learningUrl = new URL(request.url);\n for (const key of [\n \"agentId\",\n \"skillsPage\",\n \"insightsPage\",\n ] as const) {\n const value = methodCall.params?.[key];\n if (typeof value === \"string\" || typeof value === \"number\") {\n learningUrl.searchParams.set(key, String(value));\n }\n }\n request = new Request(learningUrl, {\n method: \"GET\",\n headers: request.headers,\n signal: request.signal,\n });\n }\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: methodCall.method === \"resource/request\",\n singleRouteResourceOperationsEnabled: true,\n });\n } else {\n // Multi-route: match URL pattern\n const matched = matchRoute(path, basePath);\n if (!matched) {\n // A single-endpoint client POSTing `{ method }` at the base path\n // matches no route here. Say so, rather than leaving the developer\n // with a bare 404 and no way to tell a transport mismatch from a\n // wrong `basePath` (issue OSS-882).\n const envelopeMethod = await detectSingleRouteEnvelope(request);\n if (envelopeMethod) {\n logger.warn(\n { url: request.url, path, method: envelopeMethod },\n SINGLE_ROUTE_ENVELOPE_MESSAGE,\n );\n throw jsonResponse(\n {\n error: \"Not found\",\n code: SINGLE_ROUTE_ENVELOPE_CODE,\n message: SINGLE_ROUTE_ENVELOPE_MESSAGE,\n },\n 404,\n );\n }\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure\n // default: off). Runs BEFORE method validation so a hidden route 404s\n // uniformly regardless of HTTP method — a 405 here would otherwise leak\n // that the route exists. `dispatchRoute` re-applies the same gate as\n // defense-in-depth (and to cover the single-route path).\n if (\n matched.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n route = matched;\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Validate HTTP method\n const methodError = validateHttpMethod(request.method, matched);\n if (methodError) {\n route = matched;\n throw methodError;\n }\n\n route = matched;\n\n // 5. onBeforeHandler hook\n request = await runOnBeforeHandler(hooks, {\n request,\n path,\n runtime,\n route,\n });\n\n // 6. Handler dispatch\n response = await dispatchRoute(runtime, request, route, {\n threadEndpointsEnabled: true,\n singleRouteResourceOperationsEnabled: false,\n });\n }\n\n // 7. onResponse hook\n response = await runOnResponse(hooks, {\n request,\n response,\n path: handlerPath,\n runtime,\n route,\n });\n\n // 8. CORS headers on response\n response = maybeAddCors(response, corsConfig, requestOrigin);\n\n // 9. Legacy afterRequestMiddleware (non-blocking)\n // Clone the response so middleware can read the body without consuming\n // the original stream that will be sent to the client. Only clone when\n // middleware is set: an unread clone still buffers every streamed chunk\n // until the response ends.\n if (runtime.afterRequestMiddleware) {\n callAfterRequestMiddleware({\n runtime,\n response: response.clone(),\n path: handlerPath,\n }).catch((error: unknown) => {\n logger.error(\n { err: error, url: request.url, path: handlerPath },\n \"Error running after request middleware\",\n );\n });\n }\n\n return response;\n } catch (error) {\n // Short-circuit with thrown Response\n if (error instanceof Response) {\n const finalResponse = await runOnResponse(hooks, {\n request,\n response: error,\n path: handlerPath,\n runtime,\n route: route ?? { method: \"info\" },\n });\n return maybeAddCors(finalResponse, corsConfig, requestOrigin);\n }\n\n // Run onError hook — wrapped so a throwing hook doesn't escape\n try {\n const errorResponse = await runOnError(hooks, {\n request,\n error,\n path: handlerPath,\n runtime,\n route,\n });\n\n if (errorResponse) {\n return maybeAddCors(errorResponse, corsConfig, requestOrigin);\n }\n } catch (hookError: unknown) {\n logger.error(\n {\n err: hookError,\n originalErr: error,\n url: request.url,\n path: handlerPath,\n },\n \"onError hook threw\",\n );\n }\n\n logger.error(\n { err: error, url: request.url, path: handlerPath },\n \"Unhandled error in CopilotKit runtime handler\",\n );\n\n return maybeAddCors(\n jsonResponse({ error: \"internal_error\" }, 500),\n corsConfig,\n requestOrigin,\n );\n }\n };\n\n // Build (but do NOT activate) the managed-Channel control surface for an\n // Intelligence runtime that declares Channels and hasn't opted out via\n // activateChannels. `handler.channels` exists immediately, but the persistent\n // gateway socket is opened lazily on the first `handler.channels.ready()` —\n // never at handler-creation time and never inside the per-request closure\n // above. This keeps the generic Fetch handler serverless/edge-safe: no\n // module-scope network I/O, and no listener a request-driven isolate cannot\n // own. See the factory TSDoc for the full lifecycle contract.\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.channels &&\n runtime.channels.length > 0 &&\n options.activateChannels !== false\n ) {\n handler.channels = getOrCreateChannelManager(\n runtime,\n options.__channelEngine,\n );\n }\n\n return handler;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Route dispatch\n * --------------------------------------------------------------------------------------------- */\n\nfunction dispatchRoute(\n runtime: CopilotKitRuntimeLike,\n request: Request,\n route: RouteInfo,\n options: {\n threadEndpointsEnabled: boolean;\n singleRouteResourceOperationsEnabled: boolean;\n },\n): Promise<Response> {\n if (\n isIntelligenceRuntime(runtime) &&\n runtime.identifyUser === undefined &&\n route.method !== \"info\" &&\n route.method !== \"trajectory/connect\"\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n // Opt-in gate for the client-facing memory proxy routes (secure default:\n // off). When not explicitly enabled, every `/memories/*` route 404s as if it\n // did not exist — this MUST run before the per-handler `isIntelligenceRuntime`\n // check so an un-opted-in deployment reveals nothing about memory (not even\n // whether Intelligence is configured). Coalesce a missing flag (external\n // `CopilotKitRuntimeLike` implementor) to `false`.\n if (\n route.method.startsWith(\"memories/\") &&\n runtime.exposeMemoryRoutes !== true\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n\n switch (route.method) {\n case \"trajectory/connect\":\n return handleTrajectoryConnect({\n runtime,\n request,\n trajectoryId: route.trajectoryId,\n });\n case \"agent/run\":\n return handleRunAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/suggest\":\n return handleSuggestAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/connect\":\n return handleConnectAgent({\n runtime,\n request,\n agentId: route.agentId,\n });\n case \"agent/stop\":\n return handleStopAgent({\n runtime,\n request,\n agentId: route.agentId,\n threadId: route.threadId,\n });\n case \"info\":\n return handleGetRuntimeInfo({\n runtime,\n request,\n threadEndpointsEnabled: options.threadEndpointsEnabled,\n singleRouteResourceOperationsEnabled:\n options.singleRouteResourceOperationsEnabled,\n });\n case \"inspector/metadata\":\n return handleInspectorMetadata({ runtime, request });\n case \"inspector/learning\":\n return handleInspectorLearning({\n runtime,\n request,\n });\n case \"transcribe\":\n return handleTranscribe({ runtime, request });\n case \"threads/clear\":\n return handleClearThreads({ runtime, request });\n case \"threads/list\":\n return handleListThreads({ runtime, request });\n case \"memories/list\":\n return request.method.toUpperCase() === \"POST\"\n ? handleCreateMemory({ runtime, request })\n : handleListMemories({ runtime, request });\n case \"memories/recall\":\n return handleRecallMemories({ runtime, request });\n case \"memories/subscribe\":\n return handleSubscribeToMemories({ runtime, request });\n case \"memories/mutate\":\n return request.method.toUpperCase() === \"DELETE\"\n ? handleRemoveMemory({ runtime, request, memoryId: route.memoryId })\n : handleUpdateMemory({ runtime, request, memoryId: route.memoryId });\n case \"threads/subscribe\":\n return handleSubscribeToThreads({ runtime, request });\n case \"threads/update\":\n if (request.method.toUpperCase() === \"DELETE\") {\n return handleDeleteThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n }\n return handleUpdateThread({ runtime, request, threadId: route.threadId });\n case \"threads/archive\":\n return handleArchiveThread({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/messages\":\n return handleGetThreadMessages({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/events\":\n return handleGetThreadEvents({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"threads/state\":\n return handleGetThreadState({\n runtime,\n request,\n threadId: route.threadId,\n });\n case \"annotate\":\n return handleAnnotate({ runtime, request });\n case \"cpk-debug-events\":\n return Promise.resolve(handleDebugEvents({ runtime, request }));\n default: {\n // Exhaustiveness guard: a new `RouteInfo` variant added without a case\n // above becomes a compile error here instead of silently returning\n // `undefined` at runtime.\n const _exhaustive: never = route;\n throw jsonResponse(\n { error: \"Not found\", method: (_exhaustive as RouteInfo).method },\n 404,\n );\n }\n }\n}\n\ninterface SingleRouteResolution {\n route: RouteInfo;\n methodCall: MethodCall;\n request: Request;\n path: string;\n}\n\nasync function resolveSingleRoute(\n request: Request,\n basePath: string | undefined,\n pathname: string,\n memoryRoutesExposed: boolean,\n): Promise<SingleRouteResolution> {\n if (basePath) {\n const normalizedBase =\n basePath.length > 1 && basePath.endsWith(\"/\")\n ? basePath.slice(0, -1)\n : basePath;\n // Same boundary rule as multi-route matchRoute: \"/\" matches everything;\n // otherwise the character after basePath must be \"/\" or end of string.\n if (normalizedBase !== \"/\") {\n const afterBase = pathname.slice(normalizedBase.length);\n if (\n !pathname.startsWith(normalizedBase) ||\n (afterBase.length > 0 && !afterBase.startsWith(\"/\"))\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n }\n }\n\n if (request.method !== \"POST\") {\n throw jsonResponse({ error: \"Method not allowed\" }, 405, { Allow: \"POST\" });\n }\n\n const methodCall = await parseMethodCall(request);\n\n let route: RouteInfo;\n switch (methodCall.method) {\n case \"trajectory/connect\": {\n const trajectoryId = methodCall.params?.trajectoryId;\n if (typeof trajectoryId !== \"string\") {\n throw trajectoryErrorResponse(\n \"INVALID_REQUEST\",\n \"A valid trajectoryId is required\",\n 400,\n );\n }\n route = { method: \"trajectory/connect\", trajectoryId };\n break;\n }\n case \"agent/run\":\n route = {\n method: \"agent/run\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/suggest\":\n route = {\n method: \"agent/suggest\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/connect\":\n route = {\n method: \"agent/connect\",\n agentId: expectString(methodCall.params, \"agentId\"),\n };\n break;\n case \"agent/stop\":\n route = {\n method: \"agent/stop\",\n agentId: expectString(methodCall.params, \"agentId\"),\n threadId: expectString(methodCall.params, \"threadId\"),\n };\n break;\n case \"info\":\n route = { method: \"info\" };\n break;\n case \"inspector/metadata\":\n route = { method: \"inspector/metadata\" };\n break;\n case \"inspector/learning\":\n route = { method: \"inspector/learning\" };\n break;\n case \"transcribe\":\n route = { method: \"transcribe\" };\n break;\n case \"resource/request\": {\n const resourceRequest = createResourceRequest(\n request,\n expectString(methodCall.params, \"path\"),\n expectString(methodCall.params, \"httpMethod\"),\n methodCall.body,\n );\n const resourceUrl = new URL(resourceRequest.url);\n const resourceRoute = matchRoute(resourceUrl.pathname, pathname);\n if (!resourceRoute || !isSingleRouteResourceRoute(resourceRoute)) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n if (\n resourceRoute.method.startsWith(\"memories/\") &&\n !memoryRoutesExposed\n ) {\n throw jsonResponse({ error: \"Not found\" }, 404);\n }\n return {\n route: resourceRoute,\n methodCall,\n request: resourceRequest,\n path: resourceUrl.pathname,\n };\n }\n default: {\n // Exhaustiveness guard: a new `METHOD_NAMES`/`EndpointMethod` variant\n // added without a case above becomes a compile error here instead of\n // leaving `route` unassigned at runtime.\n const _exhaustive: never = methodCall.method;\n throw jsonResponse({ error: \"Not found\", method: _exhaustive }, 404);\n }\n }\n\n return { route, methodCall, request, path: pathname };\n}\n\n/** Limits the generic envelope bridge to the Runtime's resource APIs. */\nfunction isSingleRouteResourceRoute(route: RouteInfo): boolean {\n switch (route.method) {\n case \"threads/list\":\n case \"threads/subscribe\":\n case \"threads/update\":\n case \"threads/archive\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"threads/clear\":\n case \"memories/list\":\n case \"memories/recall\":\n case \"memories/subscribe\":\n case \"memories/mutate\":\n case \"annotate\":\n return true;\n case \"agent/connect\":\n case \"agent/run\":\n case \"agent/stop\":\n case \"agent/suggest\":\n case \"cpk-debug-events\":\n case \"info\":\n case \"inspector/learning\":\n case \"inspector/metadata\":\n case \"trajectory/connect\":\n case \"transcribe\":\n default:\n return false;\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * HTTP method validation\n * --------------------------------------------------------------------------------------------- */\n\nfunction validateHttpMethod(\n httpMethod: string,\n route: RouteInfo,\n): Response | null {\n const method = httpMethod.toUpperCase();\n\n switch (route.method) {\n case \"info\":\n case \"inspector/metadata\":\n case \"inspector/learning\":\n case \"threads/list\":\n case \"threads/messages\":\n case \"threads/events\":\n case \"threads/state\":\n case \"cpk-debug-events\":\n if (method === \"GET\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET\",\n });\n\n case \"memories/list\":\n // GET lists the user's memories; POST creates one.\n if (method === \"GET\" || method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"GET, POST\",\n });\n\n case \"memories/mutate\":\n // PATCH supersedes; DELETE retires.\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"memories/recall\":\n // POST-only: semantic recall carries its query in the body.\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n\n case \"threads/update\":\n if (method === \"PATCH\" || method === \"DELETE\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"PATCH, DELETE\",\n });\n\n case \"agent/connect\":\n case \"agent/run\":\n case \"agent/stop\":\n case \"agent/suggest\":\n case \"annotate\":\n case \"memories/subscribe\":\n case \"threads/archive\":\n case \"threads/clear\":\n case \"threads/subscribe\":\n case \"trajectory/connect\":\n case \"transcribe\":\n default:\n if (method === \"POST\") return null;\n return jsonResponse({ error: \"Method not allowed\" }, 405, {\n Allow: \"POST\",\n });\n }\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Helpers\n * --------------------------------------------------------------------------------------------- */\n\nfunction resolveCorsConfig(\n cors: boolean | CopilotKitCorsConfig | undefined,\n): CopilotKitCorsConfig | null {\n if (!cors) return null;\n if (cors === true) return {};\n return cors;\n}\n\nfunction maybeAddCors(\n response: Response,\n config: CopilotKitCorsConfig | null,\n requestOrigin: string | null,\n): Response {\n if (!config) return response;\n return addCorsHeaders(response, config, requestOrigin);\n}\n\nfunction jsonResponse(\n body: unknown,\n status: number,\n extraHeaders?: Record<string, string>,\n): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { \"Content-Type\": \"application/json\", ...extraHeaders },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,M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src/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"trajectory/connect\"; trajectoryId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;AAuIA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
1
+ {"version":3,"file":"hooks.cjs","names":[],"sources":["../../../src/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotKitRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"trajectory/connect\"; trajectoryId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotKitRuntimeLike instance. */\n runtime: CopilotKitRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotKitRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";;AAuIA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
@@ -1,4 +1,4 @@
1
- import { CopilotRuntimeLike } from "./runtime.cjs";
1
+ import { CopilotKitRuntimeLike } from "./runtime.cjs";
2
2
  import { MaybePromise } from "@copilotkit/shared";
3
3
 
4
4
  //#region src/runtime/core/hooks.d.ts
@@ -66,8 +66,8 @@ interface HookContext {
66
66
  request: Request;
67
67
  /** The resolved URL pathname. */
68
68
  path: string;
69
- /** The CopilotRuntimeLike instance. */
70
- runtime: CopilotRuntimeLike;
69
+ /** The CopilotKitRuntimeLike instance. */
70
+ runtime: CopilotKitRuntimeLike;
71
71
  }
72
72
  interface HandlerHookContext extends HookContext {
73
73
  /** The resolved route information. */
@@ -85,7 +85,7 @@ interface ErrorHookContext extends HookContext {
85
85
  /** The route info, if routing had already succeeded. */
86
86
  route?: RouteInfo;
87
87
  }
88
- interface CopilotRuntimeHooks {
88
+ interface CopilotKitRuntimeHooks {
89
89
  /**
90
90
  * Called at the start of every request, before routing.
91
91
  * Use to validate auth, attach headers, initialize correlation IDs, etc.
@@ -117,5 +117,5 @@ interface CopilotRuntimeHooks {
117
117
  onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;
118
118
  }
119
119
  //#endregion
120
- export { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo };
120
+ export { CopilotKitRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo };
121
121
  //# sourceMappingURL=hooks.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.cts","names":[],"sources":["../../../src/runtime/core/hooks.ts"],"mappings":";;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAA8B,YAAA;AAAA;EAC9B,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;EAA4B,QAAA;AAAA;EAC5B,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAAyB,QAAA;AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;A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AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;EAyBE;EAvBjB,OAAA,EAAS,OAAA;EA8B4B;EA5BrC,IAAA;EAoCkB;EAlClB,OAAA,EAAS,qBAAA;AAAA;AAAA,UAGM,kBAAA,SAA2B,WAAA;EAyCkB;EAvC5D,KAAA,EAAO,SAAA;AAAA;AAAA,UAGQ,mBAAA,SAA4B,WAAA;EA4CA;EA1C3C,QAAA,EAAU,QAAA;EAgDwC;EA9ClD,KAAA,EAAO,SAAA;AAAA;AAAA,UAGQ,gBAAA,SAAyB,WAAA;EAmBxC;EAjBA,KAAA;EAiBa;EAfb,KAAA,GAAQ,SAAA;AAAA;AAAA,UAOO,sBAAA;EAkBS;;;;;;;EAVxB,SAAA,IAAa,GAAA,EAAK,WAAA,KAAgB,YAAA,CAAa,OAAA;EAkBS;;;;;;;;EARxD,eAAA,IAAmB,GAAA,EAAK,kBAAA,KAAuB,YAAA,CAAa,OAAA;;;;;;;EAQ5D,UAAA,IAAc,GAAA,EAAK,mBAAA,KAAwB,YAAA,CAAa,QAAA;;;;;EAMxD,OAAA,IAAW,GAAA,EAAK,gBAAA,KAAqB,YAAA,CAAa,QAAA;AAAA"}
@@ -1,4 +1,4 @@
1
- import { CopilotRuntimeLike } from "./runtime.mjs";
1
+ import { CopilotKitRuntimeLike } from "./runtime.mjs";
2
2
  import { MaybePromise } from "@copilotkit/shared";
3
3
 
4
4
  //#region src/runtime/core/hooks.d.ts
@@ -66,8 +66,8 @@ interface HookContext {
66
66
  request: Request;
67
67
  /** The resolved URL pathname. */
68
68
  path: string;
69
- /** The CopilotRuntimeLike instance. */
70
- runtime: CopilotRuntimeLike;
69
+ /** The CopilotKitRuntimeLike instance. */
70
+ runtime: CopilotKitRuntimeLike;
71
71
  }
72
72
  interface HandlerHookContext extends HookContext {
73
73
  /** The resolved route information. */
@@ -85,7 +85,7 @@ interface ErrorHookContext extends HookContext {
85
85
  /** The route info, if routing had already succeeded. */
86
86
  route?: RouteInfo;
87
87
  }
88
- interface CopilotRuntimeHooks {
88
+ interface CopilotKitRuntimeHooks {
89
89
  /**
90
90
  * Called at the start of every request, before routing.
91
91
  * Use to validate auth, attach headers, initialize correlation IDs, etc.
@@ -117,5 +117,5 @@ interface CopilotRuntimeHooks {
117
117
  onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;
118
118
  }
119
119
  //#endregion
120
- export { CopilotRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo };
120
+ export { CopilotKitRuntimeHooks, ErrorHookContext, HandlerHookContext, HookContext, ResponseHookContext, RouteInfo };
121
121
  //# sourceMappingURL=hooks.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.mts","names":[],"sources":["../../../src/runtime/core/hooks.ts"],"mappings":";;;;KAmCY,SAAA;EACN,MAAA;EAAqB,OAAA;AAAA;EACrB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAAyB,OAAA;AAAA;EACzB,MAAA;EAA8B,YAAA;AAAA;EAC9B,MAAA;EAAsB,OAAA;EAAiB,QAAA;AAAA;EACvC,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;EAA4B,QAAA;AAAA;EAC5B,MAAA;EAA0B,QAAA;AAAA;EAC1B,MAAA;EAAyB,QAAA;AAAA;EACzB,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;EAyBE;EAvBjB,OAAA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A,MAAA;AAAA;EACA,MAAA;AAAA;EACA,MAAA;EAA2B,QAAA;AAAA;EAC3B,MAAA;AAAA;EACA,MAAA;AAAA;AAAA,UAMW,WAAA;EAyBE;EAvBjB,OAAA,EAAS,OAAA;EA8B4B;EA5BrC,IAAA;EAoCkB;EAlClB,OAAA,EAAS,qBAAA;AAAA;AAAA,UAGM,kBAAA,SAA2B,WAAA;EAyCkB;EAvC5D,KAAA,EAAO,SAAA;AAAA;AAAA,UAGQ,mBAAA,SAA4B,WAAA;EA4CA;EA1C3C,QAAA,EAAU,QAAA;EAgDwC;EA9ClD,KAAA,EAAO,SAAA;AAAA;AAAA,UAGQ,gBAAA,SAAyB,WAAA;EAmBxC;EAjBA,KAAA;EAiBa;EAfb,KAAA,GAAQ,SAAA;AAAA;AAAA,UAOO,sBAAA;EAkBS;;;;;;;EAVxB,SAAA,IAAa,GAAA,EAAK,WAAA,KAAgB,YAAA,CAAa,OAAA;EAkBS;;;;;;;;EARxD,eAAA,IAAmB,GAAA,EAAK,kBAAA,KAAuB,YAAA,CAAa,OAAA;;;;;;;EAQ5D,UAAA,IAAc,GAAA,EAAK,mBAAA,KAAwB,YAAA,CAAa,QAAA;;;;;EAMxD,OAAA,IAAW,GAAA,EAAK,gBAAA,KAAqB,YAAA,CAAa,QAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.mjs","names":[],"sources":["../../../src/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"trajectory/connect\"; trajectoryId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotRuntimeLike instance. */\n runtime: CopilotRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";AAuIA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
1
+ {"version":3,"file":"hooks.mjs","names":[],"sources":["../../../src/runtime/core/hooks.ts"],"sourcesContent":["/**\n * Lifecycle hooks for CopilotKit runtime request processing.\n *\n * Hooks let you intercept requests at various stages of the pipeline:\n * - `onRequest`: Before routing — auth, correlation IDs, header injection\n * - `onBeforeHandler`: After routing — route-specific authorization\n * - `onResponse`: After handler — add headers, log, set cookies\n * - `onError`: On error — custom error responses\n *\n * @example\n * ```typescript\n * const handler = createCopilotKitRuntimeHandler({\n * runtime,\n * hooks: {\n * onRequest: async ({ request }) => {\n * const token = request.headers.get(\"authorization\");\n * if (!token) throw new Response(\"Unauthorized\", { status: 401 });\n * },\n * onResponse: async ({ response }) => {\n * const headers = new Headers(response.headers);\n * headers.set(\"x-copilot-version\", \"2.0\");\n * return new Response(response.body, { ...response, headers });\n * },\n * },\n * });\n * ```\n */\n\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\n\n/* ------------------------------------------------------------------------------------------------\n * Route info\n * --------------------------------------------------------------------------------------------- */\n\nexport type RouteInfo =\n | { method: \"agent/run\"; agentId: string }\n | { method: \"agent/suggest\"; agentId: string }\n | { method: \"agent/connect\"; agentId: string }\n | { method: \"trajectory/connect\"; trajectoryId: string }\n | { method: \"agent/stop\"; agentId: string; threadId: string }\n | { method: \"info\" }\n | { method: \"inspector/metadata\" }\n | { method: \"inspector/learning\" }\n | { method: \"transcribe\" }\n | { method: \"threads/list\" }\n | { method: \"threads/subscribe\" }\n | { method: \"threads/update\"; threadId: string }\n | { method: \"threads/archive\"; threadId: string }\n | { method: \"threads/messages\"; threadId: string }\n | { method: \"threads/events\"; threadId: string }\n | { method: \"threads/state\"; threadId: string }\n | { method: \"threads/clear\" }\n | { method: \"memories/list\" }\n | { method: \"memories/recall\" }\n | { method: \"memories/subscribe\" }\n | { method: \"memories/mutate\"; memoryId: string }\n | { method: \"annotate\" }\n | { method: \"cpk-debug-events\" };\n\n/* ------------------------------------------------------------------------------------------------\n * Hook contexts\n * --------------------------------------------------------------------------------------------- */\n\nexport interface HookContext {\n /** The incoming Fetch Request (possibly modified by prior hooks). */\n request: Request;\n /** The resolved URL pathname. */\n path: string;\n /** The CopilotKitRuntimeLike instance. */\n runtime: CopilotKitRuntimeLike;\n}\n\nexport interface HandlerHookContext extends HookContext {\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ResponseHookContext extends HookContext {\n /** The Response produced by the handler. */\n response: Response;\n /** The resolved route information. */\n route: RouteInfo;\n}\n\nexport interface ErrorHookContext extends HookContext {\n /** The error that occurred. */\n error: unknown;\n /** The route info, if routing had already succeeded. */\n route?: RouteInfo;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Hooks interface\n * --------------------------------------------------------------------------------------------- */\n\nexport interface CopilotKitRuntimeHooks {\n /**\n * Called at the start of every request, before routing.\n * Use to validate auth, attach headers, initialize correlation IDs, etc.\n *\n * Return a modified Request to replace the original, or void to continue.\n * Throw a Response to short-circuit with an early response.\n */\n onRequest?: (ctx: HookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after routing is resolved but before the handler executes.\n * Receives the resolved route info (method, agentId, threadId).\n *\n * Use to do route-specific authorization, attach headers for agent calls, etc.\n * Return a modified Request or void.\n * Throw a Response to short-circuit.\n */\n onBeforeHandler?: (ctx: HandlerHookContext) => MaybePromise<Request | void>;\n\n /**\n * Called after the handler produces a Response, before it's sent to the client.\n * Use to set cookies, add debugging headers, log, etc.\n *\n * Return a modified Response to replace the original, or void.\n */\n onResponse?: (ctx: ResponseHookContext) => MaybePromise<Response | void>;\n\n /**\n * Called when an error occurs during request processing.\n * Return a Response to override the default error response, or void to use the default.\n */\n onError?: (ctx: ErrorHookContext) => MaybePromise<Response | void>;\n}\n\n/* ------------------------------------------------------------------------------------------------\n * Internal hook runners\n * --------------------------------------------------------------------------------------------- */\n\nexport async function runOnRequest(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: HookContext,\n): Promise<Request> {\n if (!hooks?.onRequest) return ctx.request;\n const result = await hooks.onRequest(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnBeforeHandler(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: HandlerHookContext,\n): Promise<Request> {\n if (!hooks?.onBeforeHandler) return ctx.request;\n const result = await hooks.onBeforeHandler(ctx);\n return result instanceof Request ? result : ctx.request;\n}\n\nexport async function runOnResponse(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: ResponseHookContext,\n): Promise<Response> {\n if (!hooks?.onResponse) return ctx.response;\n const result = await hooks.onResponse(ctx);\n return result instanceof Response ? result : ctx.response;\n}\n\nexport async function runOnError(\n hooks: CopilotKitRuntimeHooks | undefined,\n ctx: ErrorHookContext,\n): Promise<Response | void> {\n if (!hooks?.onError) return;\n return hooks.onError(ctx);\n}\n"],"mappings":";AAuIA,eAAsB,aACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,UAAW,QAAO,IAAI;CAClC,MAAM,SAAS,MAAM,MAAM,UAAU,IAAI;AACzC,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,mBACpB,OACA,KACkB;AAClB,KAAI,CAAC,OAAO,gBAAiB,QAAO,IAAI;CACxC,MAAM,SAAS,MAAM,MAAM,gBAAgB,IAAI;AAC/C,QAAO,kBAAkB,UAAU,SAAS,IAAI;;AAGlD,eAAsB,cACpB,OACA,KACmB;AACnB,KAAI,CAAC,OAAO,WAAY,QAAO,IAAI;CACnC,MAAM,SAAS,MAAM,MAAM,WAAW,IAAI;AAC1C,QAAO,kBAAkB,WAAW,SAAS,IAAI;;AAGnD,eAAsB,WACpB,OACA,KAC0B;AAC1B,KAAI,CAAC,OAAO,QAAS;AACrB,QAAO,MAAM,QAAQ,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"learning.cjs","names":[],"sources":["../../../src/runtime/core/learning.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotRuntimeLike } from \"./runtime\";\n\n/** Checks configuration without invoking a selector that requires a real run. */\nexport function hasLearningContainerConfiguration(\n runtime: CopilotRuntimeLike,\n): boolean {\n return (\n runtime.intelligence?.ɵgetLearningContainerId?.() !== undefined ||\n runtime.learning?.containerId !== undefined\n );\n}\n\n/** Application user resolved by an Intelligence runtime. */\nexport interface CopilotRuntimeUser {\n readonly id: string;\n readonly name: string;\n}\n\n/** Context for choosing a Learning Container through the public Intelligence SDK. */\nexport type LearningContainerSelectorInput =\n | {\n readonly surface: \"web\";\n readonly user: CopilotRuntimeUser;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n }\n | {\n readonly surface: \"channel\";\n readonly user: CopilotRuntimeUser | null;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n };\n\n/** Chooses one developer-created Learning Container for an Intelligence run. */\nexport type GetLearningContainerId = (\n input: LearningContainerSelectorInput,\n) => MaybePromise<string | null | undefined>;\n\n/**\n * Context for assigning browser activity to Learning Spaces. The Runtime\n * verifies `user`; the browser chooses `trajectoryId`, which is only checked\n * to be a UUID.\n */\nexport interface TrajectoryLearningContainerSelectorInput {\n readonly trajectoryId: string;\n readonly user: CopilotRuntimeUser;\n}\n\n/**\n * Selects existing Learning Spaces without requiring an agent run or Thread.\n * The optional signal cancels on request abort or the five-second deadline.\n */\nexport type GetTrajectoryLearningContainerIds = (\n input: TrajectoryLearningContainerSelectorInput,\n signal?: AbortSignal,\n) => MaybePromise<readonly string[] | null | undefined>;\n\n/** Resolves bounded, validated Space IDs selected by application server code. */\nexport async function resolveTrajectoryLearningContainerIds(\n selector: GetTrajectoryLearningContainerIds | undefined,\n input: TrajectoryLearningContainerSelectorInput,\n signal?: AbortSignal,\n): Promise<readonly string[] | undefined> {\n signal?.throwIfAborted();\n if (!selector) return undefined;\n const controller = new AbortController();\n const onAbort = () => controller.abort(signal?.reason);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const timeout = setTimeout(\n () =>\n controller.abort(\n new Error(\"Trajectory Learning Container selection timed out\"),\n ),\n 5_000,\n );\n let onCancelled: (() => void) | undefined;\n try {\n const cancelled = new Promise<never>((_resolve, reject) => {\n onCancelled = () => reject(controller.signal.reason);\n controller.signal.addEventListener(\"abort\", onCancelled, { once: true });\n });\n const selection = new Promise<readonly string[] | null | undefined>(\n (resolve) => {\n resolve(selector(input, controller.signal));\n },\n );\n const value = await Promise.race([selection, cancelled]);\n controller.signal.throwIfAborted();\n if (value == null) return undefined;\n if (!Array.isArray(value) || value.length > 100) {\n throw new Error(\n \"Trajectory Learning Container selection must be an array of at most 100 IDs\",\n );\n }\n // Array.from visits holes in sparse arrays, so they fail validation.\n return [...new Set(Array.from(value, assertStableLearningContainerId))];\n } finally {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", onAbort);\n if (onCancelled)\n controller.signal.removeEventListener(\"abort\", onCancelled);\n }\n}\n\n/** Context for choosing one Learning Container for an Intelligence run. */\nexport type CopilotRuntimeLearningContext =\n | {\n readonly surface: \"web\";\n readonly request: Request;\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n }\n | {\n readonly surface: \"channel\";\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n readonly deliveryId: string;\n };\n\n/** Assigns each Intelligence Thread to one developer-created Learning Container. */\nexport interface CopilotRuntimeLearningConfig {\n readonly containerId:\n | string\n | ((\n input: CopilotRuntimeLearningContext,\n ) => MaybePromise<string | null | undefined>);\n}\n\nconst STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** Validates and returns a stable Learning Container ID. */\nexport function assertStableLearningContainerId(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > 64 ||\n !STABLE_CONTAINER_ID.test(value)\n ) {\n throw new Error(\n \"Learning Container must use a 1-64 character stable ID with lowercase letters, numbers, and single hyphens\",\n );\n }\n return value;\n}\n\n/** Resolves and validates a public Intelligence Learning Container selection. */\nexport async function resolveLearningContainerSelector(\n selector: GetLearningContainerId,\n input: LearningContainerSelectorInput,\n): Promise<string | undefined> {\n const value = await selector(input);\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n\n/** Resolves the configured Container once for one web or Channel run. */\nexport async function resolveLearningContainerId(\n config: CopilotRuntimeLearningConfig | undefined,\n input: CopilotRuntimeLearningContext,\n): Promise<string | undefined> {\n if (config === undefined) return undefined;\n const value =\n typeof config.containerId === \"function\"\n ? await config.containerId(input)\n : config.containerId;\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n"],"mappings":";;;AAKA,SAAgB,kCACd,SACS;AACT,QACE,QAAQ,cAAc,2BAA2B,KAAK,UACtD,QAAQ,UAAU,gBAAgB;;;AAkDtC,eAAsB,sCACpB,UACA,OACA,QACwC;AACxC,SAAQ,gBAAgB;AACxB,KAA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B;AAC7B,KAAI,WAAW,OAAW,QAAO;CACjC,MAAM,QACJ,OAAO,OAAO,gBAAgB,aAC1B,MAAM,OAAO,YAAY,MAAM,GAC/B,OAAO;AACb,KAAI,SAAS,KAAM,QAAO;AAC1B,QAAO,gCAAgC,MAAM"}
1
+ {"version":3,"file":"learning.cjs","names":[],"sources":["../../../src/runtime/core/learning.ts"],"sourcesContent":["import type { RunAgentInput } from \"@ag-ui/client\";\nimport type { MaybePromise } from \"@copilotkit/shared\";\nimport type { CopilotKitRuntimeLike } from \"./runtime\";\n\n/** Checks configuration without invoking a selector that requires a real run. */\nexport function hasLearningContainerConfiguration(\n runtime: CopilotKitRuntimeLike,\n): boolean {\n return (\n runtime.intelligence?.ɵgetLearningContainerId?.() !== undefined ||\n runtime.learning?.containerId !== undefined\n );\n}\n\n/** Application user resolved by an Intelligence runtime. */\nexport interface CopilotKitRuntimeUser {\n readonly id: string;\n readonly name: string;\n}\n\n/** Context for choosing a Learning Container through the public Intelligence SDK. */\nexport type LearningContainerSelectorInput =\n | {\n readonly surface: \"web\";\n readonly user: CopilotKitRuntimeUser;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n }\n | {\n readonly surface: \"channel\";\n readonly user: CopilotKitRuntimeUser | null;\n readonly agentId: string;\n readonly input: Readonly<RunAgentInput>;\n };\n\n/** Chooses one developer-created Learning Container for an Intelligence run. */\nexport type GetLearningContainerId = (\n input: LearningContainerSelectorInput,\n) => MaybePromise<string | null | undefined>;\n\n/**\n * Context for assigning browser activity to Learning Spaces. The Runtime\n * verifies `user`; the browser chooses `trajectoryId`, which is only checked\n * to be a UUID.\n */\nexport interface TrajectoryLearningContainerSelectorInput {\n readonly trajectoryId: string;\n readonly user: CopilotKitRuntimeUser;\n}\n\n/**\n * Selects existing Learning Spaces without requiring an agent run or Thread.\n * The optional signal cancels on request abort or the five-second deadline.\n */\nexport type GetTrajectoryLearningContainerIds = (\n input: TrajectoryLearningContainerSelectorInput,\n signal?: AbortSignal,\n) => MaybePromise<readonly string[] | null | undefined>;\n\n/** Resolves bounded, validated Space IDs selected by application server code. */\nexport async function resolveTrajectoryLearningContainerIds(\n selector: GetTrajectoryLearningContainerIds | undefined,\n input: TrajectoryLearningContainerSelectorInput,\n signal?: AbortSignal,\n): Promise<readonly string[] | undefined> {\n signal?.throwIfAborted();\n if (!selector) return undefined;\n const controller = new AbortController();\n const onAbort = () => controller.abort(signal?.reason);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const timeout = setTimeout(\n () =>\n controller.abort(\n new Error(\"Trajectory Learning Container selection timed out\"),\n ),\n 5_000,\n );\n let onCancelled: (() => void) | undefined;\n try {\n const cancelled = new Promise<never>((_resolve, reject) => {\n onCancelled = () => reject(controller.signal.reason);\n controller.signal.addEventListener(\"abort\", onCancelled, { once: true });\n });\n const selection = new Promise<readonly string[] | null | undefined>(\n (resolve) => {\n resolve(selector(input, controller.signal));\n },\n );\n const value = await Promise.race([selection, cancelled]);\n controller.signal.throwIfAborted();\n if (value == null) return undefined;\n if (!Array.isArray(value) || value.length > 100) {\n throw new Error(\n \"Trajectory Learning Container selection must be an array of at most 100 IDs\",\n );\n }\n // Array.from visits holes in sparse arrays, so they fail validation.\n return [...new Set(Array.from(value, assertStableLearningContainerId))];\n } finally {\n clearTimeout(timeout);\n signal?.removeEventListener(\"abort\", onAbort);\n if (onCancelled)\n controller.signal.removeEventListener(\"abort\", onCancelled);\n }\n}\n\n/** Context for choosing one Learning Container for an Intelligence run. */\nexport type CopilotKitRuntimeLearningContext =\n | {\n readonly surface: \"web\";\n readonly request: Request;\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n }\n | {\n readonly surface: \"channel\";\n readonly threadId: string;\n readonly runId: string;\n readonly agentId: string;\n readonly userId: string;\n readonly deliveryId: string;\n };\n\n/** Assigns each Intelligence Thread to one developer-created Learning Container. */\nexport interface CopilotKitRuntimeLearningConfig {\n readonly containerId:\n | string\n | ((\n input: CopilotKitRuntimeLearningContext,\n ) => MaybePromise<string | null | undefined>);\n}\n\nconst STABLE_CONTAINER_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\n\n/** Validates and returns a stable Learning Container ID. */\nexport function assertStableLearningContainerId(value: unknown): string {\n if (\n typeof value !== \"string\" ||\n value.length < 1 ||\n value.length > 64 ||\n !STABLE_CONTAINER_ID.test(value)\n ) {\n throw new Error(\n \"Learning Container must use a 1-64 character stable ID with lowercase letters, numbers, and single hyphens\",\n );\n }\n return value;\n}\n\n/** Resolves and validates a public Intelligence Learning Container selection. */\nexport async function resolveLearningContainerSelector(\n selector: GetLearningContainerId,\n input: LearningContainerSelectorInput,\n): Promise<string | undefined> {\n const value = await selector(input);\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n\n/** Resolves the configured Container once for one web or Channel run. */\nexport async function resolveLearningContainerId(\n config: CopilotKitRuntimeLearningConfig | undefined,\n input: CopilotKitRuntimeLearningContext,\n): Promise<string | undefined> {\n if (config === undefined) return undefined;\n const value =\n typeof config.containerId === \"function\"\n ? await config.containerId(input)\n : config.containerId;\n if (value == null) return undefined;\n return assertStableLearningContainerId(value);\n}\n"],"mappings":";;;AAKA,SAAgB,kCACd,SACS;AACT,QACE,QAAQ,cAAc,2BAA2B,KAAK,UACtD,QAAQ,UAAU,gBAAgB;;;AAkDtC,eAAsB,sCACpB,UACA,OACA,QACwC;AACxC,SAAQ,gBAAgB;AACxB,KAAI,CAAC,SAAU,QAAO;CACtB,MAAM,aAAa,IAAI,iBAAiB;CACxC,MAAM,gBAAgB,WAAW,MAAM,QAAQ,OAAO;AACtD,SAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;CAC1D,MAAM,UAAU,iBAEZ,WAAW,sBACT,IAAI,MAAM,oDAAoD,CAC/D,EACH,IACD;CACD,IAAI;AACJ,KAAI;EACF,MAAM,YAAY,IAAI,SAAgB,UAAU,WAAW;AACzD,uBAAoB,OAAO,WAAW,OAAO,OAAO;AACpD,c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