@copilotkit/runtime 1.54.1 → 1.55.0-next.7

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 (337) hide show
  1. package/.eslintrc.js +4 -4
  2. package/CHANGELOG.md +113 -113
  3. package/dist/_virtual/_rolldown/runtime.mjs +25 -1
  4. package/dist/agent/index.cjs +643 -0
  5. package/dist/agent/index.cjs.map +1 -0
  6. package/dist/agent/index.d.cts +263 -0
  7. package/dist/agent/index.d.cts.map +1 -0
  8. package/dist/agent/index.d.mts +263 -0
  9. package/dist/agent/index.d.mts.map +1 -0
  10. package/dist/agent/index.mjs +635 -0
  11. package/dist/agent/index.mjs.map +1 -0
  12. package/dist/graphql/message-conversion/agui-to-gql.cjs.map +1 -1
  13. package/dist/graphql/message-conversion/agui-to-gql.mjs.map +1 -1
  14. package/dist/lib/integrations/nextjs/app-router.cjs +2 -2
  15. package/dist/lib/integrations/nextjs/app-router.cjs.map +1 -1
  16. package/dist/lib/integrations/nextjs/app-router.mjs +1 -1
  17. package/dist/lib/integrations/nextjs/app-router.mjs.map +1 -1
  18. package/dist/lib/integrations/node-http/index.cjs +2 -3
  19. package/dist/lib/integrations/node-http/index.cjs.map +1 -1
  20. package/dist/lib/integrations/node-http/index.mjs +1 -1
  21. package/dist/lib/integrations/node-http/index.mjs.map +1 -1
  22. package/dist/lib/runtime/agent-integrations/langgraph/agent.cjs +1 -1
  23. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts +2 -2
  24. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.cts.map +1 -1
  25. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.mts +3 -3
  26. package/dist/lib/runtime/agent-integrations/langgraph/agent.d.mts.map +1 -1
  27. package/dist/lib/runtime/agent-integrations/langgraph/agent.mjs +1 -1
  28. package/dist/lib/runtime/copilot-runtime.cjs +7 -5
  29. package/dist/lib/runtime/copilot-runtime.cjs.map +1 -1
  30. package/dist/lib/runtime/copilot-runtime.d.cts +10 -8
  31. package/dist/lib/runtime/copilot-runtime.d.cts.map +1 -1
  32. package/dist/lib/runtime/copilot-runtime.d.mts +10 -8
  33. package/dist/lib/runtime/copilot-runtime.d.mts.map +1 -1
  34. package/dist/lib/runtime/copilot-runtime.mjs +7 -5
  35. package/dist/lib/runtime/copilot-runtime.mjs.map +1 -1
  36. package/dist/lib/runtime/telemetry-agent-runner.cjs +2 -2
  37. package/dist/lib/runtime/telemetry-agent-runner.cjs.map +1 -1
  38. package/dist/lib/runtime/telemetry-agent-runner.d.cts +2 -1
  39. package/dist/lib/runtime/telemetry-agent-runner.d.cts.map +1 -1
  40. package/dist/lib/runtime/telemetry-agent-runner.d.mts +2 -1
  41. package/dist/lib/runtime/telemetry-agent-runner.d.mts.map +1 -1
  42. package/dist/lib/runtime/telemetry-agent-runner.mjs +1 -1
  43. package/dist/lib/runtime/telemetry-agent-runner.mjs.map +1 -1
  44. package/dist/lib/telemetry-client.cjs +1 -1
  45. package/dist/lib/telemetry-client.mjs +1 -1
  46. package/dist/package.cjs +21 -4
  47. package/dist/package.mjs +21 -4
  48. package/dist/service-adapters/anthropic/anthropic-adapter.d.mts +1 -1
  49. package/dist/v2/index.cjs +41 -15
  50. package/dist/v2/index.d.cts +14 -2
  51. package/dist/v2/index.d.mts +14 -2
  52. package/dist/v2/index.mjs +13 -4
  53. package/dist/v2/runtime/endpoints/express-single.cjs +190 -0
  54. package/dist/v2/runtime/endpoints/express-single.cjs.map +1 -0
  55. package/dist/v2/runtime/endpoints/express-single.d.cts +16 -0
  56. package/dist/v2/runtime/endpoints/express-single.d.cts.map +1 -0
  57. package/dist/v2/runtime/endpoints/express-single.d.mts +16 -0
  58. package/dist/v2/runtime/endpoints/express-single.d.mts.map +1 -0
  59. package/dist/v2/runtime/endpoints/express-single.mjs +187 -0
  60. package/dist/v2/runtime/endpoints/express-single.mjs.map +1 -0
  61. package/dist/v2/runtime/endpoints/express-utils.cjs +119 -0
  62. package/dist/v2/runtime/endpoints/express-utils.cjs.map +1 -0
  63. package/dist/v2/runtime/endpoints/express-utils.mjs +117 -0
  64. package/dist/v2/runtime/endpoints/express-utils.mjs.map +1 -0
  65. package/dist/v2/runtime/endpoints/express.cjs +217 -0
  66. package/dist/v2/runtime/endpoints/express.cjs.map +1 -0
  67. package/dist/v2/runtime/endpoints/express.d.cts +16 -0
  68. package/dist/v2/runtime/endpoints/express.d.cts.map +1 -0
  69. package/dist/v2/runtime/endpoints/express.d.mts +16 -0
  70. package/dist/v2/runtime/endpoints/express.d.mts.map +1 -0
  71. package/dist/v2/runtime/endpoints/express.mjs +214 -0
  72. package/dist/v2/runtime/endpoints/express.mjs.map +1 -0
  73. package/dist/v2/runtime/endpoints/hono-single.cjs +141 -0
  74. package/dist/v2/runtime/endpoints/hono-single.cjs.map +1 -0
  75. package/dist/v2/runtime/endpoints/hono-single.d.cts +41 -0
  76. package/dist/v2/runtime/endpoints/hono-single.d.cts.map +1 -0
  77. package/dist/v2/runtime/endpoints/hono-single.d.mts +41 -0
  78. package/dist/v2/runtime/endpoints/hono-single.d.mts.map +1 -0
  79. package/dist/v2/runtime/endpoints/hono-single.mjs +140 -0
  80. package/dist/v2/runtime/endpoints/hono-single.mjs.map +1 -0
  81. package/dist/v2/runtime/endpoints/hono.cjs +248 -0
  82. package/dist/v2/runtime/endpoints/hono.cjs.map +1 -0
  83. package/dist/v2/runtime/endpoints/hono.d.cts +164 -0
  84. package/dist/v2/runtime/endpoints/hono.d.cts.map +1 -0
  85. package/dist/v2/runtime/endpoints/hono.d.mts +164 -0
  86. package/dist/v2/runtime/endpoints/hono.d.mts.map +1 -0
  87. package/dist/v2/runtime/endpoints/hono.mjs +247 -0
  88. package/dist/v2/runtime/endpoints/hono.mjs.map +1 -0
  89. package/dist/v2/runtime/endpoints/index.d.cts +5 -0
  90. package/dist/v2/runtime/endpoints/index.d.mts +5 -0
  91. package/dist/v2/runtime/endpoints/single-route-helpers.cjs +68 -0
  92. package/dist/v2/runtime/endpoints/single-route-helpers.cjs.map +1 -0
  93. package/dist/v2/runtime/endpoints/single-route-helpers.mjs +65 -0
  94. package/dist/v2/runtime/endpoints/single-route-helpers.mjs.map +1 -0
  95. package/dist/v2/runtime/handlers/get-runtime-info.cjs +51 -0
  96. package/dist/v2/runtime/handlers/get-runtime-info.cjs.map +1 -0
  97. package/dist/v2/runtime/handlers/get-runtime-info.mjs +51 -0
  98. package/dist/v2/runtime/handlers/get-runtime-info.mjs.map +1 -0
  99. package/dist/v2/runtime/handlers/handle-connect.cjs +49 -0
  100. package/dist/v2/runtime/handlers/handle-connect.cjs.map +1 -0
  101. package/dist/v2/runtime/handlers/handle-connect.mjs +49 -0
  102. package/dist/v2/runtime/handlers/handle-connect.mjs.map +1 -0
  103. package/dist/v2/runtime/handlers/handle-run.cjs +61 -0
  104. package/dist/v2/runtime/handlers/handle-run.cjs.map +1 -0
  105. package/dist/v2/runtime/handlers/handle-run.mjs +61 -0
  106. package/dist/v2/runtime/handlers/handle-run.mjs.map +1 -0
  107. package/dist/v2/runtime/handlers/handle-stop.cjs +47 -0
  108. package/dist/v2/runtime/handlers/handle-stop.cjs.map +1 -0
  109. package/dist/v2/runtime/handlers/handle-stop.mjs +46 -0
  110. package/dist/v2/runtime/handlers/handle-stop.mjs.map +1 -0
  111. package/dist/v2/runtime/handlers/handle-transcribe.cjs +112 -0
  112. package/dist/v2/runtime/handlers/handle-transcribe.cjs.map +1 -0
  113. package/dist/v2/runtime/handlers/handle-transcribe.mjs +111 -0
  114. package/dist/v2/runtime/handlers/handle-transcribe.mjs.map +1 -0
  115. package/dist/v2/runtime/handlers/header-utils.cjs +26 -0
  116. package/dist/v2/runtime/handlers/header-utils.cjs.map +1 -0
  117. package/dist/v2/runtime/handlers/header-utils.mjs +25 -0
  118. package/dist/v2/runtime/handlers/header-utils.mjs.map +1 -0
  119. package/dist/v2/runtime/handlers/intelligence/connect.cjs +37 -0
  120. package/dist/v2/runtime/handlers/intelligence/connect.cjs.map +1 -0
  121. package/dist/v2/runtime/handlers/intelligence/connect.mjs +37 -0
  122. package/dist/v2/runtime/handlers/intelligence/connect.mjs.map +1 -0
  123. package/dist/v2/runtime/handlers/intelligence/run.cjs +89 -0
  124. package/dist/v2/runtime/handlers/intelligence/run.cjs.map +1 -0
  125. package/dist/v2/runtime/handlers/intelligence/run.mjs +88 -0
  126. package/dist/v2/runtime/handlers/intelligence/run.mjs.map +1 -0
  127. package/dist/v2/runtime/handlers/intelligence/thread-names.cjs +146 -0
  128. package/dist/v2/runtime/handlers/intelligence/thread-names.cjs.map +1 -0
  129. package/dist/v2/runtime/handlers/intelligence/thread-names.mjs +145 -0
  130. package/dist/v2/runtime/handlers/intelligence/thread-names.mjs.map +1 -0
  131. package/dist/v2/runtime/handlers/intelligence/threads.cjs +159 -0
  132. package/dist/v2/runtime/handlers/intelligence/threads.cjs.map +1 -0
  133. package/dist/v2/runtime/handlers/intelligence/threads.mjs +154 -0
  134. package/dist/v2/runtime/handlers/intelligence/threads.mjs.map +1 -0
  135. package/dist/v2/runtime/handlers/shared/agent-utils.cjs +74 -0
  136. package/dist/v2/runtime/handlers/shared/agent-utils.cjs.map +1 -0
  137. package/dist/v2/runtime/handlers/shared/agent-utils.mjs +70 -0
  138. package/dist/v2/runtime/handlers/shared/agent-utils.mjs.map +1 -0
  139. package/dist/v2/runtime/handlers/shared/intelligence-utils.cjs +21 -0
  140. package/dist/v2/runtime/handlers/shared/intelligence-utils.cjs.map +1 -0
  141. package/dist/v2/runtime/handlers/shared/intelligence-utils.mjs +20 -0
  142. package/dist/v2/runtime/handlers/shared/intelligence-utils.mjs.map +1 -0
  143. package/dist/v2/runtime/handlers/shared/json-response.cjs +12 -0
  144. package/dist/v2/runtime/handlers/shared/json-response.cjs.map +1 -0
  145. package/dist/v2/runtime/handlers/shared/json-response.mjs +10 -0
  146. package/dist/v2/runtime/handlers/shared/json-response.mjs.map +1 -0
  147. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs +20 -0
  148. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -0
  149. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs +20 -0
  150. package/dist/v2/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -0
  151. package/dist/v2/runtime/handlers/shared/sse-response.cjs +69 -0
  152. package/dist/v2/runtime/handlers/shared/sse-response.cjs.map +1 -0
  153. package/dist/v2/runtime/handlers/shared/sse-response.mjs +68 -0
  154. package/dist/v2/runtime/handlers/shared/sse-response.mjs.map +1 -0
  155. package/dist/v2/runtime/handlers/sse/connect.cjs +18 -0
  156. package/dist/v2/runtime/handlers/sse/connect.cjs.map +1 -0
  157. package/dist/v2/runtime/handlers/sse/connect.mjs +18 -0
  158. package/dist/v2/runtime/handlers/sse/connect.mjs.map +1 -0
  159. package/dist/v2/runtime/handlers/sse/run.cjs +18 -0
  160. package/dist/v2/runtime/handlers/sse/run.cjs.map +1 -0
  161. package/dist/v2/runtime/handlers/sse/run.mjs +18 -0
  162. package/dist/v2/runtime/handlers/sse/run.mjs.map +1 -0
  163. package/dist/v2/runtime/index.d.cts +13 -0
  164. package/dist/v2/runtime/index.d.mts +14 -0
  165. package/dist/v2/runtime/intelligence-platform/client.cjs +333 -0
  166. package/dist/v2/runtime/intelligence-platform/client.cjs.map +1 -0
  167. package/dist/v2/runtime/intelligence-platform/client.d.cts +336 -0
  168. package/dist/v2/runtime/intelligence-platform/client.d.cts.map +1 -0
  169. package/dist/v2/runtime/intelligence-platform/client.d.mts +336 -0
  170. package/dist/v2/runtime/intelligence-platform/client.d.mts.map +1 -0
  171. package/dist/v2/runtime/intelligence-platform/client.mjs +331 -0
  172. package/dist/v2/runtime/intelligence-platform/client.mjs.map +1 -0
  173. package/dist/v2/runtime/intelligence-platform/index.d.mts +2 -0
  174. package/dist/v2/runtime/middleware-sse-parser.cjs +138 -0
  175. package/dist/v2/runtime/middleware-sse-parser.cjs.map +1 -0
  176. package/dist/v2/runtime/middleware-sse-parser.d.cts +22 -0
  177. package/dist/v2/runtime/middleware-sse-parser.d.cts.map +1 -0
  178. package/dist/v2/runtime/middleware-sse-parser.d.mts +22 -0
  179. package/dist/v2/runtime/middleware-sse-parser.d.mts.map +1 -0
  180. package/dist/v2/runtime/middleware-sse-parser.mjs +137 -0
  181. package/dist/v2/runtime/middleware-sse-parser.mjs.map +1 -0
  182. package/dist/v2/runtime/middleware.cjs +35 -0
  183. package/dist/v2/runtime/middleware.cjs.map +1 -0
  184. package/dist/v2/runtime/middleware.d.cts +32 -0
  185. package/dist/v2/runtime/middleware.d.cts.map +1 -0
  186. package/dist/v2/runtime/middleware.d.mts +32 -0
  187. package/dist/v2/runtime/middleware.d.mts.map +1 -0
  188. package/dist/v2/runtime/middleware.mjs +33 -0
  189. package/dist/v2/runtime/middleware.mjs.map +1 -0
  190. package/dist/v2/runtime/runner/agent-runner.cjs +8 -0
  191. package/dist/v2/runtime/runner/agent-runner.cjs.map +1 -0
  192. package/dist/v2/runtime/runner/agent-runner.d.cts +32 -0
  193. package/dist/v2/runtime/runner/agent-runner.d.cts.map +1 -0
  194. package/dist/v2/runtime/runner/agent-runner.d.mts +32 -0
  195. package/dist/v2/runtime/runner/agent-runner.d.mts.map +1 -0
  196. package/dist/v2/runtime/runner/agent-runner.mjs +7 -0
  197. package/dist/v2/runtime/runner/agent-runner.mjs.map +1 -0
  198. package/dist/v2/runtime/runner/in-memory.cjs +223 -0
  199. package/dist/v2/runtime/runner/in-memory.cjs.map +1 -0
  200. package/dist/v2/runtime/runner/in-memory.d.cts +15 -0
  201. package/dist/v2/runtime/runner/in-memory.d.cts.map +1 -0
  202. package/dist/v2/runtime/runner/in-memory.d.mts +15 -0
  203. package/dist/v2/runtime/runner/in-memory.d.mts.map +1 -0
  204. package/dist/v2/runtime/runner/in-memory.mjs +222 -0
  205. package/dist/v2/runtime/runner/in-memory.mjs.map +1 -0
  206. package/dist/v2/runtime/runner/index.d.cts +6 -0
  207. package/dist/v2/runtime/runner/index.d.mts +6 -0
  208. package/dist/v2/runtime/runner/index.mjs +7 -0
  209. package/dist/v2/runtime/runner/intelligence.cjs +246 -0
  210. package/dist/v2/runtime/runner/intelligence.cjs.map +1 -0
  211. package/dist/v2/runtime/runner/intelligence.d.cts +57 -0
  212. package/dist/v2/runtime/runner/intelligence.d.cts.map +1 -0
  213. package/dist/v2/runtime/runner/intelligence.d.mts +57 -0
  214. package/dist/v2/runtime/runner/intelligence.d.mts.map +1 -0
  215. package/dist/v2/runtime/runner/intelligence.mjs +245 -0
  216. package/dist/v2/runtime/runner/intelligence.mjs.map +1 -0
  217. package/dist/v2/runtime/runtime.cjs +101 -0
  218. package/dist/v2/runtime/runtime.cjs.map +1 -0
  219. package/dist/v2/runtime/runtime.d.cts +132 -0
  220. package/dist/v2/runtime/runtime.d.cts.map +1 -0
  221. package/dist/v2/runtime/runtime.d.mts +133 -0
  222. package/dist/v2/runtime/runtime.d.mts.map +1 -0
  223. package/dist/v2/runtime/runtime.mjs +97 -0
  224. package/dist/v2/runtime/runtime.mjs.map +1 -0
  225. package/dist/v2/runtime/telemetry/scarf-client.cjs +32 -0
  226. package/dist/v2/runtime/telemetry/scarf-client.cjs.map +1 -0
  227. package/dist/v2/runtime/telemetry/scarf-client.mjs +32 -0
  228. package/dist/v2/runtime/telemetry/scarf-client.mjs.map +1 -0
  229. package/dist/v2/runtime/telemetry/telemetry-client.cjs +35 -0
  230. package/dist/v2/runtime/telemetry/telemetry-client.cjs.map +1 -0
  231. package/dist/v2/runtime/telemetry/telemetry-client.mjs +35 -0
  232. package/dist/v2/runtime/telemetry/telemetry-client.mjs.map +1 -0
  233. package/dist/v2/runtime/transcription-service/transcription-service.cjs +8 -0
  234. package/dist/v2/runtime/transcription-service/transcription-service.cjs.map +1 -0
  235. package/dist/v2/runtime/transcription-service/transcription-service.d.cts +15 -0
  236. package/dist/v2/runtime/transcription-service/transcription-service.d.cts.map +1 -0
  237. package/dist/v2/runtime/transcription-service/transcription-service.d.mts +15 -0
  238. package/dist/v2/runtime/transcription-service/transcription-service.d.mts.map +1 -0
  239. package/dist/v2/runtime/transcription-service/transcription-service.mjs +7 -0
  240. package/dist/v2/runtime/transcription-service/transcription-service.mjs.map +1 -0
  241. package/package.json +24 -7
  242. package/src/agent/__tests__/ai-sdk-v6-compat.test.ts +116 -0
  243. package/src/agent/__tests__/basic-agent.test.ts +1248 -0
  244. package/src/agent/__tests__/config-tools-execution.test.ts +516 -0
  245. package/src/agent/__tests__/mcp-clients.test.ts +260 -0
  246. package/src/agent/__tests__/property-overrides.test.ts +598 -0
  247. package/src/agent/__tests__/standard-schema-tools.test.ts +313 -0
  248. package/src/agent/__tests__/standard-schema-types.test.ts +158 -0
  249. package/src/agent/__tests__/state-tools.test.ts +436 -0
  250. package/src/agent/__tests__/test-helpers.ts +178 -0
  251. package/src/agent/__tests__/utils.test.ts +536 -0
  252. package/src/agent/__tests__/zod-regression.test.ts +350 -0
  253. package/src/agent/index.ts +1305 -0
  254. package/src/graphql/message-conversion/agui-to-gql.test.ts +1 -1
  255. package/src/graphql/message-conversion/agui-to-gql.ts +1 -1
  256. package/src/graphql/message-conversion/gql-to-agui.ts +1 -1
  257. package/src/graphql/message-conversion/roundtrip-conversion.test.ts +1 -1
  258. package/src/lib/integrations/nextjs/app-router.ts +2 -2
  259. package/src/lib/integrations/node-http/index.ts +2 -2
  260. package/src/lib/runtime/copilot-runtime.ts +3 -5
  261. package/src/lib/runtime/telemetry-agent-runner.ts +1 -1
  262. package/src/service-adapters/conversion.test.ts +1 -1
  263. package/src/service-adapters/conversion.ts +1 -28
  264. package/src/v2/index.ts +5 -2
  265. package/src/v2/runtime/__tests__/cors-credentials.test.ts +320 -0
  266. package/src/v2/runtime/__tests__/express-abort-signal.test.ts +25 -0
  267. package/src/v2/runtime/__tests__/express-body-order.test.ts +76 -0
  268. package/src/v2/runtime/__tests__/express-single-sse.test.ts +122 -0
  269. package/src/v2/runtime/__tests__/get-runtime-info.test.ts +141 -0
  270. package/src/v2/runtime/__tests__/handle-connect.test.ts +423 -0
  271. package/src/v2/runtime/__tests__/handle-run.test.ts +910 -0
  272. package/src/v2/runtime/__tests__/handle-threads.test.ts +388 -0
  273. package/src/v2/runtime/__tests__/handle-transcribe.test.ts +301 -0
  274. package/src/v2/runtime/__tests__/header-utils.test.ts +88 -0
  275. package/src/v2/runtime/__tests__/in-process-agent-runner-messages.test.ts +230 -0
  276. package/src/v2/runtime/__tests__/in-process-agent-runner.test.ts +1030 -0
  277. package/src/v2/runtime/__tests__/middleware-express.test.ts +206 -0
  278. package/src/v2/runtime/__tests__/middleware-single-express.test.ts +211 -0
  279. package/src/v2/runtime/__tests__/middleware-single.test.ts +225 -0
  280. package/src/v2/runtime/__tests__/middleware-sse-parser.test.ts +187 -0
  281. package/src/v2/runtime/__tests__/middleware.test.ts +251 -0
  282. package/src/v2/runtime/__tests__/routing-express.test.ts +174 -0
  283. package/src/v2/runtime/__tests__/routing-single-express.test.ts +168 -0
  284. package/src/v2/runtime/__tests__/routing-single.test.ts +193 -0
  285. package/src/v2/runtime/__tests__/routing.test.ts +257 -0
  286. package/src/v2/runtime/__tests__/runtime.test.ts +123 -0
  287. package/src/v2/runtime/__tests__/telemetry.test.ts +167 -0
  288. package/src/v2/runtime/__tests__/thread-names.test.ts +188 -0
  289. package/src/v2/runtime/endpoints/express-single.ts +231 -0
  290. package/src/v2/runtime/endpoints/express-utils.ts +182 -0
  291. package/src/v2/runtime/endpoints/express.ts +275 -0
  292. package/src/v2/runtime/endpoints/hono-single.ts +212 -0
  293. package/src/v2/runtime/endpoints/hono.ts +314 -0
  294. package/src/v2/runtime/endpoints/index.ts +4 -0
  295. package/src/v2/runtime/endpoints/single-route-helpers.ts +125 -0
  296. package/src/v2/runtime/express.ts +2 -0
  297. package/src/v2/runtime/handler.ts +3 -0
  298. package/src/v2/runtime/handlers/get-runtime-info.ts +79 -0
  299. package/src/v2/runtime/handlers/handle-connect.ts +76 -0
  300. package/src/v2/runtime/handlers/handle-run.ts +89 -0
  301. package/src/v2/runtime/handlers/handle-stop.ts +76 -0
  302. package/src/v2/runtime/handlers/handle-threads.ts +7 -0
  303. package/src/v2/runtime/handlers/handle-transcribe.ts +256 -0
  304. package/src/v2/runtime/handlers/header-utils.ts +24 -0
  305. package/src/v2/runtime/handlers/intelligence/connect.ts +65 -0
  306. package/src/v2/runtime/handlers/intelligence/run.ts +152 -0
  307. package/src/v2/runtime/handlers/intelligence/thread-names.ts +246 -0
  308. package/src/v2/runtime/handlers/intelligence/threads.ts +233 -0
  309. package/src/v2/runtime/handlers/shared/agent-utils.ts +136 -0
  310. package/src/v2/runtime/handlers/shared/intelligence-utils.ts +21 -0
  311. package/src/v2/runtime/handlers/shared/json-response.ts +6 -0
  312. package/src/v2/runtime/handlers/shared/resolve-intelligence-user.ts +25 -0
  313. package/src/v2/runtime/handlers/shared/sse-response.ts +100 -0
  314. package/src/v2/runtime/handlers/sse/connect.ts +24 -0
  315. package/src/v2/runtime/handlers/sse/run.ts +27 -0
  316. package/src/v2/runtime/index.ts +20 -0
  317. package/src/v2/runtime/intelligence-platform/__tests__/client.test.ts +605 -0
  318. package/src/v2/runtime/intelligence-platform/client.ts +659 -0
  319. package/src/v2/runtime/intelligence-platform/index.ts +10 -0
  320. package/src/v2/runtime/middleware-sse-parser.ts +200 -0
  321. package/src/v2/runtime/middleware.ts +115 -0
  322. package/src/v2/runtime/runner/__tests__/finalize-events.test.ts +109 -0
  323. package/src/v2/runtime/runner/__tests__/in-memory-runner.e2e.test.ts +775 -0
  324. package/src/v2/runtime/runner/__tests__/in-memory-runner.test.ts +363 -0
  325. package/src/v2/runtime/runner/__tests__/intelligence-runner.test.ts +981 -0
  326. package/src/v2/runtime/runner/agent-runner.ts +36 -0
  327. package/src/v2/runtime/runner/in-memory.ts +381 -0
  328. package/src/v2/runtime/runner/index.ts +4 -0
  329. package/src/v2/runtime/runner/intelligence.ts +429 -0
  330. package/src/v2/runtime/runtime.ts +260 -0
  331. package/src/v2/runtime/telemetry/events.ts +35 -0
  332. package/src/v2/runtime/telemetry/index.ts +7 -0
  333. package/src/v2/runtime/telemetry/scarf-client.ts +39 -0
  334. package/src/v2/runtime/telemetry/telemetry-client.ts +70 -0
  335. package/src/v2/runtime/transcription-service/transcription-service.ts +11 -0
  336. package/tsconfig.json +9 -2
  337. package/tsdown.config.ts +1 -0
