@copilotkit/runtime 1.68.3 → 1.69.1

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 (582) hide show
  1. package/dist/_virtual/_rolldown/runtime.mjs +1 -15
  2. package/dist/agent/converters/aisdk.d.cts +1 -1
  3. package/dist/agent/converters/aisdk.d.mts +1 -1
  4. package/dist/agent/converters/index.d.mts +1 -1
  5. package/dist/agent/converters/tanstack.d.cts +1 -1
  6. package/dist/agent/converters/tanstack.d.mts +1 -1
  7. package/dist/agent/index.cjs.map +1 -1
  8. package/dist/agent/index.d.cts +2 -2
  9. package/dist/agent/index.d.cts.map +1 -1
  10. package/dist/agent/index.d.mts +2 -2
  11. package/dist/agent/index.d.mts.map +1 -1
  12. package/dist/agent/index.mjs.map +1 -1
  13. package/dist/agents/langgraph/events.cjs +1 -1
  14. package/dist/agents/langgraph/events.cjs.map +1 -1
  15. package/dist/agents/langgraph/events.mjs +1 -1
  16. package/dist/agents/langgraph/events.mjs.map +1 -1
  17. package/dist/graphql/inputs/action.input.cjs +1 -1
  18. package/dist/graphql/inputs/action.input.cjs.map +1 -1
  19. package/dist/graphql/inputs/action.input.d.cts +2 -2
  20. package/dist/graphql/inputs/action.input.d.cts.map +1 -1
  21. package/dist/graphql/inputs/action.input.d.mts +2 -2
  22. package/dist/graphql/inputs/action.input.d.mts.map +1 -1
  23. package/dist/graphql/inputs/action.input.mjs +1 -1
  24. package/dist/graphql/inputs/action.input.mjs.map +1 -1
  25. package/dist/graphql/inputs/agent-session.input.cjs +1 -1
  26. package/dist/graphql/inputs/agent-session.input.cjs.map +1 -1
  27. package/dist/graphql/inputs/agent-session.input.d.cts +2 -2
  28. package/dist/graphql/inputs/agent-session.input.d.cts.map +1 -1
  29. package/dist/graphql/inputs/agent-session.input.d.mts +2 -2
  30. package/dist/graphql/inputs/agent-session.input.d.mts.map +1 -1
  31. package/dist/graphql/inputs/agent-session.input.mjs +1 -1
  32. package/dist/graphql/inputs/agent-session.input.mjs.map +1 -1
  33. package/dist/graphql/inputs/agent-state.input.cjs +1 -1
  34. package/dist/graphql/inputs/agent-state.input.cjs.map +1 -1
  35. package/dist/graphql/inputs/agent-state.input.d.cts +2 -2
  36. package/dist/graphql/inputs/agent-state.input.d.cts.map +1 -1
  37. package/dist/graphql/inputs/agent-state.input.d.mts +2 -2
  38. package/dist/graphql/inputs/agent-state.input.d.mts.map +1 -1
  39. package/dist/graphql/inputs/agent-state.input.mjs +1 -1
  40. package/dist/graphql/inputs/agent-state.input.mjs.map +1 -1
  41. package/dist/graphql/inputs/cloud-guardrails.input.cjs +1 -1
  42. package/dist/graphql/inputs/cloud-guardrails.input.cjs.map +1 -1
  43. package/dist/graphql/inputs/cloud-guardrails.input.mjs +1 -1
  44. package/dist/graphql/inputs/cloud-guardrails.input.mjs.map +1 -1
  45. package/dist/graphql/inputs/cloud.input.cjs +1 -1
  46. package/dist/graphql/inputs/cloud.input.cjs.map +1 -1
  47. package/dist/graphql/inputs/cloud.input.mjs +1 -1
  48. package/dist/graphql/inputs/cloud.input.mjs.map +1 -1
  49. package/dist/graphql/inputs/copilot-context.input.cjs +1 -1
  50. package/dist/graphql/inputs/copilot-context.input.cjs.map +1 -1
  51. package/dist/graphql/inputs/copilot-context.input.mjs +1 -1
  52. package/dist/graphql/inputs/copilot-context.input.mjs.map +1 -1
  53. package/dist/graphql/inputs/extensions.input.cjs +1 -1
  54. package/dist/graphql/inputs/extensions.input.cjs.map +1 -1
  55. package/dist/graphql/inputs/extensions.input.d.cts +2 -2
  56. package/dist/graphql/inputs/extensions.input.d.cts.map +1 -1
  57. package/dist/graphql/inputs/extensions.input.d.mts +2 -2
  58. package/dist/graphql/inputs/extensions.input.d.mts.map +1 -1
  59. package/dist/graphql/inputs/extensions.input.mjs +1 -1
  60. package/dist/graphql/inputs/extensions.input.mjs.map +1 -1
  61. package/dist/graphql/inputs/forwarded-parameters.input.cjs +2 -3
  62. package/dist/graphql/inputs/forwarded-parameters.input.cjs.map +1 -1
  63. package/dist/graphql/inputs/forwarded-parameters.input.d.cts +3 -3
  64. package/dist/graphql/inputs/forwarded-parameters.input.d.cts.map +1 -1
  65. package/dist/graphql/inputs/forwarded-parameters.input.d.mts +3 -3
  66. package/dist/graphql/inputs/forwarded-parameters.input.d.mts.map +1 -1
  67. package/dist/graphql/inputs/forwarded-parameters.input.mjs +2 -3
  68. package/dist/graphql/inputs/forwarded-parameters.input.mjs.map +1 -1
  69. package/dist/graphql/inputs/frontend.input.cjs +1 -1
  70. package/dist/graphql/inputs/frontend.input.cjs.map +1 -1
  71. package/dist/graphql/inputs/frontend.input.mjs +1 -1
  72. package/dist/graphql/inputs/frontend.input.mjs.map +1 -1
  73. package/dist/graphql/inputs/generate-copilot-response.input.cjs +1 -1
  74. package/dist/graphql/inputs/generate-copilot-response.input.cjs.map +1 -1
  75. package/dist/graphql/inputs/generate-copilot-response.input.mjs +1 -1
  76. package/dist/graphql/inputs/generate-copilot-response.input.mjs.map +1 -1
  77. package/dist/graphql/inputs/load-agent-state.input.cjs +1 -1
  78. package/dist/graphql/inputs/load-agent-state.input.cjs.map +1 -1
  79. package/dist/graphql/inputs/load-agent-state.input.mjs +1 -1
  80. package/dist/graphql/inputs/load-agent-state.input.mjs.map +1 -1
  81. package/dist/graphql/inputs/message.input.cjs +10 -10
  82. package/dist/graphql/inputs/message.input.cjs.map +1 -1
  83. package/dist/graphql/inputs/message.input.d.cts +3 -3
  84. package/dist/graphql/inputs/message.input.d.cts.map +1 -1
  85. package/dist/graphql/inputs/message.input.d.mts +3 -3
  86. package/dist/graphql/inputs/message.input.d.mts.map +1 -1
  87. package/dist/graphql/inputs/message.input.mjs +10 -10
  88. package/dist/graphql/inputs/message.input.mjs.map +1 -1
  89. package/dist/graphql/inputs/meta-event.input.cjs +1 -1
  90. package/dist/graphql/inputs/meta-event.input.cjs.map +1 -1
  91. package/dist/graphql/inputs/meta-event.input.mjs +1 -1
  92. package/dist/graphql/inputs/meta-event.input.mjs.map +1 -1
  93. package/dist/graphql/message-conversion/agui-to-gql.cjs +1 -1
  94. package/dist/graphql/message-conversion/agui-to-gql.cjs.map +1 -1
  95. package/dist/graphql/message-conversion/agui-to-gql.mjs +1 -1
  96. package/dist/graphql/message-conversion/agui-to-gql.mjs.map +1 -1
  97. package/dist/graphql/resolvers/copilot.resolver.cjs +1 -1
  98. package/dist/graphql/resolvers/copilot.resolver.cjs.map +1 -1
  99. package/dist/graphql/resolvers/copilot.resolver.mjs +1 -1
  100. package/dist/graphql/resolvers/copilot.resolver.mjs.map +1 -1
  101. package/dist/graphql/resolvers/resolve-message-id.cjs +1 -1
  102. package/dist/graphql/resolvers/resolve-message-id.cjs.map +1 -1
  103. package/dist/graphql/resolvers/resolve-message-id.mjs +1 -1
  104. package/dist/graphql/resolvers/resolve-message-id.mjs.map +1 -1
  105. package/dist/graphql/resolvers/state.resolver.cjs +1 -1
  106. package/dist/graphql/resolvers/state.resolver.cjs.map +1 -1
  107. package/dist/graphql/resolvers/state.resolver.mjs +1 -1
  108. package/dist/graphql/resolvers/state.resolver.mjs.map +1 -1
  109. package/dist/graphql/types/agents-response.type.cjs +1 -1
  110. package/dist/graphql/types/agents-response.type.cjs.map +1 -1
  111. package/dist/graphql/types/agents-response.type.mjs +1 -1
  112. package/dist/graphql/types/agents-response.type.mjs.map +1 -1
  113. package/dist/graphql/types/base/index.cjs +1 -1
  114. package/dist/graphql/types/base/index.cjs.map +1 -1
  115. package/dist/graphql/types/base/index.d.cts +2 -2
  116. package/dist/graphql/types/base/index.d.cts.map +1 -1
  117. package/dist/graphql/types/base/index.d.mts +2 -2
  118. package/dist/graphql/types/base/index.d.mts.map +1 -1
  119. package/dist/graphql/types/base/index.mjs +1 -1
  120. package/dist/graphql/types/base/index.mjs.map +1 -1
  121. package/dist/graphql/types/converted/index.cjs +2 -2
  122. package/dist/graphql/types/converted/index.cjs.map +1 -1
  123. package/dist/graphql/types/converted/index.d.cts +2 -2
  124. package/dist/graphql/types/converted/index.d.cts.map +1 -1
  125. package/dist/graphql/types/converted/index.d.mts +2 -2
  126. package/dist/graphql/types/converted/index.d.mts.map +1 -1
  127. package/dist/graphql/types/converted/index.mjs +2 -2
  128. package/dist/graphql/types/converted/index.mjs.map +1 -1
  129. package/dist/graphql/types/copilot-response.type.cjs +1 -1
  130. package/dist/graphql/types/copilot-response.type.cjs.map +1 -1
  131. package/dist/graphql/types/copilot-response.type.d.cts +2 -2
  132. package/dist/graphql/types/copilot-response.type.d.cts.map +1 -1
  133. package/dist/graphql/types/copilot-response.type.d.mts +2 -2
  134. package/dist/graphql/types/copilot-response.type.d.mts.map +1 -1
  135. package/dist/graphql/types/copilot-response.type.mjs +1 -1
  136. package/dist/graphql/types/copilot-response.type.mjs.map +1 -1
  137. package/dist/graphql/types/enums.cjs +1 -1
  138. package/dist/graphql/types/enums.cjs.map +1 -1
  139. package/dist/graphql/types/enums.d.cts +2 -2
  140. package/dist/graphql/types/enums.d.cts.map +1 -1
  141. package/dist/graphql/types/enums.d.mts +2 -2
  142. package/dist/graphql/types/enums.d.mts.map +1 -1
  143. package/dist/graphql/types/enums.mjs +1 -1
  144. package/dist/graphql/types/enums.mjs.map +1 -1
  145. package/dist/graphql/types/extensions-response.type.cjs +1 -1
  146. package/dist/graphql/types/extensions-response.type.cjs.map +1 -1
  147. package/dist/graphql/types/extensions-response.type.d.cts +2 -2
  148. package/dist/graphql/types/extensions-response.type.d.cts.map +1 -1
  149. package/dist/graphql/types/extensions-response.type.d.mts +2 -2
  150. package/dist/graphql/types/extensions-response.type.d.mts.map +1 -1
  151. package/dist/graphql/types/extensions-response.type.mjs +1 -1
  152. package/dist/graphql/types/extensions-response.type.mjs.map +1 -1
  153. package/dist/graphql/types/load-agent-state-response.type.cjs +1 -1
  154. package/dist/graphql/types/load-agent-state-response.type.cjs.map +1 -1
  155. package/dist/graphql/types/load-agent-state-response.type.mjs +1 -1
  156. package/dist/graphql/types/load-agent-state-response.type.mjs.map +1 -1
  157. package/dist/graphql/types/message-status.type.cjs +1 -1
  158. package/dist/graphql/types/message-status.type.cjs.map +1 -1
  159. package/dist/graphql/types/message-status.type.d.cts +2 -2
  160. package/dist/graphql/types/message-status.type.d.cts.map +1 -1
  161. package/dist/graphql/types/message-status.type.d.mts +2 -2
  162. package/dist/graphql/types/message-status.type.d.mts.map +1 -1
  163. package/dist/graphql/types/message-status.type.mjs +1 -1
  164. package/dist/graphql/types/message-status.type.mjs.map +1 -1
  165. package/dist/graphql/types/meta-events.type.cjs +2 -2
  166. package/dist/graphql/types/meta-events.type.cjs.map +1 -1
  167. package/dist/graphql/types/meta-events.type.mjs +2 -2
  168. package/dist/graphql/types/meta-events.type.mjs.map +1 -1
  169. package/dist/graphql/types/response-status.type.cjs +1 -1
  170. package/dist/graphql/types/response-status.type.cjs.map +1 -1
  171. package/dist/graphql/types/response-status.type.d.cts +2 -2
  172. package/dist/graphql/types/response-status.type.d.cts.map +1 -1
  173. package/dist/graphql/types/response-status.type.d.mts +2 -2
  174. package/dist/graphql/types/response-status.type.d.mts.map +1 -1
  175. package/dist/graphql/types/response-status.type.mjs +1 -1
  176. package/dist/graphql/types/response-status.type.mjs.map +1 -1
  177. package/dist/index.d.cts +619 -5
  178. package/dist/index.d.mts +619 -5
  179. package/dist/langgraph.d.cts +55 -2
  180. package/dist/langgraph.d.mts +55 -2
  181. package/dist/lib/cloud/index.d.cts +2 -2
  182. package/dist/lib/cloud/index.d.cts.map +1 -1
  183. package/dist/lib/cloud/index.d.mts +2 -2
  184. package/dist/lib/cloud/index.d.mts.map +1 -1
  185. package/dist/lib/index.cjs +1 -1
  186. package/dist/lib/index.cjs.map +1 -1
  187. package/dist/lib/index.d.cts +3 -3
  188. package/dist/lib/index.d.cts.map +1 -1
  189. package/dist/lib/index.d.mts +3 -3
  190. package/dist/lib/index.d.mts.map +1 -1
  191. package/dist/lib/index.mjs +1 -1
  192. package/dist/lib/index.mjs.map +1 -1
  193. package/dist/lib/integrations/index.d.cts +2 -2
  194. package/dist/lib/integrations/index.d.mts +2 -2
  195. package/dist/lib/integrations/nest/index.cjs +1 -1
  196. package/dist/lib/integrations/nest/index.cjs.map +1 -1
  197. package/dist/lib/integrations/nest/index.d.cts +2 -2
  198. package/dist/lib/integrations/nest/index.d.cts.map +1 -1
  199. package/dist/lib/integrations/nest/index.d.mts +2 -2
  200. package/dist/lib/integrations/nest/index.d.mts.map +1 -1
  201. package/dist/lib/integrations/nest/index.mjs +1 -1
  202. package/dist/lib/integrations/nest/index.mjs.map +1 -1
  203. package/dist/lib/integrations/nextjs/app-router.cjs +1 -1
  204. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  205. package/dist/lib/integrations/nextjs/app-router.d.cts +2 -2
  206. package/dist/lib/integrations/nextjs/app-router.d.cts.map +1 -1
  207. package/dist/lib/integrations/nextjs/app-router.d.mts +2 -2
  208. package/dist/lib/integrations/nextjs/app-router.d.mts.map +1 -1
  209. package/dist/lib/integrations/nextjs/app-router.mjs +1 -1
  210. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  211. package/dist/lib/integrations/nextjs/pages-router.cjs +1 -1
  212. package/dist/lib/integrations/nextjs/pages-router.cjs.map +1 -1
  213. package/dist/lib/integrations/nextjs/pages-router.d.cts +2 -3
  214. package/dist/lib/integrations/nextjs/pages-router.d.cts.map +1 -1
  215. package/dist/lib/integrations/nextjs/pages-router.d.mts +2 -3
  216. package/dist/lib/integrations/nextjs/pages-router.d.mts.map +1 -1
  217. package/dist/lib/integrations/nextjs/pages-router.mjs +1 -1
  218. package/dist/lib/integrations/nextjs/pages-router.mjs.map +1 -1
  219. package/dist/lib/integrations/node-express/index.cjs +1 -1
  220. package/dist/lib/integrations/node-express/index.cjs.map +1 -1
  221. package/dist/lib/integrations/node-express/index.d.cts +2 -2
  222. package/dist/lib/integrations/node-express/index.d.cts.map +1 -1
  223. package/dist/lib/integrations/node-express/index.d.mts +2 -2
  224. package/dist/lib/integrations/node-express/index.d.mts.map +1 -1
  225. package/dist/lib/integrations/node-express/index.mjs +1 -1
  226. package/dist/lib/integrations/node-express/index.mjs.map +1 -1
  227. package/dist/lib/integrations/node-http/index.cjs +1 -1
  228. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  229. package/dist/lib/integrations/node-http/index.d.cts +2 -2
  230. package/dist/lib/integrations/node-http/index.d.cts.map +1 -1
  231. package/dist/lib/integrations/node-http/index.d.mts +2 -2
  232. package/dist/lib/integrations/node-http/index.d.mts.map +1 -1
  233. package/dist/lib/integrations/node-http/index.mjs +1 -1
  234. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  235. package/dist/lib/integrations/node-http/request-handler.cjs +1 -1
  236. package/dist/lib/integrations/node-http/request-handler.cjs.map +1 -1
  237. package/dist/lib/integrations/node-http/request-handler.mjs +1 -1
  238. package/dist/lib/integrations/node-http/request-handler.mjs.map +1 -1
  239. package/dist/lib/integrations/shared.cjs +1 -1
  240. package/dist/lib/integrations/shared.cjs.map +1 -1
  241. package/dist/lib/integrations/shared.d.cts +31 -5
  242. package/dist/lib/integrations/shared.d.cts.map +1 -1
  243. package/dist/lib/integrations/shared.d.mts +31 -5
  244. package/dist/lib/integrations/shared.d.mts.map +1 -1
  245. package/dist/lib/integrations/shared.mjs +1 -1
  246. package/dist/lib/integrations/shared.mjs.map +1 -1
  247. package/dist/lib/logger.cjs +1 -1
  248. package/dist/lib/logger.cjs.map +1 -1
  249. package/dist/lib/logger.d.cts +2 -2
  250. package/dist/lib/logger.d.cts.map +1 -1
  251. package/dist/lib/logger.d.mts +2 -2
  252. package/dist/lib/logger.d.mts.map +1 -1
  253. package/dist/lib/logger.mjs +1 -1
  254. package/dist/lib/logger.mjs.map +1 -1
  255. package/dist/lib/observability.d.cts +2 -2
  256. package/dist/lib/observability.d.cts.map +1 -1
  257. package/dist/lib/observability.d.mts +2 -2
  258. package/dist/lib/observability.d.mts.map +1 -1
  259. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs +1 -1
  260. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs.map +1 -1
  261. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts +14 -4
  262. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts.map +1 -1
  263. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.mts +14 -4
  264. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.mts.map +1 -1
  265. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs +1 -1
  266. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs.map +1 -1
  267. package/dist/lib/runtime/agent-integrations/langgraph/consts.cjs +1 -1
  268. package/dist/lib/runtime/agent-integrations/langgraph/consts.cjs.map +1 -1
  269. package/dist/lib/runtime/agent-integrations/langgraph/consts.d.cts +2 -2
  270. package/dist/lib/runtime/agent-integrations/langgraph/consts.d.cts.map +1 -1
  271. package/dist/lib/runtime/agent-integrations/langgraph/consts.d.mts +2 -2
  272. package/dist/lib/runtime/agent-integrations/langgraph/consts.d.mts.map +1 -1
  273. package/dist/lib/runtime/agent-integrations/langgraph/consts.mjs +1 -1
  274. package/dist/lib/runtime/agent-integrations/langgraph/consts.mjs.map +1 -1
  275. package/dist/lib/runtime/agent-integrations/langgraph/index.d.cts +1 -1
  276. package/dist/lib/runtime/agent-integrations/langgraph/index.d.mts +1 -1
  277. package/dist/lib/runtime/copilot-runtime.cjs +9 -1
  278. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  279. package/dist/lib/runtime/copilot-runtime.d.cts +10 -2
  280. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  281. package/dist/lib/runtime/copilot-runtime.d.mts +10 -2
  282. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  283. package/dist/lib/runtime/copilot-runtime.mjs +9 -1
  284. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  285. package/dist/lib/runtime/mcp-tools-utils.cjs +1 -1
  286. package/dist/lib/runtime/mcp-tools-utils.cjs.map +1 -1
  287. package/dist/lib/runtime/mcp-tools-utils.d.cts +2 -2
  288. package/dist/lib/runtime/mcp-tools-utils.d.cts.map +1 -1
  289. package/dist/lib/runtime/mcp-tools-utils.d.mts +2 -2
  290. package/dist/lib/runtime/mcp-tools-utils.d.mts.map +1 -1
  291. package/dist/lib/runtime/mcp-tools-utils.mjs +1 -1
  292. package/dist/lib/runtime/mcp-tools-utils.mjs.map +1 -1
  293. package/dist/lib/runtime/telemetry-agent-runner.cjs +1 -1
  294. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  295. package/dist/lib/runtime/telemetry-agent-runner.d.cts +2 -2
  296. package/dist/lib/runtime/telemetry-agent-runner.d.cts.map +1 -1
  297. package/dist/lib/runtime/telemetry-agent-runner.d.mts +2 -2
  298. package/dist/lib/runtime/telemetry-agent-runner.d.mts.map +1 -1
  299. package/dist/lib/runtime/telemetry-agent-runner.mjs +1 -1
  300. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  301. package/dist/lib/runtime/types.cjs +1 -1
  302. package/dist/lib/runtime/types.cjs.map +1 -1
  303. package/dist/lib/runtime/types.d.cts +2 -2
  304. package/dist/lib/runtime/types.d.cts.map +1 -1
  305. package/dist/lib/runtime/types.d.mts +2 -2
  306. package/dist/lib/runtime/types.d.mts.map +1 -1
  307. package/dist/lib/runtime/types.mjs +1 -1
  308. package/dist/lib/runtime/types.mjs.map +1 -1
  309. package/dist/lib/telemetry-client.cjs +1 -1
  310. package/dist/lib/telemetry-client.cjs.map +1 -1
  311. package/dist/lib/telemetry-client.mjs +2 -2
  312. package/dist/lib/telemetry-client.mjs.map +1 -1
  313. package/dist/lib/telemetry-disclosure.cjs +1 -1
  314. package/dist/lib/telemetry-disclosure.cjs.map +1 -1
  315. package/dist/lib/telemetry-disclosure.mjs +1 -1
  316. package/dist/lib/telemetry-disclosure.mjs.map +1 -1
  317. package/dist/package.cjs +5 -4
  318. package/dist/{runtime/package.mjs → package.mjs} +6 -5
  319. package/dist/package.mjs.map +1 -0
  320. package/dist/service-adapters/anthropic/anthropic-adapter.cjs +3 -3
  321. package/dist/service-adapters/anthropic/anthropic-adapter.cjs.map +1 -1
  322. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts +5 -5
  323. package/dist/service-adapters/anthropic/anthropic-adapter.d.cts.map +1 -1
  324. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts +6 -5
  325. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts.map +1 -1
  326. package/dist/service-adapters/anthropic/anthropic-adapter.mjs +3 -3
  327. package/dist/service-adapters/anthropic/anthropic-adapter.mjs.map +1 -1
  328. package/dist/service-adapters/anthropic/utils.cjs +1 -1
  329. package/dist/service-adapters/anthropic/utils.cjs.map +1 -1
  330. package/dist/service-adapters/anthropic/utils.mjs +1 -1
  331. package/dist/service-adapters/anthropic/utils.mjs.map +1 -1
  332. package/dist/service-adapters/bedrock/bedrock-adapter.cjs +1 -1
  333. package/dist/service-adapters/bedrock/bedrock-adapter.cjs.map +1 -1
  334. package/dist/service-adapters/bedrock/bedrock-adapter.d.cts +2 -2
  335. package/dist/service-adapters/bedrock/bedrock-adapter.d.cts.map +1 -1
  336. package/dist/service-adapters/bedrock/bedrock-adapter.d.mts +2 -2
  337. package/dist/service-adapters/bedrock/bedrock-adapter.d.mts.map +1 -1
  338. package/dist/service-adapters/bedrock/bedrock-adapter.mjs +1 -1
  339. package/dist/service-adapters/bedrock/bedrock-adapter.mjs.map +1 -1
  340. package/dist/service-adapters/empty/empty-adapter.cjs +1 -1
  341. package/dist/service-adapters/empty/empty-adapter.cjs.map +1 -1
  342. package/dist/service-adapters/empty/empty-adapter.d.cts +2 -2
  343. package/dist/service-adapters/empty/empty-adapter.d.cts.map +1 -1
  344. package/dist/service-adapters/empty/empty-adapter.d.mts +2 -2
  345. package/dist/service-adapters/empty/empty-adapter.d.mts.map +1 -1
  346. package/dist/service-adapters/empty/empty-adapter.mjs +1 -1
  347. package/dist/service-adapters/empty/empty-adapter.mjs.map +1 -1
  348. package/dist/service-adapters/events.cjs +1 -1
  349. package/dist/service-adapters/events.cjs.map +1 -1
  350. package/dist/service-adapters/events.d.cts +2 -2
  351. package/dist/service-adapters/events.d.cts.map +1 -1
  352. package/dist/service-adapters/events.d.mts +2 -2
  353. package/dist/service-adapters/events.d.mts.map +1 -1
  354. package/dist/service-adapters/events.mjs +1 -1
  355. package/dist/service-adapters/events.mjs.map +1 -1
  356. package/dist/service-adapters/experimental/ollama/ollama-adapter.cjs +1 -1
  357. package/dist/service-adapters/experimental/ollama/ollama-adapter.cjs.map +1 -1
  358. package/dist/service-adapters/experimental/ollama/ollama-adapter.d.cts +2 -2
  359. package/dist/service-adapters/experimental/ollama/ollama-adapter.d.cts.map +1 -1
  360. package/dist/service-adapters/experimental/ollama/ollama-adapter.d.mts +2 -2
  361. package/dist/service-adapters/experimental/ollama/ollama-adapter.d.mts.map +1 -1
  362. package/dist/service-adapters/experimental/ollama/ollama-adapter.mjs +1 -1
  363. package/dist/service-adapters/experimental/ollama/ollama-adapter.mjs.map +1 -1
  364. package/dist/service-adapters/google/google-genai-adapter.cjs +1 -1
  365. package/dist/service-adapters/google/google-genai-adapter.cjs.map +1 -1
  366. package/dist/service-adapters/google/google-genai-adapter.d.cts +2 -2
  367. package/dist/service-adapters/google/google-genai-adapter.d.cts.map +1 -1
  368. package/dist/service-adapters/google/google-genai-adapter.d.mts +2 -2
  369. package/dist/service-adapters/google/google-genai-adapter.d.mts.map +1 -1
  370. package/dist/service-adapters/google/google-genai-adapter.mjs +1 -1
  371. package/dist/service-adapters/google/google-genai-adapter.mjs.map +1 -1
  372. package/dist/service-adapters/groq/groq-adapter.cjs +1 -1
  373. package/dist/service-adapters/groq/groq-adapter.cjs.map +1 -1
  374. package/dist/service-adapters/groq/groq-adapter.d.cts +5 -5
  375. package/dist/service-adapters/groq/groq-adapter.d.cts.map +1 -1
  376. package/dist/service-adapters/groq/groq-adapter.d.mts +6 -5
  377. package/dist/service-adapters/groq/groq-adapter.d.mts.map +1 -1
  378. package/dist/service-adapters/groq/groq-adapter.mjs +1 -1
  379. package/dist/service-adapters/groq/groq-adapter.mjs.map +1 -1
  380. package/dist/service-adapters/index.d.cts +3 -3
  381. package/dist/service-adapters/index.d.mts +4 -4
  382. package/dist/service-adapters/langchain/langchain-adapter.cjs +1 -1
  383. package/dist/service-adapters/langchain/langchain-adapter.cjs.map +1 -1
  384. package/dist/service-adapters/langchain/langchain-adapter.d.cts +2 -2
  385. package/dist/service-adapters/langchain/langchain-adapter.d.cts.map +1 -1
  386. package/dist/service-adapters/langchain/langchain-adapter.d.mts +2 -2
  387. package/dist/service-adapters/langchain/langchain-adapter.d.mts.map +1 -1
  388. package/dist/service-adapters/langchain/langchain-adapter.mjs +1 -1
  389. package/dist/service-adapters/langchain/langchain-adapter.mjs.map +1 -1
  390. package/dist/service-adapters/langchain/langserve.cjs +1 -1
  391. package/dist/service-adapters/langchain/langserve.cjs.map +1 -1
  392. package/dist/service-adapters/langchain/langserve.d.cts +2 -2
  393. package/dist/service-adapters/langchain/langserve.d.cts.map +1 -1
  394. package/dist/service-adapters/langchain/langserve.d.mts +2 -2
  395. package/dist/service-adapters/langchain/langserve.d.mts.map +1 -1
  396. package/dist/service-adapters/langchain/langserve.mjs +1 -1
  397. package/dist/service-adapters/langchain/langserve.mjs.map +1 -1
  398. package/dist/service-adapters/langchain/types.d.cts +2 -2
  399. package/dist/service-adapters/langchain/types.d.cts.map +1 -1
  400. package/dist/service-adapters/langchain/types.d.mts +2 -2
  401. package/dist/service-adapters/langchain/types.d.mts.map +1 -1
  402. package/dist/service-adapters/langchain/utils.cjs +1 -1
  403. package/dist/service-adapters/langchain/utils.cjs.map +1 -1
  404. package/dist/service-adapters/langchain/utils.mjs +1 -1
  405. package/dist/service-adapters/langchain/utils.mjs.map +1 -1
  406. package/dist/service-adapters/openai/openai-adapter.cjs +1 -1
  407. package/dist/service-adapters/openai/openai-adapter.cjs.map +1 -1
  408. package/dist/service-adapters/openai/openai-adapter.d.cts +2 -2
  409. package/dist/service-adapters/openai/openai-adapter.d.cts.map +1 -1
  410. package/dist/service-adapters/openai/openai-adapter.d.mts +2 -2
  411. package/dist/service-adapters/openai/openai-adapter.d.mts.map +1 -1
  412. package/dist/service-adapters/openai/openai-adapter.mjs +1 -1
  413. package/dist/service-adapters/openai/openai-adapter.mjs.map +1 -1
  414. package/dist/service-adapters/openai/openai-assistant-adapter.cjs +1 -1
  415. package/dist/service-adapters/openai/openai-assistant-adapter.cjs.map +1 -1
  416. package/dist/service-adapters/openai/openai-assistant-adapter.d.cts +2 -2
  417. package/dist/service-adapters/openai/openai-assistant-adapter.d.cts.map +1 -1
  418. package/dist/service-adapters/openai/openai-assistant-adapter.d.mts +2 -2
  419. package/dist/service-adapters/openai/openai-assistant-adapter.d.mts.map +1 -1
  420. package/dist/service-adapters/openai/openai-assistant-adapter.mjs +1 -1
  421. package/dist/service-adapters/openai/openai-assistant-adapter.mjs.map +1 -1
  422. package/dist/service-adapters/openai/utils.cjs +1 -1
  423. package/dist/service-adapters/openai/utils.cjs.map +1 -1
  424. package/dist/service-adapters/openai/utils.mjs +1 -1
  425. package/dist/service-adapters/openai/utils.mjs.map +1 -1
  426. package/dist/service-adapters/service-adapter.d.cts +2 -2
  427. package/dist/service-adapters/service-adapter.d.cts.map +1 -1
  428. package/dist/service-adapters/service-adapter.d.mts +2 -2
  429. package/dist/service-adapters/service-adapter.d.mts.map +1 -1
  430. package/dist/service-adapters/shared/error-utils.cjs +1 -1
  431. package/dist/service-adapters/shared/error-utils.cjs.map +1 -1
  432. package/dist/service-adapters/shared/error-utils.d.cts +2 -2
  433. package/dist/service-adapters/shared/error-utils.d.cts.map +1 -1
  434. package/dist/service-adapters/shared/error-utils.d.mts +2 -2
  435. package/dist/service-adapters/shared/error-utils.d.mts.map +1 -1
  436. package/dist/service-adapters/shared/error-utils.mjs +1 -1
  437. package/dist/service-adapters/shared/error-utils.mjs.map +1 -1
  438. package/dist/service-adapters/shared/index.d.mts +2 -2
  439. package/dist/service-adapters/shared/sdk-client-utils.cjs +1 -1
  440. package/dist/service-adapters/shared/sdk-client-utils.cjs.map +1 -1
  441. package/dist/service-adapters/shared/sdk-client-utils.d.cts +22 -3
  442. package/dist/service-adapters/shared/sdk-client-utils.d.cts.map +1 -1
  443. package/dist/service-adapters/shared/sdk-client-utils.d.mts +22 -3
  444. package/dist/service-adapters/shared/sdk-client-utils.d.mts.map +1 -1
  445. package/dist/service-adapters/shared/sdk-client-utils.mjs +1 -1
  446. package/dist/service-adapters/shared/sdk-client-utils.mjs.map +1 -1
  447. package/dist/service-adapters/unify/unify-adapter.cjs +1 -1
  448. package/dist/service-adapters/unify/unify-adapter.cjs.map +1 -1
  449. package/dist/service-adapters/unify/unify-adapter.d.cts +2 -2
  450. package/dist/service-adapters/unify/unify-adapter.d.cts.map +1 -1
  451. package/dist/service-adapters/unify/unify-adapter.d.mts +2 -2
  452. package/dist/service-adapters/unify/unify-adapter.d.mts.map +1 -1
  453. package/dist/service-adapters/unify/unify-adapter.mjs +1 -1
  454. package/dist/service-adapters/unify/unify-adapter.mjs.map +1 -1
  455. package/dist/utils/failed-response-status-reasons.cjs +1 -1
  456. package/dist/utils/failed-response-status-reasons.cjs.map +1 -1
  457. package/dist/utils/failed-response-status-reasons.d.cts +2 -2
  458. package/dist/utils/failed-response-status-reasons.d.cts.map +1 -1
  459. package/dist/utils/failed-response-status-reasons.d.mts +2 -2
  460. package/dist/utils/failed-response-status-reasons.d.mts.map +1 -1
  461. package/dist/utils/failed-response-status-reasons.mjs +1 -1
  462. package/dist/utils/failed-response-status-reasons.mjs.map +1 -1
  463. package/dist/v2/express.d.cts +1 -1
  464. package/dist/v2/express.d.mts +1 -1
  465. package/dist/v2/hono.d.cts +1 -1
  466. package/dist/v2/hono.d.mts +1 -1
  467. package/dist/v2/index.d.cts +1 -1
  468. package/dist/v2/index.d.mts +1 -1
  469. package/dist/v2/node.d.cts +1 -1
  470. package/dist/v2/node.d.mts +1 -1
  471. package/dist/v2/runtime/core/channel-activation-config.cjs.map +1 -1
  472. package/dist/v2/runtime/core/channel-activation-config.d.cts +3 -3
  473. package/dist/v2/runtime/core/channel-activation-config.d.cts.map +1 -1
  474. package/dist/v2/runtime/core/channel-activation-config.d.mts +3 -3
  475. package/dist/v2/runtime/core/channel-activation-config.d.mts.map +1 -1
  476. package/dist/v2/runtime/core/channel-activation-config.mjs.map +1 -1
  477. package/dist/v2/runtime/core/channel-manager.cjs.map +1 -1
  478. package/dist/v2/runtime/core/channel-manager.d.cts +3 -3
  479. package/dist/v2/runtime/core/channel-manager.d.cts.map +1 -1
  480. package/dist/v2/runtime/core/channel-manager.d.mts +3 -3
  481. package/dist/v2/runtime/core/channel-manager.d.mts.map +1 -1
  482. package/dist/v2/runtime/core/channel-manager.mjs.map +1 -1
  483. package/dist/v2/runtime/core/debug-event-bus.d.cts +1 -1
  484. package/dist/v2/runtime/core/debug-event-bus.d.mts +1 -1
  485. package/dist/v2/runtime/core/fetch-cors.d.cts +1 -1
  486. package/dist/v2/runtime/core/fetch-cors.d.mts +1 -1
  487. package/dist/v2/runtime/core/fetch-handler.cjs +1 -1
  488. package/dist/v2/runtime/core/fetch-handler.cjs.map +1 -1
  489. package/dist/v2/runtime/core/fetch-handler.d.cts +1 -1
  490. package/dist/v2/runtime/core/fetch-handler.d.mts +1 -1
  491. package/dist/v2/runtime/core/fetch-handler.mjs +1 -1
  492. package/dist/v2/runtime/core/fetch-handler.mjs.map +1 -1
  493. package/dist/v2/runtime/core/hooks.d.cts +1 -1
  494. package/dist/v2/runtime/core/hooks.d.mts +1 -1
  495. package/dist/v2/runtime/core/learning.d.cts +1 -1
  496. package/dist/v2/runtime/core/learning.d.mts +1 -1
  497. package/dist/v2/runtime/core/middleware-sse-parser.d.cts +1 -1
  498. package/dist/v2/runtime/core/middleware-sse-parser.d.mts +1 -1
  499. package/dist/v2/runtime/core/middleware.d.cts +1 -1
  500. package/dist/v2/runtime/core/middleware.d.mts +1 -1
  501. package/dist/v2/runtime/core/runtime.cjs +1 -0
  502. package/dist/v2/runtime/core/runtime.cjs.map +1 -1
  503. package/dist/v2/runtime/core/runtime.d.cts +1 -1
  504. package/dist/v2/runtime/core/runtime.d.cts.map +1 -1
  505. package/dist/v2/runtime/core/runtime.d.mts +1 -1
  506. package/dist/v2/runtime/core/runtime.d.mts.map +1 -1
  507. package/dist/v2/runtime/core/runtime.mjs +2 -1
  508. package/dist/v2/runtime/core/runtime.mjs.map +1 -1
  509. package/dist/v2/runtime/endpoints/express-single.d.cts +1 -1
  510. package/dist/v2/runtime/endpoints/express-single.d.mts +1 -1
  511. package/dist/v2/runtime/endpoints/express.d.cts +1 -1
  512. package/dist/v2/runtime/endpoints/express.d.mts +1 -1
  513. package/dist/v2/runtime/endpoints/hono-single.d.cts +1 -1
  514. package/dist/v2/runtime/endpoints/hono-single.d.mts +1 -1
  515. package/dist/v2/runtime/endpoints/hono.d.cts +1 -1
  516. package/dist/v2/runtime/endpoints/hono.d.mts +1 -1
  517. package/dist/v2/runtime/endpoints/index.d.cts +1 -1
  518. package/dist/v2/runtime/endpoints/index.d.mts +1 -1
  519. package/dist/v2/runtime/endpoints/node-fetch-handler.d.cts +1 -1
  520. package/dist/v2/runtime/endpoints/node-fetch-handler.d.mts +1 -1
  521. package/dist/v2/runtime/endpoints/node.d.cts +1 -1
  522. package/dist/v2/runtime/endpoints/node.d.mts +1 -1
  523. package/dist/v2/runtime/express.d.cts +1 -1
  524. package/dist/v2/runtime/express.d.mts +1 -1
  525. package/dist/v2/runtime/handlers/header-utils.d.cts +1 -1
  526. package/dist/v2/runtime/handlers/header-utils.d.mts +1 -1
  527. package/dist/v2/runtime/handlers/intelligence/memories.cjs +1 -1
  528. package/dist/v2/runtime/handlers/intelligence/memories.cjs.map +1 -1
  529. package/dist/v2/runtime/handlers/intelligence/memories.mjs +1 -1
  530. package/dist/v2/runtime/handlers/intelligence/memories.mjs.map +1 -1
  531. package/dist/v2/runtime/handlers/intelligence/threads.cjs +1 -1
  532. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -1
  533. package/dist/v2/runtime/handlers/intelligence/threads.mjs +1 -1
  534. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -1
  535. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +1 -1
  536. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  537. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +1 -1
  538. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  539. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -1
  540. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -1
  541. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -1
  542. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -1
  543. package/dist/v2/runtime/hono.d.cts +1 -1
  544. package/dist/v2/runtime/hono.d.mts +1 -1
  545. package/dist/v2/runtime/index.d.cts +1 -1
  546. package/dist/v2/runtime/index.d.mts +1 -1
  547. package/dist/v2/runtime/intelligence-platform/client.cjs +8 -8
  548. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -1
  549. package/dist/v2/runtime/intelligence-platform/client.d.cts +11 -11
  550. package/dist/v2/runtime/intelligence-platform/client.d.mts +11 -11
  551. package/dist/v2/runtime/intelligence-platform/client.mjs +8 -8
  552. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -1
  553. package/dist/v2/runtime/intelligence-platform/index.d.mts +1 -1
  554. package/dist/v2/runtime/node.d.cts +1 -1
  555. package/dist/v2/runtime/node.d.mts +1 -1
  556. package/dist/v2/runtime/runner/agent-runner.d.cts +1 -1
  557. package/dist/v2/runtime/runner/agent-runner.d.mts +1 -1
  558. package/dist/v2/runtime/runner/in-memory.cjs +3 -3
  559. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -1
  560. package/dist/v2/runtime/runner/in-memory.d.cts +5 -5
  561. package/dist/v2/runtime/runner/in-memory.d.mts +5 -5
  562. package/dist/v2/runtime/runner/in-memory.mjs +3 -3
  563. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -1
  564. package/dist/v2/runtime/runner/index.d.cts +1 -1
  565. package/dist/v2/runtime/runner/index.d.mts +1 -1
  566. package/dist/v2/runtime/runner/intelligence.d.cts +1 -1
  567. package/dist/v2/runtime/runner/intelligence.d.mts +1 -1
  568. package/dist/v2/runtime/telemetry/telemetry-client.mjs +1 -1
  569. package/dist/v2/runtime/transcription-service/transcription-service.d.cts +1 -1
  570. package/dist/v2/runtime/transcription-service/transcription-service.d.mts +1 -1
  571. package/package.json +7 -6
  572. package/skills/runtime/SKILL.md +1 -1
  573. package/skills/runtime/references/agent-runners-custom.md +1 -1
  574. package/skills/runtime/references/agent-runners.md +11 -5
  575. package/skills/runtime/references/built-in-agent-factory-modes.md +1 -1
  576. package/skills/runtime/references/built-in-agent-model-identifiers.md +3 -4
  577. package/skills/runtime/references/intelligence-mode.md +12 -13
  578. package/dist/channels/dist/index.d.cts +0 -10
  579. package/dist/channels/dist/index.d.cts.map +0 -1
  580. package/dist/channels/dist/index.d.mts +0 -10
  581. package/dist/channels/dist/index.d.mts.map +0 -1
  582. package/dist/runtime/package.mjs.map +0 -1
