@copilotkit/runtime 2.0.0-next.1 → 2.0.0-rc.0

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 (673) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -1
  3. package/dist/_virtual/_rolldown/runtime.cjs +29 -0
  4. package/dist/_virtual/_rolldown/runtime.mjs +20 -0
  5. package/dist/agent/converters/aisdk.cjs +355 -0
  6. package/dist/agent/converters/aisdk.cjs.map +1 -0
  7. package/dist/agent/converters/aisdk.d.cts +22 -0
  8. package/dist/agent/converters/aisdk.d.cts.map +1 -0
  9. package/dist/agent/converters/aisdk.d.mts +22 -0
  10. package/dist/agent/converters/aisdk.d.mts.map +1 -0
  11. package/dist/agent/converters/aisdk.mjs +351 -0
  12. package/dist/agent/converters/aisdk.mjs.map +1 -0
  13. package/dist/agent/converters/index.d.mts +2 -0
  14. package/dist/agent/converters/tanstack.cjs +374 -0
  15. package/dist/agent/converters/tanstack.cjs.map +1 -0
  16. package/dist/agent/converters/tanstack.d.cts +83 -0
  17. package/dist/agent/converters/tanstack.d.cts.map +1 -0
  18. package/dist/agent/converters/tanstack.d.mts +83 -0
  19. package/dist/agent/converters/tanstack.d.mts.map +1 -0
  20. package/dist/agent/converters/tanstack.mjs +372 -0
  21. package/dist/agent/converters/tanstack.mjs.map +1 -0
  22. package/dist/agent/converters/usage.cjs +68 -0
  23. package/dist/agent/converters/usage.cjs.map +1 -0
  24. package/dist/agent/converters/usage.d.cts +19 -0
  25. package/dist/agent/converters/usage.d.cts.map +1 -0
  26. package/dist/agent/converters/usage.d.mts +19 -0
  27. package/dist/agent/converters/usage.d.mts.map +1 -0
  28. package/dist/agent/converters/usage.mjs +62 -0
  29. package/dist/agent/converters/usage.mjs.map +1 -0
  30. package/dist/agent/index.cjs +1328 -0
  31. package/dist/agent/index.cjs.map +1 -0
  32. package/dist/agent/index.d.cts +467 -0
  33. package/dist/agent/index.d.cts.map +1 -0
  34. package/dist/agent/index.d.mts +468 -0
  35. package/dist/agent/index.d.mts.map +1 -0
  36. package/dist/agent/index.mjs +1318 -0
  37. package/dist/agent/index.mjs.map +1 -0
  38. package/dist/agent/learned-skills.cjs +76 -0
  39. package/dist/agent/learned-skills.cjs.map +1 -0
  40. package/dist/agent/learned-skills.d.cts +15 -0
  41. package/dist/agent/learned-skills.d.cts.map +1 -0
  42. package/dist/agent/learned-skills.d.mts +15 -0
  43. package/dist/agent/learned-skills.d.mts.map +1 -0
  44. package/dist/agent/learned-skills.mjs +74 -0
  45. package/dist/agent/learned-skills.mjs.map +1 -0
  46. package/dist/agent/mcp-tool-names.cjs +82 -0
  47. package/dist/agent/mcp-tool-names.cjs.map +1 -0
  48. package/dist/agent/mcp-tool-names.mjs +80 -0
  49. package/dist/agent/mcp-tool-names.mjs.map +1 -0
  50. package/dist/agent/state-delta.cjs +321 -0
  51. package/dist/agent/state-delta.cjs.map +1 -0
  52. package/dist/agent/state-delta.mjs +320 -0
  53. package/dist/agent/state-delta.mjs.map +1 -0
  54. package/dist/agent/url-download.cjs +503 -0
  55. package/dist/agent/url-download.cjs.map +1 -0
  56. package/dist/agent/url-download.d.cts +79 -0
  57. package/dist/agent/url-download.d.cts.map +1 -0
  58. package/dist/agent/url-download.d.mts +79 -0
  59. package/dist/agent/url-download.d.mts.map +1 -0
  60. package/dist/agent/url-download.mjs +500 -0
  61. package/dist/agent/url-download.mjs.map +1 -0
  62. package/dist/express.cjs +7 -0
  63. package/dist/express.d.cts +4 -0
  64. package/dist/express.d.mts +4 -0
  65. package/dist/express.mjs +4 -0
  66. package/dist/hono.cjs +8 -0
  67. package/dist/hono.d.cts +4 -0
  68. package/dist/hono.d.mts +4 -0
  69. package/dist/hono.mjs +4 -0
  70. package/dist/index.cjs +86 -0
  71. package/dist/index.d.cts +28 -0
  72. package/dist/index.d.mts +28 -0
  73. package/dist/index.mjs +21 -5598
  74. package/dist/internal/learned-skills.cjs +21 -0
  75. package/dist/internal/learned-skills.d.cts +9 -0
  76. package/dist/internal/learned-skills.d.mts +9 -0
  77. package/dist/internal/learned-skills.mjs +9 -0
  78. package/dist/node.cjs +7 -0
  79. package/dist/node.d.cts +4 -0
  80. package/dist/node.d.mts +4 -0
  81. package/dist/node.mjs +4 -0
  82. package/dist/runtime/core/channel-activation-config.cjs +87 -0
  83. package/dist/runtime/core/channel-activation-config.cjs.map +1 -0
  84. package/dist/runtime/core/channel-activation-config.d.cts +39 -0
  85. package/dist/runtime/core/channel-activation-config.d.cts.map +1 -0
  86. package/dist/runtime/core/channel-activation-config.d.mts +39 -0
  87. package/dist/runtime/core/channel-activation-config.d.mts.map +1 -0
  88. package/dist/runtime/core/channel-activation-config.mjs +85 -0
  89. package/dist/runtime/core/channel-activation-config.mjs.map +1 -0
  90. package/dist/runtime/core/channel-manager.cjs +973 -0
  91. package/dist/runtime/core/channel-manager.cjs.map +1 -0
  92. package/dist/runtime/core/channel-manager.d.cts +166 -0
  93. package/dist/runtime/core/channel-manager.d.cts.map +1 -0
  94. package/dist/runtime/core/channel-manager.d.mts +167 -0
  95. package/dist/runtime/core/channel-manager.d.mts.map +1 -0
  96. package/dist/runtime/core/channel-manager.mjs +972 -0
  97. package/dist/runtime/core/channel-manager.mjs.map +1 -0
  98. package/dist/runtime/core/debug-event-bus.cjs +57 -0
  99. package/dist/runtime/core/debug-event-bus.cjs.map +1 -0
  100. package/dist/runtime/core/debug-event-bus.d.cts +18 -0
  101. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -0
  102. package/dist/runtime/core/debug-event-bus.d.mts +18 -0
  103. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -0
  104. package/dist/runtime/core/debug-event-bus.mjs +55 -0
  105. package/dist/runtime/core/debug-event-bus.mjs.map +1 -0
  106. package/dist/runtime/core/fetch-cors.cjs +71 -0
  107. package/dist/runtime/core/fetch-cors.cjs.map +1 -0
  108. package/dist/runtime/core/fetch-cors.d.cts +19 -0
  109. package/dist/runtime/core/fetch-cors.d.cts.map +1 -0
  110. package/dist/runtime/core/fetch-cors.d.mts +19 -0
  111. package/dist/runtime/core/fetch-cors.d.mts.map +1 -0
  112. package/dist/runtime/core/fetch-cors.mjs +69 -0
  113. package/dist/runtime/core/fetch-cors.mjs.map +1 -0
  114. package/dist/runtime/core/fetch-handler.cjs +539 -0
  115. package/dist/runtime/core/fetch-handler.cjs.map +1 -0
  116. package/dist/runtime/core/fetch-handler.d.cts +100 -0
  117. package/dist/runtime/core/fetch-handler.d.cts.map +1 -0
  118. package/dist/runtime/core/fetch-handler.d.mts +100 -0
  119. package/dist/runtime/core/fetch-handler.d.mts.map +1 -0
  120. package/dist/runtime/core/fetch-handler.mjs +538 -0
  121. package/dist/runtime/core/fetch-handler.mjs.map +1 -0
  122. package/dist/runtime/core/fetch-router.cjs +141 -0
  123. package/dist/runtime/core/fetch-router.cjs.map +1 -0
  124. package/dist/runtime/core/fetch-router.mjs +140 -0
  125. package/dist/runtime/core/fetch-router.mjs.map +1 -0
  126. package/dist/runtime/core/hooks.cjs +28 -0
  127. package/dist/runtime/core/hooks.cjs.map +1 -0
  128. package/dist/runtime/core/hooks.d.cts +121 -0
  129. package/dist/runtime/core/hooks.d.cts.map +1 -0
  130. package/dist/runtime/core/hooks.d.mts +121 -0
  131. package/dist/runtime/core/hooks.d.mts.map +1 -0
  132. package/dist/runtime/core/hooks.mjs +24 -0
  133. package/dist/runtime/core/hooks.mjs.map +1 -0
  134. package/dist/runtime/core/learning.cjs +61 -0
  135. package/dist/runtime/core/learning.cjs.map +1 -0
  136. package/dist/runtime/core/learning.d.cts +61 -0
  137. package/dist/runtime/core/learning.d.cts.map +1 -0
  138. package/dist/runtime/core/learning.d.mts +61 -0
  139. package/dist/runtime/core/learning.d.mts.map +1 -0
  140. package/dist/runtime/core/learning.mjs +56 -0
  141. package/dist/runtime/core/learning.mjs.map +1 -0
  142. package/dist/runtime/core/logger.cjs +21 -0
  143. package/dist/runtime/core/logger.cjs.map +1 -0
  144. package/dist/runtime/core/logger.d.cts +12 -0
  145. package/dist/runtime/core/logger.d.cts.map +1 -0
  146. package/dist/runtime/core/logger.d.mts +12 -0
  147. package/dist/runtime/core/logger.d.mts.map +1 -0
  148. package/dist/runtime/core/logger.mjs +18 -0
  149. package/dist/runtime/core/logger.mjs.map +1 -0
  150. package/dist/runtime/core/middleware-sse-parser.cjs +149 -0
  151. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -0
  152. package/dist/runtime/core/middleware-sse-parser.d.cts +21 -0
  153. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -0
  154. package/dist/runtime/core/middleware-sse-parser.d.mts +21 -0
  155. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -0
  156. package/dist/runtime/core/middleware-sse-parser.mjs +148 -0
  157. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -0
  158. package/dist/runtime/core/middleware.cjs +34 -0
  159. package/dist/runtime/core/middleware.cjs.map +1 -0
  160. package/dist/runtime/core/middleware.d.cts +31 -0
  161. package/dist/runtime/core/middleware.d.cts.map +1 -0
  162. package/dist/runtime/core/middleware.d.mts +31 -0
  163. package/dist/runtime/core/middleware.d.mts.map +1 -0
  164. package/dist/runtime/core/middleware.mjs +32 -0
  165. package/dist/runtime/core/middleware.mjs.map +1 -0
  166. package/dist/runtime/core/package-info.cjs +9 -0
  167. package/dist/runtime/core/package-info.cjs.map +1 -0
  168. package/dist/runtime/core/package-info.mjs +7 -0
  169. package/dist/runtime/core/package-info.mjs.map +1 -0
  170. package/dist/runtime/core/runtime-error-reporter.cjs +21 -0
  171. package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -0
  172. package/dist/runtime/core/runtime-error-reporter.mjs +18 -0
  173. package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -0
  174. package/dist/runtime/core/runtime.cjs +256 -0
  175. package/dist/runtime/core/runtime.cjs.map +1 -0
  176. package/dist/runtime/core/runtime.d.cts +481 -0
  177. package/dist/runtime/core/runtime.d.cts.map +1 -0
  178. package/dist/runtime/core/runtime.d.mts +481 -0
  179. package/dist/runtime/core/runtime.d.mts.map +1 -0
  180. package/dist/runtime/core/runtime.mjs +249 -0
  181. package/dist/runtime/core/runtime.mjs.map +1 -0
  182. package/dist/runtime/endpoints/auto-start-channels.cjs +46 -0
  183. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -0
  184. package/dist/runtime/endpoints/auto-start-channels.mjs +45 -0
  185. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -0
  186. package/dist/runtime/endpoints/express-single.cjs +43 -0
  187. package/dist/runtime/endpoints/express-single.cjs.map +1 -0
  188. package/dist/runtime/endpoints/express-single.d.cts +48 -0
  189. package/dist/runtime/endpoints/express-single.d.cts.map +1 -0
  190. package/dist/runtime/endpoints/express-single.d.mts +48 -0
  191. package/dist/runtime/endpoints/express-single.d.mts.map +1 -0
  192. package/dist/runtime/endpoints/express-single.mjs +43 -0
  193. package/dist/runtime/endpoints/express-single.mjs.map +1 -0
  194. package/dist/runtime/endpoints/express.cjs +68 -0
  195. package/dist/runtime/endpoints/express.cjs.map +1 -0
  196. package/dist/runtime/endpoints/express.d.cts +84 -0
  197. package/dist/runtime/endpoints/express.d.cts.map +1 -0
  198. package/dist/runtime/endpoints/express.d.mts +84 -0
  199. package/dist/runtime/endpoints/express.d.mts.map +1 -0
  200. package/dist/runtime/endpoints/express.mjs +66 -0
  201. package/dist/runtime/endpoints/express.mjs.map +1 -0
  202. package/dist/runtime/endpoints/hono-single.cjs +28 -0
  203. package/dist/runtime/endpoints/hono-single.cjs.map +1 -0
  204. package/dist/runtime/endpoints/hono-single.d.cts +43 -0
  205. package/dist/runtime/endpoints/hono-single.d.cts.map +1 -0
  206. package/dist/runtime/endpoints/hono-single.d.mts +43 -0
  207. package/dist/runtime/endpoints/hono-single.d.mts.map +1 -0
  208. package/dist/runtime/endpoints/hono-single.mjs +27 -0
  209. package/dist/runtime/endpoints/hono-single.mjs.map +1 -0
  210. package/dist/runtime/endpoints/hono.cjs +37 -0
  211. package/dist/runtime/endpoints/hono.cjs.map +1 -0
  212. package/dist/runtime/endpoints/hono.d.cts +96 -0
  213. package/dist/runtime/endpoints/hono.d.cts.map +1 -0
  214. package/dist/runtime/endpoints/hono.d.mts +96 -0
  215. package/dist/runtime/endpoints/hono.d.mts.map +1 -0
  216. package/dist/runtime/endpoints/hono.mjs +34 -0
  217. package/dist/runtime/endpoints/hono.mjs.map +1 -0
  218. package/dist/runtime/endpoints/index.d.cts +4 -0
  219. package/dist/runtime/endpoints/index.d.mts +4 -0
  220. package/dist/runtime/endpoints/load-express.cjs +35 -0
  221. package/dist/runtime/endpoints/load-express.cjs.map +1 -0
  222. package/dist/runtime/endpoints/load-express.mjs +34 -0
  223. package/dist/runtime/endpoints/load-express.mjs.map +1 -0
  224. package/dist/runtime/endpoints/node-fetch-handler.cjs +75 -0
  225. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -0
  226. package/dist/runtime/endpoints/node-fetch-handler.d.cts +11 -0
  227. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -0
  228. package/dist/runtime/endpoints/node-fetch-handler.d.mts +11 -0
  229. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -0
  230. package/dist/runtime/endpoints/node-fetch-handler.mjs +73 -0
  231. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -0
  232. package/dist/runtime/endpoints/node.cjs +16 -0
  233. package/dist/runtime/endpoints/node.cjs.map +1 -0
  234. package/dist/runtime/endpoints/node.d.cts +104 -0
  235. package/dist/runtime/endpoints/node.d.cts.map +1 -0
  236. package/dist/runtime/endpoints/node.d.mts +104 -0
  237. package/dist/runtime/endpoints/node.d.mts.map +1 -0
  238. package/dist/runtime/endpoints/node.mjs +16 -0
  239. package/dist/runtime/endpoints/node.mjs.map +1 -0
  240. package/dist/runtime/endpoints/single-route-helpers.cjs +130 -0
  241. package/dist/runtime/endpoints/single-route-helpers.cjs.map +1 -0
  242. package/dist/runtime/endpoints/single-route-helpers.mjs +125 -0
  243. package/dist/runtime/endpoints/single-route-helpers.mjs.map +1 -0
  244. package/dist/runtime/express.d.cts +2 -0
  245. package/dist/runtime/express.d.mts +2 -0
  246. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +393 -0
  247. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -0
  248. package/dist/runtime/generative-ui/generative-ui-middleware.d.cts +20 -0
  249. package/dist/runtime/generative-ui/generative-ui-middleware.d.cts.map +1 -0
  250. package/dist/runtime/generative-ui/generative-ui-middleware.d.mts +20 -0
  251. package/dist/runtime/generative-ui/generative-ui-middleware.d.mts.map +1 -0
  252. package/dist/runtime/generative-ui/generative-ui-middleware.mjs +392 -0
  253. package/dist/runtime/generative-ui/generative-ui-middleware.mjs.map +1 -0
  254. package/dist/runtime/generative-ui/index.d.cts +2 -0
  255. package/dist/runtime/generative-ui/index.d.mts +2 -0
  256. package/dist/runtime/generative-ui/surface-writer.cjs +85 -0
  257. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -0
  258. package/dist/runtime/generative-ui/surface-writer.d.cts +32 -0
  259. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -0
  260. package/dist/runtime/generative-ui/surface-writer.d.mts +32 -0
  261. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -0
  262. package/dist/runtime/generative-ui/surface-writer.mjs +84 -0
  263. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -0
  264. package/dist/runtime/handlers/get-runtime-info.cjs +140 -0
  265. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -0
  266. package/dist/runtime/handlers/get-runtime-info.mjs +140 -0
  267. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -0
  268. package/dist/runtime/handlers/handle-connect.cjs +62 -0
  269. package/dist/runtime/handlers/handle-connect.cjs.map +1 -0
  270. package/dist/runtime/handlers/handle-connect.mjs +62 -0
  271. package/dist/runtime/handlers/handle-connect.mjs.map +1 -0
  272. package/dist/runtime/handlers/handle-debug-events.cjs +33 -0
  273. package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -0
  274. package/dist/runtime/handlers/handle-debug-events.mjs +33 -0
  275. package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -0
  276. package/dist/runtime/handlers/handle-inspector-learning.cjs +56 -0
  277. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -0
  278. package/dist/runtime/handlers/handle-inspector-learning.mjs +55 -0
  279. package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -0
  280. package/dist/runtime/handlers/handle-inspector-metadata.cjs +36 -0
  281. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -0
  282. package/dist/runtime/handlers/handle-inspector-metadata.mjs +35 -0
  283. package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -0
  284. package/dist/runtime/handlers/handle-run.cjs +111 -0
  285. package/dist/runtime/handlers/handle-run.cjs.map +1 -0
  286. package/dist/runtime/handlers/handle-run.mjs +110 -0
  287. package/dist/runtime/handlers/handle-run.mjs.map +1 -0
  288. package/dist/runtime/handlers/handle-stop.cjs +102 -0
  289. package/dist/runtime/handlers/handle-stop.cjs.map +1 -0
  290. package/dist/runtime/handlers/handle-stop.mjs +101 -0
  291. package/dist/runtime/handlers/handle-stop.mjs.map +1 -0
  292. package/dist/runtime/handlers/handle-suggest.cjs +83 -0
  293. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -0
  294. package/dist/runtime/handlers/handle-suggest.mjs +82 -0
  295. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -0
  296. package/dist/runtime/handlers/handle-trajectory-connect.cjs +40 -0
  297. package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -0
  298. package/dist/runtime/handlers/handle-trajectory-connect.mjs +39 -0
  299. package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -0
  300. package/dist/runtime/handlers/handle-transcribe.cjs +112 -0
  301. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -0
  302. package/dist/runtime/handlers/handle-transcribe.mjs +111 -0
  303. package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -0
  304. package/dist/runtime/handlers/header-utils.cjs +185 -0
  305. package/dist/runtime/handlers/header-utils.cjs.map +1 -0
  306. package/dist/runtime/handlers/header-utils.d.cts +53 -0
  307. package/dist/runtime/handlers/header-utils.d.cts.map +1 -0
  308. package/dist/runtime/handlers/header-utils.d.mts +53 -0
  309. package/dist/runtime/handlers/header-utils.d.mts.map +1 -0
  310. package/dist/runtime/handlers/header-utils.mjs +183 -0
  311. package/dist/runtime/handlers/header-utils.mjs.map +1 -0
  312. package/dist/runtime/handlers/intelligence/annotate.cjs +83 -0
  313. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -0
  314. package/dist/runtime/handlers/intelligence/annotate.mjs +82 -0
  315. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -0
  316. package/dist/runtime/handlers/intelligence/connect.cjs +68 -0
  317. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -0
  318. package/dist/runtime/handlers/intelligence/connect.mjs +68 -0
  319. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -0
  320. package/dist/runtime/handlers/intelligence/memories.cjs +260 -0
  321. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -0
  322. package/dist/runtime/handlers/intelligence/memories.mjs +254 -0
  323. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -0
  324. package/dist/runtime/handlers/intelligence/run.cjs +283 -0
  325. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -0
  326. package/dist/runtime/handlers/intelligence/run.mjs +282 -0
  327. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -0
  328. package/dist/runtime/handlers/intelligence/thread-names.cjs +172 -0
  329. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -0
  330. package/dist/runtime/handlers/intelligence/thread-names.mjs +171 -0
  331. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -0
  332. package/dist/runtime/handlers/intelligence/threads.cjs +399 -0
  333. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -0
  334. package/dist/runtime/handlers/intelligence/threads.mjs +390 -0
  335. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -0
  336. package/dist/runtime/handlers/shared/agent-utils.cjs +267 -0
  337. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -0
  338. package/dist/runtime/handlers/shared/agent-utils.mjs +262 -0
  339. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -0
  340. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +30 -0
  341. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -0
  342. package/dist/runtime/handlers/shared/cloud-telemetry.mjs +29 -0
  343. package/dist/runtime/handlers/shared/cloud-telemetry.mjs.map +1 -0
  344. package/dist/runtime/handlers/shared/describe-endpoint.cjs +25 -0
  345. package/dist/runtime/handlers/shared/describe-endpoint.cjs.map +1 -0
  346. package/dist/runtime/handlers/shared/describe-endpoint.mjs +24 -0
  347. package/dist/runtime/handlers/shared/describe-endpoint.mjs.map +1 -0
  348. package/dist/runtime/handlers/shared/intelligence-utils.cjs +24 -0
  349. package/dist/runtime/handlers/shared/intelligence-utils.cjs.map +1 -0
  350. package/dist/runtime/handlers/shared/intelligence-utils.mjs +23 -0
  351. package/dist/runtime/handlers/shared/intelligence-utils.mjs.map +1 -0
  352. package/dist/runtime/handlers/shared/json-response.cjs +14 -0
  353. package/dist/runtime/handlers/shared/json-response.cjs.map +1 -0
  354. package/dist/runtime/handlers/shared/json-response.mjs +12 -0
  355. package/dist/runtime/handlers/shared/json-response.mjs.map +1 -0
  356. package/dist/runtime/handlers/shared/mcp-apps-servers.cjs +22 -0
  357. package/dist/runtime/handlers/shared/mcp-apps-servers.cjs.map +1 -0
  358. package/dist/runtime/handlers/shared/mcp-apps-servers.mjs +22 -0
  359. package/dist/runtime/handlers/shared/mcp-apps-servers.mjs.map +1 -0
  360. package/dist/runtime/handlers/shared/memory-policy.cjs +78 -0
  361. package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -0
  362. package/dist/runtime/handlers/shared/memory-policy.mjs +77 -0
  363. package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -0
  364. package/dist/runtime/handlers/shared/platform-error.cjs +39 -0
  365. package/dist/runtime/handlers/shared/platform-error.cjs.map +1 -0
  366. package/dist/runtime/handlers/shared/platform-error.mjs +39 -0
  367. package/dist/runtime/handlers/shared/platform-error.mjs.map +1 -0
  368. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +50 -0
  369. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -0
  370. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +49 -0
  371. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -0
  372. package/dist/runtime/handlers/shared/sse-keep-alive.cjs +68 -0
  373. package/dist/runtime/handlers/shared/sse-keep-alive.cjs.map +1 -0
  374. package/dist/runtime/handlers/shared/sse-keep-alive.mjs +66 -0
  375. package/dist/runtime/handlers/shared/sse-keep-alive.mjs.map +1 -0
  376. package/dist/runtime/handlers/shared/sse-response.cjs +237 -0
  377. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -0
  378. package/dist/runtime/handlers/shared/sse-response.mjs +236 -0
  379. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -0
  380. package/dist/runtime/handlers/shared/thread-access.cjs +137 -0
  381. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -0
  382. package/dist/runtime/handlers/shared/thread-access.d.cts +28 -0
  383. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -0
  384. package/dist/runtime/handlers/shared/thread-access.d.mts +28 -0
  385. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -0
  386. package/dist/runtime/handlers/shared/thread-access.mjs +132 -0
  387. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -0
  388. package/dist/runtime/handlers/sse/connect.cjs +23 -0
  389. package/dist/runtime/handlers/sse/connect.cjs.map +1 -0
  390. package/dist/runtime/handlers/sse/connect.mjs +23 -0
  391. package/dist/runtime/handlers/sse/connect.mjs.map +1 -0
  392. package/dist/runtime/handlers/sse/run.cjs +44 -0
  393. package/dist/runtime/handlers/sse/run.cjs.map +1 -0
  394. package/dist/runtime/handlers/sse/run.mjs +44 -0
  395. package/dist/runtime/handlers/sse/run.mjs.map +1 -0
  396. package/dist/runtime/hono.d.cts +2 -0
  397. package/dist/runtime/hono.d.mts +2 -0
  398. package/dist/runtime/index.d.cts +34 -0
  399. package/dist/runtime/index.d.cts.map +1 -0
  400. package/dist/runtime/index.d.mts +34 -0
  401. package/dist/runtime/index.d.mts.map +1 -0
  402. package/dist/runtime/intelligence-platform/client.cjs +1338 -0
  403. package/dist/runtime/intelligence-platform/client.cjs.map +1 -0
  404. package/dist/runtime/intelligence-platform/client.d.cts +824 -0
  405. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -0
  406. package/dist/runtime/intelligence-platform/client.d.mts +824 -0
  407. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -0
  408. package/dist/runtime/intelligence-platform/client.mjs +1334 -0
  409. package/dist/runtime/intelligence-platform/client.mjs.map +1 -0
  410. package/dist/runtime/intelligence-platform/experimental.d.cts +26 -0
  411. package/dist/runtime/intelligence-platform/experimental.d.cts.map +1 -0
  412. package/dist/runtime/intelligence-platform/experimental.d.mts +26 -0
  413. package/dist/runtime/intelligence-platform/experimental.d.mts.map +1 -0
  414. package/dist/runtime/intelligence-platform/index.d.cts +3 -0
  415. package/dist/runtime/intelligence-platform/index.d.mts +3 -0
  416. package/dist/runtime/intelligence-platform/learned-skills.cjs +95 -0
  417. package/dist/runtime/intelligence-platform/learned-skills.cjs.map +1 -0
  418. package/dist/runtime/intelligence-platform/learned-skills.d.cts +43 -0
  419. package/dist/runtime/intelligence-platform/learned-skills.d.cts.map +1 -0
  420. package/dist/runtime/intelligence-platform/learned-skills.d.mts +43 -0
  421. package/dist/runtime/intelligence-platform/learned-skills.d.mts.map +1 -0
  422. package/dist/runtime/intelligence-platform/learned-skills.mjs +92 -0
  423. package/dist/runtime/intelligence-platform/learned-skills.mjs.map +1 -0
  424. package/dist/runtime/intelligence-platform/learning-management.cjs +203 -0
  425. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -0
  426. package/dist/runtime/intelligence-platform/learning-management.d.cts +111 -0
  427. package/dist/runtime/intelligence-platform/learning-management.d.cts.map +1 -0
  428. package/dist/runtime/intelligence-platform/learning-management.d.mts +111 -0
  429. package/dist/runtime/intelligence-platform/learning-management.d.mts.map +1 -0
  430. package/dist/runtime/intelligence-platform/learning-management.mjs +193 -0
  431. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -0
  432. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +131 -0
  433. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -0
  434. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +10 -0
  435. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -0
  436. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +10 -0
  437. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -0
  438. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +127 -0
  439. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -0
  440. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +65 -0
  441. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -0
  442. package/dist/runtime/intelligence-platform/skill-registry/config.d.cts +47 -0
  443. package/dist/runtime/intelligence-platform/skill-registry/config.d.cts.map +1 -0
  444. package/dist/runtime/intelligence-platform/skill-registry/config.d.mts +47 -0
  445. package/dist/runtime/intelligence-platform/skill-registry/config.d.mts.map +1 -0
  446. package/dist/runtime/intelligence-platform/skill-registry/config.mjs +65 -0
  447. package/dist/runtime/intelligence-platform/skill-registry/config.mjs.map +1 -0
  448. package/dist/runtime/intelligence-platform/skill-registry/errors.cjs +10 -0
  449. package/dist/runtime/intelligence-platform/skill-registry/errors.cjs.map +1 -0
  450. package/dist/runtime/intelligence-platform/skill-registry/errors.d.cts +7 -0
  451. package/dist/runtime/intelligence-platform/skill-registry/errors.d.cts.map +1 -0
  452. package/dist/runtime/intelligence-platform/skill-registry/errors.d.mts +7 -0
  453. package/dist/runtime/intelligence-platform/skill-registry/errors.d.mts.map +1 -0
  454. package/dist/runtime/intelligence-platform/skill-registry/errors.mjs +10 -0
  455. package/dist/runtime/intelligence-platform/skill-registry/errors.mjs.map +1 -0
  456. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +7 -0
  457. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +7 -0
  458. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +247 -0
  459. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -0
  460. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts +36 -0
  461. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -0
  462. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts +36 -0
  463. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -0
  464. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +246 -0
  465. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -0
  466. package/dist/runtime/intelligence-platform/skill-registry/skill-content.cjs +41 -0
  467. package/dist/runtime/intelligence-platform/skill-registry/skill-content.cjs.map +1 -0
  468. package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.cts +12 -0
  469. package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.cts.map +1 -0
  470. package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.mts +12 -0
  471. package/dist/runtime/intelligence-platform/skill-registry/skill-content.d.mts.map +1 -0
  472. package/dist/runtime/intelligence-platform/skill-registry/skill-content.mjs +38 -0
  473. package/dist/runtime/intelligence-platform/skill-registry/skill-content.mjs.map +1 -0
  474. package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs +92 -0
  475. package/dist/runtime/intelligence-platform/skill-registry/snapshot.cjs.map +1 -0
  476. package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.cts +27 -0
  477. package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.cts.map +1 -0
  478. package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.mts +27 -0
  479. package/dist/runtime/intelligence-platform/skill-registry/snapshot.d.mts.map +1 -0
  480. package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs +91 -0
  481. package/dist/runtime/intelligence-platform/skill-registry/snapshot.mjs.map +1 -0
  482. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +142 -0
  483. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -0
  484. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +141 -0
  485. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -0
  486. package/dist/runtime/intelligence-platform/trajectories.cjs +95 -0
  487. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -0
  488. package/dist/runtime/intelligence-platform/trajectories.d.cts +11 -0
  489. package/dist/runtime/intelligence-platform/trajectories.d.cts.map +1 -0
  490. package/dist/runtime/intelligence-platform/trajectories.d.mts +11 -0
  491. package/dist/runtime/intelligence-platform/trajectories.d.mts.map +1 -0
  492. package/dist/runtime/intelligence-platform/trajectories.mjs +91 -0
  493. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -0
  494. package/dist/runtime/node.d.cts +2 -0
  495. package/dist/runtime/node.d.mts +2 -0
  496. package/dist/runtime/runner/agent-runner.cjs +82 -0
  497. package/dist/runtime/runner/agent-runner.cjs.map +1 -0
  498. package/dist/runtime/runner/agent-runner.d.cts +151 -0
  499. package/dist/runtime/runner/agent-runner.d.cts.map +1 -0
  500. package/dist/runtime/runner/agent-runner.d.mts +151 -0
  501. package/dist/runtime/runner/agent-runner.d.mts.map +1 -0
  502. package/dist/runtime/runner/agent-runner.mjs +73 -0
  503. package/dist/runtime/runner/agent-runner.mjs.map +1 -0
  504. package/dist/runtime/runner/in-memory.cjs +741 -0
  505. package/dist/runtime/runner/in-memory.cjs.map +1 -0
  506. package/dist/runtime/runner/in-memory.d.cts +427 -0
  507. package/dist/runtime/runner/in-memory.d.cts.map +1 -0
  508. package/dist/runtime/runner/in-memory.d.mts +427 -0
  509. package/dist/runtime/runner/in-memory.d.mts.map +1 -0
  510. package/dist/runtime/runner/in-memory.mjs +734 -0
  511. package/dist/runtime/runner/in-memory.mjs.map +1 -0
  512. package/dist/runtime/runner/index.d.cts +5 -0
  513. package/dist/runtime/runner/index.d.mts +5 -0
  514. package/dist/runtime/runner/index.mjs +6 -0
  515. package/dist/runtime/runner/intelligence.cjs +617 -0
  516. package/dist/runtime/runner/intelligence.cjs.map +1 -0
  517. package/dist/runtime/runner/intelligence.d.cts +104 -0
  518. package/dist/runtime/runner/intelligence.d.cts.map +1 -0
  519. package/dist/runtime/runner/intelligence.d.mts +104 -0
  520. package/dist/runtime/runner/intelligence.d.mts.map +1 -0
  521. package/dist/runtime/runner/intelligence.mjs +616 -0
  522. package/dist/runtime/runner/intelligence.mjs.map +1 -0
  523. package/dist/runtime/telemetry/disclosure.cjs +25 -0
  524. package/dist/runtime/telemetry/disclosure.cjs.map +1 -0
  525. package/dist/runtime/telemetry/disclosure.mjs +24 -0
  526. package/dist/runtime/telemetry/disclosure.mjs.map +1 -0
  527. package/dist/runtime/telemetry/events.d.cts +66 -0
  528. package/dist/runtime/telemetry/events.d.cts.map +1 -0
  529. package/dist/runtime/telemetry/events.d.mts +66 -0
  530. package/dist/runtime/telemetry/events.d.mts.map +1 -0
  531. package/dist/runtime/telemetry/instance-created.cjs +34 -0
  532. package/dist/runtime/telemetry/instance-created.cjs.map +1 -0
  533. package/dist/runtime/telemetry/instance-created.mjs +34 -0
  534. package/dist/runtime/telemetry/instance-created.mjs.map +1 -0
  535. package/dist/runtime/telemetry/telemetry-client.cjs +108 -0
  536. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -0
  537. package/dist/runtime/telemetry/telemetry-client.d.cts +10 -0
  538. package/dist/runtime/telemetry/telemetry-client.d.cts.map +1 -0
  539. package/dist/runtime/telemetry/telemetry-client.d.mts +10 -0
  540. package/dist/runtime/telemetry/telemetry-client.d.mts.map +1 -0
  541. package/dist/runtime/telemetry/telemetry-client.mjs +107 -0
  542. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -0
  543. package/dist/runtime/telemetry/telemetry-identity.cjs +12 -0
  544. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -0
  545. package/dist/runtime/telemetry/telemetry-identity.mjs +11 -0
  546. package/dist/runtime/telemetry/telemetry-identity.mjs.map +1 -0
  547. package/dist/runtime/transcription-service/transcription-service.cjs +7 -0
  548. package/dist/runtime/transcription-service/transcription-service.cjs.map +1 -0
  549. package/dist/runtime/transcription-service/transcription-service.d.cts +14 -0
  550. package/dist/runtime/transcription-service/transcription-service.d.cts.map +1 -0
  551. package/dist/runtime/transcription-service/transcription-service.d.mts +14 -0
  552. package/dist/runtime/transcription-service/transcription-service.d.mts.map +1 -0
  553. package/dist/runtime/transcription-service/transcription-service.mjs +6 -0
  554. package/dist/runtime/transcription-service/transcription-service.mjs.map +1 -0
  555. package/package.json +119 -104
  556. package/.eslintrc.js +0 -7
  557. package/CHANGELOG.md +0 -2920
  558. package/__snapshots__/schema/schema.graphql +0 -371
  559. package/dist/index.d.ts +0 -1494
  560. package/dist/index.js +0 -5641
  561. package/dist/index.js.map +0 -1
  562. package/dist/index.mjs.map +0 -1
  563. package/dist/langgraph.d.ts +0 -284
  564. package/dist/langgraph.js +0 -211
  565. package/dist/langgraph.js.map +0 -1
  566. package/dist/langgraph.mjs +0 -206
  567. package/dist/langgraph.mjs.map +0 -1
  568. package/dist/v2/index.d.ts +0 -2
  569. package/dist/v2/index.js +0 -22
  570. package/dist/v2/index.js.map +0 -1
  571. package/dist/v2/index.mjs +0 -5
  572. package/dist/v2/index.mjs.map +0 -1
  573. package/jest.config.js +0 -10
  574. package/scripts/generate-gql-schema.ts +0 -13
  575. package/src/agents/langgraph/event-source.ts +0 -329
  576. package/src/agents/langgraph/events.ts +0 -377
  577. package/src/graphql/inputs/action.input.ts +0 -16
  578. package/src/graphql/inputs/agent-session.input.ts +0 -13
  579. package/src/graphql/inputs/agent-state.input.ts +0 -13
  580. package/src/graphql/inputs/cloud-guardrails.input.ts +0 -16
  581. package/src/graphql/inputs/cloud.input.ts +0 -8
  582. package/src/graphql/inputs/context-property.input.ts +0 -10
  583. package/src/graphql/inputs/copilot-context.input.ts +0 -10
  584. package/src/graphql/inputs/custom-property.input.ts +0 -15
  585. package/src/graphql/inputs/extensions.input.ts +0 -21
  586. package/src/graphql/inputs/forwarded-parameters.input.ts +0 -22
  587. package/src/graphql/inputs/frontend.input.ts +0 -14
  588. package/src/graphql/inputs/generate-copilot-response.input.ts +0 -59
  589. package/src/graphql/inputs/load-agent-state.input.ts +0 -10
  590. package/src/graphql/inputs/message.input.ts +0 -110
  591. package/src/graphql/inputs/meta-event.input.ts +0 -18
  592. package/src/graphql/message-conversion/agui-to-gql.test.ts +0 -1263
  593. package/src/graphql/message-conversion/agui-to-gql.ts +0 -333
  594. package/src/graphql/message-conversion/gql-to-agui.test.ts +0 -1580
  595. package/src/graphql/message-conversion/gql-to-agui.ts +0 -278
  596. package/src/graphql/message-conversion/index.ts +0 -2
  597. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +0 -526
  598. package/src/graphql/resolvers/copilot.resolver.ts +0 -708
  599. package/src/graphql/resolvers/state.resolver.ts +0 -27
  600. package/src/graphql/types/agents-response.type.ts +0 -19
  601. package/src/graphql/types/base/index.ts +0 -10
  602. package/src/graphql/types/converted/index.ts +0 -176
  603. package/src/graphql/types/copilot-response.type.ts +0 -138
  604. package/src/graphql/types/enums.ts +0 -38
  605. package/src/graphql/types/extensions-response.type.ts +0 -23
  606. package/src/graphql/types/guardrails-result.type.ts +0 -20
  607. package/src/graphql/types/load-agent-state-response.type.ts +0 -17
  608. package/src/graphql/types/message-status.type.ts +0 -42
  609. package/src/graphql/types/meta-events.type.ts +0 -71
  610. package/src/graphql/types/response-status.type.ts +0 -66
  611. package/src/index.ts +0 -4
  612. package/src/langgraph.ts +0 -1
  613. package/src/lib/cloud/index.ts +0 -4
  614. package/src/lib/error-messages.ts +0 -200
  615. package/src/lib/index.ts +0 -52
  616. package/src/lib/integrations/index.ts +0 -6
  617. package/src/lib/integrations/nest/index.ts +0 -14
  618. package/src/lib/integrations/nextjs/app-router.ts +0 -38
  619. package/src/lib/integrations/nextjs/pages-router.ts +0 -39
  620. package/src/lib/integrations/node-express/index.ts +0 -14
  621. package/src/lib/integrations/node-http/index.ts +0 -143
  622. package/src/lib/integrations/node-http/request-handler.ts +0 -111
  623. package/src/lib/integrations/shared.ts +0 -161
  624. package/src/lib/logger.ts +0 -28
  625. package/src/lib/observability.ts +0 -160
  626. package/src/lib/runtime/__tests__/copilot-runtime-error.test.ts +0 -169
  627. package/src/lib/runtime/__tests__/mcp-tools-utils.test.ts +0 -464
  628. package/src/lib/runtime/agent-integrations/langgraph/agent.ts +0 -209
  629. package/src/lib/runtime/agent-integrations/langgraph/consts.ts +0 -34
  630. package/src/lib/runtime/agent-integrations/langgraph/index.ts +0 -2
  631. package/src/lib/runtime/copilot-runtime.ts +0 -710
  632. package/src/lib/runtime/mcp-tools-utils.ts +0 -254
  633. package/src/lib/runtime/retry-utils.ts +0 -96
  634. package/src/lib/runtime/telemetry-agent-runner.ts +0 -139
  635. package/src/lib/runtime/types.ts +0 -49
  636. package/src/lib/runtime/utils.ts +0 -87
  637. package/src/lib/streaming.ts +0 -202
  638. package/src/lib/telemetry-client.ts +0 -64
  639. package/src/service-adapters/anthropic/anthropic-adapter.ts +0 -452
  640. package/src/service-adapters/anthropic/utils.ts +0 -152
  641. package/src/service-adapters/bedrock/bedrock-adapter.ts +0 -73
  642. package/src/service-adapters/conversion.ts +0 -67
  643. package/src/service-adapters/empty/empty-adapter.ts +0 -38
  644. package/src/service-adapters/events.ts +0 -294
  645. package/src/service-adapters/experimental/ollama/ollama-adapter.ts +0 -84
  646. package/src/service-adapters/google/google-genai-adapter.test.ts +0 -104
  647. package/src/service-adapters/google/google-genai-adapter.ts +0 -88
  648. package/src/service-adapters/groq/groq-adapter.ts +0 -203
  649. package/src/service-adapters/index.ts +0 -18
  650. package/src/service-adapters/langchain/langchain-adapter.ts +0 -111
  651. package/src/service-adapters/langchain/langserve.ts +0 -88
  652. package/src/service-adapters/langchain/types.ts +0 -14
  653. package/src/service-adapters/langchain/utils.ts +0 -313
  654. package/src/service-adapters/openai/openai-adapter.ts +0 -283
  655. package/src/service-adapters/openai/openai-assistant-adapter.ts +0 -344
  656. package/src/service-adapters/openai/utils.ts +0 -199
  657. package/src/service-adapters/service-adapter.ts +0 -41
  658. package/src/service-adapters/shared/error-utils.ts +0 -61
  659. package/src/service-adapters/shared/index.ts +0 -1
  660. package/src/service-adapters/unify/unify-adapter.ts +0 -151
  661. package/src/utils/failed-response-status-reasons.ts +0 -70
  662. package/src/utils/index.ts +0 -1
  663. package/src/v2/index.ts +0 -3
  664. package/tests/global.d.ts +0 -13
  665. package/tests/service-adapters/anthropic/allowlist-approach.test.ts +0 -226
  666. package/tests/service-adapters/anthropic/anthropic-adapter.test.ts +0 -389
  667. package/tests/service-adapters/openai/allowlist-approach.test.ts +0 -238
  668. package/tests/service-adapters/openai/openai-adapter.test.ts +0 -301
  669. package/tests/setup.jest.ts +0 -21
  670. package/tests/tsconfig.json +0 -10
  671. package/tsconfig.json +0 -13
  672. package/tsup.config.ts +0 -20
  673. package/typedoc.json +0 -4
