@copilotkit/runtime 2.0.0-rc.5 → 2.0.0-rc.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/README.md +29 -4
  2. package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -76
  3. package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
  4. package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
  5. package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
  6. package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
  7. package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
  8. package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
  9. package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
  10. package/dist/agent/ai-sdk.cjs +425 -0
  11. package/dist/agent/ai-sdk.cjs.map +1 -0
  12. package/dist/agent/ai-sdk.d.cts +119 -0
  13. package/dist/agent/ai-sdk.d.cts.map +1 -0
  14. package/dist/agent/ai-sdk.d.mts +119 -0
  15. package/dist/agent/ai-sdk.d.mts.map +1 -0
  16. package/dist/agent/ai-sdk.mjs +419 -0
  17. package/dist/agent/ai-sdk.mjs.map +1 -0
  18. package/dist/agent/classic-tools.cjs +185 -0
  19. package/dist/agent/classic-tools.cjs.map +1 -0
  20. package/dist/agent/classic-tools.mjs +183 -0
  21. package/dist/agent/classic-tools.mjs.map +1 -0
  22. package/dist/agent/converters/aisdk.cjs +17 -4
  23. package/dist/agent/converters/aisdk.cjs.map +1 -1
  24. package/dist/agent/converters/aisdk.d.cts.map +1 -1
  25. package/dist/agent/converters/aisdk.d.mts.map +1 -1
  26. package/dist/agent/converters/aisdk.mjs +18 -2
  27. package/dist/agent/converters/aisdk.mjs.map +1 -1
  28. package/dist/agent/converters/tanstack.cjs +202 -30
  29. package/dist/agent/converters/tanstack.cjs.map +1 -1
  30. package/dist/agent/converters/tanstack.d.cts +90 -6
  31. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  32. package/dist/agent/converters/tanstack.d.mts +90 -6
  33. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  34. package/dist/agent/converters/tanstack.mjs +202 -29
  35. package/dist/agent/converters/tanstack.mjs.map +1 -1
  36. package/dist/agent/learned-skills.cjs +15 -17
  37. package/dist/agent/learned-skills.cjs.map +1 -1
  38. package/dist/agent/learned-skills.d.cts +9 -3
  39. package/dist/agent/learned-skills.d.cts.map +1 -1
  40. package/dist/agent/learned-skills.d.mts +9 -3
  41. package/dist/agent/learned-skills.d.mts.map +1 -1
  42. package/dist/agent/learned-skills.mjs +15 -16
  43. package/dist/agent/learned-skills.mjs.map +1 -1
  44. package/dist/agent/model.cjs +42 -0
  45. package/dist/agent/model.cjs.map +1 -0
  46. package/dist/agent/model.d.cts +19 -0
  47. package/dist/agent/model.d.cts.map +1 -0
  48. package/dist/agent/model.d.mts +19 -0
  49. package/dist/agent/model.d.mts.map +1 -0
  50. package/dist/agent/model.mjs +41 -0
  51. package/dist/agent/model.mjs.map +1 -0
  52. package/dist/agent/state-delta.cjs +0 -1
  53. package/dist/agent/state-delta.cjs.map +1 -1
  54. package/dist/agent.cjs +558 -0
  55. package/dist/agent.cjs.map +1 -0
  56. package/dist/agent.d.cts +455 -0
  57. package/dist/agent.d.cts.map +1 -0
  58. package/dist/agent.d.mts +455 -0
  59. package/dist/agent.d.mts.map +1 -0
  60. package/dist/agent.mjs +551 -0
  61. package/dist/agent.mjs.map +1 -0
  62. package/dist/index.cjs +27 -27
  63. package/dist/index.d.cts +15 -15
  64. package/dist/index.d.mts +15 -15
  65. package/dist/index.mjs +9 -8
  66. package/dist/internal/learned-skills.d.cts +1 -1
  67. package/dist/internal/learned-skills.d.mts +1 -1
  68. package/dist/node.cjs +3 -2
  69. package/dist/node.d.cts +3 -3
  70. package/dist/node.d.mts +3 -3
  71. package/dist/node.mjs +3 -3
  72. package/dist/runtime/core/channel-manager.cjs +10 -2
  73. package/dist/runtime/core/channel-manager.cjs.map +1 -1
  74. package/dist/runtime/core/channel-manager.d.cts +1 -1
  75. package/dist/runtime/core/channel-manager.d.mts +1 -1
  76. package/dist/runtime/core/channel-manager.mjs +10 -1
  77. package/dist/runtime/core/channel-manager.mjs.map +1 -1
  78. package/dist/runtime/core/debug-event-bus.cjs +4 -3
  79. package/dist/runtime/core/debug-event-bus.cjs.map +1 -1
  80. package/dist/runtime/core/debug-event-bus.d.cts +5 -1
  81. package/dist/runtime/core/debug-event-bus.d.cts.map +1 -1
  82. package/dist/runtime/core/debug-event-bus.d.mts +4 -0
  83. package/dist/runtime/core/debug-event-bus.d.mts.map +1 -1
  84. package/dist/runtime/core/debug-event-bus.mjs +5 -3
  85. package/dist/runtime/core/debug-event-bus.mjs.map +1 -1
  86. package/dist/runtime/core/fetch-cors.cjs.map +1 -1
  87. package/dist/runtime/core/fetch-cors.d.cts +2 -2
  88. package/dist/runtime/core/fetch-cors.d.cts.map +1 -1
  89. package/dist/runtime/core/fetch-cors.d.mts +2 -2
  90. package/dist/runtime/core/fetch-cors.d.mts.map +1 -1
  91. package/dist/runtime/core/fetch-cors.mjs.map +1 -1
  92. package/dist/runtime/core/fetch-handler.cjs +24 -13
  93. package/dist/runtime/core/fetch-handler.cjs.map +1 -1
  94. package/dist/runtime/core/fetch-handler.d.cts +35 -14
  95. package/dist/runtime/core/fetch-handler.d.cts.map +1 -1
  96. package/dist/runtime/core/fetch-handler.d.mts +35 -14
  97. package/dist/runtime/core/fetch-handler.d.mts.map +1 -1
  98. package/dist/runtime/core/fetch-handler.mjs +16 -5
  99. package/dist/runtime/core/fetch-handler.mjs.map +1 -1
  100. package/dist/runtime/core/hooks.cjs.map +1 -1
  101. package/dist/runtime/core/hooks.d.cts +5 -5
  102. package/dist/runtime/core/hooks.d.cts.map +1 -1
  103. package/dist/runtime/core/hooks.d.mts +5 -5
  104. package/dist/runtime/core/hooks.d.mts.map +1 -1
  105. package/dist/runtime/core/hooks.mjs.map +1 -1
  106. package/dist/runtime/core/learning.cjs.map +1 -1
  107. package/dist/runtime/core/learning.d.cts +9 -9
  108. package/dist/runtime/core/learning.d.cts.map +1 -1
  109. package/dist/runtime/core/learning.d.mts +8 -8
  110. package/dist/runtime/core/learning.d.mts.map +1 -1
  111. package/dist/runtime/core/learning.mjs.map +1 -1
  112. package/dist/runtime/core/logger.cjs +105 -14
  113. package/dist/runtime/core/logger.cjs.map +1 -1
  114. package/dist/runtime/core/logger.d.cts +26 -9
  115. package/dist/runtime/core/logger.d.cts.map +1 -1
  116. package/dist/runtime/core/logger.d.mts +26 -9
  117. package/dist/runtime/core/logger.d.mts.map +1 -1
  118. package/dist/runtime/core/logger.mjs +105 -12
  119. package/dist/runtime/core/logger.mjs.map +1 -1
  120. package/dist/runtime/core/middleware-sse-parser.cjs +3 -4
  121. package/dist/runtime/core/middleware-sse-parser.cjs.map +1 -1
  122. package/dist/runtime/core/middleware-sse-parser.d.cts.map +1 -1
  123. package/dist/runtime/core/middleware-sse-parser.d.mts.map +1 -1
  124. package/dist/runtime/core/middleware-sse-parser.mjs +2 -2
  125. package/dist/runtime/core/middleware-sse-parser.mjs.map +1 -1
  126. package/dist/runtime/core/middleware.cjs +5 -5
  127. package/dist/runtime/core/middleware.cjs.map +1 -1
  128. package/dist/runtime/core/middleware.d.cts +3 -3
  129. package/dist/runtime/core/middleware.d.cts.map +1 -1
  130. package/dist/runtime/core/middleware.d.mts +3 -3
  131. package/dist/runtime/core/middleware.d.mts.map +1 -1
  132. package/dist/runtime/core/middleware.mjs +4 -3
  133. package/dist/runtime/core/middleware.mjs.map +1 -1
  134. package/dist/runtime/core/package-info.cjs +1 -1
  135. package/dist/runtime/core/package-info.mjs +1 -1
  136. package/dist/runtime/core/runtime-error-reporter.cjs.map +1 -1
  137. package/dist/runtime/core/runtime-error-reporter.mjs.map +1 -1
  138. package/dist/runtime/core/runtime.cjs +29 -46
  139. package/dist/runtime/core/runtime.cjs.map +1 -1
  140. package/dist/runtime/core/runtime.d.cts +157 -91
  141. package/dist/runtime/core/runtime.d.cts.map +1 -1
  142. package/dist/runtime/core/runtime.d.mts +157 -91
  143. package/dist/runtime/core/runtime.d.mts.map +1 -1
  144. package/dist/runtime/core/runtime.mjs +27 -42
  145. package/dist/runtime/core/runtime.mjs.map +1 -1
  146. package/dist/runtime/endpoints/auto-start-channels.cjs +3 -4
  147. package/dist/runtime/endpoints/auto-start-channels.cjs.map +1 -1
  148. package/dist/runtime/endpoints/auto-start-channels.mjs +2 -2
  149. package/dist/runtime/endpoints/auto-start-channels.mjs.map +1 -1
  150. package/dist/runtime/endpoints/node-fetch-handler.cjs +11 -7
  151. package/dist/runtime/endpoints/node-fetch-handler.cjs.map +1 -1
  152. package/dist/runtime/endpoints/node-fetch-handler.d.cts +9 -5
  153. package/dist/runtime/endpoints/node-fetch-handler.d.cts.map +1 -1
  154. package/dist/runtime/endpoints/node-fetch-handler.d.mts +9 -5
  155. package/dist/runtime/endpoints/node-fetch-handler.d.mts.map +1 -1
  156. package/dist/runtime/endpoints/node-fetch-handler.mjs +10 -5
  157. package/dist/runtime/endpoints/node-fetch-handler.mjs.map +1 -1
  158. package/dist/runtime/endpoints/node.cjs +14 -4
  159. package/dist/runtime/endpoints/node.cjs.map +1 -1
  160. package/dist/runtime/endpoints/node.d.cts +39 -16
  161. package/dist/runtime/endpoints/node.d.cts.map +1 -1
  162. package/dist/runtime/endpoints/node.d.mts +39 -16
  163. package/dist/runtime/endpoints/node.d.mts.map +1 -1
  164. package/dist/runtime/endpoints/node.mjs +16 -7
  165. package/dist/runtime/endpoints/node.mjs.map +1 -1
  166. package/dist/runtime/event-transforms/index.d.cts +4 -0
  167. package/dist/runtime/event-transforms/index.d.mts +4 -0
  168. package/dist/runtime/event-transforms/index.mjs +5 -0
  169. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs +277 -0
  170. package/dist/runtime/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  171. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts +61 -0
  172. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  173. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts +61 -0
  174. package/dist/runtime/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  175. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs +276 -0
  176. package/dist/runtime/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  177. package/dist/runtime/event-transforms/recorded-events.cjs +68 -0
  178. package/dist/runtime/event-transforms/recorded-events.cjs.map +1 -0
  179. package/dist/runtime/event-transforms/recorded-events.d.cts +27 -0
  180. package/dist/runtime/event-transforms/recorded-events.d.cts.map +1 -0
  181. package/dist/runtime/event-transforms/recorded-events.d.mts +27 -0
  182. package/dist/runtime/event-transforms/recorded-events.d.mts.map +1 -0
  183. package/dist/runtime/event-transforms/recorded-events.mjs +68 -0
  184. package/dist/runtime/event-transforms/recorded-events.mjs.map +1 -0
  185. package/dist/runtime/event-transforms/streaming-json-scanner.cjs +289 -0
  186. package/dist/runtime/event-transforms/streaming-json-scanner.cjs.map +1 -0
  187. package/dist/runtime/event-transforms/streaming-json-scanner.mjs +288 -0
  188. package/dist/runtime/event-transforms/streaming-json-scanner.mjs.map +1 -0
  189. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs +106 -0
  190. package/dist/runtime/generative-ui/a2ui-v09-actions.cjs.map +1 -0
  191. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs +106 -0
  192. package/dist/runtime/generative-ui/a2ui-v09-actions.mjs.map +1 -0
  193. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs +422 -0
  194. package/dist/runtime/generative-ui/a2ui-v09-catalog.cjs.map +1 -0
  195. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs +422 -0
  196. package/dist/runtime/generative-ui/a2ui-v09-catalog.mjs.map +1 -0
  197. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs +84 -0
  198. package/dist/runtime/generative-ui/a2ui-v09-middleware.cjs.map +1 -0
  199. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts +41 -0
  200. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.cts.map +1 -0
  201. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts +41 -0
  202. package/dist/runtime/generative-ui/a2ui-v09-middleware.d.mts.map +1 -0
  203. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs +83 -0
  204. package/dist/runtime/generative-ui/a2ui-v09-middleware.mjs.map +1 -0
  205. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs +694 -0
  206. package/dist/runtime/generative-ui/a2ui-v09-operations.cjs.map +1 -0
  207. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs +694 -0
  208. package/dist/runtime/generative-ui/a2ui-v09-operations.mjs.map +1 -0
  209. package/dist/runtime/generative-ui/generative-ui-middleware.cjs +0 -1
  210. package/dist/runtime/generative-ui/generative-ui-middleware.cjs.map +1 -1
  211. package/dist/runtime/generative-ui/index.d.cts +1 -0
  212. package/dist/runtime/generative-ui/index.d.mts +1 -0
  213. package/dist/runtime/generative-ui/surface-writer.cjs +4 -5
  214. package/dist/runtime/generative-ui/surface-writer.cjs.map +1 -1
  215. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  216. package/dist/runtime/generative-ui/surface-writer.d.cts.map +1 -1
  217. package/dist/runtime/generative-ui/surface-writer.d.mts.map +1 -1
  218. package/dist/runtime/generative-ui/surface-writer.mjs +5 -5
  219. package/dist/runtime/generative-ui/surface-writer.mjs.map +1 -1
  220. package/dist/runtime/handlers/get-runtime-info.cjs +24 -6
  221. package/dist/runtime/handlers/get-runtime-info.cjs.map +1 -1
  222. package/dist/runtime/handlers/get-runtime-info.mjs +25 -7
  223. package/dist/runtime/handlers/get-runtime-info.mjs.map +1 -1
  224. package/dist/runtime/handlers/handle-connect.cjs +3 -8
  225. package/dist/runtime/handlers/handle-connect.cjs.map +1 -1
  226. package/dist/runtime/handlers/handle-connect.mjs +3 -8
  227. package/dist/runtime/handlers/handle-connect.mjs.map +1 -1
  228. package/dist/runtime/handlers/handle-debug-events.cjs.map +1 -1
  229. package/dist/runtime/handlers/handle-debug-events.mjs.map +1 -1
  230. package/dist/runtime/handlers/handle-inspector-learning.cjs +2 -3
  231. package/dist/runtime/handlers/handle-inspector-learning.cjs.map +1 -1
  232. package/dist/runtime/handlers/handle-inspector-learning.mjs.map +1 -1
  233. package/dist/runtime/handlers/handle-inspector-metadata.cjs +2 -3
  234. package/dist/runtime/handlers/handle-inspector-metadata.cjs.map +1 -1
  235. package/dist/runtime/handlers/handle-inspector-metadata.mjs.map +1 -1
  236. package/dist/runtime/handlers/handle-run.cjs +11 -16
  237. package/dist/runtime/handlers/handle-run.cjs.map +1 -1
  238. package/dist/runtime/handlers/handle-run.mjs +8 -12
  239. package/dist/runtime/handlers/handle-run.mjs.map +1 -1
  240. package/dist/runtime/handlers/handle-stop.cjs +5 -5
  241. package/dist/runtime/handlers/handle-stop.cjs.map +1 -1
  242. package/dist/runtime/handlers/handle-stop.mjs +2 -1
  243. package/dist/runtime/handlers/handle-stop.mjs.map +1 -1
  244. package/dist/runtime/handlers/handle-suggest.cjs +6 -3
  245. package/dist/runtime/handlers/handle-suggest.cjs.map +1 -1
  246. package/dist/runtime/handlers/handle-suggest.mjs +6 -2
  247. package/dist/runtime/handlers/handle-suggest.mjs.map +1 -1
  248. package/dist/runtime/handlers/handle-trajectory-connect.cjs.map +1 -1
  249. package/dist/runtime/handlers/handle-trajectory-connect.mjs.map +1 -1
  250. package/dist/runtime/handlers/handle-transcribe.cjs +0 -1
  251. package/dist/runtime/handlers/handle-transcribe.cjs.map +1 -1
  252. package/dist/runtime/handlers/handle-transcribe.mjs.map +1 -1
  253. package/dist/runtime/handlers/intelligence/annotate.cjs +8 -8
  254. package/dist/runtime/handlers/intelligence/annotate.cjs.map +1 -1
  255. package/dist/runtime/handlers/intelligence/annotate.mjs +5 -4
  256. package/dist/runtime/handlers/intelligence/annotate.mjs.map +1 -1
  257. package/dist/runtime/handlers/intelligence/connect.cjs +6 -2
  258. package/dist/runtime/handlers/intelligence/connect.cjs.map +1 -1
  259. package/dist/runtime/handlers/intelligence/connect.mjs +6 -2
  260. package/dist/runtime/handlers/intelligence/connect.mjs.map +1 -1
  261. package/dist/runtime/handlers/intelligence/memories.cjs +28 -23
  262. package/dist/runtime/handlers/intelligence/memories.cjs.map +1 -1
  263. package/dist/runtime/handlers/intelligence/memories.mjs +12 -6
  264. package/dist/runtime/handlers/intelligence/memories.mjs.map +1 -1
  265. package/dist/runtime/handlers/intelligence/run.cjs +38 -30
  266. package/dist/runtime/handlers/intelligence/run.cjs.map +1 -1
  267. package/dist/runtime/handlers/intelligence/run.mjs +37 -28
  268. package/dist/runtime/handlers/intelligence/run.mjs.map +1 -1
  269. package/dist/runtime/handlers/intelligence/thread-names.cjs +6 -5
  270. package/dist/runtime/handlers/intelligence/thread-names.cjs.map +1 -1
  271. package/dist/runtime/handlers/intelligence/thread-names.mjs +3 -1
  272. package/dist/runtime/handlers/intelligence/thread-names.mjs.map +1 -1
  273. package/dist/runtime/handlers/intelligence/threads.cjs +40 -31
  274. package/dist/runtime/handlers/intelligence/threads.cjs.map +1 -1
  275. package/dist/runtime/handlers/intelligence/threads.mjs +18 -8
  276. package/dist/runtime/handlers/intelligence/threads.mjs.map +1 -1
  277. package/dist/runtime/handlers/shared/agent-utils.cjs +50 -46
  278. package/dist/runtime/handlers/shared/agent-utils.cjs.map +1 -1
  279. package/dist/runtime/handlers/shared/agent-utils.mjs +47 -42
  280. package/dist/runtime/handlers/shared/agent-utils.mjs.map +1 -1
  281. package/dist/runtime/handlers/shared/cloud-telemetry.cjs +0 -1
  282. package/dist/runtime/handlers/shared/cloud-telemetry.cjs.map +1 -1
  283. package/dist/runtime/handlers/shared/memory-policy.cjs.map +1 -1
  284. package/dist/runtime/handlers/shared/memory-policy.mjs.map +1 -1
  285. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs +4 -3
  286. package/dist/runtime/handlers/shared/resolve-intelligence-user.cjs.map +1 -1
  287. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs +4 -3
  288. package/dist/runtime/handlers/shared/resolve-intelligence-user.mjs.map +1 -1
  289. package/dist/runtime/handlers/shared/sse-response.cjs +77 -78
  290. package/dist/runtime/handlers/shared/sse-response.cjs.map +1 -1
  291. package/dist/runtime/handlers/shared/sse-response.mjs +77 -77
  292. package/dist/runtime/handlers/shared/sse-response.mjs.map +1 -1
  293. package/dist/runtime/handlers/shared/thread-access.cjs +4 -3
  294. package/dist/runtime/handlers/shared/thread-access.cjs.map +1 -1
  295. package/dist/runtime/handlers/shared/thread-access.d.cts.map +1 -1
  296. package/dist/runtime/handlers/shared/thread-access.d.mts.map +1 -1
  297. package/dist/runtime/handlers/shared/thread-access.mjs +4 -3
  298. package/dist/runtime/handlers/shared/thread-access.mjs.map +1 -1
  299. package/dist/runtime/handlers/sse/connect.cjs +2 -0
  300. package/dist/runtime/handlers/sse/connect.cjs.map +1 -1
  301. package/dist/runtime/handlers/sse/connect.mjs +2 -0
  302. package/dist/runtime/handlers/sse/connect.mjs.map +1 -1
  303. package/dist/runtime/handlers/sse/run.cjs +5 -2
  304. package/dist/runtime/handlers/sse/run.cjs.map +1 -1
  305. package/dist/runtime/handlers/sse/run.mjs +5 -2
  306. package/dist/runtime/handlers/sse/run.mjs.map +1 -1
  307. package/dist/runtime/index.cjs +29 -0
  308. package/dist/runtime/index.cjs.map +1 -0
  309. package/dist/runtime/index.d.cts +61 -15
  310. package/dist/runtime/index.d.cts.map +1 -1
  311. package/dist/runtime/index.d.mts +61 -15
  312. package/dist/runtime/index.d.mts.map +1 -1
  313. package/dist/runtime/index.mjs +27 -0
  314. package/dist/runtime/index.mjs.map +1 -0
  315. package/dist/runtime/intelligence-platform/analytics-context.cjs +84 -0
  316. package/dist/runtime/intelligence-platform/analytics-context.cjs.map +1 -0
  317. package/dist/runtime/intelligence-platform/analytics-context.mjs +83 -0
  318. package/dist/runtime/intelligence-platform/analytics-context.mjs.map +1 -0
  319. package/dist/runtime/intelligence-platform/client.cjs +30 -4
  320. package/dist/runtime/intelligence-platform/client.cjs.map +1 -1
  321. package/dist/runtime/intelligence-platform/client.d.cts +25 -2
  322. package/dist/runtime/intelligence-platform/client.d.cts.map +1 -1
  323. package/dist/runtime/intelligence-platform/client.d.mts +25 -2
  324. package/dist/runtime/intelligence-platform/client.d.mts.map +1 -1
  325. package/dist/runtime/intelligence-platform/client.mjs +30 -3
  326. package/dist/runtime/intelligence-platform/client.mjs.map +1 -1
  327. package/dist/runtime/intelligence-platform/learning-management.cjs +7 -8
  328. package/dist/runtime/intelligence-platform/learning-management.cjs.map +1 -1
  329. package/dist/runtime/intelligence-platform/learning-management.mjs +7 -7
  330. package/dist/runtime/intelligence-platform/learning-management.mjs.map +1 -1
  331. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs +104 -110
  332. package/dist/runtime/intelligence-platform/skill-registry/archive.cjs.map +1 -1
  333. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts +8 -2
  334. package/dist/runtime/intelligence-platform/skill-registry/archive.d.cts.map +1 -1
  335. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts +8 -2
  336. package/dist/runtime/intelligence-platform/skill-registry/archive.d.mts.map +1 -1
  337. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs +104 -109
  338. package/dist/runtime/intelligence-platform/skill-registry/archive.mjs.map +1 -1
  339. package/dist/runtime/intelligence-platform/skill-registry/config.cjs +0 -1
  340. package/dist/runtime/intelligence-platform/skill-registry/config.cjs.map +1 -1
  341. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  342. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  343. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs +22 -19
  344. package/dist/runtime/intelligence-platform/skill-registry/registry.cjs.map +1 -1
  345. package/dist/runtime/intelligence-platform/skill-registry/registry.d.cts.map +1 -1
  346. package/dist/runtime/intelligence-platform/skill-registry/registry.d.mts.map +1 -1
  347. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs +22 -19
  348. package/dist/runtime/intelligence-platform/skill-registry/registry.mjs.map +1 -1
  349. package/dist/runtime/intelligence-platform/stop-run.cjs +50 -0
  350. package/dist/runtime/intelligence-platform/stop-run.cjs.map +1 -0
  351. package/dist/runtime/intelligence-platform/stop-run.mjs +50 -0
  352. package/dist/runtime/intelligence-platform/stop-run.mjs.map +1 -0
  353. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs +3 -3
  354. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.cjs.map +1 -1
  355. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs +2 -1
  356. package/dist/runtime/intelligence-platform/thread-lock-heartbeat.mjs.map +1 -1
  357. package/dist/runtime/intelligence-platform/trajectories.cjs +2 -3
  358. package/dist/runtime/intelligence-platform/trajectories.cjs.map +1 -1
  359. package/dist/runtime/intelligence-platform/trajectories.mjs +2 -2
  360. package/dist/runtime/intelligence-platform/trajectories.mjs.map +1 -1
  361. package/dist/runtime/node.d.cts +2 -2
  362. package/dist/runtime/node.d.mts +2 -2
  363. package/dist/runtime/runner/agent-runner.cjs +0 -1
  364. package/dist/runtime/runner/agent-runner.cjs.map +1 -1
  365. package/dist/runtime/runner/agent-runner.d.cts +9 -0
  366. package/dist/runtime/runner/agent-runner.d.cts.map +1 -1
  367. package/dist/runtime/runner/agent-runner.d.mts +9 -0
  368. package/dist/runtime/runner/agent-runner.d.mts.map +1 -1
  369. package/dist/runtime/runner/agent-runner.mjs.map +1 -1
  370. package/dist/runtime/runner/in-memory.cjs +0 -1
  371. package/dist/runtime/runner/in-memory.cjs.map +1 -1
  372. package/dist/runtime/runner/index.d.cts +1 -1
  373. package/dist/runtime/runner/index.d.mts +1 -1
  374. package/dist/runtime/runner/index.mjs +1 -1
  375. package/dist/runtime/runner/intelligence.cjs +55 -9
  376. package/dist/runtime/runner/intelligence.cjs.map +1 -1
  377. package/dist/runtime/runner/intelligence.d.cts +12 -1
  378. package/dist/runtime/runner/intelligence.d.cts.map +1 -1
  379. package/dist/runtime/runner/intelligence.d.mts +12 -1
  380. package/dist/runtime/runner/intelligence.d.mts.map +1 -1
  381. package/dist/runtime/runner/intelligence.mjs +56 -10
  382. package/dist/runtime/runner/intelligence.mjs.map +1 -1
  383. package/dist/runtime/telemetry/disclosure.cjs +2 -3
  384. package/dist/runtime/telemetry/disclosure.cjs.map +1 -1
  385. package/dist/runtime/telemetry/disclosure.mjs +3 -3
  386. package/dist/runtime/telemetry/disclosure.mjs.map +1 -1
  387. package/dist/runtime/telemetry/events.d.cts +1 -1
  388. package/dist/runtime/telemetry/events.d.mts +1 -1
  389. package/dist/runtime/telemetry/instance-created.cjs +33 -12
  390. package/dist/runtime/telemetry/instance-created.cjs.map +1 -1
  391. package/dist/runtime/telemetry/instance-created.mjs +33 -12
  392. package/dist/runtime/telemetry/instance-created.mjs.map +1 -1
  393. package/dist/runtime/telemetry/telemetry-client.cjs +0 -5
  394. package/dist/runtime/telemetry/telemetry-client.cjs.map +1 -1
  395. package/dist/runtime/telemetry/telemetry-client.mjs +0 -4
  396. package/dist/runtime/telemetry/telemetry-client.mjs.map +1 -1
  397. package/dist/runtime/telemetry/telemetry-identity.cjs +0 -1
  398. package/dist/runtime/telemetry/telemetry-identity.cjs.map +1 -1
  399. package/package.json +54 -29
  400. package/dist/_virtual/_rolldown/runtime.cjs +0 -29
  401. package/dist/agent/converters/index.d.mts +0 -2
  402. package/dist/agent/index.cjs +0 -1328
  403. package/dist/agent/index.cjs.map +0 -1
  404. package/dist/agent/index.d.cts +0 -467
  405. package/dist/agent/index.d.cts.map +0 -1
  406. package/dist/agent/index.d.mts +0 -468
  407. package/dist/agent/index.d.mts.map +0 -1
  408. package/dist/agent/index.mjs +0 -1318
  409. package/dist/agent/index.mjs.map +0 -1
  410. package/dist/agent/mcp-tool-names.cjs +0 -82
  411. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  412. package/dist/agent/mcp-tool-names.mjs +0 -80
  413. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  414. package/dist/agent/url-download.cjs.map +0 -1
  415. package/dist/agent/url-download.d.cts.map +0 -1
  416. package/dist/agent/url-download.d.mts.map +0 -1
  417. package/dist/agent/url-download.mjs.map +0 -1