@@ -0,0 +1,57 @@
1
+
2
+ import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./agent-runner.cjs";
3
+ import { Observable } from "rxjs";
4
+ import { BaseEvent } from "@ag-ui/client";
5
+
6
+ //#region src/v2/runtime/runner/intelligence.d.ts
7
+ interface IntelligenceAgentRunnerOptions {
8
+ /** Phoenix runner websocket URL, e.g. "ws://localhost:4000/runner" */
9
+ url: string;
10
+ /** Optional Phoenix socket auth token used during websocket connect. */
11
+ authToken?: string;
12
+ }
13
+ declare class IntelligenceAgentRunner extends AgentRunner {
14
+ private options;
15
+ private threads;
16
+ constructor(options: IntelligenceAgentRunnerOptions);
17
+ /**
18
+ * Create a new Phoenix socket with explicit exponential backoff.
19
+ *
20
+ * Each run/connect gets its own socket so that:
21
+ * - A socket failure only affects a single thread, not all threads.
22
+ * - Cleanup is simple: channel.leave() + socket.disconnect() tears
23
+ * down everything for that run with no shared-state concerns.
24
+ * - Each run gets its own independent retry budget.
25
+ *
26
+ * reconnectAfterMs — delay before Phoenix reconnects the WebSocket
27
+ * after an unclean close. 100ms base, doubling up to a 10s cap.
28
+ *
29
+ * rejoinAfterMs — delay before Phoenix re-joins a channel that
30
+ * entered the "errored" state. 1s base, doubling up to 30s cap.
31
+ *
32
+ * These are set explicitly because Phoenix's default schedule is a
33
+ * fixed stepped array (not exponential), and any code that calls
34
+ * socket.disconnect() in an onError handler will set
35
+ * closeWasClean = true and reset the reconnect timer — permanently
36
+ * killing retries.
37
+ */
38
+ private createSocket;
39
+ private createRunnerEventPayload;
40
+ private stampRunnerMetadata;
41
+ run(request: AgentRunnerRunRequest): Observable<BaseEvent>;
42
+ connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;
43
+ isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;
44
+ stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;
45
+ private executeAgentRun;
46
+ /**
47
+ * Tear down all resources for a thread: leave the channel,
48
+ * disconnect the per-run socket, and remove the thread state.
49
+ *
50
+ * Idempotent — safe to call multiple times for the same threadId
51
+ * (e.g. from join error handlers, finalize, and Observable teardown).
52
+ */
53
+ private removeThread;
54
+ }
55
+ //#endregion
56
+ export { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions };
57
+ //# sourceMappingURL=intelligence.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intelligence.d.cts","names":[],"sources":["../../../../src/v2/runtime/runner/intelligence.ts"],"mappings":";;;;;;UAuBiB,8BAAA;;EAEf,GAAA;EAF6C;EAI7C,SAAA;AAAA;AAAA,cAcW,uBAAA,SAAgC,WAAA;EAAA,QACnC,OAAA;EAAA,QACA,OAAA;cAEI,OAAA,EAAS,8BAAA;EAAA;;;;;;;;;;;;;;;;;;;;;EAAA,QA2Bb,YAAA;EAAA,QAUA,wBAAA;EAAA,QAqBA,mBAAA;EA8BR,GAAA,CAAI,OAAA,EAAS,qBAAA,GAAwB,UAAA,CAAW,SAAA;EA8GhD,OAAA,CAAQ,OAAA,EAAS,yBAAA,GAA4B,UAAA,CAAW,SAAA;EA4CxD,SAAA,CAAU,OAAA,EAAS,2BAAA,GAA8B,OAAA;EAKjD,IAAA,CAAK,OAAA,EAAS,sBAAA,GAAyB,OAAA;EAAA,QAoB/B,eAAA;EArES;;;;;;;EAAA,QAqKT,YAAA;AAAA"}
@@ -0,0 +1,57 @@
1
+ import "reflect-metadata";
2
+ import { AgentRunner, AgentRunnerConnectRequest, AgentRunnerIsRunningRequest, AgentRunnerRunRequest, AgentRunnerStopRequest } from "./agent-runner.mjs";
3
+ import { Observable } from "rxjs";
4
+ import { BaseEvent } from "@ag-ui/client";
5
+
6
+ //#region src/v2/runtime/runner/intelligence.d.ts
7
+ interface IntelligenceAgentRunnerOptions {
8
+ /** Phoenix runner websocket URL, e.g. "ws://localhost:4000/runner" */
9
+ url: string;
10
+ /** Optional Phoenix socket auth token used during websocket connect. */
11
+ authToken?: string;
12
+ }
13
+ declare class IntelligenceAgentRunner extends AgentRunner {
14
+ private options;
15
+ private threads;
16
+ constructor(options: IntelligenceAgentRunnerOptions);
17
+ /**
18
+ * Create a new Phoenix socket with explicit exponential backoff.
19
+ *
20
+ * Each run/connect gets its own socket so that:
21
+ * - A socket failure only affects a single thread, not all threads.
22
+ * - Cleanup is simple: channel.leave() + socket.disconnect() tears
23
+ * down everything for that run with no shared-state concerns.
24
+ * - Each run gets its own independent retry budget.
25
+ *
26
+ * reconnectAfterMs — delay before Phoenix reconnects the WebSocket
27
+ * after an unclean close. 100ms base, doubling up to a 10s cap.
28
+ *
29
+ * rejoinAfterMs — delay before Phoenix re-joins a channel that
30
+ * entered the "errored" state. 1s base, doubling up to 30s cap.
31
+ *
32
+ * These are set explicitly because Phoenix's default schedule is a
33
+ * fixed stepped array (not exponential), and any code that calls
34
+ * socket.disconnect() in an onError handler will set
35
+ * closeWasClean = true and reset the reconnect timer — permanently
36
+ * killing retries.
37
+ */
38
+ private createSocket;
39
+ private createRunnerEventPayload;
40
+ private stampRunnerMetadata;
41
+ run(request: AgentRunnerRunRequest): Observable<BaseEvent>;
42
+ connect(request: AgentRunnerConnectRequest): Observable<BaseEvent>;
43
+ isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean>;
44
+ stop(request: AgentRunnerStopRequest): Promise<boolean | undefined>;
45
+ private executeAgentRun;
46
+ /**
47
+ * Tear down all resources for a thread: leave the channel,
48
+ * disconnect the per-run socket, and remove the thread state.
49
+ *
50
+ * Idempotent — safe to call multiple times for the same threadId
51
+ * (e.g. from join error handlers, finalize, and Observable teardown).
52
+ */
53
+ private removeThread;
54
+ }
55
+ //#endregion
56
+ export { IntelligenceAgentRunner, IntelligenceAgentRunnerOptions };
57
+ //# sourceMappingURL=intelligence.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intelligence.d.mts","names":[],"sources":["../../../../src/v2/runtime/runner/intelligence.ts"],"mappings":";;;;;;UAuBiB,8BAAA;;EAEf,GAAA;EAF6C;EAI7C,SAAA;AAAA;AAAA,cAcW,uBAAA,SAAgC,WAAA;EAAA,QACnC,OAAA;EAAA,QACA,OAAA;cAEI,OAAA,EAAS,8BAAA;EAAA;;;;;;;;;;;;;;;;;;;;;EAAA,QA2Bb,YAAA;EAAA,QAUA,wBAAA;EAAA,QAqBA,mBAAA;EA8BR,GAAA,CAAI,OAAA,EAAS,qBAAA,GAAwB,UAAA,CAAW,SAAA;EA8GhD,OAAA,CAAQ,OAAA,EAAS,yBAAA,GAA4B,UAAA,CAAW,SAAA;EA4CxD,SAAA,CAAU,OAAA,EAAS,2BAAA,GAA8B,OAAA;EAKjD,IAAA,CAAK,OAAA,EAAS,sBAAA,GAAyB,OAAA;EAAA,QAoB/B,eAAA;EArES;;;;;;;EAAA,QAqKT,YAAA;AAAA"}
@@ -0,0 +1,245 @@
1
+ import "reflect-metadata";
2
+ import { AgentRunner } from "./agent-runner.mjs";
3
+ import { AG_UI_CHANNEL_EVENT, finalizeRunEvents, phoenixExponentialBackoff } from "@copilotkit/shared";
4
+ import { EMPTY, Observable, from } from "rxjs";
5
+ import { randomUUID as randomUUID$1 } from "node:crypto";
6
+ import { EventType } from "@ag-ui/client";
7
+ import { catchError as catchError$1, finalize as finalize$1 } from "rxjs/operators";
8
+ import { Socket } from "phoenix";
9
+
10
+ //#region src/v2/runtime/runner/intelligence.ts
11
+ var IntelligenceAgentRunner = class extends AgentRunner {
12
+ constructor(options) {
13
+ super();
14
+ this.threads = /* @__PURE__ */ new Map();
15
+ this.options = options;
16
+ }
17
+ /**
18
+ * Create a new Phoenix socket with explicit exponential backoff.
19
+ *
20
+ * Each run/connect gets its own socket so that:
21
+ * - A socket failure only affects a single thread, not all threads.
22
+ * - Cleanup is simple: channel.leave() + socket.disconnect() tears
23
+ * down everything for that run with no shared-state concerns.
24
+ * - Each run gets its own independent retry budget.
25
+ *
26
+ * reconnectAfterMs — delay before Phoenix reconnects the WebSocket
27
+ * after an unclean close. 100ms base, doubling up to a 10s cap.
28
+ *
29
+ * rejoinAfterMs — delay before Phoenix re-joins a channel that
30
+ * entered the "errored" state. 1s base, doubling up to 30s cap.
31
+ *
32
+ * These are set explicitly because Phoenix's default schedule is a
33
+ * fixed stepped array (not exponential), and any code that calls
34
+ * socket.disconnect() in an onError handler will set
35
+ * closeWasClean = true and reset the reconnect timer — permanently
36
+ * killing retries.
37
+ */
38
+ createSocket() {
39
+ const socket = new Socket(this.options.url, {
40
+ ...this.options.authToken ? { authToken: this.options.authToken } : {},
41
+ reconnectAfterMs: phoenixExponentialBackoff(100, 1e4),
42
+ rejoinAfterMs: phoenixExponentialBackoff(1e3, 3e4)
43
+ });
44
+ socket.connect();
45
+ return socket;
46
+ }
47
+ createRunnerEventPayload(event, request, state) {
48
+ const payload = { ...this.stampRunnerMetadata(event, state) };
49
+ payload.thread_id ??= request.threadId;
50
+ const runId = payload.runId ?? payload.run_id ?? request.input.runId;
51
+ if (runId) payload.run_id = runId;
52
+ return payload;
53
+ }
54
+ stampRunnerMetadata(event, state) {
55
+ const eventRecord = event;
56
+ const existingMetadata = eventRecord.metadata ?? {};
57
+ const hasEventId = typeof existingMetadata.cpki_event_id === "string";
58
+ const hasEventSeq = typeof existingMetadata.cpki_event_seq === "number";
59
+ if (hasEventId && hasEventSeq) {
60
+ const eventSeq = existingMetadata.cpki_event_seq;
61
+ state.nextEventSeq = Math.max(state.nextEventSeq, eventSeq + 1);
62
+ return eventRecord;
63
+ }
64
+ const eventSeq = state.nextEventSeq++;
65
+ return {
66
+ ...eventRecord,
67
+ metadata: {
68
+ ...existingMetadata,
69
+ cpki_event_id: typeof existingMetadata.cpki_event_id === "string" ? existingMetadata.cpki_event_id : randomUUID$1(),
70
+ cpki_event_seq: eventSeq
71
+ }
72
+ };
73
+ }
74
+ run(request) {
75
+ const { threadId, agent, input, joinCode } = request;
76
+ if (this.threads.get(threadId)?.isRunning) throw new Error("Thread already running");
77
+ return new Observable((observer) => {
78
+ const socket = this.createSocket();
79
+ const channelTopic = joinCode ?? threadId;
80
+ const channel = socket.channel(`ingestion:${channelTopic}`, { runId: input.runId });
81
+ const state = {
82
+ socket,
83
+ channel,
84
+ isRunning: true,
85
+ stopRequested: false,
86
+ agent,
87
+ currentEvents: [],
88
+ nextEventSeq: 1,
89
+ hasRunStarted: false
90
+ };
91
+ this.threads.set(threadId, state);
92
+ const MAX_CONSECUTIVE_ERRORS = 5;
93
+ let consecutiveErrors = 0;
94
+ socket.onError(() => {
95
+ consecutiveErrors++;
96
+ if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS && state.agent) try {
97
+ state.agent.abortRun();
98
+ } catch {}
99
+ });
100
+ socket.onOpen(() => {
101
+ consecutiveErrors = 0;
102
+ });
103
+ channel.on(AG_UI_CHANNEL_EVENT, (payload) => {
104
+ if (payload.type === EventType.CUSTOM && payload.name === "stop") this.stop({ threadId });
105
+ });
106
+ channel.join().receive("ok", () => {
107
+ this.executeAgentRun(request, state, threadId).subscribe({ complete: () => observer.complete() });
108
+ }).receive("error", (resp) => {
109
+ const errorEvent = {
110
+ type: EventType.RUN_ERROR,
111
+ message: `Failed to join channel: ${JSON.stringify(resp)}`,
112
+ code: "CHANNEL_JOIN_ERROR"
113
+ };
114
+ observer.next(errorEvent);
115
+ state.currentEvents.push(errorEvent);
116
+ this.removeThread(threadId);
117
+ observer.complete();
118
+ }).receive("timeout", () => {
119
+ const errorEvent = {
120
+ type: EventType.RUN_ERROR,
121
+ message: "Timed out joining channel",
122
+ code: "CHANNEL_JOIN_TIMEOUT"
123
+ };
124
+ observer.next(errorEvent);
125
+ state.currentEvents.push(errorEvent);
126
+ this.removeThread(threadId);
127
+ observer.complete();
128
+ });
129
+ return () => {
130
+ this.removeThread(threadId);
131
+ };
132
+ });
133
+ }
134
+ connect(request) {
135
+ const { threadId } = request;
136
+ return new Observable((observer) => {
137
+ const socket = this.createSocket();
138
+ const channel = socket.channel(`thread:${threadId}`);
139
+ channel.on("ag_ui_event", (payload) => {
140
+ observer.next(payload);
141
+ if (payload.type === EventType.RUN_FINISHED || payload.type === EventType.RUN_ERROR) observer.complete();
142
+ });
143
+ const cleanup = () => {
144
+ channel.leave();
145
+ socket.disconnect();
146
+ };
147
+ channel.join().receive("ok", () => void 0).receive("error", (resp) => {
148
+ observer.error(/* @__PURE__ */ new Error(`Failed to join channel: ${JSON.stringify(resp)}`));
149
+ cleanup();
150
+ }).receive("timeout", () => {
151
+ observer.error(/* @__PURE__ */ new Error("Timed out joining channel"));
152
+ cleanup();
153
+ });
154
+ return () => {
155
+ cleanup();
156
+ };
157
+ });
158
+ }
159
+ isRunning(request) {
160
+ const state = this.threads.get(request.threadId);
161
+ return Promise.resolve(state?.isRunning ?? false);
162
+ }
163
+ stop(request) {
164
+ const state = this.threads.get(request.threadId);
165
+ if (!state || !state.isRunning || state.stopRequested) return Promise.resolve(false);
166
+ state.stopRequested = true;
167
+ if (state.agent) try {
168
+ state.agent.abortRun();
169
+ } catch {}
170
+ return Promise.resolve(true);
171
+ }
172
+ executeAgentRun(request, state, threadId) {
173
+ const { currentEvents, channel } = state;
174
+ const pushCanonicalEvent = (event) => {
175
+ const canonicalEvent = this.stampRunnerMetadata(event, state);
176
+ currentEvents.push(canonicalEvent);
177
+ if (canonicalEvent.type === EventType.RUN_STARTED) state.hasRunStarted = true;
178
+ channel.push("event", this.createRunnerEventPayload(canonicalEvent, request, state));
179
+ };
180
+ const getPersistedInputMessages = () => request.persistedInputMessages ?? request.input.messages;
181
+ const buildRunStartedEvent = (source) => {
182
+ const baseInput = source?.input ?? request.input;
183
+ const persistedInputMessages = getPersistedInputMessages();
184
+ return {
185
+ ...source ?? {
186
+ type: EventType.RUN_STARTED,
187
+ threadId: request.threadId,
188
+ runId: request.input.runId
189
+ },
190
+ input: {
191
+ ...baseInput,
192
+ ...persistedInputMessages !== void 0 ? { messages: persistedInputMessages } : {}
193
+ }
194
+ };
195
+ };
196
+ const ensureRunStarted = () => {
197
+ if (!state.hasRunStarted) {
198
+ state.hasRunStarted = true;
199
+ pushCanonicalEvent(buildRunStartedEvent());
200
+ }
201
+ };
202
+ return from(request.agent.runAgent(request.input, { onEvent: ({ event }) => {
203
+ if (event.type === EventType.RUN_STARTED) {
204
+ pushCanonicalEvent(buildRunStartedEvent(event));
205
+ return;
206
+ }
207
+ ensureRunStarted();
208
+ pushCanonicalEvent(event);
209
+ } })).pipe(catchError$1((error) => {
210
+ ensureRunStarted();
211
+ pushCanonicalEvent({
212
+ type: EventType.RUN_ERROR,
213
+ message: error instanceof Error ? error.message : String(error)
214
+ });
215
+ return EMPTY;
216
+ }), finalize$1(() => {
217
+ ensureRunStarted();
218
+ const appended = finalizeRunEvents(currentEvents, { stopRequested: state.stopRequested });
219
+ for (const event of appended) channel.push("event", this.createRunnerEventPayload(event, request, state));
220
+ this.removeThread(threadId);
221
+ }));
222
+ }
223
+ /**
224
+ * Tear down all resources for a thread: leave the channel,
225
+ * disconnect the per-run socket, and remove the thread state.
226
+ *
227
+ * Idempotent — safe to call multiple times for the same threadId
228
+ * (e.g. from join error handlers, finalize, and Observable teardown).
229
+ */
230
+ removeThread(threadId) {
231
+ const state = this.threads.get(threadId);
232
+ if (!state) return;
233
+ this.threads.delete(threadId);
234
+ try {
235
+ state.channel.leave();
236
+ } catch {}
237
+ try {
238
+ state.socket.disconnect();
239
+ } catch {}
240
+ }
241
+ };
242
+
243
+ //#endregion
244
+ export { IntelligenceAgentRunner };
245
+ //# sourceMappingURL=intelligence.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intelligence.mjs","names":["randomUUID","catchError","finalize"],"sources":["../../../../src/v2/runtime/runner/intelligence.ts"],"sourcesContent":["import {\n AgentRunner,\n AgentRunnerConnectRequest,\n AgentRunnerIsRunningRequest,\n AgentRunnerRunRequest,\n type AgentRunnerStopRequest,\n} from \"./agent-runner\";\nimport { EMPTY, Observable, from } from \"rxjs\";\nimport { catchError, finalize } from \"rxjs/operators\";\nimport {\n AbstractAgent,\n BaseEvent,\n EventType,\n RunStartedEvent,\n} from \"@ag-ui/client\";\nimport {\n finalizeRunEvents,\n AG_UI_CHANNEL_EVENT,\n phoenixExponentialBackoff,\n} from \"@copilotkit/shared\";\nimport { Socket, Channel } from \"phoenix\";\nimport { randomUUID } from \"node:crypto\";\n\nexport interface IntelligenceAgentRunnerOptions {\n /** Phoenix runner websocket URL, e.g. \"ws://localhost:4000/runner\" */\n url: string;\n /** Optional Phoenix socket auth token used during websocket connect. */\n authToken?: string;\n}\n\ninterface ThreadState {\n socket: Socket;\n channel: Channel;\n isRunning: boolean;\n stopRequested: boolean;\n agent: AbstractAgent | null;\n currentEvents: BaseEvent[];\n nextEventSeq: number;\n hasRunStarted: boolean;\n}\n\nexport class IntelligenceAgentRunner extends AgentRunner {\n private options: IntelligenceAgentRunnerOptions;\n private threads = new Map<string, ThreadState>();\n\n constructor(options: IntelligenceAgentRunnerOptions) {\n super();\n // Store config — sockets are created per-run, not eagerly.\n this.options = options;\n }\n\n /**\n * Create a new Phoenix socket with explicit exponential backoff.\n *\n * Each run/connect gets its own socket so that:\n * - A socket failure only affects a single thread, not all threads.\n * - Cleanup is simple: channel.leave() + socket.disconnect() tears\n * down everything for that run with no shared-state concerns.\n * - Each run gets its own independent retry budget.\n *\n * reconnectAfterMs — delay before Phoenix reconnects the WebSocket\n * after an unclean close. 100ms base, doubling up to a 10s cap.\n *\n * rejoinAfterMs — delay before Phoenix re-joins a channel that\n * entered the \"errored\" state. 1s base, doubling up to 30s cap.\n *\n * These are set explicitly because Phoenix's default schedule is a\n * fixed stepped array (not exponential), and any code that calls\n * socket.disconnect() in an onError handler will set\n * closeWasClean = true and reset the reconnect timer — permanently\n * killing retries.\n */\n private createSocket(): Socket {\n const socket = new Socket(this.options.url, {\n ...(this.options.authToken ? { authToken: this.options.authToken } : {}),\n reconnectAfterMs: phoenixExponentialBackoff(100, 10_000),\n rejoinAfterMs: phoenixExponentialBackoff(1_000, 30_000),\n });\n socket.connect();\n return socket;\n }\n\n private createRunnerEventPayload(\n event: BaseEvent,\n request: AgentRunnerRunRequest,\n state: ThreadState,\n ): Record<string, unknown> {\n const canonicalEvent = this.stampRunnerMetadata(event, state);\n const payload = {\n ...(canonicalEvent as Record<string, unknown>),\n };\n\n payload.thread_id ??= request.threadId;\n\n const runId = payload.runId ?? payload.run_id ?? request.input.runId;\n\n if (runId) {\n payload.run_id = runId;\n }\n\n return payload;\n }\n\n private stampRunnerMetadata(event: BaseEvent, state: ThreadState): BaseEvent {\n const eventRecord = event as BaseEvent & {\n metadata?: Record<string, unknown>;\n };\n\n const existingMetadata = eventRecord.metadata ?? {};\n const hasEventId = typeof existingMetadata.cpki_event_id === \"string\";\n const hasEventSeq = typeof existingMetadata.cpki_event_seq === \"number\";\n\n if (hasEventId && hasEventSeq) {\n const eventSeq = existingMetadata.cpki_event_seq as number;\n state.nextEventSeq = Math.max(state.nextEventSeq, eventSeq + 1);\n return eventRecord;\n }\n\n const eventSeq = state.nextEventSeq++;\n\n return {\n ...eventRecord,\n metadata: {\n ...existingMetadata,\n cpki_event_id:\n typeof existingMetadata.cpki_event_id === \"string\"\n ? existingMetadata.cpki_event_id\n : randomUUID(),\n cpki_event_seq: eventSeq,\n },\n };\n }\n\n run(request: AgentRunnerRunRequest): Observable<BaseEvent> {\n const { threadId, agent, input, joinCode } = request;\n\n const existing = this.threads.get(threadId);\n if (existing?.isRunning) {\n throw new Error(\"Thread already running\");\n }\n\n return new Observable((observer) => {\n const socket = this.createSocket();\n\n const channelTopic = joinCode ?? threadId;\n const channel = socket.channel(`ingestion:${channelTopic}`, {\n runId: input.runId,\n });\n\n const state: ThreadState = {\n socket,\n channel,\n isRunning: true,\n stopRequested: false,\n agent,\n currentEvents: [],\n nextEventSeq: 1,\n hasRunStarted: false,\n };\n this.threads.set(threadId, state);\n\n // Track consecutive socket errors for this run. Phoenix retries\n // automatically via reconnectAfterMs, but if the connection fails\n // repeatedly we abort the agent — otherwise runAgent() completes\n // normally, finalization events buffer silently on the dead\n // channel, and the client never receives them.\n //\n // Aborting the agent is the single trigger that cascades through\n // the existing error pipeline: runAgent() rejects → catchError\n // pushes RUN_ERROR → finalize calls finalizeRunEvents +\n // removeThread → channel.leave() + socket.disconnect().\n const MAX_CONSECUTIVE_ERRORS = 5;\n let consecutiveErrors = 0;\n\n socket.onError(() => {\n consecutiveErrors++;\n if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS && state.agent) {\n try {\n state.agent.abortRun();\n } catch {\n // Ignore abort errors.\n }\n }\n // Otherwise: Phoenix retries automatically using the exponential\n // backoff schedule configured in createSocket().\n });\n\n socket.onOpen(() => {\n // A successful (re)connection resets the counter so transient\n // network blips don't accumulate across recoveries.\n consecutiveErrors = 0;\n });\n\n // Listen for custom \"stop\" events pushed by the client over the\n // channel. This must be registered before channel.join() so the\n // handler is in place by the time the server starts relaying messages.\n // The client sends the stop event before leaving the channel, so the\n // runner is guaranteed to receive it while still joined.\n channel.on(AG_UI_CHANNEL_EVENT, (payload: BaseEvent) => {\n if (\n payload.type === EventType.CUSTOM &&\n (payload as BaseEvent & { name?: string }).name === \"stop\"\n ) {\n this.stop({ threadId });\n }\n });\n\n channel\n .join()\n .receive(\"ok\", () => {\n this.executeAgentRun(request, state, threadId).subscribe({\n complete: () => observer.complete(),\n });\n })\n .receive(\"error\", (resp) => {\n const errorEvent = {\n type: EventType.RUN_ERROR,\n message: `Failed to join channel: ${JSON.stringify(resp)}`,\n code: \"CHANNEL_JOIN_ERROR\",\n } as BaseEvent;\n observer.next(errorEvent);\n state.currentEvents.push(errorEvent);\n this.removeThread(threadId);\n observer.complete();\n })\n .receive(\"timeout\", () => {\n const errorEvent = {\n type: EventType.RUN_ERROR,\n message: \"Timed out joining channel\",\n code: \"CHANNEL_JOIN_TIMEOUT\",\n } as BaseEvent;\n observer.next(errorEvent);\n state.currentEvents.push(errorEvent);\n this.removeThread(threadId);\n observer.complete();\n });\n\n return () => {\n this.removeThread(threadId);\n };\n });\n }\n\n connect(request: AgentRunnerConnectRequest): Observable<BaseEvent> {\n const { threadId } = request;\n\n return new Observable((observer) => {\n const socket = this.createSocket();\n\n const channel = socket.channel(`thread:${threadId}`);\n\n channel.on(\"ag_ui_event\", (payload: BaseEvent) => {\n observer.next(payload);\n\n if (\n payload.type === EventType.RUN_FINISHED ||\n payload.type === EventType.RUN_ERROR\n ) {\n observer.complete();\n }\n });\n\n const cleanup = () => {\n channel.leave();\n socket.disconnect();\n };\n\n channel\n .join()\n .receive(\"ok\", () => undefined)\n .receive(\"error\", (resp) => {\n observer.error(\n new Error(`Failed to join channel: ${JSON.stringify(resp)}`),\n );\n cleanup();\n })\n .receive(\"timeout\", () => {\n observer.error(new Error(\"Timed out joining channel\"));\n cleanup();\n });\n\n return () => {\n cleanup();\n };\n });\n }\n\n isRunning(request: AgentRunnerIsRunningRequest): Promise<boolean> {\n const state = this.threads.get(request.threadId);\n return Promise.resolve(state?.isRunning ?? false);\n }\n\n stop(request: AgentRunnerStopRequest): Promise<boolean | undefined> {\n const state = this.threads.get(request.threadId);\n if (!state || !state.isRunning || state.stopRequested) {\n return Promise.resolve(false);\n }\n\n state.stopRequested = true;\n\n // Direct local abort — the runtime is the authority.\n if (state.agent) {\n try {\n state.agent.abortRun();\n } catch {\n // Ignore abort errors.\n }\n }\n\n return Promise.resolve(true);\n }\n\n private executeAgentRun(\n request: AgentRunnerRunRequest,\n state: ThreadState,\n threadId: string,\n ): Observable<void> {\n const { currentEvents, channel } = state;\n const pushCanonicalEvent = (event: BaseEvent): void => {\n const canonicalEvent = this.stampRunnerMetadata(event, state);\n currentEvents.push(canonicalEvent);\n\n if (canonicalEvent.type === EventType.RUN_STARTED) {\n state.hasRunStarted = true;\n }\n\n channel.push(\n \"event\",\n this.createRunnerEventPayload(canonicalEvent, request, state),\n );\n };\n\n const getPersistedInputMessages = () =>\n request.persistedInputMessages ?? request.input.messages;\n\n const buildRunStartedEvent = (\n source?: RunStartedEvent,\n ): RunStartedEvent => {\n const baseInput = source?.input ?? request.input;\n const persistedInputMessages = getPersistedInputMessages();\n\n return {\n ...(source ?? {\n type: EventType.RUN_STARTED,\n threadId: request.threadId,\n runId: request.input.runId,\n }),\n input: {\n ...baseInput,\n ...(persistedInputMessages !== undefined\n ? { messages: persistedInputMessages }\n : {}),\n },\n } as RunStartedEvent;\n };\n\n const ensureRunStarted = (): void => {\n if (!state.hasRunStarted) {\n state.hasRunStarted = true;\n pushCanonicalEvent(buildRunStartedEvent());\n }\n };\n\n return from(\n request.agent.runAgent(request.input, {\n onEvent: ({ event }: { event: BaseEvent }) => {\n if (event.type === EventType.RUN_STARTED) {\n pushCanonicalEvent(buildRunStartedEvent(event as RunStartedEvent));\n return;\n }\n\n ensureRunStarted();\n pushCanonicalEvent(event);\n },\n }),\n ).pipe(\n catchError((error) => {\n ensureRunStarted();\n const errorEvent = {\n type: EventType.RUN_ERROR,\n message: error instanceof Error ? error.message : String(error),\n } as BaseEvent;\n pushCanonicalEvent(errorEvent);\n return EMPTY;\n }),\n finalize(() => {\n ensureRunStarted();\n const appended = finalizeRunEvents(currentEvents, {\n stopRequested: state.stopRequested,\n });\n for (const event of appended) {\n channel.push(\n \"event\",\n this.createRunnerEventPayload(event, request, state),\n );\n }\n this.removeThread(threadId);\n }),\n );\n }\n\n /**\n * Tear down all resources for a thread: leave the channel,\n * disconnect the per-run socket, and remove the thread state.\n *\n * Idempotent — safe to call multiple times for the same threadId\n * (e.g. from join error handlers, finalize, and Observable teardown).\n */\n private removeThread(threadId: string): void {\n const state = this.threads.get(threadId);\n if (!state) {\n return;\n }\n\n // Delete first so concurrent calls see the entry as already removed.\n this.threads.delete(threadId);\n\n try {\n state.channel.leave();\n } catch {\n // Channel may already be closed/left.\n }\n try {\n state.socket.disconnect();\n } catch {\n // Socket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,OAAO;UACf;AAGR,MAAI;AACF,SAAM,OAAO,YAAY;UACnB"}
@@ -0,0 +1,101 @@
1
+ require("reflect-metadata");
2
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
3
+ const require_package$1 = require('../../package.cjs');
4
+ const require_in_memory = require('./runner/in-memory.cjs');
5
+ const require_intelligence = require('./runner/intelligence.cjs');
6
+ let _copilotkit_shared = require("@copilotkit/shared");
7
+
8
+ //#region src/v2/runtime/runtime.ts
9
+ var import_package = /* @__PURE__ */ require_runtime.__toESM(require_package$1.default);
10
+ const VERSION = import_package.default.version;
11
+ var BaseCopilotRuntime = class {
12
+ constructor(options, runner) {
13
+ const { agents, transcriptionService, beforeRequestMiddleware, afterRequestMiddleware, a2ui, mcpApps } = options;
14
+ this.agents = agents;
15
+ this.transcriptionService = transcriptionService;
16
+ this.beforeRequestMiddleware = beforeRequestMiddleware;
17
+ this.afterRequestMiddleware = afterRequestMiddleware;
18
+ this.a2ui = a2ui;
19
+ this.mcpApps = mcpApps;
20
+ this.runner = runner;
21
+ this.licenseChecker = (0, _copilotkit_shared.createLicenseChecker)(options.licenseToken);
22
+ }
23
+ };
24
+ var CopilotSseRuntime = class extends BaseCopilotRuntime {
25
+ constructor(options) {
26
+ super(options, options.runner ?? new require_in_memory.InMemoryAgentRunner());
27
+ this.intelligence = void 0;
28
+ this.mode = _copilotkit_shared.RUNTIME_MODE_SSE;
29
+ }
30
+ };
31
+ var CopilotIntelligenceRuntime = class extends BaseCopilotRuntime {
32
+ constructor(options) {
33
+ super(options, new require_intelligence.IntelligenceAgentRunner({
34
+ url: options.intelligence.ɵgetRunnerWsUrl(),
35
+ authToken: options.intelligence.ɵgetRunnerAuthToken()
36
+ }));
37
+ this.mode = _copilotkit_shared.RUNTIME_MODE_INTELLIGENCE;
38
+ this.intelligence = options.intelligence;
39
+ this.identifyUser = options.identifyUser;
40
+ this.generateThreadNames = options.generateThreadNames ?? true;
41
+ }
42
+ };
43
+ function hasIntelligenceOptions(options) {
44
+ return "intelligence" in options && !!options.intelligence;
45
+ }
46
+ function isIntelligenceRuntime(runtime) {
47
+ return runtime.mode === _copilotkit_shared.RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;
48
+ }
49
+ /**
50
+ * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.
51
+ * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.
52
+ */
53
+ var CopilotRuntime = class {
54
+ constructor(options) {
55
+ this.delegate = hasIntelligenceOptions(options) ? new CopilotIntelligenceRuntime(options) : new CopilotSseRuntime(options);
56
+ }
57
+ get agents() {
58
+ return this.delegate.agents;
59
+ }
60
+ get transcriptionService() {
61
+ return this.delegate.transcriptionService;
62
+ }
63
+ get beforeRequestMiddleware() {
64
+ return this.delegate.beforeRequestMiddleware;
65
+ }
66
+ get afterRequestMiddleware() {
67
+ return this.delegate.afterRequestMiddleware;
68
+ }
69
+ get runner() {
70
+ return this.delegate.runner;
71
+ }
72
+ get a2ui() {
73
+ return this.delegate.a2ui;
74
+ }
75
+ get mcpApps() {
76
+ return this.delegate.mcpApps;
77
+ }
78
+ get intelligence() {
79
+ return this.delegate.intelligence;
80
+ }
81
+ get generateThreadNames() {
82
+ return isIntelligenceRuntime(this.delegate) ? this.delegate.generateThreadNames : void 0;
83
+ }
84
+ get identifyUser() {
85
+ return isIntelligenceRuntime(this.delegate) ? this.delegate.identifyUser : void 0;
86
+ }
87
+ get mode() {
88
+ return this.delegate.mode;
89
+ }
90
+ get licenseChecker() {
91
+ return this.delegate.licenseChecker;
92
+ }
93
+ };
94
+
95
+ //#endregion
96
+ exports.CopilotIntelligenceRuntime = CopilotIntelligenceRuntime;
97
+ exports.CopilotRuntime = CopilotRuntime;
98
+ exports.CopilotSseRuntime = CopilotSseRuntime;
99
+ exports.VERSION = VERSION;
100
+ exports.isIntelligenceRuntime = isIntelligenceRuntime;
101
+ //# sourceMappingURL=runtime.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.cjs","names":["pkg","InMemoryAgentRunner","RUNTIME_MODE_SSE","IntelligenceAgentRunner","RUNTIME_MODE_INTELLIGENCE"],"sources":["../../../src/v2/runtime/runtime.ts"],"sourcesContent":["import {\n MaybePromise,\n NonEmptyRecord,\n RuntimeMode,\n RUNTIME_MODE_SSE,\n RUNTIME_MODE_INTELLIGENCE,\n createLicenseChecker,\n type LicenseChecker,\n} from \"@copilotkit/shared\";\nimport { AbstractAgent } from \"@ag-ui/client\";\nimport type { MCPClientConfig } from \"@ag-ui/mcp-apps-middleware\";\nimport { A2UIMiddlewareConfig } from \"@ag-ui/a2ui-middleware\";\nimport pkg from \"../../../package.json\";\nimport type {\n BeforeRequestMiddleware,\n AfterRequestMiddleware,\n} from \"./middleware\";\nimport { TranscriptionService } from \"./transcription-service/transcription-service\";\nimport { AgentRunner } from \"./runner/agent-runner\";\nimport { InMemoryAgentRunner } from \"./runner/in-memory\";\nimport { IntelligenceAgentRunner } from \"./runner/intelligence\";\nimport { CopilotKitIntelligence } from \"./intelligence-platform\";\n\nexport const VERSION = pkg.version;\n\ninterface BaseCopilotRuntimeMiddlewareOptions {\n /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */\n agents?: string[];\n}\n\nexport type McpAppsServerConfig = MCPClientConfig & {\n /** Agent to bind this server to. If omitted, the server is available to all agents. */\n agentId?: string;\n};\n\nexport interface McpAppsConfig {\n /** List of MCP server configurations. */\n servers: McpAppsServerConfig[];\n}\n\ninterface CopilotRuntimeMiddlewares {\n /** Auto-apply A2UIMiddleware to agents at run time. */\n a2ui?: BaseCopilotRuntimeMiddlewareOptions & A2UIMiddlewareConfig;\n /** Auto-apply MCPAppsMiddleware to agents at run time. */\n mcpApps?: McpAppsConfig;\n}\n\ninterface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {\n /** Map of available agents (loaded lazily is fine). */\n agents: MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;\n /** Optional transcription service for audio processing. */\n transcriptionService?: TranscriptionService;\n /** Optional *before* middleware – callback function or webhook URL. */\n beforeRequestMiddleware?: BeforeRequestMiddleware;\n /** Optional *after* middleware – callback function or webhook URL. */\n afterRequestMiddleware?: AfterRequestMiddleware;\n /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */\n licenseToken?: string;\n}\n\nexport interface CopilotRuntimeUser {\n id: string;\n}\n\nexport type IdentifyUserCallback = (\n request: Request,\n) => MaybePromise<CopilotRuntimeUser>;\n\nexport interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** The runner to use for running agents in SSE mode. */\n runner?: AgentRunner;\n intelligence?: undefined;\n generateThreadNames?: undefined;\n}\n\nexport interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {\n /** Configures Intelligence mode for durable threads and realtime events. */\n intelligence: CopilotKitIntelligence;\n /** Resolves the authenticated user for intelligence requests. */\n identifyUser: IdentifyUserCallback;\n /** Auto-generate short names for newly created threads. */\n generateThreadNames?: boolean;\n}\n\nexport type CopilotRuntimeOptions =\n | CopilotSseRuntimeOptions\n | CopilotIntelligenceRuntimeOptions;\n\nexport interface CopilotRuntimeLike {\n agents: CopilotRuntimeOptions[\"agents\"];\n transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n runner: AgentRunner;\n a2ui: CopilotRuntimeOptions[\"a2ui\"];\n mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n intelligence?: CopilotKitIntelligence;\n identifyUser?: IdentifyUserCallback;\n mode: RuntimeMode;\n licenseChecker?: LicenseChecker;\n}\n\nexport interface CopilotSseRuntimeLike extends CopilotRuntimeLike {\n intelligence?: undefined;\n mode: RUNTIME_MODE_SSE;\n}\n\nexport interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {\n intelligence: CopilotKitIntelligence;\n identifyUser: IdentifyUserCallback;\n generateThreadNames: boolean;\n mode: RUNTIME_MODE_INTELLIGENCE;\n}\n\nabstract class BaseCopilotRuntime implements CopilotRuntimeLike {\n public agents: CopilotRuntimeOptions[\"agents\"];\n public transcriptionService: CopilotRuntimeOptions[\"transcriptionService\"];\n public beforeRequestMiddleware: CopilotRuntimeOptions[\"beforeRequestMiddleware\"];\n public afterRequestMiddleware: CopilotRuntimeOptions[\"afterRequestMiddleware\"];\n public runner: AgentRunner;\n public a2ui: CopilotRuntimeOptions[\"a2ui\"];\n public mcpApps: CopilotRuntimeOptions[\"mcpApps\"];\n public licenseChecker?: LicenseChecker;\n\n abstract readonly intelligence?: CopilotKitIntelligence;\n abstract readonly mode: RuntimeMode;\n\n constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner) {\n const {\n agents,\n transcriptionService,\n beforeRequestMiddleware,\n afterRequestMiddleware,\n a2ui,\n mcpApps,\n } = options;\n\n this.agents = agents;\n this.transcriptionService = transcriptionService;\n this.beforeRequestMiddleware = beforeRequestMiddleware;\n this.afterRequestMiddleware = afterRequestMiddleware;\n this.a2ui = a2ui;\n this.mcpApps = mcpApps;\n this.runner = runner;\n this.licenseChecker = createLicenseChecker(options.licenseToken);\n }\n}\n\nexport class CopilotSseRuntime\n extends BaseCopilotRuntime\n implements CopilotSseRuntimeLike\n{\n readonly intelligence = undefined;\n readonly mode = RUNTIME_MODE_SSE;\n\n constructor(options: CopilotSseRuntimeOptions) {\n super(options, options.runner ?? new InMemoryAgentRunner());\n }\n}\n\nexport class CopilotIntelligenceRuntime\n extends BaseCopilotRuntime\n implements CopilotIntelligenceRuntimeLike\n{\n readonly intelligence: CopilotKitIntelligence;\n readonly identifyUser: IdentifyUserCallback;\n readonly generateThreadNames: boolean;\n readonly mode = RUNTIME_MODE_INTELLIGENCE;\n\n constructor(options: CopilotIntelligenceRuntimeOptions) {\n super(\n options,\n new IntelligenceAgentRunner({\n url: options.intelligence.ɵgetRunnerWsUrl(),\n authToken: options.intelligence.ɵgetRunnerAuthToken(),\n }),\n );\n this.intelligence = options.intelligence;\n this.identifyUser = options.identifyUser;\n this.generateThreadNames = options.generateThreadNames ?? true;\n }\n}\n\nfunction hasIntelligenceOptions(\n options: CopilotRuntimeOptions,\n): options is CopilotIntelligenceRuntimeOptions {\n return \"intelligence\" in options && !!options.intelligence;\n}\n\nexport function isIntelligenceRuntime(\n runtime: CopilotRuntimeLike,\n): runtime is CopilotIntelligenceRuntimeLike {\n return runtime.mode === RUNTIME_MODE_INTELLIGENCE && !!runtime.intelligence;\n}\n\n/**\n * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.\n * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.\n */\nexport class CopilotRuntime implements CopilotRuntimeLike {\n private delegate: CopilotRuntimeLike;\n\n constructor(options: CopilotRuntimeOptions) {\n this.delegate = hasIntelligenceOptions(options)\n ? new CopilotIntelligenceRuntime(options)\n : new CopilotSseRuntime(options);\n }\n\n get agents(): CopilotRuntimeOptions[\"agents\"] {\n return this.delegate.agents;\n }\n\n get transcriptionService(): CopilotRuntimeOptions[\"transcriptionService\"] {\n return this.delegate.transcriptionService;\n }\n\n get beforeRequestMiddleware(): CopilotRuntimeOptions[\"beforeRequestMiddleware\"] {\n return this.delegate.beforeRequestMiddleware;\n }\n\n get afterRequestMiddleware(): CopilotRuntimeOptions[\"afterRequestMiddleware\"] {\n return this.delegate.afterRequestMiddleware;\n }\n\n get runner(): AgentRunner {\n return this.delegate.runner;\n }\n\n get a2ui(): CopilotRuntimeOptions[\"a2ui\"] {\n return this.delegate.a2ui;\n }\n\n get mcpApps(): CopilotRuntimeOptions[\"mcpApps\"] {\n return this.delegate.mcpApps;\n }\n\n get intelligence(): CopilotKitIntelligence | undefined {\n return this.delegate.intelligence;\n }\n\n get generateThreadNames(): boolean | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.generateThreadNames\n : undefined;\n }\n\n get identifyUser(): IdentifyUserCallback | undefined {\n return isIntelligenceRuntime(this.delegate)\n ? this.delegate.identifyUser\n : undefined;\n }\n\n get mode(): RuntimeMode {\n return this.delegate.mode;\n }\n\n get licenseChecker() {\n return this.delegate.licenseChecker;\n }\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAa,UAAUA,uBAAI;AA2F3B,IAAe,qBAAf,MAAgE;CAa9D,YAAY,SAAoC,QAAqB;EACnE,MAAM,EACJ,QACA,sBACA,yBACA,wBACA,MACA,YACE;AAEJ,OAAK,SAAS;AACd,OAAK,uBAAuB;AAC5B,OAAK,0BAA0B;AAC/B,OAAK,yBAAyB;AAC9B,OAAK,OAAO;AACZ,OAAK,UAAU;AACf,OAAK,SAAS;AACd,OAAK,8DAAsC,QAAQ,aAAa;;;AAIpE,IAAa,oBAAb,cACU,mBAEV;CAIE,YAAY,SAAmC;AAC7C,QAAM,SAAS,QAAQ,UAAU,IAAIC,uCAAqB,CAAC;sBAJrC;cACRC;;;AAOlB,IAAa,6BAAb,cACU,mBAEV;CAME,YAAY,SAA4C;AACtD,QACE,SACA,IAAIC,6CAAwB;GAC1B,KAAK,QAAQ,aAAa,iBAAiB;GAC3C,WAAW,QAAQ,aAAa,qBAAqB;GACtD,CAAC,CACH;cATaC;AAUd,OAAK,eAAe,QAAQ;AAC5B,OAAK,eAAe,QAAQ;AAC5B,OAAK,sBAAsB,QAAQ,uBAAuB;;;AAI9D,SAAS,uBACP,SAC8C;AAC9C,QAAO,kBAAkB,WAAW,CAAC,CAAC,QAAQ;;AAGhD,SAAgB,sBACd,SAC2C;AAC3C,QAAO,QAAQ,SAASA,gDAA6B,CAAC,CAAC,QAAQ;;;;;;AAOjE,IAAa,iBAAb,MAA0D;CAGxD,YAAY,SAAgC;AAC1C,OAAK,WAAW,uBAAuB,QAAQ,GAC3C,IAAI,2BAA2B,QAAQ,GACvC,IAAI,kBAAkB,QAAQ;;CAGpC,IAAI,SAA0C;AAC5C,SAAO,KAAK,SAAS;;CAGvB,IAAI,uBAAsE;AACxE,SAAO,KAAK,SAAS;;CAGvB,IAAI,0BAA4E;AAC9E,SAAO,KAAK,SAAS;;CAGvB,IAAI,yBAA0E;AAC5E,SAAO,KAAK,SAAS;;CAGvB,IAAI,SAAsB;AACxB,SAAO,KAAK,SAAS;;CAGvB,IAAI,OAAsC;AACxC,SAAO,KAAK,SAAS;;CAGvB,IAAI,UAA4C;AAC9C,SAAO,KAAK,SAAS;;CAGvB,IAAI,eAAmD;AACrD,SAAO,KAAK,SAAS;;CAGvB,IAAI,sBAA2C;AAC7C,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,sBACd;;CAGN,IAAI,eAAiD;AACnD,SAAO,sBAAsB,KAAK,SAAS,GACvC,KAAK,SAAS,eACd;;CAGN,IAAI,OAAoB;AACtB,SAAO,KAAK,SAAS;;CAGvB,IAAI,iBAAiB;AACnB,SAAO,KAAK,SAAS"}
@@ -0,0 +1,132 @@
1
+
2
+ import { AfterRequestMiddleware, BeforeRequestMiddleware } from "./middleware.cjs";
3
+ import { TranscriptionService } from "./transcription-service/transcription-service.cjs";
4
+ import { AgentRunner } from "./runner/agent-runner.cjs";
5
+ import { CopilotKitIntelligence } from "./intelligence-platform/client.cjs";
6
+ import { LicenseChecker, MaybePromise, NonEmptyRecord, RuntimeMode } from "@copilotkit/shared";
7
+ import { AbstractAgent } from "@ag-ui/client";
8
+ import { MCPClientConfig } from "@ag-ui/mcp-apps-middleware";
9
+ import { A2UIMiddlewareConfig } from "@ag-ui/a2ui-middleware";
10
+
11
+ //#region src/v2/runtime/runtime.d.ts
12
+ declare const VERSION: string;
13
+ interface BaseCopilotRuntimeMiddlewareOptions {
14
+ /** If set, middleware only applies to these named agents. Applies to all agents if omitted. */
15
+ agents?: string[];
16
+ }
17
+ type McpAppsServerConfig = MCPClientConfig & {
18
+ /** Agent to bind this server to. If omitted, the server is available to all agents. */agentId?: string;
19
+ };
20
+ interface McpAppsConfig {
21
+ /** List of MCP server configurations. */
22
+ servers: McpAppsServerConfig[];
23
+ }
24
+ interface CopilotRuntimeMiddlewares {
25
+ /** Auto-apply A2UIMiddleware to agents at run time. */
26
+ a2ui?: BaseCopilotRuntimeMiddlewareOptions & A2UIMiddlewareConfig;
27
+ /** Auto-apply MCPAppsMiddleware to agents at run time. */
28
+ mcpApps?: McpAppsConfig;
29
+ }
30
+ interface BaseCopilotRuntimeOptions extends CopilotRuntimeMiddlewares {
31
+ /** Map of available agents (loaded lazily is fine). */
32
+ agents: MaybePromise<NonEmptyRecord<Record<string, AbstractAgent>>>;
33
+ /** Optional transcription service for audio processing. */
34
+ transcriptionService?: TranscriptionService;
35
+ /** Optional *before* middleware – callback function or webhook URL. */
36
+ beforeRequestMiddleware?: BeforeRequestMiddleware;
37
+ /** Optional *after* middleware – callback function or webhook URL. */
38
+ afterRequestMiddleware?: AfterRequestMiddleware;
39
+ /** Signed license token for server-side feature verification. Falls back to COPILOTKIT_LICENSE_TOKEN env var. */
40
+ licenseToken?: string;
41
+ }
42
+ interface CopilotRuntimeUser {
43
+ id: string;
44
+ }
45
+ type IdentifyUserCallback = (request: Request) => MaybePromise<CopilotRuntimeUser>;
46
+ interface CopilotSseRuntimeOptions extends BaseCopilotRuntimeOptions {
47
+ /** The runner to use for running agents in SSE mode. */
48
+ runner?: AgentRunner;
49
+ intelligence?: undefined;
50
+ generateThreadNames?: undefined;
51
+ }
52
+ interface CopilotIntelligenceRuntimeOptions extends BaseCopilotRuntimeOptions {
53
+ /** Configures Intelligence mode for durable threads and realtime events. */
54
+ intelligence: CopilotKitIntelligence;
55
+ /** Resolves the authenticated user for intelligence requests. */
56
+ identifyUser: IdentifyUserCallback;
57
+ /** Auto-generate short names for newly created threads. */
58
+ generateThreadNames?: boolean;
59
+ }
60
+ type CopilotRuntimeOptions = CopilotSseRuntimeOptions | CopilotIntelligenceRuntimeOptions;
61
+ interface CopilotRuntimeLike {
62
+ agents: CopilotRuntimeOptions["agents"];
63
+ transcriptionService: CopilotRuntimeOptions["transcriptionService"];
64
+ beforeRequestMiddleware: CopilotRuntimeOptions["beforeRequestMiddleware"];
65
+ afterRequestMiddleware: CopilotRuntimeOptions["afterRequestMiddleware"];
66
+ runner: AgentRunner;
67
+ a2ui: CopilotRuntimeOptions["a2ui"];
68
+ mcpApps: CopilotRuntimeOptions["mcpApps"];
69
+ intelligence?: CopilotKitIntelligence;
70
+ identifyUser?: IdentifyUserCallback;
71
+ mode: RuntimeMode;
72
+ licenseChecker?: LicenseChecker;
73
+ }
74
+ interface CopilotSseRuntimeLike extends CopilotRuntimeLike {
75
+ intelligence?: undefined;
76
+ mode: RUNTIME_MODE_SSE;
77
+ }
78
+ interface CopilotIntelligenceRuntimeLike extends CopilotRuntimeLike {
79
+ intelligence: CopilotKitIntelligence;
80
+ identifyUser: IdentifyUserCallback;
81
+ generateThreadNames: boolean;
82
+ mode: RUNTIME_MODE_INTELLIGENCE;
83
+ }
84
+ declare abstract class BaseCopilotRuntime implements CopilotRuntimeLike {
85
+ agents: CopilotRuntimeOptions["agents"];
86
+ transcriptionService: CopilotRuntimeOptions["transcriptionService"];
87
+ beforeRequestMiddleware: CopilotRuntimeOptions["beforeRequestMiddleware"];
88
+ afterRequestMiddleware: CopilotRuntimeOptions["afterRequestMiddleware"];
89
+ runner: AgentRunner;
90
+ a2ui: CopilotRuntimeOptions["a2ui"];
91
+ mcpApps: CopilotRuntimeOptions["mcpApps"];
92
+ licenseChecker?: LicenseChecker;
93
+ abstract readonly intelligence?: CopilotKitIntelligence;
94
+ abstract readonly mode: RuntimeMode;
95
+ constructor(options: BaseCopilotRuntimeOptions, runner: AgentRunner);
96
+ }
97
+ declare class CopilotSseRuntime extends BaseCopilotRuntime implements CopilotSseRuntimeLike {
98
+ readonly intelligence: any;
99
+ readonly mode: "sse";
100
+ constructor(options: CopilotSseRuntimeOptions);
101
+ }
102
+ declare class CopilotIntelligenceRuntime extends BaseCopilotRuntime implements CopilotIntelligenceRuntimeLike {
103
+ readonly intelligence: CopilotKitIntelligence;
104
+ readonly identifyUser: IdentifyUserCallback;
105
+ readonly generateThreadNames: boolean;
106
+ readonly mode: "intelligence";
107
+ constructor(options: CopilotIntelligenceRuntimeOptions);
108
+ }
109
+ declare function isIntelligenceRuntime(runtime: CopilotRuntimeLike): runtime is CopilotIntelligenceRuntimeLike;
110
+ /**
111
+ * Compatibility shim that preserves the legacy `CopilotRuntime` entrypoint.
112
+ * New code should prefer `CopilotSseRuntime` or `CopilotIntelligenceRuntime`.
113
+ */
114
+ declare class CopilotRuntime implements CopilotRuntimeLike {
115
+ private delegate;
116
+ constructor(options: CopilotRuntimeOptions);
117
+ get agents(): CopilotRuntimeOptions["agents"];
118
+ get transcriptionService(): CopilotRuntimeOptions["transcriptionService"];
119
+ get beforeRequestMiddleware(): CopilotRuntimeOptions["beforeRequestMiddleware"];
120
+ get afterRequestMiddleware(): CopilotRuntimeOptions["afterRequestMiddleware"];
121
+ get runner(): AgentRunner;
122
+ get a2ui(): CopilotRuntimeOptions["a2ui"];
123
+ get mcpApps(): CopilotRuntimeOptions["mcpApps"];
124
+ get intelligence(): CopilotKitIntelligence | undefined;
125
+ get generateThreadNames(): boolean | undefined;
126
+ get identifyUser(): IdentifyUserCallback | undefined;
127
+ get mode(): RuntimeMode;
128
+ get licenseChecker(): LicenseChecker;
129
+ }
130
+ //#endregion
131
+ export { CopilotIntelligenceRuntime, CopilotIntelligenceRuntimeLike, CopilotIntelligenceRuntimeOptions, CopilotRuntime, CopilotRuntimeLike, CopilotRuntimeOptions, CopilotRuntimeUser, CopilotSseRuntime, CopilotSseRuntimeLike, CopilotSseRuntimeOptions, IdentifyUserCallback, McpAppsConfig, McpAppsServerConfig, VERSION, isIntelligenceRuntime };
132
+ //# sourceMappingURL=runtime.d.cts.map