@@ -0,0 +1,1334 @@
1
+ import { learningCandidateDetailSchema, learningCandidateReviewSchema, learningCandidateSchema, learningContainerPageSchema, learningContainerPath, learningContainerSchema, learningInsightEvidenceSchema, learningObjectId, learningRunSchema, readLearningJson } from "./learning-management.mjs";
2
+ import { resolveTrajectoryLearningContainerIds } from "../core/learning.mjs";
3
+ import { TrajectoryConnectionError, parseTrajectoryConnectionGrant, trajectoryResponseError } from "./trajectories.mjs";
4
+ import { LearnedSkillsError, learnedSkillsResponseError, parseLearnedSkillsBatch } from "./learned-skills.mjs";
5
+ import { logger, parseInspectorLearningSnapshotV1, parseInspectorMetadataV1 } from "@copilotkit/shared";
6
+ import { z } from "zod";
7
+ import { randomUUID as randomUUID$1 } from "crypto";
8
+
9
+ //#region src/runtime/intelligence-platform/client.ts
10
+ /** Let a confirmed HTTP denial survive an error body that never completes. */
11
+ async function learnedSkillsErrorBody(response, signal) {
12
+ if (!signal) return response.json();
13
+ let onAbort;
14
+ try {
15
+ return await new Promise((resolve, reject) => {
16
+ onAbort = () => reject(signal.reason);
17
+ signal.addEventListener("abort", onAbort, { once: true });
18
+ if (signal.aborted) onAbort();
19
+ else response.json().then(resolve, reject);
20
+ });
21
+ } finally {
22
+ if (onAbort) signal.removeEventListener("abort", onAbort);
23
+ }
24
+ }
25
+ const RUNTIME_ENTITLEMENTS_REQUEST_TIMEOUT_MS = 1500;
26
+ const RUNTIME_ENTITLEMENTS_SUCCESS_TTL_MS = 3e4;
27
+ const RUNTIME_ENTITLEMENTS_NEGATIVE_TTL_MS = 5e3;
28
+ /** Whether a response grants Runtime access and therefore cannot be served stale. */
29
+ function grantsRuntimeAccess(response) {
30
+ return response.status === "ready" && response.entitlement.active;
31
+ }
32
+ /** Whether an HTTP status can recover without changing Runtime configuration. */
33
+ function isRetryableRuntimeEntitlementStatus(status) {
34
+ return status === 408 || status === 425 || status === 429 || status >= 500;
35
+ }
36
+ const runtimeEntitlementSchema = z.object({
37
+ active: z.boolean(),
38
+ source: z.enum([
39
+ "managedOrgSubscription",
40
+ "selfHostedDeploymentLicense",
41
+ "awsMarketplaceDeploymentLicense"
42
+ ]),
43
+ features: z.record(z.string(), z.boolean()),
44
+ limits: z.record(z.string(), z.number()),
45
+ planCode: z.string().optional(),
46
+ entitlementSource: z.string().optional()
47
+ }).strict();
48
+ const runtimeEntitlementResponseSchema = z.discriminatedUnion("status", [z.object({
49
+ status: z.literal("ready"),
50
+ entitlement: runtimeEntitlementSchema
51
+ }).strict(), z.object({
52
+ status: z.enum([
53
+ "degraded",
54
+ "misconfigured",
55
+ "unavailable"
56
+ ]),
57
+ error: z.object({
58
+ code: z.string(),
59
+ message: z.string(),
60
+ retryable: z.boolean(),
61
+ requestId: z.string().optional(),
62
+ traceId: z.string().optional()
63
+ }).strict()
64
+ }).strict()]);
65
+ const legacyRuntimeEntitlementTransportSchema = runtimeEntitlementSchema.extend({ organizationId: z.string() });
66
+ /** Check the published App API response union without widening its type. */
67
+ function isPublishedRuntimeEntitlementResponse(value) {
68
+ return runtimeEntitlementResponseSchema.safeParse(value).success;
69
+ }
70
+ /**
71
+ * Validate the published App API response union, with flat-response support
72
+ * during mixed-version rollouts.
73
+ */
74
+ function normalizeRuntimeEntitlementTransport(value) {
75
+ if (isPublishedRuntimeEntitlementResponse(value)) return value;
76
+ const legacyResponse = legacyRuntimeEntitlementTransportSchema.safeParse(value);
77
+ if (!legacyResponse.success) return;
78
+ const transport = legacyResponse.data;
79
+ return {
80
+ status: "ready",
81
+ entitlement: {
82
+ active: transport.active,
83
+ source: transport.source,
84
+ features: transport.features,
85
+ limits: transport.limits,
86
+ ...transport.planCode !== void 0 ? { planCode: transport.planCode } : {},
87
+ ...transport.entitlementSource !== void 0 ? { entitlementSource: transport.entitlementSource } : {}
88
+ }
89
+ };
90
+ }
91
+ /**
92
+ * Header name carrying the per-call end-user identity that the CopilotKit
93
+ * Intelligence `/mcp` endpoint requires. Internal CopilotKit machinery —
94
+ * `attachIntelligenceEnterpriseLearning` resolves the user via `identifyUser`
95
+ * and bakes this header onto the `MCPMiddleware`'s transport config, so every
96
+ * outbound MCP request stamps `X-Cpki-User-Id: <userId>`. Not part of the
97
+ * public user API.
98
+ *
99
+ * @internal
100
+ */
101
+ const INTELLIGENCE_USER_ID_HEADER = "x-cpki-user-id";
102
+ /** Immutable user/project Memory grant forwarded to Intelligence. */
103
+ const INTELLIGENCE_MEMORY_GRANT_HEADER = "x-cpki-memory-grant";
104
+ const memoryRequestHeaders = (userId, grant) => ({
105
+ [INTELLIGENCE_USER_ID_HEADER]: userId,
106
+ ...grant ? { [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(grant) } : {}
107
+ });
108
+ /**
109
+ * REST base URL of cloud-hosted CopilotKit Intelligence — the default
110
+ * when {@link CopilotKitIntelligenceConfig.apiUrl} is omitted.
111
+ */
112
+ const MANAGED_INTELLIGENCE_API_URL = "https://api.intelligence.copilotkit.ai";
113
+ /**
114
+ * Websocket base URL of cloud-hosted CopilotKit Intelligence — the
115
+ * default when {@link CopilotKitIntelligenceConfig.wsUrl} is omitted.
116
+ *
117
+ * A different host from {@link MANAGED_INTELLIGENCE_API_URL}: the API and
118
+ * realtime planes are deployed separately.
119
+ */
120
+ const MANAGED_INTELLIGENCE_WS_URL = "wss://realtime.intelligence.copilotkit.ai";
121
+ /** Maximum time spent on the optional Inspector metadata provider request. */
122
+ const INSPECTOR_METADATA_REQUEST_TIMEOUT_MS = 5e3;
123
+ const INSPECTOR_LEARNING_REQUEST_TIMEOUT_MS = 5e3;
124
+ /** A 404 the caller expects: a thread lookup made before the thread exists. */
125
+ const NOT_FOUND = new Set([404]);
126
+ /** A 409 the caller expects: another request created the thread first. */
127
+ const CONFLICT = new Set([409]);
128
+ /**
129
+ * Error thrown when a CopilotKit Intelligence HTTP request returns a non-2xx
130
+ * status. Carries the HTTP {@link status} code so callers can branch on
131
+ * specific failures (e.g. 404 for "not found", 409 for "conflict") without
132
+ * parsing the error message string.
133
+ *
134
+ * @example
135
+ * ```ts
136
+ * try {
137
+ * await intelligence.getThread({ threadId, userId });
138
+ * } catch (error) {
139
+ * if (error instanceof PlatformRequestError && error.status === 404) {
140
+ * // thread does not exist yet
141
+ * }
142
+ * }
143
+ * ```
144
+ */
145
+ var PlatformRequestError = class extends Error {
146
+ constructor(message, status, retryable, code) {
147
+ super(message);
148
+ this.status = status;
149
+ this.retryable = retryable;
150
+ this.code = code;
151
+ this.name = "PlatformRequestError";
152
+ }
153
+ };
154
+ /**
155
+ * Read the platform's `retryable` hint from an error response body. The
156
+ * platform sends `{ error: { code, message, category, retryable } }`; anything
157
+ * else (non-JSON, proxies, older platforms) yields `undefined`.
158
+ */
159
+ function readErrorBodyRetryable(text) {
160
+ if (!text) return void 0;
161
+ try {
162
+ const body = JSON.parse(text);
163
+ if (typeof body !== "object" || body === null) return void 0;
164
+ const error = body.error;
165
+ if (typeof error !== "object" || error === null) return void 0;
166
+ const retryable = error.retryable;
167
+ return typeof retryable === "boolean" ? retryable : void 0;
168
+ } catch {
169
+ return;
170
+ }
171
+ }
172
+ /** Copy a public Runtime entitlement so callers cannot mutate cached authority. */
173
+ function cloneRuntimeEntitlementResponse(response) {
174
+ if (response.status === "ready") return {
175
+ status: "ready",
176
+ entitlement: {
177
+ ...response.entitlement,
178
+ features: { ...response.entitlement.features },
179
+ limits: { ...response.entitlement.limits }
180
+ }
181
+ };
182
+ return {
183
+ status: response.status,
184
+ error: { ...response.error }
185
+ };
186
+ }
187
+ /** Copy a cached Error while preserving its concrete type and own fields. */
188
+ function cloneRuntimeEntitlementError(error) {
189
+ if (!(error instanceof Error)) return error;
190
+ return Object.create(Object.getPrototypeOf(error), Object.getOwnPropertyDescriptors(error));
191
+ }
192
+ /**
193
+ * Client for the CopilotKit Intelligence REST API.
194
+ *
195
+ * Construct the client once and pass it to any consumers that need it
196
+ * (e.g. `CopilotRuntime`, `IntelligenceAgentRunner`):
197
+ *
198
+ * ```ts
199
+ * import { CopilotKitIntelligence, CopilotRuntime } from "@copilotkit/runtime";
200
+ *
201
+ * const intelligence = new CopilotKitIntelligence({
202
+ * apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
203
+ * });
204
+ *
205
+ * const runtime = new CopilotRuntime({
206
+ * agents,
207
+ * intelligence,
208
+ * });
209
+ * ```
210
+ *
211
+ * `apiUrl` and `wsUrl` default to cloud-hosted CopilotKit Intelligence —
212
+ * `https://api.intelligence.copilotkit.ai` and
213
+ * `wss://realtime.intelligence.copilotkit.ai`. Those are the values for the
214
+ * managed service; leaving both unset is always correct against it.
215
+ *
216
+ * Override both together to target a non-production or future self-hosted
217
+ * deployment (the hosts below are placeholders — substitute your own):
218
+ *
219
+ * ```ts
220
+ * const intelligence = new CopilotKitIntelligence({
221
+ * apiUrl: "https://api.intelligence.example.com",
222
+ * wsUrl: "wss://realtime.intelligence.example.com",
223
+ * apiKey: process.env.CPK_INTELLIGENCE_API_KEY!,
224
+ * });
225
+ * ```
226
+ */
227
+ /**
228
+ * The thread events and state reads are scoped to one end user. A caller
229
+ * that omits `userId` (a JS caller, or one built against the earlier
230
+ * signature) would otherwise send the literal string "undefined" as the user.
231
+ */
232
+ function requireThreadReadUserId(method, userId) {
233
+ if (typeof userId !== "string" || userId === "") throw new TypeError(`${method} requires a non-empty userId: the id identifyUser returned`);
234
+ }
235
+ var CopilotKitIntelligence = class {
236
+ #apiUrl;
237
+ #runnerWsUrl;
238
+ #clientWsUrl;
239
+ #channelsWsUrl;
240
+ #apiKey;
241
+ #enterpriseLearningEnabled;
242
+ #getLearningContainerId;
243
+ #getTrajectoryLearningContainerIds;
244
+ #runtimeEntitlementsCache;
245
+ #runtimeEntitlementsFailure;
246
+ #runtimeEntitlementsInFlight;
247
+ #threadCreatedListeners = /* @__PURE__ */ new Set();
248
+ #threadUpdatedListeners = /* @__PURE__ */ new Set();
249
+ #threadDeletedListeners = /* @__PURE__ */ new Set();
250
+ constructor(config) {
251
+ this.experimental = { learning: {
252
+ listLearningContainers: this.#listLearningContainers.bind(this),
253
+ getLearningContainer: this.#getLearningContainer.bind(this),
254
+ listLearningRuns: this.#listLearningRuns.bind(this),
255
+ startLearningRun: this.#startLearningRun.bind(this),
256
+ listLearningCandidates: this.#listLearningCandidates.bind(this),
257
+ getLearningCandidate: this.#getLearningCandidate.bind(this),
258
+ getLearningInsightEvidence: this.#getLearningInsightEvidence.bind(this),
259
+ reviewLearningCandidate: this.#reviewLearningCandidate.bind(this)
260
+ } };
261
+ if (config.getLearningContainerId !== void 0 && typeof config.getLearningContainerId !== "function") throw new Error("CopilotKitIntelligence `getLearningContainerId` must be a callback");
262
+ assertConfiguredApiKey(config.apiKey);
263
+ if (config.getTrajectoryLearningContainerIds !== void 0 && typeof config.getTrajectoryLearningContainerIds !== "function") throw new Error("CopilotKitIntelligence `getTrajectoryLearningContainerIds` must be a callback");
264
+ const configuredApiUrl = configuredUrl(config.apiUrl);
265
+ const configuredWsUrl = configuredUrl(config.wsUrl);
266
+ warnOnPartialHostOverride(configuredApiUrl, configuredWsUrl);
267
+ const intelligenceWsUrl = normalizeIntelligenceWsUrl(configuredWsUrl ?? MANAGED_INTELLIGENCE_WS_URL);
268
+ this.#apiUrl = (configuredApiUrl ?? MANAGED_INTELLIGENCE_API_URL).replace(/\/$/, "");
269
+ this.#runnerWsUrl = deriveRunnerWsUrl(intelligenceWsUrl);
270
+ this.#clientWsUrl = deriveClientWsUrl(intelligenceWsUrl);
271
+ this.#channelsWsUrl = deriveChannelsWsUrl(intelligenceWsUrl);
272
+ this.#apiKey = config.apiKey;
273
+ this.#enterpriseLearningEnabled = config.enableEnterpriseLearning ?? false;
274
+ this.#getLearningContainerId = config.getLearningContainerId;
275
+ this.#getTrajectoryLearningContainerIds = config.getTrajectoryLearningContainerIds;
276
+ if (config.onThreadCreated) this.onThreadCreated(config.onThreadCreated);
277
+ if (config.onThreadUpdated) this.onThreadUpdated(config.onThreadUpdated);
278
+ if (config.onThreadDeleted) this.onThreadDeleted(config.onThreadDeleted);
279
+ }
280
+ /**
281
+ * Register a listener invoked whenever a thread is created.
282
+ *
283
+ * Multiple listeners can be registered. Each call returns an unsubscribe
284
+ * function that removes the listener when called.
285
+ *
286
+ * @param callback - Receives the newly created {@link ThreadSummary}.
287
+ * @returns A function that removes this listener when called.
288
+ *
289
+ * @example
290
+ * ```ts
291
+ * const unsubscribe = intelligence.onThreadCreated((thread) => {
292
+ * console.log("Thread created:", thread.id);
293
+ * });
294
+ * // later…
295
+ * unsubscribe();
296
+ * ```
297
+ */
298
+ onThreadCreated(callback) {
299
+ this.#threadCreatedListeners.add(callback);
300
+ return () => {
301
+ this.#threadCreatedListeners.delete(callback);
302
+ };
303
+ }
304
+ /**
305
+ * Register a listener invoked whenever a thread is updated (including archive).
306
+ *
307
+ * Multiple listeners can be registered. Each call returns an unsubscribe
308
+ * function that removes the listener when called.
309
+ *
310
+ * @param callback - Receives the updated {@link ThreadSummary}.
311
+ * @returns A function that removes this listener when called.
312
+ */
313
+ onThreadUpdated(callback) {
314
+ this.#threadUpdatedListeners.add(callback);
315
+ return () => {
316
+ this.#threadUpdatedListeners.delete(callback);
317
+ };
318
+ }
319
+ /**
320
+ * Register a listener invoked whenever a thread is deleted.
321
+ *
322
+ * Multiple listeners can be registered. Each call returns an unsubscribe
323
+ * function that removes the listener when called.
324
+ *
325
+ * @param callback - Receives the {@link ThreadDeletedPayload} identifying
326
+ * the deleted thread.
327
+ * @returns A function that removes this listener when called.
328
+ */
329
+ onThreadDeleted(callback) {
330
+ this.#threadDeletedListeners.add(callback);
331
+ return () => {
332
+ this.#threadDeletedListeners.delete(callback);
333
+ };
334
+ }
335
+ ɵgetApiUrl() {
336
+ return this.#apiUrl;
337
+ }
338
+ ɵgetRunnerWsUrl() {
339
+ return this.#runnerWsUrl;
340
+ }
341
+ ɵgetClientWsUrl() {
342
+ return this.#clientWsUrl;
343
+ }
344
+ ɵgetChannelsWsUrl() {
345
+ return this.#channelsWsUrl;
346
+ }
347
+ ɵgetRunnerAuthToken() {
348
+ return this.#apiKey;
349
+ }
350
+ /** @internal Used by `attachIntelligenceEnterpriseLearning` to populate `Authorization`. */
351
+ ɵgetApiKey() {
352
+ return this.#apiKey;
353
+ }
354
+ /** @internal Used by the Intelligence runtime to assign Learning Containers. */
355
+ ɵgetLearningContainerId() {
356
+ return this.#getLearningContainerId;
357
+ }
358
+ /** @internal Used by `attachIntelligenceEnterpriseLearning` to gate MCP attachment. */
359
+ ɵisEnterpriseLearningEnabled() {
360
+ return this.#enterpriseLearningEnabled;
361
+ }
362
+ /**
363
+ * Fetch one authorized learned-skills ZIP with this client's project key.
364
+ * No retries, archive parsing, or cache. A caller signal bounds the request
365
+ * and body read. Native cancellation is preserved; deadline failures use
366
+ * {@link LearnedSkillsError} with code `TIMEOUT`.
367
+ */
368
+ async getLearnedSkillsSnapshot(params) {
369
+ try {
370
+ params.signal?.throwIfAborted();
371
+ if (typeof params.containerId !== "string" || !params.containerId.trim() || params.revision !== void 0 && (typeof params.revision !== "string" || !params.revision.length) || params.ifNoneMatch !== void 0 && (typeof params.ifNoneMatch !== "string" || !params.ifNoneMatch.length || /[\r\n]/.test(params.ifNoneMatch))) throw new LearnedSkillsError("INVALID_CONFIG", false);
372
+ let url;
373
+ try {
374
+ url = new URL(`${this.#apiUrl}/api/v1/learning/containers/${encodeURIComponent(params.containerId)}/skills`);
375
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error("Invalid API URL");
376
+ if (params.revision !== void 0) url.searchParams.set("revision", params.revision);
377
+ } catch {
378
+ throw new LearnedSkillsError("INVALID_CONFIG", false);
379
+ }
380
+ const response = await fetch(url.toString(), {
381
+ method: "GET",
382
+ headers: {
383
+ Authorization: `Bearer ${this.#apiKey}`,
384
+ Accept: "application/zip",
385
+ ...params.ifNoneMatch !== void 0 ? { "If-None-Match": params.ifNoneMatch } : {}
386
+ },
387
+ signal: params.signal,
388
+ redirect: "error"
389
+ });
390
+ if (response.status === 401) {
391
+ response.body?.cancel().catch(() => {});
392
+ throw new LearnedSkillsError("AUTHENTICATION_FAILED", false);
393
+ }
394
+ if (response.status !== 403) params.signal?.throwIfAborted();
395
+ if (response.status !== 200 && response.status !== 304) {
396
+ const denialCode = response.status === 403 ? "AUTHORIZATION_FAILED" : void 0;
397
+ let body;
398
+ try {
399
+ body = await learnedSkillsErrorBody(response, params.signal);
400
+ } catch (error) {
401
+ if (denialCode) throw new LearnedSkillsError(denialCode, false, error instanceof SyntaxError ? void 0 : error);
402
+ params.signal?.throwIfAborted();
403
+ if (!(error instanceof SyntaxError)) throw error;
404
+ }
405
+ const responseError = learnedSkillsResponseError(body);
406
+ if (response.status === 403 && ![
407
+ "AUTHENTICATION_FAILED",
408
+ "AUTHORIZATION_FAILED",
409
+ "ENTITLEMENT_REQUIRED",
410
+ "DELIVERY_DISABLED",
411
+ "CONTAINER_NOT_FOUND",
412
+ "REVISION_NOT_FOUND",
413
+ "REVISION_REVOKED"
414
+ ].includes(responseError.code)) throw new LearnedSkillsError(denialCode, false);
415
+ throw responseError;
416
+ }
417
+ const revision = response.headers.get("X-CopilotKit-Skills-Revision");
418
+ const etag = response.headers.get("ETag");
419
+ if (!revision || !etag || !/^"[a-f0-9]{64}"$/.test(etag) || params.revision !== void 0 && revision !== params.revision) throw new LearnedSkillsError("INVALID_SNAPSHOT", false);
420
+ if (response.status === 304) {
421
+ if (params.ifNoneMatch === void 0) throw new LearnedSkillsError("INVALID_SNAPSHOT", false);
422
+ return {
423
+ status: "unchanged",
424
+ revision,
425
+ etag
426
+ };
427
+ }
428
+ const contentType = response.headers.get("Content-Type");
429
+ if (!contentType || contentType.split(";", 1)[0].trim().toLowerCase() !== "application/zip") throw new LearnedSkillsError("INVALID_SNAPSHOT", false);
430
+ const bytes = new Uint8Array(await response.arrayBuffer());
431
+ params.signal?.throwIfAborted();
432
+ return {
433
+ status: "snapshot",
434
+ bytes,
435
+ revision,
436
+ etag,
437
+ contentType
438
+ };
439
+ } catch (error) {
440
+ if (error instanceof LearnedSkillsError) throw error;
441
+ const cause = params.signal?.aborted ? params.signal.reason : error;
442
+ if (cause instanceof Error && cause.name === "TimeoutError") throw new LearnedSkillsError("TIMEOUT", true, cause);
443
+ if (params.signal?.aborted || cause instanceof Error && cause.name === "AbortError") throw cause;
444
+ throw new LearnedSkillsError("NETWORK_ERROR", true, error);
445
+ }
446
+ }
447
+ /** Fetch all requested containers in one authorized request, without retries. */
448
+ async getLearnedSkillsSnapshots(params) {
449
+ try {
450
+ params.signal?.throwIfAborted();
451
+ const containers = params.containers;
452
+ if (!Array.isArray(containers) || containers.length < 1 || containers.length > 50 || new Set(containers.map((item) => item?.containerId)).size !== containers.length) throw new LearnedSkillsError("INVALID_CONFIG", false);
453
+ for (const item of containers) {
454
+ if (!item || typeof item.containerId !== "string" || !item.containerId.trim() || /[\u0000-\u001f\u007f]/.test(item.containerId) || item.revision !== void 0 && (typeof item.revision !== "string" || !item.revision.trim()) || item.ifNoneMatch !== void 0 && (typeof item.ifNoneMatch !== "string" || !/^"[a-f0-9]{64}"$/.test(item.ifNoneMatch))) throw new LearnedSkillsError("INVALID_CONFIG", false);
455
+ try {
456
+ encodeURIComponent(item.containerId);
457
+ } catch {
458
+ throw new LearnedSkillsError("INVALID_CONFIG", false);
459
+ }
460
+ }
461
+ let url;
462
+ try {
463
+ url = new URL(`${this.#apiUrl}/api/v1/learning/skills/batch`);
464
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error();
465
+ } catch {
466
+ throw new LearnedSkillsError("INVALID_CONFIG", false);
467
+ }
468
+ const response = await fetch(url.toString(), {
469
+ method: "POST",
470
+ headers: {
471
+ Authorization: `Bearer ${this.#apiKey}`,
472
+ Accept: "application/json",
473
+ "Content-Type": "application/json"
474
+ },
475
+ body: JSON.stringify({ containers: containers.map(({ containerId, revision, ifNoneMatch }) => ({
476
+ containerId,
477
+ ...revision !== void 0 ? { revision } : {},
478
+ ...ifNoneMatch !== void 0 ? { ifNoneMatch } : {}
479
+ })) }),
480
+ signal: params.signal,
481
+ redirect: "error"
482
+ });
483
+ if (response.status === 401) {
484
+ response.body?.cancel().catch(() => {});
485
+ throw new LearnedSkillsError("AUTHENTICATION_FAILED", false);
486
+ }
487
+ if (response.status !== 403) params.signal?.throwIfAborted();
488
+ if (response.status !== 200) {
489
+ let body;
490
+ try {
491
+ body = await learnedSkillsErrorBody(response, params.signal);
492
+ } catch (error) {
493
+ if (response.status === 403) throw new LearnedSkillsError("AUTHORIZATION_FAILED", false);
494
+ params.signal?.throwIfAborted();
495
+ if (!(error instanceof SyntaxError)) throw error;
496
+ }
497
+ const error = learnedSkillsResponseError(body);
498
+ if (response.status === 403 && ![
499
+ "AUTHENTICATION_FAILED",
500
+ "AUTHORIZATION_FAILED",
501
+ "ENTITLEMENT_REQUIRED",
502
+ "DELIVERY_DISABLED",
503
+ "CONTAINER_NOT_FOUND",
504
+ "REVISION_NOT_FOUND",
505
+ "REVISION_REVOKED"
506
+ ].includes(error.code)) throw new LearnedSkillsError("AUTHORIZATION_FAILED", false);
507
+ throw error;
508
+ }
509
+ if (response.headers.get("Content-Type")?.split(";", 1)[0].trim().toLowerCase() !== "application/json") throw new LearnedSkillsError("INVALID_SNAPSHOT", false);
510
+ let body;
511
+ try {
512
+ body = await learnedSkillsErrorBody(response, params.signal);
513
+ } catch (error) {
514
+ if (error instanceof SyntaxError) throw new LearnedSkillsError("INVALID_SNAPSHOT", false);
515
+ throw error;
516
+ }
517
+ params.signal?.throwIfAborted();
518
+ return parseLearnedSkillsBatch(body, containers);
519
+ } catch (error) {
520
+ if (error instanceof LearnedSkillsError) throw error;
521
+ const cause = params.signal?.aborted ? params.signal.reason : error;
522
+ if (cause instanceof Error && cause.name === "TimeoutError") throw new LearnedSkillsError("TIMEOUT", true, cause);
523
+ if (params.signal?.aborted || cause instanceof Error && cause.name === "AbortError") throw cause;
524
+ throw new LearnedSkillsError("NETWORK_ERROR", true, error);
525
+ }
526
+ }
527
+ /**
528
+ * Fetch trusted Inspector metadata for this runtime's Intelligence project.
529
+ *
530
+ * The request always uses the server-configured Intelligence API key. A 404
531
+ * is treated as compatible absence so runtimes can work with older App API
532
+ * deployments that do not expose this endpoint yet.
533
+ *
534
+ * @returns Sanitized V1 metadata, or `undefined` when the provider has no
535
+ * supported metadata.
536
+ * @throws {@link PlatformRequestError} for provider failures other than 404.
537
+ */
538
+ async getInspectorMetadata() {
539
+ const path = "/api/inspector/metadata";
540
+ const abortController = new AbortController();
541
+ const timeoutError = /* @__PURE__ */ new Error("Intelligence inspector metadata request timed out");
542
+ let timeoutId;
543
+ const timeout = new Promise((_, reject) => {
544
+ timeoutId = setTimeout(() => {
545
+ reject(timeoutError);
546
+ abortController.abort(timeoutError);
547
+ }, INSPECTOR_METADATA_REQUEST_TIMEOUT_MS);
548
+ });
549
+ try {
550
+ const response = await Promise.race([fetch(`${this.#apiUrl}${path}`, {
551
+ method: "GET",
552
+ headers: { Authorization: `Bearer ${this.#apiKey}` },
553
+ signal: abortController.signal
554
+ }), timeout]);
555
+ if (response.status === 204 || response.status === 404) return;
556
+ if (!response.ok) {
557
+ logger.error({
558
+ status: response.status,
559
+ path
560
+ }, "Intelligence platform request failed");
561
+ throw new PlatformRequestError(`Intelligence platform error ${response.status}`, response.status);
562
+ }
563
+ const body = await Promise.race([response.text(), timeout]);
564
+ return parseInspectorMetadataV1(JSON.parse(body));
565
+ } catch (error) {
566
+ if (error === timeoutError) logger.warn({
567
+ path,
568
+ timeoutMs: INSPECTOR_METADATA_REQUEST_TIMEOUT_MS
569
+ }, "Intelligence inspector metadata request timed out");
570
+ throw error;
571
+ } finally {
572
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
573
+ }
574
+ }
575
+ /** Lists a bounded page of Learning spaces owned by this server's project key. */
576
+ async #listLearningContainers(options = {}) {
577
+ const query = options.cursor === void 0 ? "" : `?cursor=${encodeURIComponent(z.string().min(1).max(128).parse(options.cursor))}`;
578
+ return this.#learningRequest("GET", `/api/v1/learning/containers${query}`, learningContainerPageSchema, options.signal);
579
+ }
580
+ /** Reads one Learning space; this does not assign or move any conversations. */
581
+ async #getLearningContainer(options) {
582
+ return (await this.#learningRequest("GET", learningContainerPath(options.containerId), z.object({ container: learningContainerSchema }), options.signal)).container;
583
+ }
584
+ /** Reads the latest 100 Learning runs; queue admission is not completion. */
585
+ async #listLearningRuns(options) {
586
+ return (await this.#learningRequest("GET", `${learningContainerPath(options.containerId)}/runs`, z.object({ runs: z.array(learningRunSchema).max(100) }), options.signal)).runs;
587
+ }
588
+ /** Starts or recovers a manual run for all eligible evidence in this space. Never retries automatically. */
589
+ async #startLearningRun(options) {
590
+ return (await this.#learningRequest("POST", `${learningContainerPath(options.containerId)}/runs`, z.object({ run: learningRunSchema }), options.signal)).run;
591
+ }
592
+ /** Reads the latest 500 proposed Skill changes, including completed reviews. */
593
+ async #listLearningCandidates(options) {
594
+ return (await this.#learningRequest("GET", `${learningContainerPath(options.containerId)}/candidates`, z.object({ candidates: z.array(learningCandidateSchema).max(500) }), options.signal)).candidates;
595
+ }
596
+ /** Reads proposed files and supporting Insights for an explicit review decision. */
597
+ async #getLearningCandidate(options) {
598
+ return (await this.#learningRequest("GET", `${learningContainerPath(options.containerId)}/candidates/${learningObjectId(options.candidateId)}`, z.object({ candidate: learningCandidateDetailSchema }), options.signal)).candidate;
599
+ }
600
+ /** Reads scoped source evidence, including unavailable-source reasons. */
601
+ async #getLearningInsightEvidence(options) {
602
+ return (await this.#learningRequest("GET", `${learningContainerPath(options.containerId)}/insights/${learningObjectId(options.insightId)}/evidence`, z.object({ evidence: z.array(learningInsightEvidenceSchema) }), options.signal)).evidence;
603
+ }
604
+ /** Publishes or rejects a proposal. The application must authorize its reviewer before calling. */
605
+ async #reviewLearningCandidate(options) {
606
+ const action = z.enum(["approve", "reject"]).parse(options.action);
607
+ return (await this.#learningRequest("POST", `${learningContainerPath(options.containerId)}/candidates/${learningObjectId(options.candidateId)}/${action}`, z.object({ review: learningCandidateReviewSchema }), options.signal)).review;
608
+ }
609
+ /** Uses server credentials, bounded JSON, and a deadline without retrying mutations. */
610
+ async #learningRequest(method, path, schema, signal) {
611
+ signal?.throwIfAborted();
612
+ const controller = new AbortController();
613
+ const abort = () => controller.abort(signal?.reason);
614
+ signal?.addEventListener("abort", abort, { once: true });
615
+ const timeout = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Learning request timed out")), 3e4);
616
+ try {
617
+ const response = await fetch(`${this.#apiUrl}${path}`, {
618
+ method,
619
+ headers: {
620
+ Authorization: `Bearer ${this.#apiKey}`,
621
+ "Content-Type": "application/json"
622
+ },
623
+ ...method === "POST" ? { body: "{}" } : {},
624
+ signal: controller.signal
625
+ });
626
+ if (!response.ok) {
627
+ const body = await readLearningJson(response, 64 * 1024, controller.signal).catch(() => void 0);
628
+ controller.signal.throwIfAborted();
629
+ const error = z.object({ error: z.object({
630
+ code: z.string().regex(/^[A-Z][A-Z0-9_]{0,99}$/),
631
+ retryable: z.boolean()
632
+ }) }).safeParse(body);
633
+ throw new PlatformRequestError(`Learning request failed (${response.status}).`, response.status, error.success ? error.data.error.retryable : response.status === 429 || response.status >= 500, error.success ? error.data.error.code : void 0);
634
+ }
635
+ try {
636
+ return schema.parse(await readLearningJson(response, void 0, controller.signal));
637
+ } catch {
638
+ if (controller.signal.aborted) throw controller.signal.reason;
639
+ throw new PlatformRequestError("Invalid Learning response.", 502, true);
640
+ }
641
+ } finally {
642
+ clearTimeout(timeout);
643
+ signal?.removeEventListener("abort", abort);
644
+ }
645
+ }
646
+ /** Fetches one credential-scoped, bounded Learning projection for Inspector. */
647
+ async getInspectorLearning(request) {
648
+ const url = new URL(`${this.#apiUrl}/api/inspector/learning`);
649
+ if (request.agentId) url.searchParams.set("agentId", request.agentId);
650
+ if (request.skillsPage) url.searchParams.set("skillsPage", String(request.skillsPage));
651
+ if (request.insightsPage) url.searchParams.set("insightsPage", String(request.insightsPage));
652
+ if (request.runtimeContainerId) url.searchParams.set("runtimeContainerId", request.runtimeContainerId);
653
+ const controller = new AbortController();
654
+ const timeoutError = /* @__PURE__ */ new Error("Intelligence Inspector Learning request timed out");
655
+ const timeout = setTimeout(() => controller.abort(timeoutError), INSPECTOR_LEARNING_REQUEST_TIMEOUT_MS);
656
+ try {
657
+ const response = await fetch(url, {
658
+ method: "GET",
659
+ headers: { Authorization: `Bearer ${this.#apiKey}` },
660
+ signal: controller.signal
661
+ });
662
+ if (!response.ok) throw new PlatformRequestError(`Intelligence platform error ${response.status}`, response.status, response.status === 429 || response.status >= 500);
663
+ const snapshot = parseInspectorLearningSnapshotV1(await response.json());
664
+ if (!snapshot) throw new PlatformRequestError("Invalid Inspector Learning response", 502, true);
665
+ return snapshot;
666
+ } finally {
667
+ clearTimeout(timeout);
668
+ }
669
+ }
670
+ /**
671
+ * Resolve the Runtime entitlement projection for this project.
672
+ *
673
+ * Concurrent calls share one request. Active grants cache for 30 seconds;
674
+ * inactive results and failures cache for 5 seconds. Callers receive copies
675
+ * so they cannot mutate cached authority.
676
+ */
677
+ async getRuntimeEntitlements() {
678
+ const now = Date.now();
679
+ if (this.#runtimeEntitlementsCache && now < this.#runtimeEntitlementsCache.expiresAt) return cloneRuntimeEntitlementResponse(this.#runtimeEntitlementsCache.response);
680
+ if (this.#runtimeEntitlementsFailure && now < this.#runtimeEntitlementsFailure.expiresAt) throw cloneRuntimeEntitlementError(this.#runtimeEntitlementsFailure.error);
681
+ const request = this.#runtimeEntitlementsInFlight ?? this.#fetchRuntimeEntitlements().then((response) => {
682
+ this.#runtimeEntitlementsFailure = void 0;
683
+ this.#runtimeEntitlementsCache = {
684
+ response,
685
+ expiresAt: Date.now() + (grantsRuntimeAccess(response) ? RUNTIME_ENTITLEMENTS_SUCCESS_TTL_MS : RUNTIME_ENTITLEMENTS_NEGATIVE_TTL_MS)
686
+ };
687
+ return response;
688
+ }).catch((error) => {
689
+ this.#runtimeEntitlementsFailure = {
690
+ error,
691
+ expiresAt: Date.now() + RUNTIME_ENTITLEMENTS_NEGATIVE_TTL_MS
692
+ };
693
+ throw error;
694
+ });
695
+ this.#runtimeEntitlementsInFlight = request;
696
+ try {
697
+ return cloneRuntimeEntitlementResponse(await request);
698
+ } catch (error) {
699
+ throw cloneRuntimeEntitlementError(error);
700
+ } finally {
701
+ if (this.#runtimeEntitlementsInFlight === request) this.#runtimeEntitlementsInFlight = void 0;
702
+ }
703
+ }
704
+ /** Perform one bounded Runtime entitlement request without caching. */
705
+ async #fetchRuntimeEntitlements() {
706
+ const path = "/api/entitlements/runtime";
707
+ const controller = new AbortController();
708
+ const timeout = setTimeout(() => controller.abort(), RUNTIME_ENTITLEMENTS_REQUEST_TIMEOUT_MS);
709
+ try {
710
+ const response = await fetch(`${this.#apiUrl}${path}`, {
711
+ method: "GET",
712
+ headers: {
713
+ Authorization: `Bearer ${this.#apiKey}`,
714
+ "Content-Type": "application/json"
715
+ },
716
+ signal: controller.signal
717
+ });
718
+ if (!response.ok) {
719
+ await response.body?.cancel();
720
+ logger.error({
721
+ status: response.status,
722
+ path
723
+ }, "Runtime entitlement request failed");
724
+ throw new PlatformRequestError(`Runtime entitlement request failed with status ${response.status}`, response.status, isRetryableRuntimeEntitlementStatus(response.status));
725
+ }
726
+ let payload;
727
+ try {
728
+ payload = await response.json();
729
+ } catch (error) {
730
+ if (controller.signal.aborted) throw error;
731
+ throw new PlatformRequestError("Runtime entitlement response was malformed", 502, false);
732
+ }
733
+ const normalized = normalizeRuntimeEntitlementTransport(payload);
734
+ if (!normalized) throw new PlatformRequestError("Runtime entitlement response was malformed", 502, false);
735
+ return normalized;
736
+ } catch (error) {
737
+ if (error instanceof PlatformRequestError) throw error;
738
+ if (controller.signal.aborted || error instanceof DOMException && error.name === "AbortError") throw new PlatformRequestError("Runtime entitlement request timed out", 504, true);
739
+ throw new PlatformRequestError("Runtime entitlement request failed", 502, true);
740
+ } finally {
741
+ clearTimeout(timeout);
742
+ }
743
+ }
744
+ /**
745
+ * Mint a browser capture grant using only the Runtime's project and user.
746
+ *
747
+ * Learning Container assignment never stops capture: a failed selection or
748
+ * an unknown Container is logged, and the Trajectory connects without
749
+ * assignments.
750
+ */
751
+ async ɵconnectTrajectory(params) {
752
+ let learningContainerIds;
753
+ try {
754
+ learningContainerIds = await resolveTrajectoryLearningContainerIds(this.#getTrajectoryLearningContainerIds, {
755
+ trajectoryId: params.trajectoryId,
756
+ user: params.user
757
+ }, params.signal);
758
+ } catch (error) {
759
+ if (params.signal?.aborted) throw params.signal.reason;
760
+ logger.error({
761
+ err: error,
762
+ trajectoryId: params.trajectoryId
763
+ }, "Failed to resolve Trajectory Learning Containers; connecting the Trajectory without Learning Container assignments");
764
+ }
765
+ params.signal?.throwIfAborted();
766
+ try {
767
+ return await this.#joinTrajectory(params, learningContainerIds);
768
+ } catch (error) {
769
+ if (learningContainerIds === void 0 || !(error instanceof TrajectoryConnectionError) || error.code !== "LEARNING_CONTAINER_NOT_FOUND") throw error;
770
+ params.signal?.throwIfAborted();
771
+ logger.warn({
772
+ trajectoryId: params.trajectoryId,
773
+ learningContainerIds
774
+ }, "A selected Learning Container does not exist in this project; connecting the Trajectory without Learning Container assignments");
775
+ return this.#joinTrajectory(params, void 0);
776
+ }
777
+ }
778
+ /** Requests one Trajectory join token, optionally with Container assignments. */
779
+ async #joinTrajectory(params, learningContainerIds) {
780
+ let response;
781
+ try {
782
+ response = await fetch(`${this.#apiUrl}/api/trajectories/join`, {
783
+ method: "POST",
784
+ headers: {
785
+ Authorization: `Bearer ${this.#apiKey}`,
786
+ "Content-Type": "application/json"
787
+ },
788
+ body: JSON.stringify({
789
+ trajectoryId: params.trajectoryId,
790
+ appUserId: params.user.id,
791
+ ...learningContainerIds === void 0 ? {} : { learningContainerIds }
792
+ }),
793
+ signal: params.signal,
794
+ redirect: "error"
795
+ });
796
+ } catch (error) {
797
+ if (!params.signal?.aborted) logger.warn({
798
+ error: error instanceof Error ? error.name : typeof error,
799
+ causeCode: networkErrorCode(error instanceof Error ? error.cause : void 0),
800
+ host: urlHost(this.#apiUrl)
801
+ }, "Could not reach Intelligence to connect a Trajectory");
802
+ throw error;
803
+ }
804
+ const payload = await response.json().catch(() => void 0);
805
+ if (!response.ok) throw trajectoryResponseError(payload, response.status, this.#apiKey);
806
+ return parseTrajectoryConnectionGrant(payload, params.trajectoryId, this.ɵgetClientWsUrl());
807
+ }
808
+ /**
809
+ * Sends one request to the platform and parses its JSON body.
810
+ *
811
+ * @param expectedStatuses - Non-2xx statuses the caller handles as a normal
812
+ * outcome, such as the 404 of a thread that does not exist yet. They are
813
+ * logged at debug instead of error, and still throw.
814
+ * @throws {@link PlatformRequestError} on every non-2xx response.
815
+ */
816
+ async #request(method, path, body, extraHeaders, signal, expectedStatuses) {
817
+ const url = `${this.#apiUrl}${path}`;
818
+ const headers = {
819
+ Authorization: `Bearer ${this.#apiKey}`,
820
+ "Content-Type": "application/json",
821
+ ...extraHeaders
822
+ };
823
+ const response = await fetch(url, {
824
+ method,
825
+ headers,
826
+ body: body ? JSON.stringify(body) : void 0,
827
+ signal
828
+ });
829
+ if (!response.ok) {
830
+ const text = await response.text().catch(() => "");
831
+ if (expectedStatuses?.has(response.status)) logger.debug({
832
+ status: response.status,
833
+ path
834
+ }, "Intelligence platform request returned an expected status");
835
+ else logger.error({
836
+ status: response.status,
837
+ body: text,
838
+ path
839
+ }, "Intelligence platform request failed");
840
+ throw new PlatformRequestError(`Intelligence platform error ${response.status}: ${text || response.statusText}`, response.status, readErrorBodyRetryable(text));
841
+ }
842
+ const text = await response.text();
843
+ if (!text) return;
844
+ return JSON.parse(text);
845
+ }
846
+ #invokeLifecycleCallback(callbackName, payload) {
847
+ const listeners = callbackName === "onThreadCreated" ? this.#threadCreatedListeners : callbackName === "onThreadUpdated" ? this.#threadUpdatedListeners : this.#threadDeletedListeners;
848
+ for (const callback of listeners) try {
849
+ callback(payload);
850
+ } catch (error) {
851
+ logger.error({
852
+ err: error,
853
+ callbackName,
854
+ payload
855
+ }, "Intelligence lifecycle callback failed");
856
+ }
857
+ }
858
+ /**
859
+ * List all non-archived threads for a given user and agent.
860
+ *
861
+ * @param params.userId - User whose threads to list.
862
+ * @param params.agentId - Agent whose threads to list.
863
+ * @returns The thread list along with realtime subscription credentials.
864
+ * @throws {@link PlatformRequestError} on non-2xx responses.
865
+ */
866
+ async listThreads(params) {
867
+ const query = {
868
+ userId: params.userId,
869
+ agentId: params.agentId
870
+ };
871
+ if (params.includeArchived) query.includeArchived = "true";
872
+ if (params.limit != null) query.limit = String(params.limit);
873
+ if (params.cursor) query.cursor = params.cursor;
874
+ const qs = new URLSearchParams(query).toString();
875
+ return this.#request("GET", `/api/threads?${qs}`);
876
+ }
877
+ /**
878
+ * List the given user's long-term memories, newest first.
879
+ *
880
+ * The platform scopes by the opaque app user supplied in the
881
+ * `x-cpki-user-id` header (resolved by the runtime via `identifyUser`),
882
+ * not a query param. Pass `includeInvalidated` to also return retired rows.
883
+ *
884
+ * @returns The `{ memories }` envelope the client memory store consumes.
885
+ * @throws {@link PlatformRequestError} on non-2xx responses.
886
+ */
887
+ async listMemories(params) {
888
+ const qs = params.includeInvalidated ? "?includeInvalidated=true" : "";
889
+ return this.#request("GET", `/api/memories${qs}`, void 0, memoryRequestHeaders(params.userId, params.memoryGrant));
890
+ }
891
+ /**
892
+ * Create a memory for the given user (platform `POST /api/memories`).
893
+ * @returns The stored memory; `absorbed` is true if the content was merged
894
+ * into a near-duplicate rather than inserted as a new row.
895
+ * @throws {@link PlatformRequestError} on non-2xx responses.
896
+ */
897
+ async createMemory(params) {
898
+ return this.#request("POST", `/api/memories`, {
899
+ content: params.content,
900
+ kind: params.kind,
901
+ ...params.scope !== void 0 ? { scope: params.scope } : {},
902
+ sourceThreadIds: params.sourceThreadIds ?? []
903
+ }, memoryRequestHeaders(params.userId, params.memoryGrant));
904
+ }
905
+ /**
906
+ * Supersede an existing memory (platform `PATCH /api/memories/:id`). The
907
+ * `:id` row is retired and a new memory with the supplied content is
908
+ * inserted atomically.
909
+ * @returns The new memory plus `retiredId` (the id of the retired row).
910
+ * @throws {@link PlatformRequestError} on non-2xx responses (e.g. 404 when
911
+ * `:id` is not a live, same-scope memory for this user).
912
+ */
913
+ async updateMemory(params) {
914
+ return this.#request("PATCH", `/api/memories/${encodeURIComponent(params.id)}`, {
915
+ content: params.content,
916
+ kind: params.kind,
917
+ ...params.scope !== void 0 ? { scope: params.scope } : {},
918
+ sourceThreadIds: params.sourceThreadIds ?? []
919
+ }, memoryRequestHeaders(params.userId, params.memoryGrant));
920
+ }
921
+ /**
922
+ * Non-lossily retire (forget) a memory (platform `DELETE /api/memories/:id`).
923
+ * @throws {@link PlatformRequestError} on non-2xx responses.
924
+ */
925
+ async removeMemory(params) {
926
+ await this.#request("DELETE", `/api/memories/${encodeURIComponent(params.id)}`, void 0, memoryRequestHeaders(params.userId, params.memoryGrant));
927
+ }
928
+ /**
929
+ * Semantically recall the given user's memories (platform `POST
930
+ * /api/memories/recall`, hybrid RAG). Each returned memory carries a
931
+ * relevance `score`. `scope` narrows to `"user"`/`"project"`; omitted → platform default.
932
+ * @throws {@link PlatformRequestError} on non-2xx responses.
933
+ */
934
+ async recallMemories(params) {
935
+ return this.#request("POST", `/api/memories/recall`, {
936
+ query: params.query,
937
+ ...params.limit !== void 0 ? { limit: params.limit } : {},
938
+ ...params.scope !== void 0 ? { scope: params.scope } : {}
939
+ }, memoryRequestHeaders(params.userId, params.memoryGrant));
940
+ }
941
+ async ɵsubscribeToThreads(params) {
942
+ return this.#request("POST", "/api/threads/subscribe", { userId: params.userId });
943
+ }
944
+ /**
945
+ * Mint memory-realtime join credentials (platform `POST
946
+ * /api/memories/subscribe`). Returns both the single-use `joinToken` and the
947
+ * per-user `joinCode` the client needs to build the
948
+ * `user_meta:memories:<joinCode>` channel topic. When the platform also
949
+ * resolves a project scope it returns optional `projectJoinToken` /
950
+ * `projectJoinCode`; both are passed through verbatim (omitted when absent,
951
+ * the silent-degrade contract).
952
+ *
953
+ * The user is supplied via the `x-cpki-user-id` header — the same way every
954
+ * other memory endpoint (`listMemories`/`createMemory`/…) identifies the app
955
+ * user — because the platform's memory routes resolve identity from that
956
+ * header, not the body. (This differs from `ɵsubscribeToThreads`, whose
957
+ * platform endpoint reads `userId` from the body.)
958
+ *
959
+ * @throws {@link PlatformRequestError} on non-2xx responses.
960
+ */
961
+ async ɵsubscribeToMemories(params) {
962
+ return this.#request("POST", "/api/memories/subscribe", void 0, memoryRequestHeaders(params.userId, params.memoryGrant));
963
+ }
964
+ /**
965
+ * Update thread metadata (e.g. name).
966
+ *
967
+ * Fields in updates take precedence, preserving the server-side SDK contract.
968
+ * HTTP handlers must remove untrusted identity fields before calling this method.
969
+ *
970
+ * Triggers the `onThreadUpdated` lifecycle callback on success.
971
+ *
972
+ * @returns The updated thread summary.
973
+ * @throws {@link PlatformRequestError} on non-2xx responses.
974
+ */
975
+ async updateThread(params) {
976
+ const response = await this.#request("PATCH", `/api/threads/${encodeURIComponent(params.threadId)}`, {
977
+ userId: params.userId,
978
+ agentId: params.agentId,
979
+ ...params.updates
980
+ });
981
+ this.#invokeLifecycleCallback("onThreadUpdated", response.thread);
982
+ return response.thread;
983
+ }
984
+ /**
985
+ * Create a new thread on the platform.
986
+ *
987
+ * Triggers the `onThreadCreated` lifecycle callback on success.
988
+ *
989
+ * @returns The newly created thread summary.
990
+ * @throws {@link PlatformRequestError} with status 409 if a thread with the
991
+ * same `threadId` already exists.
992
+ */
993
+ async createThread(params) {
994
+ return this.#createThread(params);
995
+ }
996
+ /**
997
+ * Creates a thread. {@link getOrCreateThread} passes 409 as expected,
998
+ * because there it means another request created the thread first.
999
+ */
1000
+ async #createThread(params, expectedStatuses) {
1001
+ const response = await this.#request("POST", `/api/threads`, {
1002
+ threadId: params.threadId,
1003
+ userId: params.userId,
1004
+ agentId: params.agentId,
1005
+ ...params.name !== void 0 ? { name: params.name } : {},
1006
+ ...params.learningContainerId !== void 0 ? { learningContainerId: params.learningContainerId } : {}
1007
+ }, void 0, void 0, expectedStatuses);
1008
+ this.#invokeLifecycleCallback("onThreadCreated", response.thread);
1009
+ return response.thread;
1010
+ }
1011
+ /**
1012
+ * Fetch a single thread by ID.
1013
+ *
1014
+ * @returns The thread summary.
1015
+ * @throws {@link PlatformRequestError} with status 404 if the thread does
1016
+ * not exist.
1017
+ */
1018
+ async getThread(params) {
1019
+ return this.#getThread(params);
1020
+ }
1021
+ /**
1022
+ * Fetches a thread. {@link getOrCreateThread} passes 404 as expected,
1023
+ * because there it means the thread is about to be created (PE-678).
1024
+ */
1025
+ async #getThread(params, expectedStatuses) {
1026
+ const qs = new URLSearchParams({ userId: params.userId }).toString();
1027
+ return (await this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}?${qs}`, void 0, void 0, void 0, expectedStatuses)).thread;
1028
+ }
1029
+ /**
1030
+ * Get an existing thread or create it if it does not exist.
1031
+ *
1032
+ * Handles the race where a concurrent request creates the thread between
1033
+ * the initial 404 and the subsequent `createThread` call by catching the
1034
+ * 409 Conflict and retrying the get.
1035
+ *
1036
+ * Triggers the `onThreadCreated` lifecycle callback when a new thread is
1037
+ * created.
1038
+ *
1039
+ * @returns An object containing the thread and a `created` flag indicating
1040
+ * whether the thread was newly created (`true`) or already existed (`false`).
1041
+ * @throws {@link PlatformRequestError} on non-2xx responses other than
1042
+ * 404 (get) and 409 (create race).
1043
+ */
1044
+ async getOrCreateThread(params) {
1045
+ try {
1046
+ return {
1047
+ thread: await this.#getThread({
1048
+ threadId: params.threadId,
1049
+ userId: params.userId
1050
+ }, NOT_FOUND),
1051
+ created: false
1052
+ };
1053
+ } catch (error) {
1054
+ if (!(error instanceof PlatformRequestError && error.status === 404)) throw error;
1055
+ }
1056
+ try {
1057
+ return {
1058
+ thread: await this.#createThread(params, CONFLICT),
1059
+ created: true
1060
+ };
1061
+ } catch (error) {
1062
+ if (error instanceof PlatformRequestError && error.status === 409) return {
1063
+ thread: await this.getThread({
1064
+ threadId: params.threadId,
1065
+ userId: params.userId
1066
+ }),
1067
+ created: false
1068
+ };
1069
+ throw error;
1070
+ }
1071
+ }
1072
+ /**
1073
+ * Fetch the full message history for a thread.
1074
+ *
1075
+ * @returns All persisted messages in chronological order.
1076
+ * @throws {@link PlatformRequestError} on non-2xx responses.
1077
+ */
1078
+ async getThreadMessages(params) {
1079
+ const qs = new URLSearchParams({ userId: params.userId }).toString();
1080
+ return this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`, void 0, params.channelDeliveryId ? { "X-Cpki-Channel-Delivery-Id": params.channelDeliveryId } : void 0);
1081
+ }
1082
+ /**
1083
+ * @internal Fetch only the ids of a thread's persisted messages.
1084
+ *
1085
+ * Sends `fields=id` so the platform can omit message content. Platform
1086
+ * versions that do not know the parameter ignore it and return the full
1087
+ * transcript; ids are read from `messages[].id` either way.
1088
+ *
1089
+ * @throws {@link PlatformRequestError} on non-2xx responses.
1090
+ */
1091
+ async ɵgetThreadMessageIds(params) {
1092
+ const qs = new URLSearchParams({
1093
+ userId: params.userId,
1094
+ fields: "id"
1095
+ }).toString();
1096
+ return (await this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/messages?${qs}`, void 0, params.channelDeliveryId ? { "X-Cpki-Channel-Delivery-Id": params.channelDeliveryId } : void 0)).messages.map((message) => message.id);
1097
+ }
1098
+ /** @internal Fetches one authorized managed Channel asset for history hydration. */
1099
+ async ɵgetManagedChannelAsset(assetId) {
1100
+ const path = `/api/channels/files/${encodeURIComponent(assetId)}`;
1101
+ const response = await fetch(`${this.#apiUrl}${path}`, {
1102
+ method: "GET",
1103
+ headers: { Authorization: `Bearer ${this.#apiKey}` }
1104
+ });
1105
+ if (!response.ok) {
1106
+ const text = await response.text().catch(() => "");
1107
+ throw new PlatformRequestError(`Intelligence platform error ${response.status}: ${text || response.statusText}`, response.status);
1108
+ }
1109
+ const bytes = new Uint8Array(await response.arrayBuffer());
1110
+ const mimeType = response.headers.get("content-type") ?? void 0;
1111
+ return {
1112
+ bytes,
1113
+ ...mimeType ? { mimeType } : {}
1114
+ };
1115
+ }
1116
+ /**
1117
+ * Fetch the persisted AG-UI event stream for a thread.
1118
+ *
1119
+ * Backed by the platform's `GET /api/_inspect/threads/:id/events`
1120
+ * introspection endpoint (see Intelligence PR #144). Events are returned
1121
+ * in replay order across every run that targeted the thread. The
1122
+ * `_inspect/` prefix flags this as debug-only — production code paths
1123
+ * must not depend on it.
1124
+ *
1125
+ * @throws {@link PlatformRequestError} on non-2xx responses.
1126
+ */
1127
+ async getThreadEvents(params) {
1128
+ requireThreadReadUserId("getThreadEvents", params.userId);
1129
+ const qs = new URLSearchParams({ userId: params.userId }).toString();
1130
+ return this.#request("GET", `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/events?${qs}`);
1131
+ }
1132
+ /**
1133
+ * Fetch the current agent state for a thread.
1134
+ *
1135
+ * Backed by the platform's `GET /api/_inspect/threads/:id/state`
1136
+ * introspection endpoint (see Intelligence PR #144). The platform folds
1137
+ * RFC 6902 STATE_DELTA events on top of the latest STATE_SNAPSHOT, so
1138
+ * the returned state reflects the thread's current state — not just the
1139
+ * last snapshot. The discriminated response distinguishes "no snapshot
1140
+ * persisted yet" from "snapshot present" so consumers can render the
1141
+ * correct empty state.
1142
+ *
1143
+ * @throws {@link PlatformRequestError} on non-2xx responses.
1144
+ */
1145
+ async getThreadState(params) {
1146
+ requireThreadReadUserId("getThreadState", params.userId);
1147
+ const qs = new URLSearchParams({ userId: params.userId }).toString();
1148
+ return this.#request("GET", `/api/_inspect/threads/${encodeURIComponent(params.threadId)}/state?${qs}`);
1149
+ }
1150
+ /**
1151
+ * Mark a thread as archived.
1152
+ *
1153
+ * Archived threads are excluded from {@link listThreads} results.
1154
+ * Triggers the `onThreadUpdated` lifecycle callback on success.
1155
+ *
1156
+ * @throws {@link PlatformRequestError} on non-2xx responses.
1157
+ */
1158
+ async archiveThread(params) {
1159
+ const response = await this.#request("PATCH", `/api/threads/${encodeURIComponent(params.threadId)}`, {
1160
+ userId: params.userId,
1161
+ agentId: params.agentId,
1162
+ archived: true
1163
+ });
1164
+ this.#invokeLifecycleCallback("onThreadUpdated", response.thread);
1165
+ }
1166
+ /**
1167
+ * Permanently delete a thread and its message history.
1168
+ *
1169
+ * This is irreversible. Triggers the `onThreadDeleted` lifecycle callback
1170
+ * on success.
1171
+ *
1172
+ * @throws {@link PlatformRequestError} on non-2xx responses.
1173
+ */
1174
+ async deleteThread(params) {
1175
+ await this.#request("DELETE", `/api/threads/${encodeURIComponent(params.threadId)}`, {
1176
+ userId: params.userId,
1177
+ agentId: params.agentId,
1178
+ reason: `Deleted via CopilotKit runtime (userId=${params.userId}, agentId=${params.agentId})`
1179
+ });
1180
+ this.#invokeLifecycleCallback("onThreadDeleted", params);
1181
+ }
1182
+ /**
1183
+ * Annotate a thread event on CopilotKit Intelligence's general annotation
1184
+ * endpoint (`PUT /connector/annotate/:clientEventId`).
1185
+ *
1186
+ * This is the generalized replacement for the old
1187
+ * `PUT /connector/user-actions/record/:clientEventId` endpoint. It supports
1188
+ * multiple annotation types via the `type` discriminator. The
1189
+ * `"user_action"` type records a user UI interaction for the self-learning
1190
+ * loop.
1191
+ *
1192
+ * `userId` must be resolved on the runtime side before calling this — the
1193
+ * platform prefixes it with the project id from the API key.
1194
+ *
1195
+ * Always hits the idempotent `PUT /connector/annotate/:clientEventId`
1196
+ * endpoint. A retry with the same `clientEventId` returns
1197
+ * `{ id: <original>, duplicate: true }` instead of creating a new row.
1198
+ * When `clientEventId` is omitted, a UUID is auto-generated for this call.
1199
+ *
1200
+ * @throws {@link PlatformRequestError} on non-2xx responses, OR when the
1201
+ * platform returns an empty 2xx body (which would otherwise corrupt the
1202
+ * caller's typed result).
1203
+ */
1204
+ async annotate(params) {
1205
+ const clientEventId = params.clientEventId ?? randomUUID$1();
1206
+ const path = `/connector/annotate/${encodeURIComponent(clientEventId)}`;
1207
+ const body = {
1208
+ type: params.type,
1209
+ userId: params.userId,
1210
+ threadId: params.threadId
1211
+ };
1212
+ if (params.payload !== void 0) body.payload = params.payload;
1213
+ if (params.occurredAt !== void 0) body.occurredAt = params.occurredAt;
1214
+ const response = await this.#request("PUT", path, body);
1215
+ if (response == null) {
1216
+ logger.error({ path }, "annotate: Intelligence platform returned 200 with empty or null body");
1217
+ throw new PlatformRequestError("annotate: empty or null response body from Intelligence platform", 502);
1218
+ }
1219
+ return response;
1220
+ }
1221
+ async ɵacquireThreadLock(params) {
1222
+ return this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, {
1223
+ runId: params.runId,
1224
+ userId: params.userId,
1225
+ agentId: params.agentId,
1226
+ ...params.supportsBackendThreadId === void 0 ? {} : { supportsBackendThreadId: params.supportsBackendThreadId },
1227
+ ...params.learningContainerId !== void 0 ? { learningContainerId: params.learningContainerId } : {},
1228
+ ...params.requestId !== void 0 ? { requestId: params.requestId } : {},
1229
+ ...params.lockKeyPrefix !== void 0 ? { lockKeyPrefix: params.lockKeyPrefix } : {},
1230
+ ...params.ttlSeconds !== void 0 ? { ttlSeconds: params.ttlSeconds } : {}
1231
+ }, params.channelDeliveryId ? { "X-Cpki-Channel-Delivery-Id": params.channelDeliveryId } : void 0);
1232
+ }
1233
+ async ɵcleanupThreadLock(params) {
1234
+ return this.#request("DELETE", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, { runId: params.runId });
1235
+ }
1236
+ async ɵrenewThreadLock(params) {
1237
+ return this.#request("PATCH", `/api/threads/${encodeURIComponent(params.threadId)}/lock`, {
1238
+ runId: params.runId,
1239
+ ttlSeconds: params.ttlSeconds,
1240
+ ...params.lockKeyPrefix !== void 0 ? { lockKeyPrefix: params.lockKeyPrefix } : {}
1241
+ }, void 0, params.signal);
1242
+ }
1243
+ async ɵgetActiveJoinCode(params) {
1244
+ const qs = new URLSearchParams({ userId: params.userId }).toString();
1245
+ return this.#request("GET", `/api/threads/${encodeURIComponent(params.threadId)}/join-code?${qs}`);
1246
+ }
1247
+ async ɵconnectThread(params) {
1248
+ return await this.#request("POST", `/api/threads/${encodeURIComponent(params.threadId)}/connect`, {
1249
+ userId: params.userId,
1250
+ agentId: params.agentId
1251
+ }) ?? null;
1252
+ }
1253
+ };
1254
+ /**
1255
+ * Normalize a configured URL to "provided" or "not provided". A blank string
1256
+ * counts as not provided: these URLs are typically wired from environment
1257
+ * variables, and a declared-but-empty variable (`COPILOTKIT_INTELLIGENCE_URL=`,
1258
+ * common in generated `.env` files and container configs) arrives as `""`. Left
1259
+ * as-is it would produce host-relative requests instead of falling back to the
1260
+ * managed platform.
1261
+ */
1262
+ function configuredUrl(url) {
1263
+ const trimmed = url?.trim();
1264
+ return trimmed ? trimmed : void 0;
1265
+ }
1266
+ /**
1267
+ * Reject an Intelligence project API key that carries no credential.
1268
+ *
1269
+ * `apiKey` is required on the config type, so TypeScript catches an absent
1270
+ * property. It does not catch an empty one, and the common shape is a
1271
+ * `process.env` read that TypeScript is told to trust — `?? ""` in the starter
1272
+ * wiring block, `!` in this file's own examples. When the variable is unset,
1273
+ * both produce a blank key that is sent verbatim as `Authorization: Bearer `
1274
+ * and fails much later as a 401 that points at nothing.
1275
+ *
1276
+ * A runtime with no credential cannot serve managed Intelligence, so this
1277
+ * throws at construction: callers build the client during boot, which puts the
1278
+ * error at startup rather than on a user's first message.
1279
+ */
1280
+ function assertConfiguredApiKey(apiKey) {
1281
+ if (typeof apiKey === "string" && apiKey.trim() !== "") return;
1282
+ throw new Error("CopilotKitIntelligence `apiKey` is required and cannot be blank. It is the CopilotKit Intelligence project API key, normally read from the CPK_INTELLIGENCE_API_KEY environment variable. Run `copilotkit project select` to provision one for your project.");
1283
+ }
1284
+ /**
1285
+ * Warn when exactly one of `apiUrl`/`wsUrl` is configured. The API and realtime
1286
+ * planes are separate hosts, so a lone override silently leaves the other plane
1287
+ * on CopilotKit's managed platform — a self-hosted API paired with the managed
1288
+ * gateway (or vice versa), which fails as a hang rather than an error.
1289
+ */
1290
+ function warnOnPartialHostOverride(apiUrl, wsUrl) {
1291
+ if (apiUrl && !wsUrl) {
1292
+ logger.warn(`CopilotKitIntelligence: apiUrl is set to "${apiUrl}" but wsUrl is not, so wsUrl falls back to the managed default "${MANAGED_INTELLIGENCE_WS_URL}". The API and realtime planes are separate hosts — set both when pointing at a self-hosted deployment.`);
1293
+ return;
1294
+ }
1295
+ if (wsUrl && !apiUrl) logger.warn(`CopilotKitIntelligence: wsUrl is set to "${wsUrl}" but apiUrl is not, so apiUrl falls back to the managed default "${MANAGED_INTELLIGENCE_API_URL}". The API and realtime planes are separate hosts — set both when pointing at a self-hosted deployment.`);
1296
+ }
1297
+ function normalizeIntelligenceWsUrl(wsUrl) {
1298
+ return wsUrl.replace(/\/$/, "");
1299
+ }
1300
+ function deriveRunnerWsUrl(wsUrl) {
1301
+ if (wsUrl.endsWith("/runner")) return wsUrl;
1302
+ if (wsUrl.endsWith("/client")) return `${wsUrl.slice(0, -7)}/runner`;
1303
+ if (wsUrl.endsWith("/channels")) return `${wsUrl.slice(0, -9)}/runner`;
1304
+ return `${wsUrl}/runner`;
1305
+ }
1306
+ /** A system error code such as ECONNREFUSED, or undefined for anything else. */
1307
+ function networkErrorCode(cause) {
1308
+ const code = typeof cause === "object" && cause !== null && "code" in cause ? cause.code : void 0;
1309
+ return typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : void 0;
1310
+ }
1311
+ /** The host of a URL without its credentials, path or query. */
1312
+ function urlHost(url) {
1313
+ try {
1314
+ return new URL(url).host;
1315
+ } catch {
1316
+ return;
1317
+ }
1318
+ }
1319
+ function deriveClientWsUrl(wsUrl) {
1320
+ if (wsUrl.endsWith("/client")) return wsUrl;
1321
+ if (wsUrl.endsWith("/runner")) return `${wsUrl.slice(0, -7)}/client`;
1322
+ if (wsUrl.endsWith("/channels")) return `${wsUrl.slice(0, -9)}/client`;
1323
+ return `${wsUrl}/client`;
1324
+ }
1325
+ function deriveChannelsWsUrl(wsUrl) {
1326
+ if (wsUrl.endsWith("/channels")) return wsUrl;
1327
+ if (wsUrl.endsWith("/runner")) return `${wsUrl.slice(0, -7)}/channels`;
1328
+ if (wsUrl.endsWith("/client")) return `${wsUrl.slice(0, -7)}/channels`;
1329
+ return `${wsUrl}/channels`;
1330
+ }
1331
+
1332
+ //#endregion
1333
+ export { CopilotKitIntelligence, INTELLIGENCE_MEMORY_GRANT_HEADER, INTELLIGENCE_USER_ID_HEADER, PlatformRequestError };
1334
+ //# sourceMappingURL=client.mjs.map