package/README.md CHANGED
@@ -98,7 +98,7 @@ need `identifyUser(request)`. Each Channel has its own `identifyUser` policy in
98
98
  functional web routes.
99
99
 
100
100
  ```ts
101
- const runtime = new CopilotRuntime({
101
+ const runtime = new CopilotKitRuntime({
102
102
  agents,
103
103
  intelligence,
104
104
  identifyUser: authenticateApplicationUser,
@@ -125,9 +125,27 @@ routes and does not attach Memory tools.
125
125
  `CopilotKitIntelligence({ enableEnterpriseLearning: true })` remain for one
126
126
  compatibility window. New code should use `memory.access`.
127
127
 
128
+ ## Recorded event transforms
129
+
130
+ `@copilotkit/runtime` exports `OpenGenerativeUIMiddleware`, the upstream
131
+ `A2UIMiddleware`, and `transformRecordedEvents(input, events, options)`. In 1.x
132
+ they were in `@copilotkit/shared/event-transforms`.
133
+
134
+ `transformRecordedEvents` applies the same converters to one recorded,
135
+ pre-middleware AG-UI run without executing tools or contacting an agent. Enable converters explicitly with `openGenerativeUI: true`
136
+ and/or `a2ui: { ...originalRuntimeOptions }`. Pass the recorded input, including
137
+ prior messages and catalog context, to preserve live conversion behavior.
138
+
139
+ The result includes the original events and generated activities in runtime
140
+ order. The caller owns persistence IDs, historical timestamps, and provenance.
141
+ A2UI can generate random message IDs for synthetic tool results; an importer
142
+ that needs deterministic IDs must assign them before saving. Do not process
143
+ already transformed histories a second time. It does not include MCP
144
+ execution or recreate runtime configuration absent from the recording.
145
+
128
146
  ## Analytics & Privacy
129
147
 
130
- CopilotKit uses [Scarf](https://scarf.sh) for anonymous usage analytics to help improve the product. Scarf handles all privacy compliance and does not store raw IP addresses. This helps us understand how CopilotKit is being used and prioritize improvements.
148
+ The runtime sends anonymous usage telemetry to help improve the product. This helps us understand how CopilotKit is being used and prioritize improvements.
131
149
 
132
150
  ### Opting Out
133
151
 
@@ -167,11 +185,18 @@ events and supports both single-event and batched gateway acknowledgments.
167
185
 
168
186
  ## BuiltInAgent skill delivery from multiple containers
169
187
 
188
+ `BuiltInAgent` takes a TanStack AI adapter as `model`. The runtime installs TanStack AI (`@tanstack/ai`). Install the adapter for your provider:
189
+
190
+ ```bash
191
+ npm install @tanstack/ai-openai
192
+ ```
193
+
170
194
  ```typescript