@@ -91,7 +91,7 @@ function parseRecallBody(body) {
91
91
  };
92
92
  }
93
93
  /**
94
- * Lists the resolved user's long-term memories via the Intelligence platform.
94
+ * Lists the resolved user's long-term memories via CopilotKit Intelligence.
95
95
  *
96
96
  * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`
97
97
  * runtime, resolves the user with `identifyUser` (never trusting a
@@ -1 +1 @@
1
- {"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","PlatformRequestError","errorResponse","isIntelligenceRuntime"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n return resolveWebMemory(runtime, request, user, \"client\");\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via the Intelligence platform.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KAAK,CAAE,QAAO;AACpC,QAAOC,uCAAiB,SAAS,SAAS,MAAM,SAAS;;AAG3D,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiBC,qCAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,OAAO,UAAU,OAAO,IAAI,UAAU,OAAO,UAAU,IACzD,QAAOC,oCAAc,SAAS,OAAO;AAEvC,SAAOA,oCAAc,SAAS,IAAI;;AAEpC,QAAOA,oCAAc,SAAS,IAAI;;AAGpC,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wCAAwC;AACrE,SAAOA,oCAAc,wBAAwB,IAAI;;;;;;;AAQrD,SAAS,gBAAgB,MAOZ;CACX,MAAM,EAAE,SAAS,MAAM,OAAO,oBAAoB;AAClD,KAAI,OAAO,YAAY,YAAY,OAAO,SAAS,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C,KAAI,CAACI,wCAAsB,QAAQ,CACjC,QAAOD,oCAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAIH,wCAAkB,OAAO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
1
+ {"version":3,"file":"memories.cjs","names":["resolveIntelligenceUser","isHandlerResponse","resolveWebMemory","PlatformRequestError","errorResponse","isIntelligenceRuntime"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n return resolveWebMemory(runtime, request, user, \"client\");\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via CopilotKit Intelligence.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAMA,0DAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAIC,wCAAkB,KA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parseRecallBody(body) {
90
90
  };
91
91
  }
92
92
  /**
93
- * Lists the resolved user's long-term memories via the Intelligence platform.
93
+ * Lists the resolved user's long-term memories via CopilotKit Intelligence.
94
94
  *
95
95
  * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`
96
96
  * runtime, resolves the user with `identifyUser` (never trusting a
@@ -1 +1 @@
1
- {"version":3,"file":"memories.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n return resolveWebMemory(runtime, request, user, \"client\");\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via the Intelligence platform.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;AACpC,QAAO,iBAAiB,SAAS,SAAS,MAAM,SAAS;;AAG3D,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiB,sBAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,O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QAAO;EAEtC,MAAM,OAAO,MAAM,QAAQ,aAAa,aAAa;GACnD,QAAQ,OAAO,KAAK;GACpB,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACvD,IAAI;GACJ,GAAG;GACJ,CAAC;AACF,SAAO,SAAS,KAAK,KAAK;UACnB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B;;;;;;;AAQhE,eAAsB,mBAAmB,EACvC,SACA,SACA,YAC0C;AAC1C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cAAc,8BAA8B,IAAI;AAEzD,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,SAAS,QAAQ;AAC1D,MAAI,kBAAkB,OAAO,CAAE,QAAO;AAEtC,QAAM,QAAQ,aAAa,aAAa;GACtC,QAAQ,OAAO,KAAK;GACpB,IAAI;GACJ,GAAI,QAAQ,SAAS,EAAE,aAAa,OAAO,OAAO,GAAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
1
+ {"version":3,"file":"memories.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/memories.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { resolveWebMemory } from \"../shared/memory-policy\";\nimport { PlatformRequestError } from \"../../intelligence-platform/client\";\n\ninterface MemoriesHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface MemoryMutationParams extends MemoriesHandlerParams {\n memoryId: string;\n}\n\nasync function resolveClientMemory(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n) {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n return resolveWebMemory(runtime, request, user, \"client\");\n}\n\nconst MISSING_INTELLIGENCE_MESSAGE =\n \"Missing CopilotKitIntelligence configuration. Memory operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\";\n\n/** Allowed `kind` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_KINDS: ReadonlySet<string> = new Set([\n \"topical\",\n \"episodic\",\n \"operational\",\n]);\n/** Allowed `scope` vocabulary the platform's memory endpoints accept. */\nconst MEMORY_SCOPES: ReadonlySet<string> = new Set([\"user\", \"project\"]);\n\n/**\n * Maps a thrown error to a `Response`.\n *\n * For a {@link PlatformRequestError}, forward only client-actionable **4xx**\n * statuses verbatim (e.g. 404 missing/wrong-scope memory, 409 conflict, 422\n * unprocessable) so a `useMemories` consumer can branch on them — a flat 500\n * would erase that distinction. A platform **5xx** (or any non-4xx / malformed\n * status) means the runtime is healthy but its dependency failed, so it surfaces\n * as `502 Bad Gateway` rather than echoing the upstream status as if the runtime\n * itself broke — and this also avoids a `new Response(..., { status })`\n * `RangeError` on an out-of-range status. Non-platform throws stay 500.\n */\nfunction memoryErrorResponse(error: unknown, message: string): Response {\n if (error instanceof PlatformRequestError) {\n const { status } = error;\n if (Number.isInteger(status) && status >= 400 && status <= 499) {\n return errorResponse(message, status);\n }\n return errorResponse(message, 502);\n }\n return errorResponse(message, 500);\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in memory request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\n/**\n * Extracts and validates the create/supersede body fields the platform's\n * memory endpoints require. Returns a `Response` (400) on invalid input.\n */\nfunction parseMemoryBody(body: Record<string, unknown>):\n | {\n content: string;\n kind: string;\n scope?: string;\n sourceThreadIds?: string[];\n }\n | Response {\n const { content, kind, scope, sourceThreadIds } = body;\n if (typeof content !== \"string\" || typeof kind !== \"string\") {\n return errorResponse(\"Memory requires string `content` and `kind`\", 400);\n }\n // `kind` must be one of the platform's known kinds. Reject an out-of-vocabulary\n // value here rather than forwarding it for the platform to reject.\n if (!MEMORY_KINDS.has(kind)) {\n return errorResponse(\n \"Memory `kind` must be one of: topical, episodic, operational\",\n 400,\n );\n }\n // `scope` is optional: when omitted the platform applies its default\n // (`\"user\"`). Only reject a present-but-wrong-typed scope.\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Memory `scope` must be a string when provided\", 400);\n }\n // When `scope` is present, it must be one of the known scopes.\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Memory `scope` must be one of: user, project\", 400);\n }\n // `sourceThreadIds` is optional, but when present it must be a string array.\n // Validate every element so non-string ids are not forwarded to the platform.\n if (\n sourceThreadIds !== undefined &&\n (!Array.isArray(sourceThreadIds) ||\n !sourceThreadIds.every((id) => typeof id === \"string\"))\n ) {\n return errorResponse(\n \"Memory `sourceThreadIds` must be an array of strings when provided\",\n 400,\n );\n }\n return {\n content,\n kind,\n ...(typeof scope === \"string\" ? { scope } : {}),\n ...(Array.isArray(sourceThreadIds)\n ? { sourceThreadIds: sourceThreadIds as string[] }\n : {}),\n // `sourceThreadIds` elements are validated as strings above; the cast is safe.\n };\n}\n\n/**\n * Validates the recall body: `query` required non-empty string (trimmed);\n * `limit` optional finite positive integer; `scope` optional and in the known\n * scopes. Returns a 400 Response on invalid input. The returned `query` is the\n * trimmed value so a whitespace-padded query is never forwarded to the platform.\n */\nfunction parseRecallBody(\n body: Record<string, unknown>,\n): { query: string; limit?: number; scope?: string } | Response {\n const { query, limit, scope } = body;\n // Trim before the emptiness check so whitespace-only queries (e.g. \" \")\n // are rejected rather than forwarded as a useless query to the platform.\n const trimmedQuery = typeof query === \"string\" ? query.trim() : query;\n if (typeof trimmedQuery !== \"string\" || trimmedQuery.length === 0) {\n return errorResponse(\"Recall requires a non-empty string `query`\", 400);\n }\n // When provided, `limit` must be a finite positive integer. `Number.isInteger`\n // already rejects NaN, Infinity, and fractions (NaN/Infinity would otherwise\n // JSON-serialize to `null` and silently corrupt the forwarded request);\n // the `> 0` guard rejects zero and negatives.\n if (\n limit !== undefined &&\n !(typeof limit === \"number\" && Number.isInteger(limit) && limit > 0)\n ) {\n return errorResponse(\"Recall `limit` must be a positive integer\", 400);\n }\n if (scope !== undefined && typeof scope !== \"string\") {\n return errorResponse(\"Recall `scope` must be a string when provided\", 400);\n }\n if (typeof scope === \"string\" && !MEMORY_SCOPES.has(scope)) {\n return errorResponse(\"Recall `scope` must be one of: user, project\", 400);\n }\n return {\n query: trimmedQuery,\n ...(typeof limit === \"number\" ? { limit } : {}),\n ...(typeof scope === \"string\" ? { scope } : {}),\n };\n}\n\n/**\n * Lists the resolved user's long-term memories via CopilotKit Intelligence.\n *\n * Mirrors {@link handleListThreads}: requires a `CopilotKitIntelligence`\n * runtime, resolves the user with `identifyUser` (never trusting a\n * client-supplied id), and proxies to the platform's `GET /api/memories`\n * with the project API key + resolved user. The `?includeInvalidated=true`\n * query is forwarded so callers can opt into retired rows. The response is\n * the platform's `{ memories }` envelope, which the client memory store\n * consumes directly.\n */\nexport async function handleListMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const includeInvalidated =\n url.searchParams.get(\"includeInvalidated\") === \"true\";\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.listMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...(includeInvalidated ? { includeInvalidated: true } : {}),\n });\n\n // The client memory store consumes the `{ memories: [...] }` envelope\n // directly. Assert the shape before forwarding so a platform contract\n // violation surfaces as a clear 502 (the runtime is healthy but its\n // dependency returned the wrong shape) instead of a 200 the client will\n // choke on.\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"listMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid list response\",\n 502,\n );\n }\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing memories\");\n return memoryErrorResponse(error, \"Failed to list memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Semantically recalls the resolved user's memories via the platform (`POST\n * /api/memories/recall`, hybrid RAG). Mirrors {@link handleListMemories}:\n * requires a `CopilotKitIntelligence` runtime, resolves the user with\n * `identifyUser` (never a client-supplied id), proxies with the project API\n * key + resolved user. Body `{ query, limit?, scope? }`; response `{ memories }`,\n * each optionally carrying `score`.\n */\nexport async function handleRecallMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseRecallBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.recallMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n\n if (\n data == null ||\n typeof data !== \"object\" ||\n !Array.isArray((data as { memories?: unknown }).memories)\n ) {\n logger.error(\n { data },\n \"recallMemories: platform returned a response without a `memories` array\",\n );\n return errorResponse(\n \"Memory platform returned an invalid recall response\",\n 502,\n );\n }\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error recalling memories\");\n return memoryErrorResponse(error, \"Failed to recall memories\");\n }\n}\n\n/**\n * Mints memory-realtime join credentials (platform `POST\n * /api/memories/subscribe`). Mirrors {@link handleSubscribeToThreads}: requires\n * a `CopilotKitIntelligence` runtime and resolves the user with `identifyUser`\n * (never a client-supplied id). Returns `{ joinToken, joinCode }` — memory needs\n * the `joinCode` here (unlike threads, where it rides the thread-list response)\n * because the client builds the `user_meta:memories:<joinCode>` channel topic\n * from it.\n *\n * When the platform also resolves a project scope, the response additionally\n * carries `projectJoinToken` / `projectJoinCode`, which the client uses to open\n * a second `project_meta:memories:<projectJoinCode>` channel. These are\n * optional: absent project scope → both fields are omitted (silent-degrade\n * contract; the client opens only the user channel).\n */\nexport async function handleSubscribeToMemories({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (isIntelligenceRuntime(runtime)) {\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const credentials = await runtime.intelligence.ɵsubscribeToMemories({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n\n return Response.json({\n ...(credentials.joinToken !== undefined\n ? { joinToken: credentials.joinToken }\n : {}),\n ...(credentials.joinCode !== undefined\n ? { joinCode: credentials.joinCode }\n : {}),\n // Project-scoped credentials ride along only when the platform minted\n // them; omit both when absent (silent-degrade contract).\n ...(credentials.projectJoinToken !== undefined\n ? { projectJoinToken: credentials.projectJoinToken }\n : {}),\n ...(credentials.projectJoinCode !== undefined\n ? { projectJoinCode: credentials.projectJoinCode }\n : {}),\n });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to memories\");\n return memoryErrorResponse(error, \"Failed to subscribe to memories\");\n }\n }\n\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n}\n\n/**\n * Creates a memory for the resolved user (platform `POST /api/memories`).\n * Identity comes from `identifyUser`, never the request body. Returns 201\n * with the stored memory (the client store applies it server-authoritatively).\n */\nexport async function handleCreateMemory({\n runtime,\n request,\n}: MemoriesHandlerParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.createMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n ...fields,\n });\n return Response.json(data, { status: 201 });\n } catch (error) {\n logger.error({ err: error }, \"Error creating memory\");\n return memoryErrorResponse(error, \"Failed to create memory\");\n }\n}\n\n/**\n * Supersedes a memory (platform `PATCH /api/memories/:id`): retires `:id` and\n * inserts the new content atomically; the response carries `retiredId`.\n */\nexport async function handleUpdateMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n const fields = parseMemoryBody(body);\n if (isHandlerResponse(fields)) return fields;\n\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n const data = await runtime.intelligence.updateMemory({\n userId: access.user.id,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n id: memoryId,\n ...fields,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error updating memory\");\n return memoryErrorResponse(error, \"Failed to update memory\");\n }\n}\n\n/**\n * Retires (forgets) a memory (platform `DELETE /api/memories/:id`). Non-lossy\n * on the platform side; returns 204.\n */\nexport async function handleRemoveMemory({\n runtime,\n request,\n memoryId,\n}: MemoryMutationParams): Promise<Response> {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(MISSING_INTELLIGENCE_MESSAGE, 422);\n }\n try {\n const access = await resolveClientMemory(runtime, request);\n if (isHandlerResponse(access)) return access;\n\n await runtime.intelligence.removeMemory({\n userId: access.user.id,\n id: memoryId,\n ...(runtime.memory ? { memoryGrant: access.grant } : {}),\n });\n return new Response(null, { status: 204 });\n } catch (error) {\n logger.error({ err: error }, \"Error removing memory\");\n return memoryErrorResponse(error, \"Failed to remove memory\");\n }\n}\n"],"mappings":";;;;;;;;;AAoBA,eAAe,oBACb,SACA,SACA;CACA,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;AACpC,QAAO,iBAAiB,SAAS,SAAS,MAAM,SAAS;;AAG3D,MAAM,+BACJ;;AAGF,MAAM,eAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACD,CAAC;;AAEF,MAAM,gBAAqC,IAAI,IAAI,CAAC,QAAQ,UAAU,CAAC;;;;;;;;;;;;;AAcvE,SAAS,oBAAoB,OAAgB,SAA2B;AACtE,KAAI,iBAAiB,sBAAsB;EACzC,MAAM,EAAE,WAAW;AACnB,MAAI,OAAO,UAAU,OAAO,IAAI,UAAU,OAAO,UAAU,IACzD,QAAO,cAAc,SAAS,OAAO;AAEvC,SAAO,cAAc,SAAS,IAAI;;AAEpC,QAAO,cAAc,SAAS,IAAI;;AAGpC,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wCAAwC;AACrE,SAAO,cAAc,wBAAwB,IAAI;;;;;;;AAQrD,SAAS,gBAAgB,MAOZ;CACX,MAAM,EAAE,SAAS,MAAM,OAAO,oBAAoB;AAClD,KAAI,OAAO,YAAY,YAAY,OAAO,SAAS,SACjD,QAAO,cAAc,+CAA+C,IAAI;AAI1E,KAAI,CAAC,aAAa,IAAI,KAAK,CACzB,QAAO,cACL,gEACA,IACD;AAIH,KAAI,UAAU,UAAa,OAAO,UAAU,SAC1C,QAAO,cAAc,iDAAiD,IAAI;AAG5E,KAAI,OAAO,UAAU,YAAY,CAAC,cAAc,IAAI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AAG,EAAE;GACxD,CAAC;AACF,SAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,KAAK,CAAC;UACnC,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,wBAAwB;AACrD,SAAO,oBAAoB,OAAO,0BAA0B"}
@@ -77,7 +77,7 @@ async function handleListThreads({ runtime, request }) {
77
77
  *
78
78
  * The local-dev fallback exposes this so consumers (e.g. the demo's Clear
79
79
  * button) can wipe in-memory thread history without restarting the runtime.
80
- * Intentionally a no-op when the Intelligence platform is configured: real
80
+ * Intentionally a no-op when CopilotKit Intelligence is configured: real
81
81
  * thread history lives in the database and must not be wiped by a
82
82
  * client-side page load.
83
83
  */
@@ -1 +1 @@
1
- {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","supportsLocalThreadEndpoints"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,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ACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOL,oCAAc,gCAAgC,IAAI;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.cjs","names":["errorResponse","isIntelligenceRuntime","isHandlerResponse","resolveIntelligenceUser","isValidIdentifier","supportsLocalThreadEndpoints"],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,4BAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAOA,oCAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAACC,wCAAsB,QAAQ,CACjC,QAAOD,oCACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAIE,wCAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAMC,0DAAwB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tC,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,+BAA+B;AACtE,SAAOF,oCAAc,iCAAiC,IAAI;;AAK9D,KAAIK,kDAA6B,QAAQ,OAAO,CAC9C,KAAI;EACF,MAAM,SAAS,QAAQ,OAAO,gBAAgB,SAAS;AACvD,SAAO,SAAS,KAAK,EAAE,QAAQ,CAAC;UACzB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,+BAA+B;AACtE,SAAOL,oCAAc,iCAAiC,IAAI;;AAI9D,QAAOA,oCACL,uJACA,IACD;;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAIC,wCAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,OAAO,MAAME,0DAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAID,wCAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe,EAAE,UAAU,CAAC;EAMpE,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOF,oCAAc,gCAAgC,IAAI;;AAI7D,KAAIK,kDAA6B,QAAQ,OAAO,CAC9C,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,4BAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAOL,oCAAc,gCAAgC,IAAI;;AAI7D,QAAOA,oCACL,uJACA,IACD"}
@@ -76,7 +76,7 @@ async function handleListThreads({ runtime, request }) {
76
76
  *
77
77
  * The local-dev fallback exposes this so consumers (e.g. the demo's Clear
78
78
  * button) can wipe in-memory thread history without restarting the runtime.
79
- * Intentionally a no-op when the Intelligence platform is configured: real
79
+ * Intentionally a no-op when CopilotKit Intelligence is configured: real
80
80
  * thread history lives in the database and must not be wiped by a
81
81
  * client-side page load.
82
82
  */
@@ -1 +1 @@
1
- {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when the Intelligence platform is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape the Intelligence platform\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // Intelligence platform path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,C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O,gBAAgB,SAAS;AACvD,SAAO,SAAS,KAAK,EAAE,QAAQ,CAAC;UACzB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,+BAA+B;AACtE,SAAO,cAAc,iCAAiC,IAAI;;AAI9D,QAAO,cACL,uJACA,IACD;;AAGH,eAAsB,qBAAqB,EACzC,SACA,SACA,YAC0C;AAI1C,KAAI,sBAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,CAAC;AAChE,MAAI,kBAAkB,KAAK,CAAE,QAAO;EAEpC,MAAM,OAAO,MAAM,QAAQ,aAAa,eAAe,EAAE,UAAU,CAAC;EAMpE,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,KAAI,6BAA6B,QAAQ,OAAO,CAC9C,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,QAAO,cACL,uJACA,IACD"}
1
+ {"version":3,"file":"threads.mjs","names":[],"sources":["../../../../../src/v2/runtime/handlers/intelligence/threads.ts"],"sourcesContent":["import type {\n CopilotIntelligenceRuntimeLike,\n CopilotRuntimeLike,\n} from \"../../core/runtime\";\nimport { isIntelligenceRuntime } from \"../../core/runtime\";\nimport { logger } from \"@copilotkit/shared\";\nimport { errorResponse, isHandlerResponse } from \"../shared/json-response\";\nimport { isValidIdentifier } from \"../shared/intelligence-utils\";\nimport { resolveIntelligenceUser } from \"../shared/resolve-intelligence-user\";\nimport { supportsLocalThreadEndpoints } from \"../../runner/agent-runner\";\n\ninterface ThreadsHandlerParams {\n runtime: CopilotRuntimeLike;\n request: Request;\n}\n\ninterface ThreadMutationParams extends ThreadsHandlerParams {\n threadId: string;\n}\n\ninterface ThreadMutationContext {\n userId: string;\n agentId: string;\n body: Record<string, unknown>;\n}\n\nasync function parseJsonBody(\n request: Request,\n): Promise<Record<string, unknown> | Response> {\n try {\n return (await request.json()) as Record<string, unknown>;\n } catch (error) {\n logger.error({ err: error }, \"Malformed JSON in request body\");\n return errorResponse(\"Invalid request body\", 400);\n }\n}\n\nfunction requireIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): CopilotIntelligenceRuntimeLike | Response {\n if (!isIntelligenceRuntime(runtime)) {\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n }\n\n return runtime;\n}\n\nasync function resolveThreadMutationContext(\n runtime: CopilotIntelligenceRuntimeLike,\n request: Request,\n): Promise<ThreadMutationContext | Response> {\n const body = await parseJsonBody(request);\n if (isHandlerResponse(body)) return body;\n\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const agentId = body.agentId;\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId is required\", 400);\n }\n\n return {\n body,\n userId: user.id,\n agentId,\n };\n}\n\nexport async function handleListThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n const includeArchived =\n url.searchParams.get(\"includeArchived\") === \"true\";\n const limitParam = url.searchParams.get(\"limit\");\n const cursor = url.searchParams.get(\"cursor\");\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n if (!isValidIdentifier(agentId)) {\n return errorResponse(\"Valid agentId query param is required\", 400);\n }\n\n const data = await runtime.intelligence.listThreads({\n userId: user.id,\n agentId,\n ...(includeArchived ? { includeArchived: true } : {}),\n ...(limitParam ? { limit: Number(limitParam) } : {}),\n ...(cursor ? { cursor } : {}),\n });\n\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error }, \"Error listing threads\");\n return errorResponse(\"Failed to list threads\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const url = new URL(request.url);\n const agentId = url.searchParams.get(\"agentId\");\n let threads = runtime.runner.listThreads();\n if (agentId) {\n threads = threads.filter((t) => t.agentId === agentId);\n }\n return Response.json({ threads, nextCursor: null });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\n/**\n * Clears all in-memory thread history for the local-dev InMemory fallback.\n *\n * The local-dev fallback exposes this so consumers (e.g. the demo's Clear\n * button) can wipe in-memory thread history without restarting the runtime.\n * Intentionally a no-op when CopilotKit Intelligence is configured: real\n * thread history lives in the database and must not be wiped by a\n * client-side page load.\n */\nexport function handleClearThreads({\n runtime,\n}: ThreadsHandlerParams): Response {\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n runtime.runner.clearThreads();\n }\n return new Response(null, { status: 204 });\n}\n\nexport async function handleUpdateThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n const updates = { ...mutation.body };\n delete updates.agentId;\n delete updates.userId;\n\n const thread = await intelligenceRuntime.intelligence.updateThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n updates,\n });\n\n return Response.json(thread);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error updating thread\");\n return errorResponse(\"Failed to update thread\", 500);\n }\n}\n\nexport async function handleSubscribeToThreads({\n runtime,\n request,\n}: ThreadsHandlerParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const user = await resolveIntelligenceUser({\n runtime: intelligenceRuntime,\n request,\n });\n if (isHandlerResponse(user)) return user;\n\n const credentials =\n await intelligenceRuntime.intelligence.ɵsubscribeToThreads({\n userId: user.id,\n });\n\n return Response.json({ joinToken: credentials.joinToken });\n } catch (error) {\n logger.error({ err: error }, \"Error subscribing to threads\");\n return errorResponse(\"Failed to subscribe to threads\", 500);\n }\n}\n\nexport async function handleArchiveThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.archiveThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, archived: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error archiving thread\");\n return errorResponse(\"Failed to archive thread\", 500);\n }\n}\n\nexport async function handleDeleteThread({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n const intelligenceRuntime = requireIntelligenceRuntime(runtime);\n if (isHandlerResponse(intelligenceRuntime)) {\n return intelligenceRuntime;\n }\n\n try {\n const mutation = await resolveThreadMutationContext(\n intelligenceRuntime,\n request,\n );\n if (isHandlerResponse(mutation)) return mutation;\n\n await intelligenceRuntime.intelligence.deleteThread({\n threadId,\n userId: mutation.userId,\n agentId: mutation.agentId,\n });\n\n return Response.json({ threadId, deleted: true });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error deleting thread\");\n return errorResponse(\"Failed to delete thread\", 500);\n }\n}\n\nexport async function handleGetThreadMessages({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadMessages({\n threadId,\n userId: user.id,\n });\n return Response.json(data);\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread messages\");\n return errorResponse(\"Failed to fetch thread messages\", 500);\n }\n }\n\n // Local in-memory fallback — useful for local development without Intelligence\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n const messages = runtime.runner.getThreadMessages(threadId);\n // Map ag-ui Message objects to the same shape CopilotKit Intelligence\n // returns. Switching on the discriminant `role` lets each branch read\n // the narrowed message arm directly, instead of laundering through\n // `Record<string, unknown>` and chained `as` casts.\n const mapped = messages.map((msg) => {\n switch (msg.role) {\n case \"assistant\": {\n const toolCalls = msg.toolCalls ?? [];\n return {\n id: msg.id,\n role: msg.role,\n ...(msg.content !== undefined ? { content: msg.content } : {}),\n ...(toolCalls.length > 0\n ? {\n toolCalls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n args: tc.function.arguments,\n })),\n }\n : {}),\n };\n }\n case \"tool\":\n return {\n id: msg.id,\n role: msg.role,\n content: msg.content,\n toolCallId: msg.toolCallId,\n };\n default:\n return {\n id: msg.id,\n role: msg.role,\n ...(\"content\" in msg && msg.content !== undefined\n ? { content: msg.content }\n : {}),\n };\n }\n });\n return Response.json({ messages: mapped });\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadEvents({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // endpoint (Intelligence PR #144). Auth still flows through the standard\n // identifyUser → API key path; threadId scoping happens server-side.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadEvents({ threadId });\n // Strip platform-internal fields (`decodeErrorRowIds`, `truncated`)\n // before returning to the inspector — those describe persistence-side\n // concerns the inspector currently has no UI for. The shape becomes\n // `{ events }`, matching the in-memory branch below.\n return Response.json({ events: data.events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n // Local in-memory fallback\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const events = runtime.runner.getThreadEvents(threadId);\n return Response.json({ events });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread events\");\n return errorResponse(\"Failed to fetch thread events\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n\nexport async function handleGetThreadState({\n runtime,\n request,\n threadId,\n}: ThreadMutationParams): Promise<Response> {\n // CopilotKit Intelligence path. Delegates to the platform's `_inspect`\n // state endpoint, which folds STATE_DELTA events onto the latest\n // STATE_SNAPSHOT to return the thread's current state.\n if (isIntelligenceRuntime(runtime)) {\n try {\n const user = await resolveIntelligenceUser({ runtime, request });\n if (isHandlerResponse(user)) return user;\n\n const data = await runtime.intelligence.getThreadState({ threadId });\n // Flatten the discriminated `ThreadStateResult` to the wire shape the\n // inspector consumes (`{ state: <value> | null }`). Missing snapshot\n // and decode-error both surface as `null`; the inspector renders an\n // empty state branch for null and the platform's decode-error case is\n // already logged platform-side.\n const state = data.kind === \"snapshot\" ? data.state : null;\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n if (supportsLocalThreadEndpoints(runtime.runner)) {\n try {\n const state = runtime.runner.getThreadState(threadId);\n return Response.json({ state });\n } catch (error) {\n logger.error({ err: error, threadId }, \"Error fetching thread state\");\n return errorResponse(\"Failed to fetch thread state\", 500);\n }\n }\n\n return errorResponse(\n \"Missing CopilotKitIntelligence configuration. Thread operations require a CopilotKitIntelligence instance to be provided in CopilotRuntime options.\",\n 422,\n );\n}\n"],"mappings":";;;;;;;;;AA0BA,eAAe,cACb,SAC6C;AAC7C,KAAI;AACF,SAAQ,MAAM,QAAQ,MAAM;UACrB,OAAO;AACd,SAAO,MAAM,EAAE,KAAK,OAAO,EAAE,iCAAiC;AAC9D,SAAO,cAAc,wBAAwB,IAAI;;;AAIrD,SAAS,2BACP,SAC2C;AAC3C,KAAI,CAAC,sBAAsB,QAAQ,CACjC,QAAO,cACL,uJACA,IACD;AAGH,QAAO;;AAGT,eAAe,6BACb,SACA,SAC2C;CAC3C,MAAM,OAAO,MAAM,cAAc,QAAQ;AACzC,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,OAAO,MAAM,wBAAwB;EAAE;EAAS;EAAS,CAAC;AAChE,KAAI,kBAAkB,KAAK,CAAE,QAAO;CAEpC,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,kBAAkB,QAAQ,CAC7B,QAAO,cAAc,6BAA6B,IAAI;AAGxD,QAAO;EACL;EACA,QAAQ,KAAK;EACb;EACD;;AAGH,eAAsB,kBAAkB,EACtC,SACA,WAC0C;AAE1C,KAAI,sBAAsB,QAAQ,CAChC,KAAI;EACF,MAAM,MAAM,IAAI,IAAI,QAAQ,IAAI;EAChC,MAAM,UAAU,IAAI,aAAa,IAAI,UAAU;EAC/C,MAAM,kBACJ,IAAI,aAAa,IAAI,kBAAkB,KAAK;EAC9C,MAAM,aAAa,IAAI,aAAa,IAAI,QAAQ;EAChD,MAAM,SAAS,IAAI,aAAa,IAAI,SAAS;EAC7C,MAAM,OAAO,MAAM,wBAAwB;GAAE;GAAS;GAAS,C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pE,MAAM,QAAQ,KAAK,SAAS,aAAa,KAAK,QAAQ;AACtD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,KAAI,6BAA6B,QAAQ,OAAO,CAC9C,KAAI;EACF,MAAM,QAAQ,QAAQ,OAAO,eAAe,SAAS;AACrD,SAAO,SAAS,KAAK,EAAE,OAAO,CAAC;UACxB,OAAO;AACd,SAAO,MAAM;GAAE,KAAK;GAAO;GAAU,EAAE,8BAA8B;AACrE,SAAO,cAAc,gCAAgC,IAAI;;AAI7D,QAAO,cACL,uJACA,IACD"}
@@ -65,7 +65,7 @@ function configureAgentForRequest(params) {
65
65
  agent.headers = require_header_utils.mergeForwardableHeaders(agent.headers, request, runtime.forwardHeadersPolicy ?? require_header_utils.resolveForwardHeadersPolicy(void 0));
66
66
  }
67
67
  /**
68
- * Attach the Intelligence platform's MCP tools to the agent run when
68
+ * Attach CopilotKit Intelligence's MCP tools to the agent run when
69
69
  * `CopilotKitIntelligence` was constructed with
70
70
  * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the
71
71
  * tools are available uniformly across agent frameworks (not just
@@ -1 +1 @@
1
- {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","isIntelligenceRuntime","errorResponse","resolveIntelligenceUser","resolveWebMemory","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach the Intelligence platform's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAYhC;CACP,MAAM,EAAE,SAAS,SAAS,SAAS,2BAA2B;CAC9D,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAIC,sCAAe;GACjB,GAAG;GAIH,gBACE,mBAAmB,yBAAyB,OAAO;GACtD,CAAC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K,UACvC,OAAO,MACR,EACF,GACD,EAAE;GACP;EACF,CACF,CAAC,CACH;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
1
+ {"version":3,"file":"agent-utils.cjs","names":["resolveAgents","isA2UIEnabled","A2UIMiddleware","resolveMcpAppsServers","MCPAppsMiddleware","OpenGenerativeUIMiddleware","mergeForwardableHeaders","resolveForwardHeadersPolicy","isIntelligenceRuntime","errorResponse","resolveIntelligenceUser","resolveWebMemory","MCPMiddleware","INTELLIGENCE_USER_ID_HEADER","INTELLIGENCE_MEMORY_GRANT_HEADER","RunAgentInputSchema"],"sources":["../../../../../src/v2/runtime/handlers/shared/agent-utils.ts"],"sourcesContent":["import type { AbstractAgent, RunAgentInput } from \"@ag-ui/client\";\nimport { RunAgentInputSchema } from \"@ag-ui/client\";\nimport { A2UIMiddleware } from \"@ag-ui/a2ui-middleware\";\nimport { MCPAppsMiddleware } from \"@ag-ui/mcp-apps-middleware\";\nimport { MCPMiddleware } from \"@ag-ui/mcp-middleware\";\nimport type { CopilotRuntimeLike } from \"../../core/runtime\";\nimport {\n isA2UIEnabled,\n isIntelligenceRuntime,\n resolveAgents,\n} from \"../../core/runtime\";\nimport { OpenGenerativeUIMiddleware } from \"../../open-generative-ui-middleware\";\nimport {\n INTELLIGENCE_MEMORY_GRANT_HEADER,\n INTELLIGENCE_USER_ID_HEADER,\n} from \"../../intelligence-platform/client\";\nimport {\n mergeForwardableHeaders,\n resolveForwardHeadersPolicy,\n} from \"../header-utils\";\nimport { resolveMcpAppsServers } from \"./mcp-apps-servers\";\nimport { resolveIntelligenceUser } from \"./resolve-intelligence-user\";\nimport { resolveWebMemory } from \"./memory-policy\";\nimport { errorResponse } from \"./json-response\";\nimport { logger } from \"@copilotkit/shared\";\n\ntype MiddlewareCapableAgent = AbstractAgent & {\n use?: (middleware: unknown) => void;\n headers?: Record<string, string>;\n};\n\nexport interface RunAgentParameters {\n request: Request;\n runtime: CopilotRuntimeLike;\n agentId: string;\n}\n\nexport interface ConnectRequestBody extends RunAgentInput {\n lastSeenEventId?: string | null;\n}\n\n/**\n * Resolve `agentId` against the runtime's agents and return a per-request\n * clone of the matching agent.\n *\n * Dual return contract — both callers (`handle-run.ts`, `handle-connect.ts`)\n * depend on it:\n * - Returns a cloned `AbstractAgent` when the agent exists.\n * - Returns a 404 `Response` (`{ error: \"Agent not found\", ... }`) when the\n * agent is unknown. Callers MUST `instanceof Response`-check the result and\n * return it directly; this doubles as the connect/run path's agent-existence\n * guard, so skipping the check would let unknown agent ids slip through.\n *\n * The clone is what subsequent per-request mutation (middleware attach,\n * `agent.headers` merge) operates on, leaving the shared agent registration\n * untouched.\n */\nexport async function cloneAgentForRequest(\n runtime: CopilotRuntimeLike,\n agentId: string,\n request?: Request,\n): Promise<AbstractAgent | Response> {\n const agents = await resolveAgents(runtime.agents, request);\n\n if (!agents[agentId]) {\n return new Response(\n JSON.stringify({\n error: \"Agent not found\",\n message: `Agent '${agentId}' does not exist`,\n }),\n {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n return (agents[agentId] as AbstractAgent).clone() as AbstractAgent;\n}\n\nexport function configureAgentForRequest(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agentId: string;\n agent: AbstractAgent;\n /**\n * True when the React provider was given an A2UI catalog\n * (`<CopilotKit a2ui={{ catalog }}>`), forwarded per-run. A catalog alone is\n * enough to enable A2UI and inject the render tool — the developer no longer\n * has to also set `a2ui.injectA2UITool` on the runtime.\n */\n providerA2UIHasCatalog?: boolean;\n}): void {\n const { runtime, request, agentId, providerA2UIHasCatalog } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n // A2UI is on when the runtime explicitly enables it, OR when the provider\n // forwarded a catalog — but an explicit `enabled: false` always wins (we\n // provide a quick default, never override a deeper opt-out).\n const a2uiEnabledByCatalog =\n !!providerA2UIHasCatalog && runtime.a2ui?.enabled !== false;\n\n if (isA2UIEnabled(runtime.a2ui) || a2uiEnabledByCatalog) {\n // `enabled` is a CopilotKit-level switch, not an A2UIMiddleware option —\n // drop it (alongside the agent filter) before forwarding to the middleware.\n const {\n agents: targetAgents,\n enabled: _enabled,\n injectA2UITool,\n ...a2uiOptions\n } = runtime.a2ui ?? {};\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(\n new A2UIMiddleware({\n ...a2uiOptions,\n // Default render-tool injection on when a catalog is present and the\n // developer hasn't set it explicitly. `??` means an explicit value\n // (including `false`) is always respected.\n injectA2UITool:\n injectA2UITool ?? (providerA2UIHasCatalog ? true : undefined),\n }),\n );\n }\n }\n\n if (runtime.mcpApps?.servers?.length) {\n const mcpServers = resolveMcpAppsServers(runtime.mcpApps.servers, agentId);\n\n if (mcpServers.length > 0 && typeof agent.use === \"function\") {\n agent.use(new MCPAppsMiddleware({ mcpServers }));\n }\n }\n\n if (runtime.openGenerativeUI) {\n const config = runtime.openGenerativeUI;\n const targetAgents = typeof config === \"object\" ? config.agents : undefined;\n const shouldApply = !targetAgents || targetAgents.includes(agentId);\n if (shouldApply && typeof agent.use === \"function\") {\n agent.use(new OpenGenerativeUIMiddleware());\n }\n }\n\n // Forward eligible inbound headers onto the outgoing agent call under the\n // runtime's resolved forwarding policy (`authorization` / custom `x-*`, with\n // known infra/proxy/platform headers stripped by the default denylist —\n // #5712), but let headers the server explicitly configured on the agent WIN\n // on collision (case-insensitively): a server-set service-to-service token\n // (e.g. an IAM bearer) must never be silently overridden by a\n // browser/edge/platform-injected inbound header. See `mergeForwardableHeaders`\n // for the casing/duplicate-key rationale and `shouldForwardHeader` for breadth.\n agent.headers = mergeForwardableHeaders(\n agent.headers,\n request,\n // `forwardHeadersPolicy` is optional on the published `CopilotRuntimeLike`\n // interface (non-breaking minor release). Concrete runtimes always set it;\n // a policy-less external implementor falls back to the default resolved\n // policy (default-on denylist) so behavior stays identical and never derefs\n // undefined.\n runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(undefined),\n );\n}\n\n/**\n * Attach CopilotKit Intelligence's MCP tools to the agent run when\n * `CopilotKitIntelligence` was constructed with\n * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the\n * tools are available uniformly across agent frameworks (not just\n * `BuiltInAgent`).\n *\n * The middleware sits on a per-request agent clone, so the per-request\n * auth (Bearer apiKey + resolved user-id) is baked into the transport\n * headers at attach time. If user resolution fails, attachment is\n * skipped silently — the intelligence run handler will reject the\n * request with the same error. Note this means `identifyUser` is\n * resolved twice per learning-enabled run (here and in the run handler);\n * the callback is expected to be idempotent and side-effect-free.\n *\n * Intentionally split out from `configureAgentForRequest`: this is only\n * relevant to actual agent runs, not auxiliary flows like thread-name\n * generation (which has no need for MCP tools and shouldn't pay the\n * `listTools` round-trip).\n */\nexport async function attachIntelligenceEnterpriseLearning(params: {\n runtime: CopilotRuntimeLike;\n request: Request;\n agent: AbstractAgent;\n}): Promise<void | Response> {\n const { runtime, request } = params;\n const agent = params.agent as MiddlewareCapableAgent;\n\n if (\n !isIntelligenceRuntime(runtime) ||\n (runtime.memory === undefined &&\n !runtime.intelligence?.ɵisEnterpriseLearningEnabled?.())\n ) {\n return;\n }\n\n // Enterprise learning is enabled, but this agent's framework can't take\n // middleware — surface it rather than silently shipping a run with none\n // of the tools the operator opted into.\n if (typeof agent.use !== \"function\") {\n if (runtime.memory) {\n return errorResponse(\n \"Memory is configured, but this agent does not support middleware\",\n 500,\n );\n }\n logger.warn(\n \"CopilotKitIntelligence.enableEnterpriseLearning is enabled, but the agent \" +\n \"does not support middleware (no `.use()` method); Intelligence tools were \" +\n \"not attached for this run.\",\n );\n return;\n }\n\n const userResult = await resolveIntelligenceUser({ runtime, request });\n if (userResult instanceof Response) return userResult;\n const access = await resolveWebMemory(runtime, request, userResult, \"agent\");\n if (access instanceof Response) return access;\n\n agent.use(\n new MCPMiddleware([\n {\n type: \"http\",\n url: `${runtime.intelligence.ɵgetApiUrl()}/mcp`,\n serverId: \"intelligence\",\n headers: {\n Authorization: `Bearer ${runtime.intelligence.ɵgetApiKey()}`,\n [INTELLIGENCE_USER_ID_HEADER]: userResult.id,\n ...(runtime.memory\n ? {\n [INTELLIGENCE_MEMORY_GRANT_HEADER]: JSON.stringify(\n access.grant,\n ),\n }\n : {}),\n },\n },\n ]),\n );\n}\n\nexport async function parseRunRequest(\n request: Request,\n): Promise<RunAgentInput | Response> {\n try {\n const requestBody = await request.json();\n return RunAgentInputSchema.parse(requestBody);\n } catch (error) {\n logger.error(\"Invalid run request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nexport async function parseConnectRequest(request: Request): Promise<\n | Response\n | {\n input: RunAgentInput;\n lastSeenEventId: string | null;\n }\n> {\n try {\n const requestBody = await request.json();\n const input = RunAgentInputSchema.parse(requestBody);\n let lastSeenEventId: string | null = null;\n\n if (\n \"lastSeenEventId\" in (requestBody as Record<string, unknown>) &&\n (typeof (requestBody as Record<string, unknown>).lastSeenEventId ===\n \"string\" ||\n (requestBody as Record<string, unknown>).lastSeenEventId === null)\n ) {\n lastSeenEventId =\n (requestBody as ConnectRequestBody).lastSeenEventId ?? null;\n }\n\n return { input, lastSeenEventId };\n } catch (error) {\n logger.error(\"Invalid connect request body:\", error);\n return new Response(\n JSON.stringify({\n error: \"Invalid request body\",\n details: error instanceof Error ? error.message : String(error),\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,eAAsB,qBACpB,SACA,SACA,SACmC;CACnC,MAAM,SAAS,MAAMA,gCAAc,QAAQ,QAAQ,QAAQ;AAE3D,KAAI,CAAC,OAAO,SACV,QAAO,IAAI,SACT,KAAK,UAAU;EACb,OAAO;EACP,SAAS,UAAU,QAAQ;EAC5B,CAAC,EACF;EACE,QAAQ;EACR,SAAS,EAAE,gBAAgB,oBAAoB;EAChD,CACF;AAGH,QAAQ,OAAO,SAA2B,OAAO;;AAGnD,SAAgB,yBAAyB,QAYhC;CACP,MAAM,EAAE,SAAS,SAAS,SAAS,2BAA2B;CAC9D,MAAM,QAAQ,OAAO;CAKrB,MAAM,uBACJ,CAAC,CAAC,0BAA0B,QAAQ,MAAM,YAAY;AAExD,KAAIC,gCAAc,QAAQ,KAAK,IAAI,sBAAsB;EAGvD,MAAM,EACJ,QAAQ,cACR,SAAS,UACT,gBACA,GAAG,gBACD,QAAQ,QAAQ,EAAE;AAEtB,OADoB,CAAC,gBAAgB,aAAa,SAAS,QAAQ,KAChD,OAAO,MAAM,QAAQ,WACtC,OAAM,IACJ,IAAIC,sC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zDC,6CAA8B,WAAW;GAC1C,GAAI,QAAQ,SACR,GACGC,kDAAmC,KAAK,UACvC,OAAO,MACR,EACF,GACD,EAAE;GACP;EACF,CACF,CAAC,CACH;;AAGH,eAAsB,gBACpB,SACmC;AACnC,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;AACxC,SAAOC,kCAAoB,MAAM,YAAY;UACtC,OAAO;AACd,4BAAO,MAAM,6BAA6B,MAAM;AAChD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;;;AAIL,eAAsB,oBAAoB,SAMxC;AACA,KAAI;EACF,MAAM,cAAc,MAAM,QAAQ,MAAM;EACxC,MAAM,QAAQA,kCAAoB,MAAM,YAAY;EACpD,IAAI,kBAAiC;AAErC,MACE,qBAAsB,gBACrB,OAAQ,YAAwC,oBAC/C,YACC,YAAwC,oBAAoB,MAE/D,mBACG,YAAmC,mBAAmB;AAG3D,SAAO;GAAE;GAAO;GAAiB;UAC1B,OAAO;AACd,4BAAO,MAAM,iCAAiC,MAAM;AACpD,SAAO,IAAI,SACT,KAAK,UAAU;GACb,OAAO;GACP,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAChE,CAAC,EACF;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF"}
@@ -64,7 +64,7 @@ function configureAgentForRequest(params) {
64
64
  agent.headers = mergeForwardableHeaders(agent.headers, request, runtime.forwardHeadersPolicy ?? resolveForwardHeadersPolicy(void 0));
65
65
  }
66
66
  /**
67
- * Attach the Intelligence platform's MCP tools to the agent run when
67
+ * Attach CopilotKit Intelligence's MCP tools to the agent run when
68
68
  * `CopilotKitIntelligence` was constructed with
69
69
  * `enableEnterpriseLearning: true`. Uses `@ag-ui/mcp-middleware`, so the
70
70
  * tools are available uniformly across agent frameworks (not just