171
- import { BuiltInAgent } from "@copilotkit/runtime";
195
+ import { BuiltInAgent } from "@copilotkit/runtime/agent";
196
+ import { openaiText } from "@tanstack/ai-openai";
172
197
 
173
198
  const agent = new BuiltInAgent({
174
- model: "openai/gpt-4o",
199
+ model: openaiText("gpt-6-luna"),
175
200
  learnedSkills: {
176
201
  containers: [
177
202
  { id: "support", revision: "revision-123" },
@@ -1,8 +1,7 @@
1
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
2
1
  let _copilotkit_shared = require("@copilotkit/shared");
3
2
  let ai = require("ai");
4
3
 
5
- //#region src/agent/url-download.ts
4
+ //#region src/agent/ai-sdk/url-download.ts
6
5
  const DEFAULT_MAX_BYTES = 20 * 1024 * 1024;
7
6
  const DEFAULT_TIMEOUT_MS = 3e4;
8
7
  const DEFAULT_MAX_REDIRECTS = 3;
@@ -92,7 +91,6 @@ function urlForLog(url) {
92
91
  function redactUrls(text) {
93
92
  return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/[^\s?#"'`<>]*)[?#][^\s"'`<>]*/gi, "$1");
94
93
  }
95
- const loggedErrors = /* @__PURE__ */ new WeakSet();
96
94
  /**
97
95
  * Returns the error for a failed or refused download and logs it on the
98
96
  * server. `detail` goes only to the log: the client sees `message`, which
@@ -102,51 +100,17 @@ const loggedErrors = /* @__PURE__ */ new WeakSet();
102
100
  * DNS names.
103
101
  */
104
102
  function refuse(url, message, detail, statusCode) {
105
- console.warn(redactUrls(`[BuiltInAgent] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : ""}`));
106
- const error = new ai.DownloadError({
103
+ console.warn(redactUrls(`[CopilotKit] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : ""}`));
104
+ return new ai.DownloadError({
107
105
  url: urlForLog(url),
108
106
  message,
109
107
  statusCode
110
108
  });
111
- loggedErrors.add(error);
112
- return error;
113
- }
114
- /**
115
- * @internal BuiltInAgent's `onError` for its `streamText` call. The AI SDK's
116
- * default handler prints the whole error, which for a download error holds
117
- * the URL with its query. This logs an error once, with the same detail
118
- * (for a provider API error, its status code and response body) but with the
119
- * query and fragment removed from every URL, and skips the download errors
120
- * that were already logged here.
121
- */
122
- function logModelCallError(error) {
123
- if (typeof error === "object" && error !== null && loggedErrors.has(error)) return;
124
- const frames = error instanceof Error && error.stack ? error.stack.split("\n").filter((line) => /^\s+at /.test(line)).join("\n") : "";
125
- console.error(redactUrls(`[BuiltInAgent] The model call failed: ${describeModelError(error)}${frames ? `\n${frames}` : ""}`));
126
109
  }
127
110
  const MAX_LOGGED_FIELD_LENGTH = 2e3;
128
111
  function truncateForLog(text) {
129
112
  return text.length > MAX_LOGGED_FIELD_LENGTH ? `${text.slice(0, MAX_LOGGED_FIELD_LENGTH)}… (${text.length} characters)` : text;
130
113
  }
131
- /**
132
- * {@link describeError}, followed by the other fields of the error, such as
133
- * the `statusCode`, `responseBody` and `url` of the AI SDK's APICallError. A
134
- * value that is not an Error, such as the plain object that a provider
135
- * stream sends as its error, is logged as JSON.
136
- */
137
- function describeModelError(error) {
138
- if (!(error instanceof Error)) return truncateForLog(describeValue(error));
139
- const fields = Object.entries(error).filter(([key]) => ![
140
- "name",
141
- "message",
142
- "stack",
143
- "cause",
144
- "code"
145
- ].includes(key)).map(([key, value]) => {
146
- return `${key}: ${truncateForLog(value instanceof Error ? describeError(value) : typeof value === "string" ? value : describeValue(value))}`;
147
- });
148
- return `${error.name && error.name !== "Error" ? `${error.name}: ` : ""}${describeError(error)}${fields.length > 0 ? ` {${fields.join("; ")}}` : ""}`;
149
- }
150
114
  /** Message, error code and causes of an error, for the server log. */
151
115
  function describeError(error, depth = 0) {
152
116
  if (typeof error === "string") return error;
@@ -186,7 +150,7 @@ function comparableHost(hostname) {
186
150
  * exact host, or `*.` followed by a host suffix.
187
151
  */
188
152
  function normalizeAllowedHost(entry) {
189
- const invalid = (reason) => /* @__PURE__ */ new Error(`urlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`);
153
+ const invalid = (reason) => /* @__PURE__ */ new Error(`createSafeUrlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`);
190
154
  if (typeof entry !== "string" || entry === "") throw invalid("it must be a non-empty hostname");
191
155
  if (/[\s/?#@\\]/.test(entry)) throw invalid("give only a hostname, without a scheme, path or user");
192
156
  const wildcard = entry.startsWith("*.");
@@ -207,7 +171,7 @@ function normalizeAllowedHost(entry) {
207
171
  }
208
172
  function normalizeAllowedHosts(entries) {
209
173
  if (entries === void 0) return void 0;
210
- if (!Array.isArray(entries)) throw new Error("urlDownload.allowedHosts must be an array of hostnames");
174
+ if (!Array.isArray(entries)) throw new Error("createSafeUrlDownload.allowedHosts must be an array of hostnames");
211
175
  return entries.map(normalizeAllowedHost);
212
176
  }
213
177
  function hostAllowed(hostname, allowedHosts) {
@@ -305,7 +269,7 @@ async function readBody(url, response, maxBytes, budget) {
305
269
  }
306
270
  async function downloadOne(original, options, internals, outer, budget) {
307
271
  const modules = await loadNodeModules().catch((error) => {
308
- throw refuse(original, "URL download needs Node.js networking modules, which are not available here.", `loading them failed: ${describeError(error)}. On a runtime without them, set urlDownload to "disabled" or to your own download function`);
272
+ throw refuse(original, "URL download needs Node.js networking modules, which are not available here.", `loading them failed: ${describeError(error)}. On a runtime without them, pass your own download function as experimental_download`);
309
273
  });
310
274
  defaultPolicy ??= buildAddressPolicy(modules.net);
311
275
  const isPublic = internals.isPublicAddress ?? defaultPolicy;
@@ -389,7 +353,7 @@ function integerOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER
389
353
  const result = value ?? fallback;
390
354
  if (!Number.isSafeInteger(result) || result < min || result > max) {
391
355
  const range = max === Number.MAX_SAFE_INTEGER ? `an integer of at least ${min}` : `an integer from ${min} to ${max}`;
392
- throw new Error(`urlDownload.${name} must be ${range}, got ${describeValue(value)}`);
356
+ throw new Error(`createSafeUrlDownload.${name} must be ${range}, got ${describeValue(value)}`);
393
357
  }
394
358
  return result;
395
359
  }
@@ -402,11 +366,11 @@ const OPTION_NAMES = {
402
366
  maxTotalBytes: true
403
367
  };
404
368
  function checkOptionsObject(options) {
405
- if (typeof options !== "object" || options === null || Array.isArray(options)) throw new Error(`urlDownload options must be an object, got ${describeValue(options)}`);
369
+ if (typeof options !== "object" || options === null || Array.isArray(options)) throw new Error(`createSafeUrlDownload options must be an object, got ${describeValue(options)}`);
406
370
  }
407
371
  function checkOptionNames(options) {
408
372
  checkOptionsObject(options);
409
- for (const name of Object.keys(options)) if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) throw new Error(`urlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(", ")}`);
373
+ for (const name of Object.keys(options)) if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) throw new Error(`createSafeUrlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(", ")}`);
410
374
  }
411
375
  /** @internal Factory with test seams; use {@link createSafeUrlDownload}. */
412
376
  function createGuardedUrlDownload(options = {}, internals = {}) {
@@ -445,27 +409,14 @@ function createGuardedUrlDownload(options = {}, internals = {}) {
445
409
  return Object.assign((requests) => downloadAll(requests), { forRun: (signal) => (requests) => downloadAll(requests, signal) });
446
410
  }
447
411
  /**
448
- * @internal Resolves BuiltInAgent's `urlDownload` setting once, so that an
449
- * invalid setting fails when the agent is constructed. The result gives the
450
- * download function for one run; the default downloader stops when the run
451
- * is aborted.
452
- */
453
- function resolveUrlDownloadSetting(setting) {
454
- if (setting === "disabled") return () => disabledUrlDownload;
455
- if (typeof setting === "function") return () => setting;
456
- if (setting === void 0 || setting === null) return createGuardedUrlDownload().forRun;
457
- if (typeof setting === "object" && !Array.isArray(setting)) return createGuardedUrlDownload(setting).forRun;
458
- throw new Error(`urlDownload must be "disabled", an options object or a download function, got ${describeValue(setting)}`);
459
- }
460
- /**
461
412
  * Creates an AI SDK download function (`experimental_download`) that only
462
- * fetches public internet addresses, with the same checks and limits as
463
- * BuiltInAgent's default downloader. Pass it to `streamText` yourself when
464
- * you use BuiltInAgent's AI SDK factory mode. Create it in the factory with
465
- * the run's abort signal, so that an aborted run stops its downloads:
413
+ * fetches public internet addresses. For `streamText` calls in a
414
+ * `type: "aisdk"` factory. Create it in the factory with the run's abort
415
+ * signal, so that an aborted run stops its downloads:
466
416
  *
467
417
  * ```ts
468
- * import { createSafeUrlDownload } from "@copilotkit/runtime";
418
+ * import { streamText } from "ai";
419
+ * import { createSafeUrlDownload } from "@copilotkit/runtime/agent/ai-sdk";
469
420
  *
470
421
  * factory: (ctx) =>
471
422
  * streamText({
@@ -476,27 +427,19 @@ function resolveUrlDownloadSetting(setting) {
476
427
  * }),
477
428
  * ```
478
429
  *
479
- * Invalid options throw here, when the function is created.
430
+ * @param options - Host allow list, size, time and count limits, and the
431
+ * abort `signal`. All are optional.
432
+ * @throws Error when an option is invalid. It throws here, when the function
433
+ * is created, not on the first download.
480
434
  */
481
435
  function createSafeUrlDownload(options = {}) {
482
436
  checkOptionsObject(options);
483
437
  const { signal, ...downloadOptions } = options;
484
- if (signal !== void 0 && !(signal instanceof AbortSignal)) throw new Error(`urlDownload signal must be an AbortSignal, got ${describeValue(signal)}`);
438
+ if (signal !== void 0 && !(signal instanceof AbortSignal)) throw new Error(`createSafeUrlDownload signal must be an AbortSignal, got ${describeValue(signal)}`);
485
439
  const download = createGuardedUrlDownload(downloadOptions);
486
440
  return signal ? download.forRun(signal) : download;
487
441
  }
488
- /**
489
- * A download function that never fetches from the network. URLs that the
490
- * model takes as-is and `data:` URLs are left to the AI SDK; any other URL,
491
- * whatever its scheme, fails the run.
492
- */
493
- const disabledUrlDownload = async (requests) => requests.map((request) => {
494
- if (leftToAiSdk(request)) return null;
495
- throw refuse(request.url, "Server-side URL download is disabled (urlDownload: \"disabled\").");
496
- });
497
442
 
498
443
  //#endregion
499
444
  exports.createSafeUrlDownload = createSafeUrlDownload;
500
- exports.logModelCallError = logModelCallError;
501
- exports.resolveUrlDownloadSetting = resolveUrlDownloadSetting;
502
445
  //# sourceMappingURL=url-download.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-download.cjs","names":["COPILOTKIT_VERSION","DownloadError"],"sources":["../../../src/agent/ai-sdk/url-download.ts"],"sourcesContent":["/**\n * Server-side download of URL attachments (image/file parts) for AI SDK\n * `streamText` calls, used as their `experimental_download`.\n *\n * The AI SDK downloads any URL attachment that the model cannot take as a URL\n * and puts the bytes into the prompt. The URL comes from the request, so the\n * default downloader lets a caller make the server fetch internal addresses.\n * The AI SDK's own check rejects literal private IPs and the names\n * `localhost`, `*.local` and `*.localhost`, but it compares the literal text\n * and never resolves DNS: a hostname that resolves to a private address, or a\n * spelling such as `localhost.`, gets through.\n *\n * This downloader:\n * - leaves `data:` URLs to the AI SDK, which decodes them without a fetch;\n * - accepts only http and https URLs without credentials;\n * - resolves the hostname and rejects any non-public address;\n * - connects only to the addresses it checked (no second DNS lookup);\n * - checks every redirect target the same way, and refuses https to http;\n * - limits the size and time of each download, and the number and total\n * size of the downloads for one model call;\n * - stops when the `signal` given to `createSafeUrlDownload` aborts, or when\n * another download of the same call fails.\n *\n * The client gets the same message whether a host did not resolve or resolved\n * to a non-public address, and the reason is only logged on the server. Two\n * residual signals are accepted: the time to fail can differ between the two\n * cases, and a DNS lookup that hangs (for example in an internal zone) ends\n * with the timeout message instead.\n */\nimport type * as DnsPromises from \"node:dns/promises\";\nimport type * as Http from \"node:http\";\nimport type { IncomingMessage } from \"node:http\";\nimport type * as Https from \"node:https\";\nimport type * as Net from \"node:net\";\nimport type { LookupAddress } from \"node:dns\";\nimport type { LookupFunction } from \"node:net\";\nimport { COPILOTKIT_VERSION } from \"@copilotkit/shared\";\nimport { DownloadError } from \"ai\";\nimport type { Experimental_DownloadFunction as DownloadFunction } from \"ai\";\n\n/** Options for the default, public-network-only URL downloader. */\nexport interface SafeUrlDownloadOptions {\n /**\n * Hostnames that may be downloaded. When omitted, any hostname is allowed.\n * Every resolved address must be public in both cases, and every redirect\n * target must match as well.\n *\n * - `cdn.example.com` matches exactly that host.\n * - `*.example.com` matches any subdomain (`a.example.com`,\n * `a.b.example.com`) but not `example.com` itself; list both if needed.\n *\n * Matching ignores case and a trailing dot. Unicode names match their\n * punycode form, and an IPv6 address may be given with or without\n * brackets. An entry with a scheme, port, path or user, and a wildcard over\n * an IP address (`*.1.2.3.4`), are rejected when the downloader is created.\n * An empty list refuses every server-side download; `data:` URLs and URLs\n * that the model takes directly are not downloaded, so they still pass.\n */\n allowedHosts?: string[];\n /** Largest response body to accept, in bytes (at least 1). Default: 20 MiB. */\n maxBytes?: number;\n /**\n * Time limit for one download, including redirects, in ms. From 1 to\n * 2147483647 (the largest delay `setTimeout` supports). Default: 30000.\n */\n timeoutMs?: number;\n /** Largest number of redirects to follow; 0 follows none. Default: 3. */\n maxRedirects?: number;\n /**\n * Largest number of distinct URLs to download for one model call (at\n * least 1); a URL that appears twice is downloaded once. The AI SDK\n * downloads the attachments of every user message again for each step of\n * a multi-step run. Default: 20.\n */\n maxDownloads?: number;\n /**\n * Largest number of bytes to download for one model call, over all its\n * URLs (at least 1). Default: 50 MiB.\n */\n maxTotalBytes?: number;\n}\n\n/** @internal Test seams. Not part of the public API. */\nexport interface UrlDownloadInternals {\n resolveHost?: (hostname: string) => Promise<LookupAddress[]>;\n /**\n * Replaces the address policy. It has the shape of the exported\n * {@link isPublicAddress}; an async answer is awaited.\n */\n isPublicAddress?: (address: string) => boolean | Promise<boolean>;\n /** CA certificates to trust for https instead of the default ones. */\n ca?: string;\n}\n\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_REDIRECTS = 3;\nconst DEFAULT_MAX_DOWNLOADS = 20;\nconst DEFAULT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;\n// One message for both cases, so that the error does not reveal whether an\n// internal name exists. The reason is logged on the server only. (A lookup\n// that hangs ends with the timeout message instead; see the file header.)\nconst HOST_REFUSED =\n \"The URL host is not a public address, or it could not be resolved.\";\n// For a network, TLS or response stream error. The cause, which can name a\n// resolved address, is only logged.\nconst DOWNLOAD_FAILED = \"The download failed.\";\nconst USER_AGENT = `CopilotKit-Runtime/${COPILOTKIT_VERSION}`;\nconst REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\ntype NodeModules = {\n dns: typeof DnsPromises;\n http: typeof Http;\n https: typeof Https;\n net: typeof Net;\n};\n\nlet nodeModules: Promise<NodeModules> | undefined;\n\ntype GetBuiltinModule = <T>(id: string) => T;\n\n// Loaded on first use so that importing the agent does not require Node\n// networking modules. Where they are not available (for example on an edge\n// runtime), downloads fail closed and the log says how to configure them.\n// `process.getBuiltinModule` (Node 20.16+) is used instead of `import(\"node:…\")`\n// so that edge bundlers (Workers, Vercel Edge) never see a Node specifier.\nfunction loadNodeModules(): Promise<NodeModules> {\n nodeModules ??= Promise.resolve()\n .then(() => {\n const load = (\n globalThis.process as\n | { getBuiltinModule?: GetBuiltinModule }\n | undefined\n )?.getBuiltinModule;\n if (!load) throw new Error(\"process.getBuiltinModule is not available\");\n return {\n dns: load<typeof DnsPromises>(\"node:dns/promises\"),\n http: load<typeof Http>(\"node:http\"),\n https: load<typeof Https>(\"node:https\"),\n net: load<typeof Net>(\"node:net\"),\n };\n })\n .catch((error: unknown) => {\n // Try again on the next download instead of failing forever.\n nodeModules = undefined;\n throw error;\n });\n return nodeModules;\n}\n\ntype AddressPolicy = (address: string) => boolean;\nlet defaultPolicy: AddressPolicy | undefined;\n\nfunction buildAddressPolicy(net: NodeModules[\"net\"]): AddressPolicy {\n const nonPublicV4 = new net.BlockList();\n for (const [address, prefix] of [\n [\"0.0.0.0\", 8],\n [\"10.0.0.0\", 8],\n [\"100.64.0.0\", 10], // Carrier-grade NAT.\n [\"127.0.0.0\", 8],\n [\"169.254.0.0\", 16], // Link-local, including cloud metadata.\n [\"172.16.0.0\", 12],\n [\"192.0.0.0\", 24],\n [\"192.0.2.0\", 24],\n [\"192.88.99.0\", 24],\n [\"192.168.0.0\", 16],\n [\"198.18.0.0\", 15],\n [\"198.51.100.0\", 24],\n [\"203.0.113.0\", 24],\n [\"224.0.0.0\", 4],\n [\"240.0.0.0\", 4],\n ] as const) {\n nonPublicV4.addSubnet(address, prefix, \"ipv4\");\n }\n\n // Only global unicast IPv6 (2000::/3) is public. This also rejects ::1,\n // fc00::/7, fe80::/10, IPv4-mapped (::ffff:0:0/96) and NAT64 (64:ff9b::/96).\n const globalV6 = new net.BlockList();\n globalV6.addSubnet(\"2000::\", 3, \"ipv6\");\n const nonPublicV6 = new net.BlockList();\n for (const [address, prefix] of [\n // IANA special-purpose block, including Teredo (2001::/32). A few ranges\n // inside it are globally reachable (for example AS112, 2001:4:112::/48);\n // the whole /23 is refused on purpose, failing closed.\n [\"2001::\", 23],\n [\"2001:db8::\", 32], // Documentation.\n [\"2002::\", 16], // 6to4.\n [\"3fff::\", 20], // Documentation.\n ] as const) {\n nonPublicV6.addSubnet(address, prefix, \"ipv6\");\n }\n\n return (address) => {\n const family = net.isIP(address);\n if (family === 4) return !nonPublicV4.check(address, \"ipv4\");\n if (family !== 6 || address.includes(\"%\")) return false;\n return (\n globalV6.check(address, \"ipv6\") && !nonPublicV6.check(address, \"ipv6\")\n );\n };\n}\n\n/** Returns true only for a public unicast IPv4 or IPv6 address. */\nexport async function isPublicAddress(address: string): Promise<boolean> {\n const { net } = await loadNodeModules();\n defaultPolicy ??= buildAddressPolicy(net);\n return defaultPolicy(address);\n}\n\n/**\n * True when the server must not fetch this URL itself and returns `null` so\n * the AI SDK handles it: the provider takes the URL as-is, or it is a `data:`\n * URL, which the AI SDK decodes locally without any network request.\n */\nfunction leftToAiSdk({\n url,\n isUrlSupportedByModel,\n}: {\n url: URL;\n isUrlSupportedByModel: boolean;\n}): boolean {\n return isUrlSupportedByModel || url.protocol === \"data:\";\n}\n\n/** The URL without its query and fragment, which can hold credentials. */\nfunction urlForLog(url: URL | string): string {\n try {\n const parsed = new URL(String(url));\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n return \"(invalid URL)\";\n }\n}\n\n/** `text` with the query and fragment removed from every URL in it. */\nfunction redactUrls(text: string): string {\n return text.replace(\n /\\b([a-z][a-z0-9+.-]*:\\/\\/[^\\s?#\"'`<>]*)[?#][^\\s\"'`<>]*/gi,\n \"$1\",\n );\n}\n\n/**\n * Returns the error for a failed or refused download and logs it on the\n * server. `detail` goes only to the log: the client sees `message`, which\n * never holds the URL's query, a resolved address or a raw network error.\n * For a refused host, `message` is the same whether the name did not resolve\n * or resolved to a non-public address, so that it does not reveal internal\n * DNS names.\n */\nfunction refuse(\n url: URL | string,\n message: string,\n detail?: string,\n statusCode?: number,\n): DownloadError {\n console.warn(\n redactUrls(\n `[CopilotKit] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : \"\"}`,\n ),\n );\n return new DownloadError({ url: urlForLog(url), message, statusCode });\n}\n\n// Longest text logged for one value in an error description.\nconst MAX_LOGGED_FIELD_LENGTH = 2000;\n\nfunction truncateForLog(text: string): string {\n return text.length > MAX_LOGGED_FIELD_LENGTH\n ? `${text.slice(0, MAX_LOGGED_FIELD_LENGTH)}… (${text.length} characters)`\n : text;\n}\n\n/** Message, error code and causes of an error, for the server log. */\nfunction describeError(error: unknown, depth = 0): string {\n if (typeof error === \"string\") return error;\n if (!(error instanceof Error)) return truncateForLog(describeValue(error));\n const code = (error as { code?: unknown }).code;\n const text =\n typeof code === \"string\" && !error.message.includes(code)\n ? `${code}: ${error.message}`\n : error.message;\n return error.cause !== undefined && depth < 3\n ? `${text}; caused by ${describeError(error.cause, depth + 1)}`\n : text;\n}\n\n/**\n * A printable form of a configuration value for an error message. Unlike\n * `JSON.stringify`, it never throws (BigInt) and never gives `undefined`\n * (Symbol, function).\n */\nfunction describeValue(value: unknown): string {\n if (typeof value === \"bigint\") return `${value}n`;\n if (typeof value === \"function\") return \"a function\";\n try {\n const text = JSON.stringify(value);\n if (text !== undefined) return text;\n } catch {\n // Not serializable, for example a cycle or a nested BigInt.\n }\n try {\n return String(value);\n } catch {\n return Object.prototype.toString.call(value);\n }\n}\n\n/**\n * The form in which hostnames are compared: a URL hostname (lowercase ASCII,\n * IDNA as punycode, IPv6 in canonical form) without IPv6 brackets and without\n * one trailing dot.\n */\nfunction comparableHost(hostname: string): string {\n return hostname.replace(/^\\[(.*)\\]$/, \"$1\").replace(/\\.$/, \"\");\n}\n\n/**\n * Validates one `allowedHosts` entry and returns it in comparable form: an\n * exact host, or `*.` followed by a host suffix.\n */\nfunction normalizeAllowedHost(entry: unknown): string {\n const invalid = (reason: string) =>\n new Error(\n `createSafeUrlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`,\n );\n if (typeof entry !== \"string\" || entry === \"\") {\n throw invalid(\"it must be a non-empty hostname\");\n }\n if (/[\\s/?#@\\\\]/.test(entry)) {\n throw invalid(\"give only a hostname, without a scheme, path or user\");\n }\n const wildcard = entry.startsWith(\"*.\");\n const host = wildcard ? entry.slice(2) : entry;\n if (host === \"\" || host === \".\" || host.includes(\"*\")) {\n throw invalid('\"*\" is allowed only as a leading \"*.\" label');\n }\n // `host:port` (one \":\" and no brackets) or `[ipv6]:port`. An IPv6 address\n // without brackets always has at least two \":\".\n if (/^[^:[\\]]*:\\d*$/.test(host) || /^\\[.*\\]:\\d*$/.test(host)) {\n throw invalid(\"give only a hostname, without a port\");\n }\n const bare = host.replace(/^\\[(.*)\\]$/, \"$1\");\n // Any \":\" left belongs to an IPv6 address, which the URL parser needs in\n // brackets.\n const authority = bare.includes(\":\") ? `[${bare}]` : host;\n let parsed: URL;\n try {\n parsed = new URL(`http://${authority}/`);\n } catch {\n throw invalid(\"it is not a valid hostname\");\n }\n const normalized = comparableHost(parsed.hostname);\n // The URL parser turns a name whose last label is a number into an IPv4\n // address (`*.0.1` becomes `0.0.0.1`), and no hostname can end in one.\n if (\n wildcard &&\n (normalized.includes(\":\") || /^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(normalized))\n ) {\n throw invalid(\"a wildcard needs a hostname suffix, not an IP address\");\n }\n return (wildcard ? \"*.\" : \"\") + normalized;\n}\n\nfunction normalizeAllowedHosts(entries: unknown): string[] | undefined {\n if (entries === undefined) return undefined;\n if (!Array.isArray(entries)) {\n throw new Error(\n \"createSafeUrlDownload.allowedHosts must be an array of hostnames\",\n );\n }\n return entries.map(normalizeAllowedHost);\n}\n\nfunction hostAllowed(hostname: string, allowedHosts?: string[]): boolean {\n if (!allowedHosts) return true;\n const host = comparableHost(hostname);\n return allowedHosts.some((pattern) =>\n pattern.startsWith(\"*.\")\n ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1\n : host === pattern,\n );\n}\n\nfunction checkUrl(url: URL, allowedHosts?: string[]): void {\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw refuse(url, \"Only http and https URLs can be downloaded.\");\n }\n if (url.username !== \"\" || url.password !== \"\") {\n throw refuse(url, \"URLs with credentials cannot be downloaded.\");\n }\n if (!hostAllowed(url.hostname, allowedHosts)) {\n throw refuse(url, \"The URL host is not in the allowed hosts list.\");\n }\n}\n\n/**\n * Waits for `work`, or rejects with the abort reason when `signal` aborts.\n * The handlers are attached to `work` first, so that a later rejection of\n * `work` is always handled: an unhandled rejection ends a Node process in\n * the default mode.\n */\nfunction withDeadline<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(signal.reason);\n work.then(resolve, reject).finally(() => {\n signal.removeEventListener(\"abort\", onAbort);\n });\n if (signal.aborted) return onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nasync function requestPinned(\n modules: NodeModules,\n url: URL,\n addresses: LookupAddress[],\n signal: AbortSignal,\n ca: string | undefined,\n): Promise<IncomingMessage> {\n // Answer the socket's lookup with the checked addresses only, so a second\n // DNS answer (DNS rebinding) can never pick the destination.\n const lookup: LookupFunction = (_hostname, options, callback) => {\n const wanted = typeof options === \"number\" ? options : options?.family;\n const available =\n wanted === 4 || wanted === 6\n ? addresses.filter((a) => a.family === wanted)\n : addresses;\n if (available.length === 0) {\n callback(\n refuse(url, \"No checked address is available for this URL.\"),\n \"\",\n 4,\n );\n } else if (typeof options === \"object\" && options?.all) {\n callback(null, available);\n } else {\n callback(null, available[0]!.address, available[0]!.family);\n }\n };\n const isHttps = url.protocol === \"https:\";\n const transport = isHttps ? modules.https : modules.http;\n // A new agent per request: no pooled socket and no proxy can bypass the\n // pinned lookup.\n const agent = isHttps\n ? new modules.https.Agent({ keepAlive: false, maxCachedSessions: 0 })\n : new modules.http.Agent({ keepAlive: false });\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n\n return new Promise<IncomingMessage>((resolve, reject) => {\n const request = transport.request(\n {\n protocol: url.protocol,\n hostname,\n // SNI must not carry the trailing dot of a fully qualified name.\n servername:\n isHttps && modules.net.isIP(hostname) === 0\n ? hostname.replace(/\\.$/, \"\")\n : undefined,\n port: url.port || (isHttps ? 443 : 80),\n path: url.pathname + url.search,\n method: \"GET\",\n // Some hosts refuse a request without a User-Agent.\n headers: { \"accept-encoding\": \"identity\", \"user-agent\": USER_AGENT },\n lookup,\n agent,\n signal,\n ...(isHttps && ca !== undefined ? { ca } : {}),\n },\n (response) => {\n response.once(\"close\", () => agent.destroy());\n resolve(response);\n },\n );\n // `on`, not `once`: an error after the first one (for example from the\n // socket while it is torn down) must not go unhandled. Rejecting twice\n // is harmless.\n request.on(\"error\", (error) => {\n agent.destroy();\n reject(error);\n });\n request.once(\"upgrade\", (_response, socket) => {\n socket.destroy();\n agent.destroy();\n reject(refuse(url, \"Protocol upgrade refused.\"));\n });\n request.end();\n });\n}\n\n/**\n * Bytes still allowed for all the downloads of one model call, the current\n * one included. Shared by them and decreased as their bodies stream in.\n */\ntype ByteBudget = { remaining: number; readonly limit: number };\n\ntype ResolvedOptions = {\n allowedHosts: string[] | undefined;\n maxBytes: number;\n timeoutMs: number;\n maxRedirects: number;\n maxDownloads: number;\n maxTotalBytes: number;\n};\n\nasync function readBody(\n url: URL,\n response: IncomingMessage,\n maxBytes: number,\n budget: ByteBudget,\n): Promise<Uint8Array> {\n const tooLarge = () =>\n refuse(url, `The response is larger than the ${maxBytes}-byte limit.`);\n const overBudget = () =>\n refuse(\n url,\n `The downloads are larger than the ${budget.limit}-byte total limit.`,\n );\n const declared = Number(response.headers[\"content-length\"]);\n if (Number.isFinite(declared) && declared > maxBytes) throw tooLarge();\n if (Number.isFinite(declared) && declared > budget.remaining) {\n throw overBudget();\n }\n const encoding = response.headers[\"content-encoding\"];\n if (encoding && encoding !== \"identity\") {\n throw refuse(url, \"Compressed responses are not accepted.\");\n }\n const chunks: Buffer[] = [];\n let total = 0;\n for await (const chunk of response) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);\n total += buffer.byteLength;\n if (total > maxBytes) throw tooLarge();\n budget.remaining -= buffer.byteLength;\n if (budget.remaining < 0) throw overBudget();\n chunks.push(buffer);\n }\n return new Uint8Array(Buffer.concat(chunks, total));\n}\n\nasync function downloadOne(\n original: URL,\n options: ResolvedOptions,\n internals: UrlDownloadInternals,\n outer: AbortSignal,\n budget: ByteBudget,\n): Promise<{ data: Uint8Array; mediaType: string | undefined }> {\n const modules = await loadNodeModules().catch((error: unknown) => {\n throw refuse(\n original,\n \"URL download needs Node.js networking modules, which are not available here.\",\n `loading them failed: ${describeError(error)}. On a runtime without them, pass your own download function as experimental_download`,\n );\n });\n defaultPolicy ??= buildAddressPolicy(modules.net);\n const isPublic = internals.isPublicAddress ?? defaultPolicy;\n const resolveHost =\n internals.resolveHost ??\n ((hostname: string) =>\n modules.dns.lookup(hostname, { all: true, verbatim: true }));\n\n // The URL of the current hop, so that a timeout names the hop that hung.\n let url = original;\n const controller = new AbortController();\n const timer = setTimeout(\n () =>\n controller.abort(\n refuse(\n url,\n `The download timed out after ${options.timeoutMs} ms (timeoutMs).`,\n ),\n ),\n options.timeoutMs,\n );\n // The run was aborted, or another download in the same call failed.\n const onOuterAbort = () => controller.abort(outer.reason);\n if (outer.aborted) onOuterAbort();\n else outer.addEventListener(\"abort\", onOuterAbort, { once: true });\n const { signal } = controller;\n try {\n for (let hop = 0; ; hop++) {\n // An aborted download does nothing more, not even a DNS query for a\n // name that the request chose.\n signal.throwIfAborted();\n checkUrl(url, options.allowedHosts);\n const hostname = url.hostname.replace(/^\\[|\\]$/g, \"\");\n const literalFamily = modules.net.isIP(hostname);\n let addresses: LookupAddress[];\n try {\n signal.throwIfAborted();\n addresses = literalFamily\n ? [{ address: hostname, family: literalFamily }]\n : await withDeadline(resolveHost(hostname), signal);\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n throw refuse(\n url,\n HOST_REFUSED,\n `DNS lookup failed: ${describeError(error)}`,\n );\n }\n const verdicts = await Promise.all(\n addresses.map(\n async ({ address, family }) =>\n (family === 4 || family === 6) &&\n (await isPublic(address)) === true,\n ),\n );\n const rejected = addresses.filter((_address, i) => !verdicts[i]);\n if (addresses.length === 0 || rejected.length > 0) {\n throw refuse(\n url,\n HOST_REFUSED,\n addresses.length === 0\n ? \"DNS lookup returned no addresses\"\n : `non-public address: ${rejected.map((a) => a.address).join(\", \")}`,\n );\n }\n\n let response: IncomingMessage;\n try {\n response = await requestPinned(\n modules,\n url,\n addresses,\n signal,\n internals.ca,\n );\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (DownloadError.isInstance(error)) throw error;\n throw refuse(url, DOWNLOAD_FAILED, describeError(error));\n }\n try {\n const status = response.statusCode ?? 0;\n if (REDIRECT_STATUSES.has(status)) {\n if (hop >= options.maxRedirects) {\n throw refuse(\n url,\n `Too many redirects: the limit is ${options.maxRedirects} (maxRedirects).`,\n );\n }\n const location = response.headers.location;\n if (!location) throw refuse(url, \"Redirect without a location.\");\n let next: URL;\n try {\n next = new URL(location, url);\n } catch (error) {\n throw refuse(\n url,\n \"Redirect to an invalid URL.\",\n `Location ${JSON.stringify(location.slice(0, 200))}: ${describeError(error)}`,\n );\n }\n // Bytes fetched over plain http could be changed in transit.\n if (url.protocol === \"https:\" && next.protocol === \"http:\") {\n throw refuse(url, \"A redirect from https to http is refused.\");\n }\n url = next;\n continue;\n }\n if (status < 200 || status >= 300) {\n throw refuse(\n url,\n `The server answered with HTTP status ${status}.`,\n response.statusMessage,\n status,\n );\n }\n const data = await readBody(url, response, options.maxBytes, budget);\n const contentType = response.headers[\"content-type\"];\n return { data, mediaType: contentType || undefined };\n } catch (error) {\n if (signal.aborted) throw signal.reason;\n if (DownloadError.isInstance(error)) throw error;\n throw refuse(url, DOWNLOAD_FAILED, describeError(error));\n } finally {\n response.destroy();\n }\n }\n } finally {\n clearTimeout(timer);\n outer.removeEventListener(\"abort\", onOuterAbort);\n controller.abort();\n }\n}\n\n// setTimeout clamps a longer delay to 1 ms, so a larger limit would end every\n// download at once.\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/** Returns `value` (or `fallback`) if it is an integer from `min` to `max`. */\nfunction integerOption(\n name: string,\n value: number | undefined,\n fallback: number,\n min: number,\n max = Number.MAX_SAFE_INTEGER,\n): number {\n const result = value ?? fallback;\n if (!Number.isSafeInteger(result) || result < min || result > max) {\n const range =\n max === Number.MAX_SAFE_INTEGER\n ? `an integer of at least ${min}`\n : `an integer from ${min} to ${max}`;\n throw new Error(\n `createSafeUrlDownload.${name} must be ${range}, got ${describeValue(value)}`,\n );\n }\n return result;\n}\n\n// Every option name, so that a mistyped name fails instead of being ignored:\n// a mistyped `allowedHosts` would otherwise allow every public host.\nconst OPTION_NAMES: Record<keyof SafeUrlDownloadOptions, true> = {\n allowedHosts: true,\n maxBytes: true,\n timeoutMs: true,\n maxRedirects: true,\n maxDownloads: true,\n maxTotalBytes: true,\n};\n\nfunction checkOptionsObject(options: unknown): asserts options is object {\n if (\n typeof options !== \"object\" ||\n options === null ||\n Array.isArray(options)\n ) {\n throw new Error(\n `createSafeUrlDownload options must be an object, got ${describeValue(options)}`,\n );\n }\n}\n\nfunction checkOptionNames(options: unknown): void {\n checkOptionsObject(options);\n for (const name of Object.keys(options)) {\n if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) {\n throw new Error(\n `createSafeUrlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(\", \")}`,\n );\n }\n }\n}\n\n/** A download function that can also be tied to a run's abort signal. */\nexport type GuardedUrlDownload = DownloadFunction & {\n /** The same download function, aborted when `signal` aborts. */\n forRun(signal: AbortSignal): DownloadFunction;\n};\n\n/** @internal Factory with test seams; use {@link createSafeUrlDownload}. */\nexport function createGuardedUrlDownload(\n options: SafeUrlDownloadOptions = {},\n internals: UrlDownloadInternals = {},\n): GuardedUrlDownload {\n checkOptionNames(options);\n const resolved: ResolvedOptions = {\n allowedHosts: normalizeAllowedHosts(options.allowedHosts),\n maxBytes: integerOption(\"maxBytes\", options.maxBytes, DEFAULT_MAX_BYTES, 1),\n timeoutMs: integerOption(\n \"timeoutMs\",\n options.timeoutMs,\n DEFAULT_TIMEOUT_MS,\n 1,\n MAX_TIMEOUT_MS,\n ),\n maxRedirects: integerOption(\n \"maxRedirects\",\n options.maxRedirects,\n DEFAULT_MAX_REDIRECTS,\n 0,\n ),\n maxDownloads: integerOption(\n \"maxDownloads\",\n options.maxDownloads,\n DEFAULT_MAX_DOWNLOADS,\n 1,\n ),\n maxTotalBytes: integerOption(\n \"maxTotalBytes\",\n options.maxTotalBytes,\n DEFAULT_MAX_TOTAL_BYTES,\n 1,\n ),\n };\n const downloadAll = async (\n requests: Parameters<DownloadFunction>[0],\n runSignal?: AbortSignal,\n ) => {\n // Aborted when the run aborts, or when one download fails, so that the\n // other downloads in this call stop as well.\n const batch = new AbortController();\n const onRunAbort = () => batch.abort(runSignal?.reason);\n if (runSignal?.aborted) onRunAbort();\n else runSignal?.addEventListener(\"abort\", onRunAbort, { once: true });\n try {\n // One download per distinct URL; duplicates share its result.\n const pending = new Map<string, URL>();\n for (const request of requests) {\n if (!leftToAiSdk(request)) pending.set(request.url.href, request.url);\n }\n if (pending.size > resolved.maxDownloads) {\n throw refuse(\n [...pending.values()][resolved.maxDownloads]!,\n `A model call can have at most ${resolved.maxDownloads} URL downloads; this one has ${pending.size}.`,\n );\n }\n const budget: ByteBudget = {\n remaining: resolved.maxTotalBytes,\n limit: resolved.maxTotalBytes,\n };\n const downloads = new Map(\n [...pending].map(([href, url]) => [\n href,\n downloadOne(url, resolved, internals, batch.signal, budget).catch(\n (error: unknown) => {\n batch.abort(error);\n throw error;\n },\n ),\n ]),\n );\n return await Promise.all(\n requests.map((request) =>\n leftToAiSdk(request) ? null : downloads.get(request.url.href)!,\n ),\n );\n } finally {\n runSignal?.removeEventListener(\"abort\", onRunAbort);\n batch.abort();\n }\n };\n return Object.assign(\n (requests: Parameters<DownloadFunction>[0]) => downloadAll(requests),\n {\n forRun:\n (signal: AbortSignal): DownloadFunction =>\n (requests) =>\n downloadAll(requests, signal),\n },\n );\n}\n\n/** Options for {@link createSafeUrlDownload}. */\nexport interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {\n /**\n * Stops every download of this function when it aborts, for example the\n * run's `ctx.abortSignal` in a `type: \"aisdk\"` factory. Without it, a\n * download that is running when the run is aborted goes on until it ends\n * or reaches `timeoutMs`.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Creates an AI SDK download function (`experimental_download`) that only\n * fetches public internet addresses. For `streamText` calls in a\n * `type: \"aisdk\"` factory. Create it in the factory with the run's abort\n * signal, so that an aborted run stops its downloads:\n *\n * ```ts\n * import { streamText } from \"ai\";\n * import { createSafeUrlDownload } from \"@copilotkit/runtime/agent/ai-sdk\";\n *\n * factory: (ctx) =>\n * streamText({\n * model,\n * messages,\n * abortSignal: ctx.abortSignal,\n * experimental_download: createSafeUrlDownload({ signal: ctx.abortSignal }),\n * }),\n * ```\n *\n * @param options - Host allow list, size, time and count limits, and the\n * abort `signal`. All are optional.\n * @throws Error when an option is invalid. It throws here, when the function\n * is created, not on the first download.\n */\nexport function createSafeUrlDownload(\n options: CreateSafeUrlDownloadOptions = {},\n) {\n checkOptionsObject(options);\n const { signal, ...downloadOptions } = options;\n if (signal !== undefined && !(signal instanceof AbortSignal)) {\n throw new Error(\n `createSafeUrlDownload signal must be an AbortSignal, got ${describeValue(signal)}`,\n );\n }\n const download = createGuardedUrlDownload(downloadOptions);\n // The public type is the plain AI SDK download function, without `forRun`.\n const runDownload: DownloadFunction = signal\n ? download.forRun(signal)\n : download;\n return runDownload;\n}\n"],"mappings":";;;;AA8FA,MAAM,oBAAoB,KAAK,OAAO;AACtC,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,wBAAwB;AAC9B,MAAM,0BAA0B,KAAK,OAAO;AAI5C,MAAM,eACJ;AAGF,MAAM,kBAAkB;AACxB,MAAM,aAAa,sBAAsBA;AACzC,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;CAAI,CAAC;AAS5D,IAAI;AASJ,SAAS,kBAAwC;AAC/C,iBAAgB,QAAQ,SAAS,CAC9B,WAAW;EACV,MAAM,OACJ,WAAW,SAGV;AACH,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,4CAA4C;AACvE,SAAO;GACL,KAAK,KAAyB,oBAAoB;GAClD,MAAM,KAAkB,YAAY;GACpC,OAAO,KAAmB,aAAa;GACvC,KAAK,KAAiB,WAAW;GAClC;GACD,CACD,OAAO,UAAmB;AAEzB,gBAAc;AACd,QAAM;GACN;AACJ,QAAO;;AAIT,IAAI;AAEJ,SAAS,mBAAmB,KAAwC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,OAAO,QACX,aAA8C,YAAY,SAAS,EACpE,EACE,SACG,YACA,aACC,YAAY,UAAU,OAAO,EAClC,CACF;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCH,SAAgB,sBACd,UAAwC,EAAE,EAC1C;AACA,oBAAmB,QAAQ;CAC3B,MAAM,EAAE,QAAQ,GAAG,oBAAoB;AACvC,KAAI,WAAW,UAAa,EAAE,kBAAkB,aAC9C,OAAM,IAAI,MACR,4DAA4D,cAAc,OAAO,GAClF;CAEH,MAAM,WAAW,yBAAyB,gBAAgB;AAK1D,QAHsC,SAClC,SAAS,OAAO,OAAO,GACvB"}
@@ -1,6 +1,6 @@
1
1
  import { Experimental_DownloadFunction } from "ai";
2
2
 
3
- //#region src/agent/url-download.d.ts
3
+ //#region src/agent/ai-sdk/url-download.d.ts
4
4
  /** Options for the default, public-network-only URL downloader. */
5
5
  interface SafeUrlDownloadOptions {
6
6
  /**
@@ -46,7 +46,7 @@ interface SafeUrlDownloadOptions {
46
46
  interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {
47
47
  /**
48
48
  * Stops every download of this function when it aborts, for example the
49
- * run's `ctx.abortSignal` in BuiltInAgent's factory mode. Without it, a
49
+ * run's `ctx.abortSignal` in a `type: "aisdk"` factory. Without it, a
50
50
  * download that is running when the run is aborted goes on until it ends
51
51
  * or reaches `timeoutMs`.
52
52
  */
@@ -54,13 +54,13 @@ interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {
54
54
  }
55
55
  /**
56
56
  * Creates an AI SDK download function (`experimental_download`) that only
57
- * fetches public internet addresses, with the same checks and limits as
58
- * BuiltInAgent's default downloader. Pass it to `streamText` yourself when
59
- * you use BuiltInAgent's AI SDK factory mode. Create it in the factory with
60
- * the run's abort signal, so that an aborted run stops its downloads:
57
+ * fetches public internet addresses. For `streamText` calls in a
58
+ * `type: "aisdk"` factory. Create it in the factory with the run's abort
59
+ * signal, so that an aborted run stops its downloads:
61
60
  *
62
61
  * ```ts
63
- * import { createSafeUrlDownload } from "@copilotkit/runtime";
62
+ * import { streamText } from "ai";
63
+ * import { createSafeUrlDownload } from "@copilotkit/runtime/agent/ai-sdk";
64
64
  *
65
65
  * factory: (ctx) =>
66
66
  * streamText({
@@ -71,7 +71,10 @@ interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {
71
71
  * }),
72
72
  * ```
73
73
  *
74
- * Invalid options throw here, when the function is created.
74
+ * @param options - Host allow list, size, time and count limits, and the
75
+ * abort `signal`. All are optional.
76
+ * @throws Error when an option is invalid. It throws here, when the function
77
+ * is created, not on the first download.
75
78
  */
76
79
  declare function createSafeUrlDownload(options?: CreateSafeUrlDownloadOptions): Experimental_DownloadFunction;
77
80
  //#endregion
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-download.d.cts","names":[],"sources":["../../../src/agent/ai-sdk/url-download.ts"],"mappings":";;;;UAyCiB,sBAAA;EAAsB;;;;;;;;;;;AAqyBvC;;;;;EApxBE,YAAA;EA2xBS;EAzxBT,QAAA;EAyxBoB;AA2BtB;;;EA/yBE,SAAA;EAgzBS;EA9yBT,YAAA;EA8yB0C;;;;;;EAvyB1C,YAAA;;;;;EAKA,aAAA;AAAA;;UA+vBe,4BAAA,SAAqC,sBAAA;;;;;;;EAOpD,MAAA,GAAS,WAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBA2BK,qBAAA,CACd,OAAA,GAAS,4BAAA,GAAiC,6BAAA"}
@@ -1,6 +1,6 @@
1
1
  import { Experimental_DownloadFunction } from "ai";
2
2
 
3
- //#region src/agent/url-download.d.ts
3
+ //#region src/agent/ai-sdk/url-download.d.ts
4
4
  /** Options for the default, public-network-only URL downloader. */
5
5
  interface SafeUrlDownloadOptions {
6
6
  /**
@@ -46,7 +46,7 @@ interface SafeUrlDownloadOptions {
46
46
  interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {
47
47
  /**
48
48
  * Stops every download of this function when it aborts, for example the
49
- * run's `ctx.abortSignal` in BuiltInAgent's factory mode. Without it, a
49
+ * run's `ctx.abortSignal` in a `type: "aisdk"` factory. Without it, a
50
50
  * download that is running when the run is aborted goes on until it ends
51
51
  * or reaches `timeoutMs`.
52
52
  */
@@ -54,13 +54,13 @@ interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {
54
54
  }
55
55
  /**
56
56
  * Creates an AI SDK download function (`experimental_download`) that only
57
- * fetches public internet addresses, with the same checks and limits as
58
- * BuiltInAgent's default downloader. Pass it to `streamText` yourself when
59
- * you use BuiltInAgent's AI SDK factory mode. Create it in the factory with
60
- * the run's abort signal, so that an aborted run stops its downloads:
57
+ * fetches public internet addresses. For `streamText` calls in a
58
+ * `type: "aisdk"` factory. Create it in the factory with the run's abort
59
+ * signal, so that an aborted run stops its downloads:
61
60
  *
62
61
  * ```ts
63
- * import { createSafeUrlDownload } from "@copilotkit/runtime";
62
+ * import { streamText } from "ai";
63
+ * import { createSafeUrlDownload } from "@copilotkit/runtime/agent/ai-sdk";
64
64
  *
65
65
  * factory: (ctx) =>
66
66
  * streamText({
@@ -71,7 +71,10 @@ interface CreateSafeUrlDownloadOptions extends SafeUrlDownloadOptions {
71
71
  * }),
72
72
  * ```
73
73
  *
74
- * Invalid options throw here, when the function is created.
74
+ * @param options - Host allow list, size, time and count limits, and the
75
+ * abort `signal`. All are optional.
76
+ * @throws Error when an option is invalid. It throws here, when the function
77
+ * is created, not on the first download.
75
78
  */
76
79
  declare function createSafeUrlDownload(options?: CreateSafeUrlDownloadOptions): Experimental_DownloadFunction;
77
80
  //#endregion
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-download.d.mts","names":[],"sources":["../../../src/agent/ai-sdk/url-download.ts"],"mappings":";;;;UAyCiB,sBAAA;EAAsB;;;;;;;;;;;AAqyBvC;;;;;EApxBE,YAAA;EA2xBS;EAzxBT,QAAA;EAyxBoB;AA2BtB;;;EA/yBE,SAAA;EAgzBS;EA9yBT,YAAA;EA8yB0C;;;;;;EAvyB1C,YAAA;;;;;EAKA,aAAA;AAAA;;UA+vBe,4BAAA,SAAqC,sBAAA;;;;;;;EAOpD,MAAA,GAAS,WAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;iBA2BK,qBAAA,CACd,OAAA,GAAS,4BAAA,GAAiC,6BAAA"}
@@ -1,7 +1,7 @@
1
1
  import { COPILOTKIT_VERSION } from "@copilotkit/shared";
2
2
  import { DownloadError } from "ai";
3
3
 
4
- //#region src/agent/url-download.ts
4
+ //#region src/agent/ai-sdk/url-download.ts
5
5
  const DEFAULT_MAX_BYTES = 20 * 1024 * 1024;
6
6
  const DEFAULT_TIMEOUT_MS = 3e4;
7
7
  const DEFAULT_MAX_REDIRECTS = 3;
@@ -91,7 +91,6 @@ function urlForLog(url) {
91
91
  function redactUrls(text) {
92
92
  return text.replace(/\b([a-z][a-z0-9+.-]*:\/\/[^\s?#"'`<>]*)[?#][^\s"'`<>]*/gi, "$1");
93
93
  }
94
- const loggedErrors = /* @__PURE__ */ new WeakSet();
95
94
  /**
96
95
  * Returns the error for a failed or refused download and logs it on the
97
96
  * server. `detail` goes only to the log: the client sees `message`, which
@@ -101,51 +100,17 @@ const loggedErrors = /* @__PURE__ */ new WeakSet();
101
100
  * DNS names.
102
101
  */
103
102
  function refuse(url, message, detail, statusCode) {
104
- console.warn(redactUrls(`[BuiltInAgent] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : ""}`));
105
- const error = new DownloadError({
103
+ console.warn(redactUrls(`[CopilotKit] URL download failed for ${urlForLog(url)}: ${message}${detail ? ` (${detail})` : ""}`));
104
+ return new DownloadError({
106
105
  url: urlForLog(url),
107
106
  message,
108
107
  statusCode
109
108
  });
110
- loggedErrors.add(error);
111
- return error;
112
- }
113
- /**
114
- * @internal BuiltInAgent's `onError` for its `streamText` call. The AI SDK's
115
- * default handler prints the whole error, which for a download error holds
116
- * the URL with its query. This logs an error once, with the same detail
117
- * (for a provider API error, its status code and response body) but with the
118
- * query and fragment removed from every URL, and skips the download errors
119
- * that were already logged here.
120
- */
121
- function logModelCallError(error) {
122
- if (typeof error === "object" && error !== null && loggedErrors.has(error)) return;
123
- const frames = error instanceof Error && error.stack ? error.stack.split("\n").filter((line) => /^\s+at /.test(line)).join("\n") : "";
124
- console.error(redactUrls(`[BuiltInAgent] The model call failed: ${describeModelError(error)}${frames ? `\n${frames}` : ""}`));
125
109
  }
126
110
  const MAX_LOGGED_FIELD_LENGTH = 2e3;
127
111
  function truncateForLog(text) {
128
112
  return text.length > MAX_LOGGED_FIELD_LENGTH ? `${text.slice(0, MAX_LOGGED_FIELD_LENGTH)}… (${text.length} characters)` : text;
129
113
  }
130
- /**
131
- * {@link describeError}, followed by the other fields of the error, such as
132
- * the `statusCode`, `responseBody` and `url` of the AI SDK's APICallError. A
133
- * value that is not an Error, such as the plain object that a provider
134
- * stream sends as its error, is logged as JSON.
135
- */
136
- function describeModelError(error) {
137
- if (!(error instanceof Error)) return truncateForLog(describeValue(error));
138
- const fields = Object.entries(error).filter(([key]) => ![
139
- "name",
140
- "message",
141
- "stack",
142
- "cause",
143
- "code"
144
- ].includes(key)).map(([key, value]) => {
145
- return `${key}: ${truncateForLog(value instanceof Error ? describeError(value) : typeof value === "string" ? value : describeValue(value))}`;
146
- });
147
- return `${error.name && error.name !== "Error" ? `${error.name}: ` : ""}${describeError(error)}${fields.length > 0 ? ` {${fields.join("; ")}}` : ""}`;
148
- }
149
114
  /** Message, error code and causes of an error, for the server log. */
150
115
  function describeError(error, depth = 0) {
151
116
  if (typeof error === "string") return error;
@@ -185,7 +150,7 @@ function comparableHost(hostname) {
185
150
  * exact host, or `*.` followed by a host suffix.
186
151
  */
187
152
  function normalizeAllowedHost(entry) {
188
- const invalid = (reason) => /* @__PURE__ */ new Error(`urlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`);
153
+ const invalid = (reason) => /* @__PURE__ */ new Error(`createSafeUrlDownload.allowedHosts entry ${describeValue(entry)} is invalid: ${reason}`);
189
154
  if (typeof entry !== "string" || entry === "") throw invalid("it must be a non-empty hostname");
190
155
  if (/[\s/?#@\\]/.test(entry)) throw invalid("give only a hostname, without a scheme, path or user");
191
156
  const wildcard = entry.startsWith("*.");
@@ -206,7 +171,7 @@ function normalizeAllowedHost(entry) {
206
171
  }
207
172
  function normalizeAllowedHosts(entries) {
208
173
  if (entries === void 0) return void 0;
209
- if (!Array.isArray(entries)) throw new Error("urlDownload.allowedHosts must be an array of hostnames");
174
+ if (!Array.isArray(entries)) throw new Error("createSafeUrlDownload.allowedHosts must be an array of hostnames");
210
175
  return entries.map(normalizeAllowedHost);
211
176
  }
212
177
  function hostAllowed(hostname, allowedHosts) {
@@ -304,7 +269,7 @@ async function readBody$1(url, response, maxBytes, budget) {
304
269
  }
305
270
  async function downloadOne(original, options, internals, outer, budget) {
306
271
  const modules = await loadNodeModules().catch((error) => {
307
- throw refuse(original, "URL download needs Node.js networking modules, which are not available here.", `loading them failed: ${describeError(error)}. On a runtime without them, set urlDownload to "disabled" or to your own download function`);
272
+ throw refuse(original, "URL download needs Node.js networking modules, which are not available here.", `loading them failed: ${describeError(error)}. On a runtime without them, pass your own download function as experimental_download`);
308
273
  });
309
274
  defaultPolicy ??= buildAddressPolicy(modules.net);
310
275
  const isPublic = internals.isPublicAddress ?? defaultPolicy;
@@ -388,7 +353,7 @@ function integerOption(name, value, fallback, min, max = Number.MAX_SAFE_INTEGER
388
353
  const result = value ?? fallback;
389
354
  if (!Number.isSafeInteger(result) || result < min || result > max) {
390
355
  const range = max === Number.MAX_SAFE_INTEGER ? `an integer of at least ${min}` : `an integer from ${min} to ${max}`;
391
- throw new Error(`urlDownload.${name} must be ${range}, got ${describeValue(value)}`);
356
+ throw new Error(`createSafeUrlDownload.${name} must be ${range}, got ${describeValue(value)}`);
392
357
  }
393
358
  return result;
394
359
  }
@@ -401,11 +366,11 @@ const OPTION_NAMES = {
401
366
  maxTotalBytes: true
402
367
  };
403
368
  function checkOptionsObject(options) {
404
- if (typeof options !== "object" || options === null || Array.isArray(options)) throw new Error(`urlDownload options must be an object, got ${describeValue(options)}`);
369
+ if (typeof options !== "object" || options === null || Array.isArray(options)) throw new Error(`createSafeUrlDownload options must be an object, got ${describeValue(options)}`);
405
370
  }
406
371
  function checkOptionNames(options) {
407
372
  checkOptionsObject(options);
408
- for (const name of Object.keys(options)) if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) throw new Error(`urlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(", ")}`);
373
+ for (const name of Object.keys(options)) if (!Object.prototype.hasOwnProperty.call(OPTION_NAMES, name)) throw new Error(`createSafeUrlDownload has an unknown option ${describeValue(name)}; the valid options are ${Object.keys(OPTION_NAMES).join(", ")}`);
409
374
  }
410
375
  /** @internal Factory with test seams; use {@link createSafeUrlDownload}. */
411
376
  function createGuardedUrlDownload(options = {}, internals = {}) {
@@ -444,27 +409,14 @@ function createGuardedUrlDownload(options = {}, internals = {}) {
444
409
  return Object.assign((requests) => downloadAll(requests), { forRun: (signal) => (requests) => downloadAll(requests, signal) });
445
410
  }
446
411
  /**
447
- * @internal Resolves BuiltInAgent's `urlDownload` setting once, so that an
448
- * invalid setting fails when the agent is constructed. The result gives the
449
- * download function for one run; the default downloader stops when the run
450
- * is aborted.
451
- */
452
- function resolveUrlDownloadSetting(setting) {
453
- if (setting === "disabled") return () => disabledUrlDownload;
454
- if (typeof setting === "function") return () => setting;
455
- if (setting === void 0 || setting === null) return createGuardedUrlDownload().forRun;
456
- if (typeof setting === "object" && !Array.isArray(setting)) return createGuardedUrlDownload(setting).forRun;
457
- throw new Error(`urlDownload must be "disabled", an options object or a download function, got ${describeValue(setting)}`);
458
- }
459
- /**
460
412
  * Creates an AI SDK download function (`experimental_download`) that only
461
- * fetches public internet addresses, with the same checks and limits as
462
- * BuiltInAgent's default downloader. Pass it to `streamText` yourself when
463
- * you use BuiltInAgent's AI SDK factory mode. Create it in the factory with
464
- * the run's abort signal, so that an aborted run stops its downloads:
413
+ * fetches public internet addresses. For `streamText` calls in a
414
+ * `type: "aisdk"` factory. Create it in the factory with the run's abort
415
+ * signal, so that an aborted run stops its downloads:
465
416
  *
466
417
  * ```ts
467
- * import { createSafeUrlDownload } from "@copilotkit/runtime";
418
+ * import { streamText } from "ai";
419
+ * import { createSafeUrlDownload } from "@copilotkit/runtime/agent/ai-sdk";
468
420
  *
469
421
  * factory: (ctx) =>
470
422
  * streamText({
@@ -475,25 +427,19 @@ function resolveUrlDownloadSetting(setting) {
475
427
  * }),
476
428
  * ```
477
429
  *
478
- * Invalid options throw here, when the function is created.
430
+ * @param options - Host allow list, size, time and count limits, and the
431
+ * abort `signal`. All are optional.
432
+ * @throws Error when an option is invalid. It throws here, when the function
433
+ * is created, not on the first download.
479
434
  */
480
435
  function createSafeUrlDownload(options = {}) {
481
436
  checkOptionsObject(options);
482
437
  const { signal, ...downloadOptions } = options;
483
- if (signal !== void 0 && !(signal instanceof AbortSignal)) throw new Error(`urlDownload signal must be an AbortSignal, got ${describeValue(signal)}`);
438
+ if (signal !== void 0 && !(signal instanceof AbortSignal)) throw new Error(`createSafeUrlDownload signal must be an AbortSignal, got ${describeValue(signal)}`);
484
439
  const download = createGuardedUrlDownload(downloadOptions);
485
440
  return signal ? download.forRun(signal) : download;
486
441
  }
487
- /**
488
- * A download function that never fetches from the network. URLs that the
489
- * model takes as-is and `data:` URLs are left to the AI SDK; any other URL,
490
- * whatever its scheme, fails the run.
491
- */
492
- const disabledUrlDownload = async (requests) => requests.map((request) => {
493
- if (leftToAiSdk(request)) return null;
494
- throw refuse(request.url, "Server-side URL download is disabled (urlDownload: \"disabled\").");
495
- });
496
442
 
497
443
  //#endregion
498
- export { createSafeUrlDownload, logModelCallError, resolveUrlDownloadSetting };
444
+ export { createSafeUrlDownload };
499
445
  //# sourceMappingURL=url-download.mjs.map