ashlr-plugin 1.36.4

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 (499) hide show
  1. package/.agents/plugins/marketplace.json +20 -0
  2. package/.claude-plugin/marketplace.json +39 -0
  3. package/.claude-plugin/plugin.json +36 -0
  4. package/.codex/agents/README.md +9 -0
  5. package/.codex/agents/ashlr-explorer.md +36 -0
  6. package/.codex/agents/ashlr-worker.md +38 -0
  7. package/.codex-plugin/plugin.json +45 -0
  8. package/.mcp.json +14 -0
  9. package/LICENSE +21 -0
  10. package/README.md +311 -0
  11. package/agents/ashlr-code.md +69 -0
  12. package/agents/ashlr-explore.md +44 -0
  13. package/agents/ashlr-plan.md +54 -0
  14. package/bench/fixtures/notebook-large.ipynb +660 -0
  15. package/bench/fixtures/notebook-small.ipynb +39 -0
  16. package/bench/fixtures/tasklist-closed.json +62 -0
  17. package/bench/fixtures/tasklist-large-mixed.json +27 -0
  18. package/bench/fixtures/tasklist-sprint-open.json +79 -0
  19. package/bench/fixtures/websearch-bun-runtime.json +32 -0
  20. package/bench/fixtures/websearch-react-hooks-patterns.json +32 -0
  21. package/bench/fixtures/websearch-typescript-generics.json +38 -0
  22. package/bench/refs/node-sdk/.refrev +1 -0
  23. package/bench/refs/node-sdk/README.md +17 -0
  24. package/bench/refs/node-sdk/src/agent/agent.ts +163 -0
  25. package/bench/refs/node-sdk/src/agent/create-agent-ui-stream.ts +83 -0
  26. package/bench/refs/node-sdk/src/agent/tool-loop-agent.ts +238 -0
  27. package/bench/refs/node-sdk/src/embed/embed-many.ts +409 -0
  28. package/bench/refs/node-sdk/src/embed/embed-result.ts +50 -0
  29. package/bench/refs/node-sdk/src/embed/embed.ts +257 -0
  30. package/bench/refs/node-sdk/src/error/invalid-argument-error.ts +34 -0
  31. package/bench/refs/node-sdk/src/error/invalid-tool-input-error.ts +33 -0
  32. package/bench/refs/node-sdk/src/error/no-object-generated-error.ts +70 -0
  33. package/bench/refs/node-sdk/src/generate-image/generate-image-result.ts +42 -0
  34. package/bench/refs/node-sdk/src/generate-image/generate-image.ts +362 -0
  35. package/bench/refs/node-sdk/src/generate-object/generate-object-result.ts +67 -0
  36. package/bench/refs/node-sdk/src/generate-object/generate-object.ts +501 -0
  37. package/bench/refs/node-sdk/src/generate-object/inject-json-instruction.ts +30 -0
  38. package/bench/refs/node-sdk/src/generate-object/output-strategy.ts +415 -0
  39. package/bench/refs/node-sdk/src/generate-object/repair-text.ts +12 -0
  40. package/bench/refs/node-sdk/src/generate-object/stream-object.ts +960 -0
  41. package/bench/refs/node-sdk/src/generate-speech/generate-speech.ts +191 -0
  42. package/bench/refs/node-sdk/src/generate-text/generate-text.ts +1484 -0
  43. package/bench/refs/node-sdk/src/generate-text/stream-text.ts +2708 -0
  44. package/bench/refs/node-sdk/src/generate-text/tool-call.ts +59 -0
  45. package/bench/refs/node-sdk/src/generate-text/tool-result.ts +36 -0
  46. package/bench/refs/node-sdk/src/telemetry/create-telemetry-dispatcher.ts +146 -0
  47. package/bench/refs/node-sdk/src/telemetry/telemetry-registry.ts +15 -0
  48. package/bench/refs/node-sdk/src/telemetry/telemetry.ts +223 -0
  49. package/bench/refs/node-sdk/src/util/async-iterable-stream.ts +94 -0
  50. package/bench/refs/node-sdk/src/util/consume-stream.ts +31 -0
  51. package/bench/refs/node-sdk/src/util/create-stitchable-stream.ts +112 -0
  52. package/bench/refs/node-sdk/src/util/download/download.ts +74 -0
  53. package/bench/refs/node-sdk/src/util/error-handler.ts +1 -0
  54. package/bench/refs/node-sdk/src/util/fix-json.ts +401 -0
  55. package/bench/refs/node-sdk/src/util/merge-objects.ts +79 -0
  56. package/bench/refs/python-lib/.refrev +1 -0
  57. package/bench/refs/python-lib/README.md +18 -0
  58. package/bench/refs/python-lib/pandas/core/_numba/executor.py +249 -0
  59. package/bench/refs/python-lib/pandas/core/_numba/extensions.py +586 -0
  60. package/bench/refs/python-lib/pandas/core/_numba/kernels/mean_.py +198 -0
  61. package/bench/refs/python-lib/pandas/core/_numba/kernels/min_max_.py +178 -0
  62. package/bench/refs/python-lib/pandas/core/_numba/kernels/sum_.py +255 -0
  63. package/bench/refs/python-lib/pandas/core/_numba/kernels/var_.py +251 -0
  64. package/bench/refs/python-lib/pandas/core/accessor.py +520 -0
  65. package/bench/refs/python-lib/pandas/core/api.py +138 -0
  66. package/bench/refs/python-lib/pandas/core/array_algos/masked_accumulations.py +97 -0
  67. package/bench/refs/python-lib/pandas/core/array_algos/masked_reductions.py +252 -0
  68. package/bench/refs/python-lib/pandas/core/array_algos/putmask.py +150 -0
  69. package/bench/refs/python-lib/pandas/core/array_algos/quantile.py +232 -0
  70. package/bench/refs/python-lib/pandas/core/array_algos/replace.py +159 -0
  71. package/bench/refs/python-lib/pandas/core/array_algos/take.py +609 -0
  72. package/bench/refs/python-lib/pandas/core/arraylike.py +534 -0
  73. package/bench/refs/python-lib/pandas/core/arrays/_arrow_string_mixins.py +434 -0
  74. package/bench/refs/python-lib/pandas/core/arrays/_mixins.py +630 -0
  75. package/bench/refs/python-lib/pandas/core/arrays/_ranges.py +276 -0
  76. package/bench/refs/python-lib/pandas/core/arrays/_utils.py +77 -0
  77. package/bench/refs/python-lib/pandas/core/arrays/arrow/accessors.py +521 -0
  78. package/bench/refs/python-lib/pandas/core/arrays/arrow/extension_types.py +174 -0
  79. package/bench/refs/python-lib/pandas/core/arrays/boolean.py +454 -0
  80. package/bench/refs/python-lib/pandas/core/arrays/floating.py +192 -0
  81. package/bench/refs/python-lib/pandas/core/arrays/integer.py +296 -0
  82. package/bench/refs/python-lib/pandas/core/arrays/masked.py +2140 -0
  83. package/bench/refs/python-lib/pandas/core/arrays/numeric.py +305 -0
  84. package/bench/refs/python-lib/pandas/core/arrays/numpy_.py +701 -0
  85. package/bench/refs/python-lib/pandas/core/arrays/period.py +1586 -0
  86. package/bench/refs/python-lib/pandas/core/arrays/sparse/accessor.py +505 -0
  87. package/bench/refs/python-lib/pandas/core/arrays/sparse/scipy_sparse.py +208 -0
  88. package/bench/refs/rust-project/.refrev +1 -0
  89. package/bench/refs/rust-project/README.md +17 -0
  90. package/bench/refs/rust-project/tokio/src/doc/os.rs +68 -0
  91. package/bench/refs/rust-project/tokio/src/fs/dir_builder.rs +129 -0
  92. package/bench/refs/rust-project/tokio/src/fs/file.rs +1113 -0
  93. package/bench/refs/rust-project/tokio/src/fs/mocks.rs +176 -0
  94. package/bench/refs/rust-project/tokio/src/fs/mod.rs +324 -0
  95. package/bench/refs/rust-project/tokio/src/fs/open_options.rs +856 -0
  96. package/bench/refs/rust-project/tokio/src/fs/read.rs +80 -0
  97. package/bench/refs/rust-project/tokio/src/fs/read_dir.rs +357 -0
  98. package/bench/refs/rust-project/tokio/src/fs/write.rs +99 -0
  99. package/bench/refs/rust-project/tokio/src/future/maybe_done.rs +123 -0
  100. package/bench/refs/rust-project/tokio/src/future/try_join.rs +82 -0
  101. package/bench/refs/rust-project/tokio/src/io/async_buf_read.rs +117 -0
  102. package/bench/refs/rust-project/tokio/src/io/async_read.rs +133 -0
  103. package/bench/refs/rust-project/tokio/src/io/async_seek.rs +96 -0
  104. package/bench/refs/rust-project/tokio/src/io/async_write.rs +402 -0
  105. package/bench/refs/rust-project/tokio/src/io/blocking.rs +339 -0
  106. package/bench/refs/rust-project/tokio/src/io/interest.rs +345 -0
  107. package/bench/refs/rust-project/tokio/src/io/join.rs +130 -0
  108. package/bench/refs/rust-project/tokio/src/io/mod.rs +308 -0
  109. package/bench/refs/rust-project/tokio/src/io/poll_evented.rs +319 -0
  110. package/bench/refs/rust-project/tokio/src/io/read_buf.rs +344 -0
  111. package/bench/refs/rust-project/tokio/src/io/ready.rs +322 -0
  112. package/bench/refs/rust-project/tokio/src/io/split.rs +166 -0
  113. package/bench/refs/rust-project/tokio/src/io/stderr.rs +148 -0
  114. package/bench/refs/rust-project/tokio/src/io/stdin.rs +98 -0
  115. package/bench/refs/rust-project/tokio/src/io/stdio_common.rs +222 -0
  116. package/bench/refs/rust-project/tokio/src/io/stdout.rs +197 -0
  117. package/bench/refs/rust-project/tokio/src/io/util/buf_reader.rs +311 -0
  118. package/bench/refs/rust-project/tokio/src/io/util/buf_stream.rs +207 -0
  119. package/bench/refs/rust-project/tokio/src/io/util/buf_writer.rs +310 -0
  120. package/bench/refs/rust-project/tokio/src/io/util/chain.rs +144 -0
  121. package/commands/_spawn-patterns.json +32 -0
  122. package/commands/ashlr-allow.md +21 -0
  123. package/commands/ashlr-benchmark.md +53 -0
  124. package/commands/ashlr-brief.md +97 -0
  125. package/commands/ashlr-budget.md +76 -0
  126. package/commands/ashlr-compact.md +54 -0
  127. package/commands/ashlr-dashboard.md +37 -0
  128. package/commands/ashlr-doctor.md +56 -0
  129. package/commands/ashlr-eco-mode.md +92 -0
  130. package/commands/ashlr-genome-init.md +24 -0
  131. package/commands/ashlr-genome-keygen.md +36 -0
  132. package/commands/ashlr-genome-loop.md +118 -0
  133. package/commands/ashlr-genome-push.md +36 -0
  134. package/commands/ashlr-genome-rewrap.md +48 -0
  135. package/commands/ashlr-genome-team-init.md +67 -0
  136. package/commands/ashlr-handoff.md +23 -0
  137. package/commands/ashlr-help.md +86 -0
  138. package/commands/ashlr-hook-timings.md +30 -0
  139. package/commands/ashlr-leaderboard.md +50 -0
  140. package/commands/ashlr-ollama-setup.md +39 -0
  141. package/commands/ashlr-orchestrate-status.md +72 -0
  142. package/commands/ashlr-orchestrate.md +83 -0
  143. package/commands/ashlr-parallelize.md +63 -0
  144. package/commands/ashlr-report-crash.md +33 -0
  145. package/commands/ashlr-resume.md +72 -0
  146. package/commands/ashlr-savings.md +24 -0
  147. package/commands/ashlr-settings.md +50 -0
  148. package/commands/ashlr-spawn.md +61 -0
  149. package/commands/ashlr-start.md +60 -0
  150. package/commands/ashlr-status.md +64 -0
  151. package/commands/ashlr-team-invite.md +47 -0
  152. package/commands/ashlr-tier.md +122 -0
  153. package/commands/ashlr-tour.md +60 -0
  154. package/commands/ashlr-update.md +155 -0
  155. package/commands/ashlr-upgrade.md +96 -0
  156. package/commands/goal.md +58 -0
  157. package/commands/loop.md +40 -0
  158. package/docs/CNAME +1 -0
  159. package/docs/PRO_TIER.md +104 -0
  160. package/docs/README.md +21 -0
  161. package/docs/architecture.md +415 -0
  162. package/docs/ashlr-pipe.md +161 -0
  163. package/docs/assets/logo.svg +19 -0
  164. package/docs/assets/og.png +0 -0
  165. package/docs/assets/og.svg +41 -0
  166. package/docs/benchmarks-v2.json +355 -0
  167. package/docs/benchmarks.json +102 -0
  168. package/docs/benchmarks.md +211 -0
  169. package/docs/billing.md +185 -0
  170. package/docs/cloud-genome.md +155 -0
  171. package/docs/competitive-wozcode.md +92 -0
  172. package/docs/deploy.md +325 -0
  173. package/docs/email-templates.md +113 -0
  174. package/docs/embed-tuning.md +103 -0
  175. package/docs/genome.md +120 -0
  176. package/docs/github-oauth-onboarding.md +127 -0
  177. package/docs/hero-video-script.md +129 -0
  178. package/docs/index.html +2262 -0
  179. package/docs/install-prompt.md +78 -0
  180. package/docs/install-windows.md +132 -0
  181. package/docs/install.ps1 +171 -0
  182. package/docs/install.sh +146 -0
  183. package/docs/launch/README.md +114 -0
  184. package/docs/launch/hn.md +49 -0
  185. package/docs/launch/reddit.md +45 -0
  186. package/docs/launch/x.md +65 -0
  187. package/docs/launch-post.md +112 -0
  188. package/docs/legal.md +78 -0
  189. package/docs/llm-providers.md +99 -0
  190. package/docs/multi-host-mcp.md +217 -0
  191. package/docs/multi-turn-architecture.md +108 -0
  192. package/docs/operations/deployment.md +108 -0
  193. package/docs/operations/error-monitoring.md +70 -0
  194. package/docs/operations/weekly-digest.md +70 -0
  195. package/docs/operations.md +494 -0
  196. package/docs/platform-support.md +133 -0
  197. package/docs/policy-packs.md +188 -0
  198. package/docs/press-kit/fact-sheet.md +78 -0
  199. package/docs/press-kit/founder-bio.md +3 -0
  200. package/docs/press-kit/logo.svg +33 -0
  201. package/docs/press-kit/screenshots.md +146 -0
  202. package/docs/pricing.md +251 -0
  203. package/docs/pro-backend-architecture.md +523 -0
  204. package/docs/producthunt.md +52 -0
  205. package/docs/router-migration.md +110 -0
  206. package/docs/session-log-schema.md +68 -0
  207. package/docs/social.md +95 -0
  208. package/docs/team-genome.md +528 -0
  209. package/docs/telemetry.md +194 -0
  210. package/docs/test-isolation.md +100 -0
  211. package/docs/upgrade.md +159 -0
  212. package/hooks/_hook-errors.ts +87 -0
  213. package/hooks/_hook-perf-emit.ts +113 -0
  214. package/hooks/_hook-timing-ledger.ts +1133 -0
  215. package/hooks/_nudge-throttle.ts +127 -0
  216. package/hooks/_recent-blocks.ts +127 -0
  217. package/hooks/audit-upload.ts +86 -0
  218. package/hooks/codex-hooks.json +171 -0
  219. package/hooks/commit-attribution.ts +179 -0
  220. package/hooks/edit-batching-nudge.ts +154 -0
  221. package/hooks/genome-scribe-hook.ts +219 -0
  222. package/hooks/hooks.json +294 -0
  223. package/hooks/orient-nudge-hook.ts +242 -0
  224. package/hooks/policy-enforce.ts +214 -0
  225. package/hooks/post-tool-use-embedding.ts +93 -0
  226. package/hooks/post-tool-use-genome.sh +37 -0
  227. package/hooks/post-tool-use-genome.ts +69 -0
  228. package/hooks/posttooluse-correlate.ts +122 -0
  229. package/hooks/posttooluse-dedupe-output.ts +241 -0
  230. package/hooks/posttooluse-genome-refresh.ts +223 -0
  231. package/hooks/posttooluse-native-nudge.ts +205 -0
  232. package/hooks/posttooluse-stale-result.ts +277 -0
  233. package/hooks/pretooluse-bash.ts +63 -0
  234. package/hooks/pretooluse-budget-guard.ts +318 -0
  235. package/hooks/pretooluse-common.ts +985 -0
  236. package/hooks/pretooluse-eco-router.ts +196 -0
  237. package/hooks/pretooluse-edit.sh +93 -0
  238. package/hooks/pretooluse-edit.ts +197 -0
  239. package/hooks/pretooluse-glob.ts +70 -0
  240. package/hooks/pretooluse-grep.sh +85 -0
  241. package/hooks/pretooluse-grep.ts +96 -0
  242. package/hooks/pretooluse-notebookedit.ts +121 -0
  243. package/hooks/pretooluse-read.sh +118 -0
  244. package/hooks/pretooluse-read.ts +118 -0
  245. package/hooks/pretooluse-task.ts +130 -0
  246. package/hooks/pretooluse-webfetch.ts +66 -0
  247. package/hooks/pretooluse-websearch.ts +85 -0
  248. package/hooks/pretooluse-write.ts +128 -0
  249. package/hooks/pulse-emit.ts +197 -0
  250. package/hooks/session-end-consolidate.sh +35 -0
  251. package/hooks/session-end-consolidate.ts +188 -0
  252. package/hooks/session-end-stats-gc.ts +80 -0
  253. package/hooks/session-log-append.sh +94 -0
  254. package/hooks/session-log-append.ts +116 -0
  255. package/hooks/session-start.ts +993 -0
  256. package/hooks/sessionend-hook-health-nudge.ts +451 -0
  257. package/hooks/sessionend-savings-nudge.ts +318 -0
  258. package/hooks/sessionend-status-line-nudge.ts +296 -0
  259. package/hooks/sessionstart-brief.ts +140 -0
  260. package/hooks/sessionstart-cost-refactor.ts +95 -0
  261. package/hooks/sessionstart-efficient.ts +110 -0
  262. package/hooks/sessionstart-genome-author.ts +93 -0
  263. package/hooks/sessionstart-lean-tools.ts +98 -0
  264. package/hooks/sessionstart-search.ts +97 -0
  265. package/hooks/stop-accounting.ts +152 -0
  266. package/hooks/subagent-stop-rollup.ts +162 -0
  267. package/hooks/userpromptsubmit-brief-trigger.ts +156 -0
  268. package/package.json +56 -0
  269. package/ports/README.md +108 -0
  270. package/ports/cursor/mcp.json +11 -0
  271. package/ports/goose/recipe.yaml +26 -0
  272. package/scripts/ashlr-mcp.ts +40 -0
  273. package/scripts/auto-update.ts +177 -0
  274. package/scripts/baseline-scan.ts +831 -0
  275. package/scripts/bench-orchestrate.ts +377 -0
  276. package/scripts/benchmark-refs.ts +292 -0
  277. package/scripts/bootstrap.mjs +100 -0
  278. package/scripts/brief-eval.ts +234 -0
  279. package/scripts/bump-version.ts +82 -0
  280. package/scripts/bun-resolve.d.mts +11 -0
  281. package/scripts/bun-resolve.mjs +59 -0
  282. package/scripts/calibrate-grep.ts +467 -0
  283. package/scripts/capture-grep-workload.ts +260 -0
  284. package/scripts/check-tier.ts +61 -0
  285. package/scripts/check-version-sync.ts +97 -0
  286. package/scripts/cli-orchestrate-status.ts +386 -0
  287. package/scripts/cli-orchestrate.ts +303 -0
  288. package/scripts/cli.ts +478 -0
  289. package/scripts/cloud-smoke-test.ts +313 -0
  290. package/scripts/coach-report.ts +373 -0
  291. package/scripts/context-db-migrate.ts +137 -0
  292. package/scripts/context-status.ts +43 -0
  293. package/scripts/demo-run.ts +255 -0
  294. package/scripts/deploy-smoke.sh +140 -0
  295. package/scripts/doctor.ts +992 -0
  296. package/scripts/embed-file-worker.ts +104 -0
  297. package/scripts/embed-tune.ts +308 -0
  298. package/scripts/errors-report.ts +428 -0
  299. package/scripts/find-test-leak.ts +69 -0
  300. package/scripts/generate-badge.ts +357 -0
  301. package/scripts/genome-auto-consolidate.ts +533 -0
  302. package/scripts/genome-auto-propose.ts +578 -0
  303. package/scripts/genome-cloud-pull.ts +363 -0
  304. package/scripts/genome-cloud-push.ts +382 -0
  305. package/scripts/genome-cloud-sync.ts +587 -0
  306. package/scripts/genome-commit-watcher.ts +295 -0
  307. package/scripts/genome-init.ts +986 -0
  308. package/scripts/genome-key.ts +233 -0
  309. package/scripts/genome-keygen.ts +168 -0
  310. package/scripts/genome-link.ts +59 -0
  311. package/scripts/genome-refresh-worker.ts +364 -0
  312. package/scripts/genome-rewrap.ts +90 -0
  313. package/scripts/genome-synthesizer.ts +679 -0
  314. package/scripts/genome-team-init.ts +312 -0
  315. package/scripts/handoff-pack.ts +438 -0
  316. package/scripts/hook-bootstrap.mjs +75 -0
  317. package/scripts/hook-timing-reader.ts +371 -0
  318. package/scripts/hook-timings-report.ts +554 -0
  319. package/scripts/install-genome-hooks.ts +196 -0
  320. package/scripts/install-onnx-model.ts +154 -0
  321. package/scripts/install-permissions.ts +276 -0
  322. package/scripts/install-status-line.ts +150 -0
  323. package/scripts/mcp-entrypoint.sh +78 -0
  324. package/scripts/mcp-entrypoint.ts +130 -0
  325. package/scripts/mdx-angle-bracket-lint.ts +152 -0
  326. package/scripts/measure-cold-start.ts +126 -0
  327. package/scripts/migrate-stats-to-sqlite.ts +86 -0
  328. package/scripts/ollama-setup.ts +498 -0
  329. package/scripts/onboarding-wizard.ts +1691 -0
  330. package/scripts/orchestrate-emit-telemetry.ts +177 -0
  331. package/scripts/orchestrate-expand.ts +517 -0
  332. package/scripts/orchestrate-run.ts +744 -0
  333. package/scripts/print-legend.ts +50 -0
  334. package/scripts/product-metadata.ts +38 -0
  335. package/scripts/prune-old-memories.ts +208 -0
  336. package/scripts/publish.sh +88 -0
  337. package/scripts/read-calibration.ts +122 -0
  338. package/scripts/report-crash.ts +226 -0
  339. package/scripts/run-benchmark.ts +750 -0
  340. package/scripts/run-root-tests.ts +28 -0
  341. package/scripts/savings-dashboard.ts +1258 -0
  342. package/scripts/savings-report-extras.ts +447 -0
  343. package/scripts/savings-status-line.ts +873 -0
  344. package/scripts/session-event-emit.ts +266 -0
  345. package/scripts/session-greet.ts +686 -0
  346. package/scripts/session-log-report.ts +551 -0
  347. package/scripts/session-resume.ts +614 -0
  348. package/scripts/set-hook-mode.ts +83 -0
  349. package/scripts/smoke-cross-platform.ts +117 -0
  350. package/scripts/smoke-realtime.ts +257 -0
  351. package/scripts/smoke-tools.ts +21 -0
  352. package/scripts/stats-cloud-pull.ts +213 -0
  353. package/scripts/stats-cloud-sync.ts +261 -0
  354. package/scripts/telemetry-flush.ts +160 -0
  355. package/scripts/telemetry-status.ts +266 -0
  356. package/scripts/timing-budget.ts +35 -0
  357. package/scripts/ui-animation.ts +120 -0
  358. package/scripts/ui.ts +431 -0
  359. package/scripts/upgrade-flow.ts +775 -0
  360. package/scripts/weekly-digest.ts +394 -0
  361. package/servers/_accounting.ts +78 -0
  362. package/servers/_ask-router.ts +84 -0
  363. package/servers/_ast-chunker.ts +434 -0
  364. package/servers/_ast-helpers.ts +183 -0
  365. package/servers/_ast-languages.ts +153 -0
  366. package/servers/_ast-refactor/_shared.ts +221 -0
  367. package/servers/_ast-refactor/cross-file-rename.ts +560 -0
  368. package/servers/_ast-refactor/extract-function.ts +357 -0
  369. package/servers/_ast-refactor/file-local-rename.ts +172 -0
  370. package/servers/_ast-refactor.ts +41 -0
  371. package/servers/_ast-skeleton.ts +107 -0
  372. package/servers/_bash-summarizers-registry.ts +1096 -0
  373. package/servers/_crash-dump.ts +210 -0
  374. package/servers/_cwd-clamp.ts +342 -0
  375. package/servers/_edit-log.ts +28 -0
  376. package/servers/_edit-match.ts +236 -0
  377. package/servers/_edit-validate.ts +196 -0
  378. package/servers/_embed-calibration.ts +123 -0
  379. package/servers/_embedding-cache.ts +401 -0
  380. package/servers/_embedding-model.ts +329 -0
  381. package/servers/_events.ts +113 -0
  382. package/servers/_genome-cache.ts +154 -0
  383. package/servers/_genome-commits.ts +172 -0
  384. package/servers/_genome-crypto-v2.ts +242 -0
  385. package/servers/_genome-crypto.ts +259 -0
  386. package/servers/_genome-discoveries.ts +140 -0
  387. package/servers/_genome-embed-populator.ts +216 -0
  388. package/servers/_genome-freshness.ts +134 -0
  389. package/servers/_genome-issues.ts +171 -0
  390. package/servers/_genome-live.ts +263 -0
  391. package/servers/_genome-prs.ts +188 -0
  392. package/servers/_genome-search.ts +479 -0
  393. package/servers/_genome-sync.ts +297 -0
  394. package/servers/_history-tracker.ts +279 -0
  395. package/servers/_http-helpers.ts +151 -0
  396. package/servers/_identity-hash.ts +151 -0
  397. package/servers/_llm-providers/anthropic.ts +132 -0
  398. package/servers/_llm-providers/cloud.ts +195 -0
  399. package/servers/_llm-providers/index.ts +350 -0
  400. package/servers/_llm-providers/local.ts +127 -0
  401. package/servers/_llm-providers/onnx.ts +393 -0
  402. package/servers/_llm-providers/types.ts +27 -0
  403. package/servers/_manifest-v2.ts +447 -0
  404. package/servers/_mcp-host.ts +93 -0
  405. package/servers/_nudge-events.ts +451 -0
  406. package/servers/_orchestrate-executor.ts +316 -0
  407. package/servers/_prefetch.ts +435 -0
  408. package/servers/_pricing.ts +256 -0
  409. package/servers/_pro.ts +381 -0
  410. package/servers/_read-cache.ts +44 -0
  411. package/servers/_router-handlers.ts +46 -0
  412. package/servers/_router.ts +55 -0
  413. package/servers/_run-with-timeout.ts +173 -0
  414. package/servers/_savings-render.ts +214 -0
  415. package/servers/_stats-sqlite.ts +640 -0
  416. package/servers/_stats.ts +1183 -0
  417. package/servers/_status-line-cells.ts +469 -0
  418. package/servers/_streaks.ts +162 -0
  419. package/servers/_summarize.ts +208 -0
  420. package/servers/_task-graph-render.ts +217 -0
  421. package/servers/_task-graph.ts +545 -0
  422. package/servers/_telemetry.ts +719 -0
  423. package/servers/_test-parsers.ts +530 -0
  424. package/servers/_test-watch.ts +626 -0
  425. package/servers/_text-helpers.ts +37 -0
  426. package/servers/_token-measure.ts +160 -0
  427. package/servers/_tool-base.ts +248 -0
  428. package/servers/_weekly-digest.ts +391 -0
  429. package/servers/ask-server-handlers.ts +49 -0
  430. package/servers/ask-server.ts +174 -0
  431. package/servers/bash-server-handlers.ts +138 -0
  432. package/servers/bash-server.ts +1136 -0
  433. package/servers/bench.ts +186 -0
  434. package/servers/diff-semantic-server-handlers.ts +39 -0
  435. package/servers/diff-semantic-server.ts +566 -0
  436. package/servers/diff-server-handlers.ts +317 -0
  437. package/servers/diff-server.ts +20 -0
  438. package/servers/edit-server-handlers.ts +31 -0
  439. package/servers/edit-server.ts +209 -0
  440. package/servers/edit-structural-server-handlers.ts +322 -0
  441. package/servers/efficiency-server-handlers.ts +161 -0
  442. package/servers/efficiency-server.ts +1135 -0
  443. package/servers/flush-server-handlers.ts +21 -0
  444. package/servers/flush-server.ts +19 -0
  445. package/servers/genome-server-handlers.ts +118 -0
  446. package/servers/genome-server.ts +397 -0
  447. package/servers/github-server-handlers.ts +187 -0
  448. package/servers/github-server.ts +856 -0
  449. package/servers/glob-server-handlers.ts +233 -0
  450. package/servers/glob-server.ts +20 -0
  451. package/servers/grep-server-handlers.ts +61 -0
  452. package/servers/grep-server.ts +564 -0
  453. package/servers/http-server-handlers.ts +36 -0
  454. package/servers/http-server.ts +149 -0
  455. package/servers/logs-server-handlers.ts +42 -0
  456. package/servers/logs-server.ts +359 -0
  457. package/servers/ls-server-handlers.ts +166 -0
  458. package/servers/ls-server.ts +20 -0
  459. package/servers/multi-edit-server-handlers.ts +51 -0
  460. package/servers/multi-edit-server.ts +422 -0
  461. package/servers/notebook-edit-server-handlers.ts +34 -0
  462. package/servers/notebook-edit-server.ts +181 -0
  463. package/servers/orient-server-handlers.ts +52 -0
  464. package/servers/orient-server.ts +436 -0
  465. package/servers/pipe-server-handlers.ts +68 -0
  466. package/servers/pipe-server.ts +300 -0
  467. package/servers/read-server-handlers.ts +42 -0
  468. package/servers/read-server.ts +206 -0
  469. package/servers/rename-file-server-handlers.ts +67 -0
  470. package/servers/rename-file-server.ts +699 -0
  471. package/servers/savings-server-handlers.ts +27 -0
  472. package/servers/savings-server.ts +54 -0
  473. package/servers/search-replace-regex-server-handlers.ts +96 -0
  474. package/servers/search-replace-regex-server.ts +751 -0
  475. package/servers/sql-server-handlers.ts +58 -0
  476. package/servers/sql-server.ts +505 -0
  477. package/servers/task-server-handlers.ts +358 -0
  478. package/servers/task-server.ts +24 -0
  479. package/servers/test-server-handlers.ts +351 -0
  480. package/servers/test-server.ts +20 -0
  481. package/servers/tree-server-handlers.ts +503 -0
  482. package/servers/tree-server.ts +20 -0
  483. package/servers/webfetch-server-handlers.ts +166 -0
  484. package/servers/webfetch-server.ts +20 -0
  485. package/servers/websearch-server-handlers.ts +215 -0
  486. package/servers/websearch-server.ts +19 -0
  487. package/servers/write-server-handlers.ts +27 -0
  488. package/servers/write-server.ts +97 -0
  489. package/skills/ashlr-brief/SKILL.md +80 -0
  490. package/skills/ashlr-codex-doctor/SKILL.md +21 -0
  491. package/skills/ashlr-codex-efficient-tools/SKILL.md +17 -0
  492. package/skills/ashlr-codex-genome-refresh/SKILL.md +20 -0
  493. package/skills/ashlr-codex-parallel-explore/SKILL.md +20 -0
  494. package/skills/ashlr-codex-savings/SKILL.md +17 -0
  495. package/skills/ashlr-cost-refactor/SKILL.md +50 -0
  496. package/skills/ashlr-efficient/SKILL.md +64 -0
  497. package/skills/ashlr-genome-author/SKILL.md +43 -0
  498. package/skills/ashlr-lean-tools/SKILL.md +43 -0
  499. package/skills/ashlr-search/SKILL.md +46 -0
@@ -0,0 +1,2708 @@
1
+ import {
2
+ getErrorMessage,
3
+ LanguageModelV4,
4
+ SharedV4Warning,
5
+ UnsupportedFunctionalityError,
6
+ } from '@ai-sdk/provider';
7
+ import type {
8
+ Arrayable,
9
+ Context,
10
+ InferToolSetContext,
11
+ ToolApprovalResponse,
12
+ ToolSet,
13
+ } from '@ai-sdk/provider-utils';
14
+ import {
15
+ asArray,
16
+ createIdGenerator,
17
+ DelayedPromise,
18
+ filterNullable,
19
+ IdGenerator,
20
+ isAbortError,
21
+ ProviderOptions,
22
+ ToolContent,
23
+ } from '@ai-sdk/provider-utils';
24
+ import { ServerResponse } from 'node:http';
25
+ import { NoOutputGeneratedError } from '../error';
26
+ import { logWarnings } from '../logger/log-warnings';
27
+ import { resolveLanguageModel } from '../model/resolve-model';
28
+ import { createToolModelOutput } from '../prompt/create-tool-model-output';
29
+ import { LanguageModelCallOptions } from '../prompt/language-model-call-options';
30
+ import { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';
31
+ import { prepareToolChoice } from '../prompt/prepare-tool-choice';
32
+ import { prepareTools } from '../prompt/prepare-tools';
33
+ import { Prompt } from '../prompt/prompt';
34
+ import {
35
+ getChunkTimeoutMs,
36
+ getStepTimeoutMs,
37
+ getTotalTimeoutMs,
38
+ RequestOptions,
39
+ TimeoutConfiguration,
40
+ } from '../prompt/request-options';
41
+ import { standardizePrompt } from '../prompt/standardize-prompt';
42
+ import { wrapGatewayError } from '../prompt/wrap-gateway-error';
43
+ import { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';
44
+ import { TelemetryOptions } from '../telemetry/telemetry-options';
45
+ import { createTextStreamResponse } from '../text-stream/create-text-stream-response';
46
+ import { pipeTextStreamToResponse } from '../text-stream/pipe-text-stream-to-response';
47
+ import { LanguageModelRequestMetadata } from '../types';
48
+ import {
49
+ CallWarning,
50
+ FinishReason,
51
+ LanguageModel,
52
+ ToolChoice,
53
+ } from '../types/language-model';
54
+ import { ProviderMetadata } from '../types/provider-metadata';
55
+ import {
56
+ addLanguageModelUsage,
57
+ createNullLanguageModelUsage,
58
+ LanguageModelUsage,
59
+ } from '../types/usage';
60
+ import { UIMessage } from '../ui';
61
+ import { createUIMessageStreamResponse } from '../ui-message-stream/create-ui-message-stream-response';
62
+ import { getResponseUIMessageId } from '../ui-message-stream/get-response-ui-message-id';
63
+ import { handleUIMessageStreamFinish } from '../ui-message-stream/handle-ui-message-stream-finish';
64
+ import { pipeUIMessageStreamToResponse } from '../ui-message-stream/pipe-ui-message-stream-to-response';
65
+ import {
66
+ InferUIMessageChunk,
67
+ UIMessageChunk,
68
+ } from '../ui-message-stream/ui-message-chunks';
69
+ import { UIMessageStreamResponseInit } from '../ui-message-stream/ui-message-stream-response-init';
70
+ import { InferUIMessageData, InferUIMessageMetadata } from '../ui/ui-messages';
71
+ import {
72
+ AsyncIterableStream,
73
+ createAsyncIterableStream,
74
+ } from '../util/async-iterable-stream';
75
+ import type { Callback } from '../util/callback';
76
+ import { consumeStream } from '../util/consume-stream';
77
+ import { createStitchableStream } from '../util/create-stitchable-stream';
78
+ import { DownloadFunction } from '../util/download/download-function';
79
+ import { mergeAbortSignals } from '../util/merge-abort-signals';
80
+ import { mergeObjects } from '../util/merge-objects';
81
+ import { notify } from '../util/notify';
82
+ import { now as originalNow } from '../util/now';
83
+ import { prepareRetries } from '../util/prepare-retries';
84
+ import { collectToolApprovals } from './collect-tool-approvals';
85
+ import { ContentPart } from './content-part';
86
+ import type {
87
+ GenerateTextEndEvent,
88
+ GenerateTextStartEvent,
89
+ GenerateTextStepEndEvent,
90
+ GenerateTextStepStartEvent,
91
+ } from './core-events';
92
+ import type {
93
+ OnLanguageModelCallEndCallback,
94
+ OnLanguageModelCallStartCallback,
95
+ } from './language-model-events';
96
+ import { createExecuteToolsTransformation } from './create-execute-tools-transformation';
97
+ import { executeToolCall } from './execute-tool-call';
98
+ import { filterActiveTools } from './filter-active-tool';
99
+ import { invokeToolCallbacksFromStream } from './invoke-tool-callbacks-from-stream';
100
+ import { Output, text } from './output';
101
+ import {
102
+ InferCompleteOutput,
103
+ InferElementOutput,
104
+ InferPartialOutput,
105
+ } from './output-utils';
106
+ import { PrepareStepFunction } from './prepare-step';
107
+ import { convertToReasoningOutputs } from './reasoning-output';
108
+ import { ResponseMessage } from './response-message';
109
+ import { DefaultStepResult, StepResult } from './step-result';
110
+ import {
111
+ isStepCount,
112
+ isStopConditionMet,
113
+ StopCondition,
114
+ } from './stop-condition';
115
+ import {
116
+ LanguageModelStreamPart,
117
+ streamLanguageModelCall,
118
+ } from './stream-language-model-call';
119
+ import {
120
+ ConsumeStreamOptions,
121
+ StreamTextResult,
122
+ TextStreamPart,
123
+ UIMessageStreamOptions,
124
+ } from './stream-text-result';
125
+ import { toResponseMessages } from './to-response-messages';
126
+ import { ToolApprovalConfiguration } from './tool-approval-configuration';
127
+ import { TypedToolCall } from './tool-call';
128
+ import { ToolCallRepairFunction } from './tool-call-repair-function';
129
+ import {
130
+ OnToolExecutionEndCallback,
131
+ OnToolExecutionStartCallback,
132
+ } from './tool-execution-events';
133
+ import { ToolOutput } from './tool-output';
134
+ import { StaticToolOutputDenied } from './tool-output-denied';
135
+ import { ToolsContextParameter } from './tools-context-parameter';
136
+
137
+ const originalGenerateId = createIdGenerator({
138
+ prefix: 'aitxt',
139
+ size: 24,
140
+ });
141
+
142
+ const originalGenerateCallId = createIdGenerator({
143
+ prefix: 'call',
144
+ size: 24,
145
+ });
146
+
147
+ /**
148
+ * A transformation that is applied to the stream.
149
+ *
150
+ * @param stopStream - A function that stops the source stream.
151
+ * @param tools - The tools that are accessible to and can be called by the model. The model needs to support calling tools.
152
+ */
153
+ export type StreamTextTransform<TOOLS extends ToolSet> = (options: {
154
+ tools: TOOLS; // for type inference
155
+ stopStream: () => void;
156
+ }) => TransformStream<TextStreamPart<TOOLS>, TextStreamPart<TOOLS>>;
157
+
158
+ /**
159
+ * Callback that is set using the `onError` option.
160
+ *
161
+ * @param event - The event that is passed to the callback.
162
+ */
163
+ export type StreamTextOnErrorCallback = Callback<{
164
+ error: unknown;
165
+ }>;
166
+
167
+ /**
168
+ * Callback that is set using the `onStepFinish` option.
169
+ *
170
+ * @param stepResult - The result of the step.
171
+ */
172
+ export type StreamTextOnStepFinishCallback<
173
+ TOOLS extends ToolSet,
174
+ RUNTIME_CONTEXT extends Context,
175
+ > = Callback<GenerateTextStepEndEvent<TOOLS, RUNTIME_CONTEXT>>;
176
+
177
+ /**
178
+ * Callback that is set using the `onChunk` option.
179
+ *
180
+ * @param event - The event that is passed to the callback.
181
+ */
182
+ export type StreamTextOnChunkCallback<TOOLS extends ToolSet> = (event: {
183
+ chunk: Extract<
184
+ TextStreamPart<TOOLS>,
185
+ {
186
+ type:
187
+ | 'text-delta'
188
+ | 'reasoning-delta'
189
+ | 'custom'
190
+ | 'source'
191
+ | 'tool-call'
192
+ | 'tool-input-start'
193
+ | 'tool-input-delta'
194
+ | 'tool-result'
195
+ | 'raw';
196
+ }
197
+ >;
198
+ }) => PromiseLike<void> | void;
199
+
200
+ /**
201
+ * Callback that is set using the `onFinish` option.
202
+ *
203
+ * @param event - The event that is passed to the callback.
204
+ */
205
+ export type StreamTextOnFinishCallback<
206
+ TOOLS extends ToolSet,
207
+ RUNTIME_CONTEXT extends Context,
208
+ > = Callback<GenerateTextEndEvent<TOOLS, RUNTIME_CONTEXT>>;
209
+
210
+ /**
211
+ * Callback that is set using the `onAbort` option.
212
+ *
213
+ * @param event - The event that is passed to the callback.
214
+ */
215
+ export type StreamTextOnAbortCallback<
216
+ TOOLS extends ToolSet,
217
+ RUNTIME_CONTEXT extends Context,
218
+ > = Callback<{
219
+ /**
220
+ * Details for all previously finished steps.
221
+ */
222
+ readonly steps: StepResult<TOOLS, RUNTIME_CONTEXT>[];
223
+ }>;
224
+
225
+ /**
226
+ * Callback that is set using the `experimental_onStart` option.
227
+ *
228
+ * Called when the streamText operation begins, before any LLM calls.
229
+ * Use this callback for logging, analytics, or initializing state at the
230
+ * start of a generation.
231
+ *
232
+ * @param event - The event object containing generation configuration.
233
+ */
234
+ export type StreamTextOnStartCallback<
235
+ TOOLS extends ToolSet = ToolSet,
236
+ RUNTIME_CONTEXT extends Context = Context,
237
+ OUTPUT extends Output = Output,
238
+ > = Callback<GenerateTextStartEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT>>;
239
+
240
+ /**
241
+ * Callback that is set using the `experimental_onStepStart` option.
242
+ *
243
+ * Called when a step (LLM call) begins, before the provider is called.
244
+ * Each step represents a single LLM invocation. Multiple steps occur when
245
+ * using tool calls (the model may be called multiple times in a loop).
246
+ *
247
+ * @param event - The event object containing step configuration.
248
+ */
249
+ export type StreamTextOnStepStartCallback<
250
+ TOOLS extends ToolSet = ToolSet,
251
+ RUNTIME_CONTEXT extends Context = Context,
252
+ OUTPUT extends Output = Output,
253
+ > = Callback<GenerateTextStepStartEvent<TOOLS, RUNTIME_CONTEXT, OUTPUT>>;
254
+
255
+ /**
256
+ * Generate a text and call tools for a given prompt using a language model.
257
+ *
258
+ * This function streams the output. If you do not want to stream the output, use `generateText` instead.
259
+ *
260
+ * @param model - The language model to use.
261
+ * @param tools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.
262
+ *
263
+ * @param system - A system message that will be part of the prompt.
264
+ * @param prompt - A simple text prompt. You can either use `prompt` or `messages` but not both.
265
+ * @param messages - A list of messages. You can either use `prompt` or `messages` but not both.
266
+ *
267
+ * @param maxOutputTokens - Maximum number of tokens to generate.
268
+ * @param temperature - Temperature setting.
269
+ * The value is passed through to the provider. The range depends on the provider and model.
270
+ * It is recommended to set either `temperature` or `topP`, but not both.
271
+ * @param topP - Nucleus sampling.
272
+ * The value is passed through to the provider. The range depends on the provider and model.
273
+ * It is recommended to set either `temperature` or `topP`, but not both.
274
+ * @param topK - Only sample from the top K options for each subsequent token.
275
+ * Used to remove "long tail" low probability responses.
276
+ * Recommended for advanced use cases only. You usually only need to use temperature.
277
+ * @param presencePenalty - Presence penalty setting.
278
+ * It affects the likelihood of the model to repeat information that is already in the prompt.
279
+ * The value is passed through to the provider. The range depends on the provider and model.
280
+ * @param frequencyPenalty - Frequency penalty setting.
281
+ * It affects the likelihood of the model to repeatedly use the same words or phrases.
282
+ * The value is passed through to the provider. The range depends on the provider and model.
283
+ * @param stopSequences - Stop sequences.
284
+ * If set, the model will stop generating text when one of the stop sequences is generated.
285
+ * @param seed - The seed (integer) to use for random sampling.
286
+ * If set and supported by the model, calls will generate deterministic results.
287
+ *
288
+ * @param maxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.
289
+ * @param abortSignal - An optional abort signal that can be used to cancel the call.
290
+ * @param timeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.
291
+ * @param headers - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
292
+ *
293
+ * @param runtimeContext - User-defined runtime context that flows through the entire generation lifecycle.
294
+ *
295
+ * @param onChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.
296
+ * @param onError - Callback that is called when an error occurs during streaming. You can use it to log errors.
297
+ * @param onStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.
298
+ * @param onFinish - Callback that is called when all steps are finished and the response is complete.
299
+ *
300
+ * @returns
301
+ * A result object for accessing different stream types and additional information.
302
+ */
303
+ export function streamText<
304
+ TOOLS extends ToolSet,
305
+ RUNTIME_CONTEXT extends Context = Context,
306
+ OUTPUT extends Output = Output<string, string, never>,
307
+ >({
308
+ model,
309
+ tools,
310
+ toolChoice,
311
+ system,
312
+ prompt,
313
+ messages,
314
+ maxRetries,
315
+ abortSignal,
316
+ timeout,
317
+ headers,
318
+ stopWhen = isStepCount(1),
319
+ output,
320
+ toolApproval,
321
+ experimental_telemetry,
322
+ telemetry = experimental_telemetry,
323
+ prepareStep,
324
+ providerOptions,
325
+ activeTools,
326
+ experimental_repairToolCall: repairToolCall,
327
+ experimental_transform: transform,
328
+ experimental_download: download,
329
+ includeRawChunks = false,
330
+ onChunk,
331
+ onError = ({ error }) => {
332
+ console.error(error);
333
+ },
334
+ onFinish,
335
+ onAbort,
336
+ onStepFinish,
337
+ experimental_onStart: onStart,
338
+ experimental_onStepStart: onStepStart,
339
+ experimental_onLanguageModelCallStart: onLanguageModelCallStart,
340
+ experimental_onLanguageModelCallEnd: onLanguageModelCallEnd,
341
+ experimental_onToolExecutionStart: onToolExecutionStart,
342
+ experimental_onToolExecutionEnd: onToolExecutionEnd,
343
+ runtimeContext = {} as RUNTIME_CONTEXT,
344
+ toolsContext = {} as InferToolSetContext<TOOLS>,
345
+ experimental_include: include,
346
+ _internal: {
347
+ now = originalNow,
348
+ generateId = originalGenerateId,
349
+ generateCallId = originalGenerateCallId,
350
+ } = {},
351
+ ...settings
352
+ }: LanguageModelCallOptions &
353
+ RequestOptions<TOOLS> &
354
+ Prompt &
355
+ ToolsContextParameter<TOOLS> & {
356
+ /**
357
+ * The language model to use.
358
+ */
359
+ model: LanguageModel;
360
+
361
+ /**
362
+ * The tool choice strategy. Default: 'auto'.
363
+ */
364
+ toolChoice?: ToolChoice<TOOLS>;
365
+
366
+ /**
367
+ * Condition for stopping the generation when there are tool results in the last step.
368
+ * When the condition is an array, any of the conditions can be met to stop the generation.
369
+ *
370
+ * @default isStepCount(1)
371
+ */
372
+ stopWhen?: Arrayable<StopCondition<NoInfer<TOOLS>, RUNTIME_CONTEXT>>;
373
+
374
+ /**
375
+ * Optional telemetry configuration.
376
+ */
377
+ telemetry?: TelemetryOptions;
378
+
379
+ /**
380
+ * Optional telemetry configuration.
381
+ *
382
+ * @deprecated Use `telemetry` instead. This alias will be removed in a future major release.
383
+ */
384
+ experimental_telemetry?: TelemetryOptions;
385
+
386
+ /**
387
+ * Additional provider-specific options. They are passed through
388
+ * to the provider from the AI SDK and enable provider-specific
389
+ * functionality that can be fully encapsulated in the provider.
390
+ */
391
+ providerOptions?: ProviderOptions;
392
+
393
+ /**
394
+ * Runtime context. Treat runtime context as immutable.
395
+ * If you need to mutate runtime context, update it in `prepareStep`.
396
+ */
397
+ runtimeContext?: RUNTIME_CONTEXT;
398
+
399
+ /**
400
+ * Limits the tools that are available for the model to call without
401
+ * changing the tool call and result types in the result.
402
+ */
403
+ activeTools?: Array<keyof NoInfer<TOOLS>>;
404
+
405
+ /**
406
+ * Optional specification for parsing structured outputs from the LLM response.
407
+ */
408
+ output?: OUTPUT;
409
+
410
+ /**
411
+ * Optional tool approval configuration.
412
+ *
413
+ * This configuration takes precedence over tool-defined approval settings.
414
+ */
415
+ toolApproval?: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT>;
416
+
417
+ /**
418
+ * Optional function that you can use to provide different settings for a step.
419
+ *
420
+ * @param options - The options for the step.
421
+ * @param options.steps - The steps that have been executed so far.
422
+ * @param options.stepNumber - The number of the step that is being executed.
423
+ * @param options.model - The model that is being used.
424
+ *
425
+ * @returns An object that contains the settings for the step.
426
+ * If you return undefined (or for undefined settings), the settings from the outer level will be used.
427
+ */
428
+ prepareStep?: PrepareStepFunction<NoInfer<TOOLS>, RUNTIME_CONTEXT>;
429
+
430
+ /**
431
+ * A function that attempts to repair a tool call that failed to parse.
432
+ */
433
+ experimental_repairToolCall?: ToolCallRepairFunction<TOOLS>;
434
+
435
+ /**
436
+ * Optional stream transformations.
437
+ * They are applied in the order they are provided.
438
+ * The stream transformations must maintain the stream structure for streamText to work correctly.
439
+ */
440
+ experimental_transform?: Arrayable<StreamTextTransform<TOOLS>>;
441
+
442
+ /**
443
+ * Custom download function to use for URLs.
444
+ *
445
+ * By default, files are downloaded if the model does not support the URL for the given media type.
446
+ */
447
+ experimental_download?: DownloadFunction | undefined;
448
+
449
+ /**
450
+ * Whether to include raw chunks from the provider in the stream.
451
+ * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.
452
+ * This allows access to cutting-edge provider features not yet wrapped by the AI SDK.
453
+ * Defaults to false.
454
+ */
455
+ includeRawChunks?: boolean;
456
+
457
+ /**
458
+ * Callback that is called for each chunk of the stream.
459
+ * The stream processing will pause until the callback promise is resolved.
460
+ */
461
+ onChunk?: StreamTextOnChunkCallback<TOOLS>;
462
+
463
+ /**
464
+ * Callback that is invoked when an error occurs during streaming.
465
+ * You can use it to log errors.
466
+ * The stream processing will pause until the callback promise is resolved.
467
+ */
468
+ onError?: StreamTextOnErrorCallback;
469
+
470
+ /**
471
+ * Callback that is called when the LLM response and all request tool executions
472
+ * (for tools that have an `execute` function) are finished.
473
+ *
474
+ * The usage is the combined usage of all steps.
475
+ */
476
+ onFinish?: StreamTextOnFinishCallback<
477
+ NoInfer<TOOLS>,
478
+ NoInfer<RUNTIME_CONTEXT>
479
+ >;
480
+
481
+ onAbort?: StreamTextOnAbortCallback<
482
+ NoInfer<TOOLS>,
483
+ NoInfer<RUNTIME_CONTEXT>
484
+ >;
485
+
486
+ /**
487
+ * Callback that is called when each step (LLM call) is finished, including intermediate steps.
488
+ */
489
+ onStepFinish?: StreamTextOnStepFinishCallback<
490
+ NoInfer<TOOLS>,
491
+ NoInfer<RUNTIME_CONTEXT>
492
+ >;
493
+
494
+ /**
495
+ * Callback that is called when the streamText operation begins,
496
+ * before any LLM calls are made.
497
+ */
498
+ experimental_onStart?: StreamTextOnStartCallback<
499
+ NoInfer<TOOLS>,
500
+ NoInfer<RUNTIME_CONTEXT>,
501
+ NoInfer<OUTPUT>
502
+ >;
503
+
504
+ /**
505
+ * Callback that is called when a step (LLM call) begins,
506
+ * before the provider is called.
507
+ */
508
+ experimental_onStepStart?: StreamTextOnStepStartCallback<
509
+ NoInfer<TOOLS>,
510
+ NoInfer<RUNTIME_CONTEXT>,
511
+ NoInfer<OUTPUT>
512
+ >;
513
+
514
+ /**
515
+ * Callback that is called immediately before the provider model call begins.
516
+ */
517
+ experimental_onLanguageModelCallStart?: OnLanguageModelCallStartCallback;
518
+
519
+ /**
520
+ * Callback that is called after the model response has been normalized and parsed,
521
+ * but before any client-side tool execution begins.
522
+ */
523
+ experimental_onLanguageModelCallEnd?: OnLanguageModelCallEndCallback<
524
+ NoInfer<TOOLS>
525
+ >;
526
+
527
+ /**
528
+ * Callback that is called right before a tool's execute function runs.
529
+ */
530
+ experimental_onToolExecutionStart?: OnToolExecutionStartCallback<
531
+ NoInfer<TOOLS>
532
+ >;
533
+
534
+ /**
535
+ * Callback that is called right after a tool's execute function completes (or errors).
536
+ */
537
+ experimental_onToolExecutionEnd?: OnToolExecutionEndCallback<
538
+ NoInfer<TOOLS>
539
+ >;
540
+
541
+ /**
542
+ * Settings for controlling what data is included in step results.
543
+ * Disabling inclusion can help reduce memory usage when processing
544
+ * large payloads like images.
545
+ *
546
+ * By default, all data is included for backwards compatibility.
547
+ */
548
+ experimental_include?: {
549
+ /**
550
+ * Whether to retain the request body in step results.
551
+ * The request body can be large when sending images or files.
552
+ * @default true
553
+ */
554
+ requestBody?: boolean;
555
+ };
556
+
557
+ /**
558
+ * Internal. For test use only. May change without notice.
559
+ */
560
+ _internal?: {
561
+ now?: () => number;
562
+ generateId?: IdGenerator;
563
+ generateCallId?: IdGenerator;
564
+ };
565
+ }): StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {
566
+ const totalTimeoutMs = getTotalTimeoutMs(timeout);
567
+ const stepTimeoutMs = getStepTimeoutMs(timeout);
568
+ const chunkTimeoutMs = getChunkTimeoutMs(timeout);
569
+ const stepAbortController =
570
+ stepTimeoutMs != null ? new AbortController() : undefined;
571
+ const chunkAbortController =
572
+ chunkTimeoutMs != null ? new AbortController() : undefined;
573
+ return new DefaultStreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>({
574
+ model: resolveLanguageModel(model),
575
+ telemetry,
576
+ headers,
577
+ settings,
578
+ maxRetries,
579
+ abortSignal: mergeAbortSignals(
580
+ abortSignal,
581
+ totalTimeoutMs,
582
+ stepAbortController?.signal,
583
+ chunkAbortController?.signal,
584
+ ),
585
+ stepTimeoutMs,
586
+ stepAbortController,
587
+ chunkTimeoutMs,
588
+ chunkAbortController,
589
+ system,
590
+ prompt,
591
+ messages,
592
+ tools,
593
+ toolsContext,
594
+ runtimeContext,
595
+ toolChoice,
596
+ transforms: asArray(transform),
597
+ activeTools,
598
+ repairToolCall,
599
+ stopConditions: asArray(stopWhen),
600
+ output,
601
+ toolApproval,
602
+ providerOptions,
603
+ prepareStep,
604
+ includeRawChunks,
605
+ timeout,
606
+ stopWhen,
607
+ onChunk,
608
+ onError,
609
+ onFinish,
610
+ onAbort,
611
+ onStepFinish,
612
+ onStart,
613
+ onStepStart,
614
+ onLanguageModelCallStart,
615
+ onLanguageModelCallEnd,
616
+ onToolExecutionStart,
617
+ onToolExecutionEnd,
618
+ now,
619
+ generateId,
620
+ generateCallId,
621
+ download,
622
+ include,
623
+ });
624
+ }
625
+
626
+ export type EnrichedStreamPart<TOOLS extends ToolSet, PARTIAL_OUTPUT> = {
627
+ part: TextStreamPart<TOOLS>;
628
+ partialOutput: PARTIAL_OUTPUT | undefined;
629
+ };
630
+
631
+ function createOutputTransformStream<
632
+ TOOLS extends ToolSet,
633
+ OUTPUT extends Output,
634
+ >(
635
+ output: OUTPUT,
636
+ ): TransformStream<
637
+ TextStreamPart<TOOLS>,
638
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
639
+ > {
640
+ let firstTextChunkId: string | undefined = undefined;
641
+ let text = '';
642
+ let textChunk = '';
643
+ let textProviderMetadata: ProviderMetadata | undefined = undefined;
644
+ let lastPublishedValue = '';
645
+
646
+ function publishTextChunk({
647
+ controller,
648
+ partialOutput = undefined,
649
+ }: {
650
+ controller: TransformStreamDefaultController<
651
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
652
+ >;
653
+ partialOutput?: InferPartialOutput<OUTPUT>;
654
+ }) {
655
+ controller.enqueue({
656
+ part: {
657
+ type: 'text-delta',
658
+ id: firstTextChunkId!,
659
+ text: textChunk,
660
+ providerMetadata: textProviderMetadata,
661
+ },
662
+ partialOutput,
663
+ });
664
+ textChunk = '';
665
+ }
666
+
667
+ return new TransformStream<
668
+ TextStreamPart<TOOLS>,
669
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
670
+ >({
671
+ async transform(chunk, controller) {
672
+ // ensure that we publish the last text chunk before the step finish:
673
+ if (chunk.type === 'finish-step' && textChunk.length > 0) {
674
+ publishTextChunk({ controller });
675
+ }
676
+
677
+ if (
678
+ chunk.type !== 'text-delta' &&
679
+ chunk.type !== 'text-start' &&
680
+ chunk.type !== 'text-end'
681
+ ) {
682
+ controller.enqueue({ part: chunk, partialOutput: undefined });
683
+ return;
684
+ }
685
+
686
+ // we have to pick a text chunk which contains the json text
687
+ // since we are streaming, we have to pick the first text chunk
688
+ if (firstTextChunkId == null) {
689
+ firstTextChunkId = chunk.id;
690
+ } else if (chunk.id !== firstTextChunkId) {
691
+ controller.enqueue({ part: chunk, partialOutput: undefined });
692
+ return;
693
+ }
694
+
695
+ if (chunk.type === 'text-start') {
696
+ controller.enqueue({ part: chunk, partialOutput: undefined });
697
+ return;
698
+ }
699
+
700
+ if (chunk.type === 'text-end') {
701
+ if (textChunk.length > 0) {
702
+ publishTextChunk({ controller });
703
+ }
704
+ controller.enqueue({ part: chunk, partialOutput: undefined });
705
+ return;
706
+ }
707
+
708
+ text += chunk.text;
709
+ textChunk += chunk.text;
710
+ textProviderMetadata = chunk.providerMetadata ?? textProviderMetadata;
711
+
712
+ // only publish if partial json can be parsed:
713
+ const result = await output.parsePartialOutput({ text });
714
+
715
+ // null should be allowed (valid JSON value) but undefined should not:
716
+ if (result !== undefined) {
717
+ // only send new value if it has changed:
718
+ // For string partials (text output), compare directly to avoid unnecessary JSON.stringify overhead
719
+ const currentValue =
720
+ typeof result.partial === 'string'
721
+ ? result.partial
722
+ : JSON.stringify(result.partial);
723
+ if (currentValue !== lastPublishedValue) {
724
+ publishTextChunk({ controller, partialOutput: result.partial });
725
+ lastPublishedValue = currentValue;
726
+ }
727
+ }
728
+ },
729
+ });
730
+ }
731
+
732
+ class DefaultStreamTextResult<
733
+ TOOLS extends ToolSet,
734
+ RUNTIME_CONTEXT extends Context,
735
+ OUTPUT extends Output,
736
+ > implements StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT> {
737
+ private readonly _totalUsage = new DelayedPromise<
738
+ Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['usage']>
739
+ >();
740
+ private readonly _finishReason = new DelayedPromise<
741
+ Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['finishReason']>
742
+ >();
743
+ private readonly _rawFinishReason = new DelayedPromise<
744
+ Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['rawFinishReason']>
745
+ >();
746
+ private readonly _steps = new DelayedPromise<
747
+ Awaited<StreamTextResult<TOOLS, RUNTIME_CONTEXT, OUTPUT>['steps']>
748
+ >();
749
+
750
+ private readonly addStream: (
751
+ stream: ReadableStream<TextStreamPart<TOOLS>>,
752
+ ) => void;
753
+
754
+ private readonly closeStream: () => void;
755
+
756
+ private baseStream: ReadableStream<
757
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
758
+ >;
759
+
760
+ private outputSpecification: OUTPUT | undefined;
761
+
762
+ private includeRawChunks: boolean;
763
+
764
+ private tools: TOOLS | undefined;
765
+
766
+ constructor({
767
+ model,
768
+ telemetry,
769
+ headers,
770
+ settings,
771
+ maxRetries: maxRetriesArg,
772
+ abortSignal,
773
+ stepTimeoutMs,
774
+ stepAbortController,
775
+ chunkTimeoutMs,
776
+ chunkAbortController,
777
+ system,
778
+ prompt,
779
+ messages,
780
+ tools,
781
+ toolChoice,
782
+ transforms,
783
+ activeTools,
784
+ repairToolCall,
785
+ stopConditions,
786
+ output,
787
+ toolApproval,
788
+ providerOptions,
789
+ prepareStep,
790
+ includeRawChunks,
791
+ now,
792
+ generateId,
793
+ generateCallId,
794
+ timeout,
795
+ stopWhen,
796
+ onChunk,
797
+ onError,
798
+ onFinish,
799
+ onAbort,
800
+ onStepFinish,
801
+ onStart,
802
+ onStepStart,
803
+ onLanguageModelCallStart,
804
+ onLanguageModelCallEnd,
805
+ onToolExecutionStart,
806
+ onToolExecutionEnd,
807
+ runtimeContext,
808
+ toolsContext,
809
+ download,
810
+ include,
811
+ }: {
812
+ model: LanguageModelV4;
813
+ telemetry: TelemetryOptions | undefined;
814
+ headers: Record<string, string | undefined> | undefined;
815
+ settings: LanguageModelCallOptions;
816
+ maxRetries: number | undefined;
817
+ abortSignal: AbortSignal | undefined;
818
+ stepTimeoutMs: number | undefined;
819
+ stepAbortController: AbortController | undefined;
820
+ chunkTimeoutMs: number | undefined;
821
+ chunkAbortController: AbortController | undefined;
822
+ toolsContext: InferToolSetContext<TOOLS>;
823
+ runtimeContext: RUNTIME_CONTEXT;
824
+ system: Prompt['system'];
825
+ prompt: Prompt['prompt'];
826
+ messages: Prompt['messages'];
827
+ tools: TOOLS | undefined;
828
+ toolChoice: ToolChoice<TOOLS> | undefined;
829
+ transforms: Array<StreamTextTransform<TOOLS>>;
830
+ activeTools: Array<keyof TOOLS> | undefined;
831
+ repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;
832
+ stopConditions: Array<
833
+ StopCondition<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>
834
+ >;
835
+ output: OUTPUT | undefined;
836
+ toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;
837
+ providerOptions: ProviderOptions | undefined;
838
+ prepareStep:
839
+ | PrepareStepFunction<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>
840
+ | undefined;
841
+ includeRawChunks: boolean;
842
+ now: () => number;
843
+ generateId: () => string;
844
+ generateCallId: () => string;
845
+ timeout: TimeoutConfiguration<TOOLS> | undefined;
846
+ stopWhen: Arrayable<
847
+ StopCondition<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>
848
+ >;
849
+ download: DownloadFunction | undefined;
850
+ include: { requestBody?: boolean } | undefined;
851
+
852
+ // callbacks:
853
+ onChunk: undefined | StreamTextOnChunkCallback<TOOLS>;
854
+ onError: StreamTextOnErrorCallback;
855
+ onFinish:
856
+ | undefined
857
+ | StreamTextOnFinishCallback<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>;
858
+ onAbort:
859
+ | undefined
860
+ | StreamTextOnAbortCallback<NoInfer<TOOLS>, NoInfer<RUNTIME_CONTEXT>>;
861
+ onStepFinish:
862
+ | undefined
863
+ | StreamTextOnStepFinishCallback<
864
+ NoInfer<TOOLS>,
865
+ NoInfer<RUNTIME_CONTEXT>
866
+ >;
867
+ onStart:
868
+ | undefined
869
+ | StreamTextOnStartCallback<
870
+ NoInfer<TOOLS>,
871
+ NoInfer<RUNTIME_CONTEXT>,
872
+ NoInfer<OUTPUT>
873
+ >;
874
+ onStepStart:
875
+ | undefined
876
+ | StreamTextOnStepStartCallback<
877
+ NoInfer<TOOLS>,
878
+ NoInfer<RUNTIME_CONTEXT>,
879
+ NoInfer<OUTPUT>
880
+ >;
881
+ onLanguageModelCallStart: undefined | OnLanguageModelCallStartCallback;
882
+ onLanguageModelCallEnd:
883
+ | undefined
884
+ | OnLanguageModelCallEndCallback<NoInfer<TOOLS>>;
885
+ onToolExecutionStart: undefined | OnToolExecutionStartCallback<TOOLS>;
886
+ onToolExecutionEnd: undefined | OnToolExecutionEndCallback<TOOLS>;
887
+ }) {
888
+ this.outputSpecification = output;
889
+ this.includeRawChunks = includeRawChunks;
890
+ this.tools = tools;
891
+
892
+ const telemetryDispatcher = createTelemetryDispatcher({
893
+ telemetry,
894
+ });
895
+
896
+ // promise to ensure that the step has been fully processed by the event processor
897
+ // before a new step is started. This is required because the continuation condition
898
+ // needs the updated steps to determine if another step is needed.
899
+ let stepFinish!: DelayedPromise<void>;
900
+
901
+ let recordedContent: Array<ContentPart<TOOLS>> = [];
902
+ const recordedResponseMessages: Array<ResponseMessage> = [];
903
+ let recordedFinishReason: FinishReason | undefined = undefined;
904
+ let recordedRawFinishReason: string | undefined = undefined;
905
+ let recordedTotalUsage: LanguageModelUsage | undefined = undefined;
906
+ let recordedRequest: LanguageModelRequestMetadata = {};
907
+ let recordedWarnings: Array<CallWarning> = [];
908
+ const recordedSteps: StepResult<TOOLS, RUNTIME_CONTEXT>[] = [];
909
+
910
+ // Track provider-executed tool calls that support deferred results
911
+ // (e.g., code_execution in programmatic tool calling scenarios).
912
+ // These tools may not return their results in the same turn as their call.
913
+ const pendingDeferredToolCalls = new Map<string, { toolName: string }>();
914
+
915
+ let activeTextContent: Record<
916
+ string,
917
+ {
918
+ type: 'text';
919
+ text: string;
920
+ providerMetadata: ProviderMetadata | undefined;
921
+ }
922
+ > = {};
923
+
924
+ let activeReasoningContent: Record<
925
+ string,
926
+ {
927
+ type: 'reasoning';
928
+ text: string;
929
+ providerMetadata: ProviderMetadata | undefined;
930
+ }
931
+ > = {};
932
+
933
+ const eventProcessor = new TransformStream<
934
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,
935
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>
936
+ >({
937
+ async transform(chunk, controller) {
938
+ controller.enqueue(chunk); // forward the chunk to the next stream
939
+
940
+ const { part } = chunk;
941
+
942
+ if (
943
+ part.type === 'text-delta' ||
944
+ part.type === 'reasoning-delta' ||
945
+ part.type === 'custom' ||
946
+ part.type === 'source' ||
947
+ part.type === 'tool-call' ||
948
+ part.type === 'tool-result' ||
949
+ part.type === 'tool-input-start' ||
950
+ part.type === 'tool-input-delta' ||
951
+ part.type === 'raw'
952
+ ) {
953
+ await onChunk?.({ chunk: part });
954
+ }
955
+
956
+ if (part.type === 'error') {
957
+ await onError({ error: wrapGatewayError(part.error) });
958
+ }
959
+
960
+ if (
961
+ part.type === 'custom' ||
962
+ part.type === 'source' ||
963
+ part.type === 'tool-call' ||
964
+ part.type === 'tool-approval-request' ||
965
+ part.type === 'tool-approval-response' ||
966
+ part.type === 'tool-error'
967
+ ) {
968
+ recordedContent.push(part);
969
+ }
970
+
971
+ if (part.type === 'text-start') {
972
+ activeTextContent[part.id] = {
973
+ type: 'text',
974
+ text: '',
975
+ providerMetadata: part.providerMetadata,
976
+ };
977
+
978
+ recordedContent.push(activeTextContent[part.id]);
979
+ }
980
+
981
+ if (part.type === 'text-delta') {
982
+ const activeText = activeTextContent[part.id];
983
+
984
+ if (activeText == null) {
985
+ controller.enqueue({
986
+ part: {
987
+ type: 'error',
988
+ error: `text part ${part.id} not found`,
989
+ },
990
+ partialOutput: undefined,
991
+ });
992
+ return;
993
+ }
994
+
995
+ activeText.text += part.text;
996
+ activeText.providerMetadata =
997
+ part.providerMetadata ?? activeText.providerMetadata;
998
+ }
999
+
1000
+ if (part.type === 'text-end') {
1001
+ const activeText = activeTextContent[part.id];
1002
+
1003
+ if (activeText == null) {
1004
+ controller.enqueue({
1005
+ part: {
1006
+ type: 'error',
1007
+ error: `text part ${part.id} not found`,
1008
+ },
1009
+ partialOutput: undefined,
1010
+ });
1011
+ return;
1012
+ }
1013
+
1014
+ activeText.providerMetadata =
1015
+ part.providerMetadata ?? activeText.providerMetadata;
1016
+
1017
+ delete activeTextContent[part.id];
1018
+ }
1019
+
1020
+ if (part.type === 'reasoning-start') {
1021
+ activeReasoningContent[part.id] = {
1022
+ type: 'reasoning',
1023
+ text: '',
1024
+ providerMetadata: part.providerMetadata,
1025
+ };
1026
+
1027
+ recordedContent.push(activeReasoningContent[part.id]);
1028
+ }
1029
+
1030
+ if (part.type === 'reasoning-delta') {
1031
+ const activeReasoning = activeReasoningContent[part.id];
1032
+
1033
+ if (activeReasoning == null) {
1034
+ controller.enqueue({
1035
+ part: {
1036
+ type: 'error',
1037
+ error: `reasoning part ${part.id} not found`,
1038
+ },
1039
+ partialOutput: undefined,
1040
+ });
1041
+ return;
1042
+ }
1043
+
1044
+ activeReasoning.text += part.text;
1045
+ activeReasoning.providerMetadata =
1046
+ part.providerMetadata ?? activeReasoning.providerMetadata;
1047
+ }
1048
+
1049
+ if (part.type === 'reasoning-end') {
1050
+ const activeReasoning = activeReasoningContent[part.id];
1051
+
1052
+ if (activeReasoning == null) {
1053
+ controller.enqueue({
1054
+ part: {
1055
+ type: 'error',
1056
+ error: `reasoning part ${part.id} not found`,
1057
+ },
1058
+ partialOutput: undefined,
1059
+ });
1060
+ return;
1061
+ }
1062
+
1063
+ activeReasoning.providerMetadata =
1064
+ part.providerMetadata ?? activeReasoning.providerMetadata;
1065
+
1066
+ delete activeReasoningContent[part.id];
1067
+ }
1068
+
1069
+ if (part.type === 'file' || part.type === 'reasoning-file') {
1070
+ recordedContent.push({
1071
+ type: part.type,
1072
+ file: part.file,
1073
+ ...(part.providerMetadata != null
1074
+ ? { providerMetadata: part.providerMetadata }
1075
+ : {}),
1076
+ });
1077
+ }
1078
+
1079
+ if (part.type === 'tool-result' && !part.preliminary) {
1080
+ recordedContent.push(part);
1081
+ }
1082
+
1083
+ if (part.type === 'start-step') {
1084
+ // reset the recorded data when a new step starts:
1085
+ recordedContent = [];
1086
+ activeReasoningContent = {};
1087
+ activeTextContent = {};
1088
+
1089
+ recordedRequest = part.request;
1090
+ recordedWarnings = part.warnings;
1091
+ }
1092
+
1093
+ if (part.type === 'finish-step') {
1094
+ const stepMessages = await toResponseMessages({
1095
+ content: recordedContent,
1096
+ tools,
1097
+ });
1098
+
1099
+ // Add step information (after response messages are updated):
1100
+ const currentStepResult: StepResult<TOOLS, RUNTIME_CONTEXT> =
1101
+ new DefaultStepResult({
1102
+ callId,
1103
+ stepNumber: recordedSteps.length,
1104
+ provider: model.provider,
1105
+ modelId: model.modelId,
1106
+ runtimeContext,
1107
+ toolsContext,
1108
+ content: recordedContent,
1109
+ finishReason: part.finishReason,
1110
+ rawFinishReason: part.rawFinishReason,
1111
+ usage: part.usage,
1112
+ warnings: recordedWarnings,
1113
+ request: recordedRequest,
1114
+ response: {
1115
+ ...part.response,
1116
+ messages: [...recordedResponseMessages, ...stepMessages],
1117
+ },
1118
+ providerMetadata: part.providerMetadata,
1119
+ });
1120
+
1121
+ await notify({
1122
+ event: currentStepResult,
1123
+ callbacks: [onStepFinish, telemetryDispatcher.onStepFinish],
1124
+ });
1125
+
1126
+ logWarnings({
1127
+ warnings: recordedWarnings,
1128
+ provider: model.provider,
1129
+ model: model.modelId,
1130
+ });
1131
+
1132
+ recordedSteps.push(currentStepResult);
1133
+
1134
+ recordedResponseMessages.push(...stepMessages);
1135
+
1136
+ // resolve the promise to signal that the step has been fully processed
1137
+ // by the event processor:
1138
+ stepFinish.resolve();
1139
+ }
1140
+
1141
+ if (part.type === 'finish') {
1142
+ recordedTotalUsage = part.totalUsage;
1143
+ recordedFinishReason = part.finishReason;
1144
+ recordedRawFinishReason = part.rawFinishReason;
1145
+ }
1146
+ },
1147
+
1148
+ async flush(controller) {
1149
+ try {
1150
+ if (recordedSteps.length === 0) {
1151
+ const error = abortSignal?.aborted
1152
+ ? abortSignal.reason
1153
+ : new NoOutputGeneratedError({
1154
+ message: 'No output generated. Check the stream for errors.',
1155
+ });
1156
+
1157
+ self._finishReason.reject(error);
1158
+ self._rawFinishReason.reject(error);
1159
+ self._totalUsage.reject(error);
1160
+ self._steps.reject(error);
1161
+
1162
+ return; // no steps recorded (e.g. in error scenario)
1163
+ }
1164
+
1165
+ // derived:
1166
+ const finishReason = recordedFinishReason ?? 'other';
1167
+ const totalUsage =
1168
+ recordedTotalUsage ?? createNullLanguageModelUsage();
1169
+
1170
+ // from finish:
1171
+ self._finishReason.resolve(finishReason);
1172
+ self._rawFinishReason.resolve(recordedRawFinishReason);
1173
+ self._totalUsage.resolve(totalUsage);
1174
+
1175
+ // aggregate results:
1176
+ self._steps.resolve(recordedSteps);
1177
+
1178
+ // call onFinish callback:
1179
+ const finalStep = recordedSteps[recordedSteps.length - 1];
1180
+
1181
+ await notify({
1182
+ event: {
1183
+ callId,
1184
+ toolsContext: finalStep.toolsContext,
1185
+ stepNumber: finalStep.stepNumber,
1186
+ model: finalStep.model,
1187
+ runtimeContext: finalStep.runtimeContext,
1188
+ finishReason: finalStep.finishReason,
1189
+ rawFinishReason: finalStep.rawFinishReason,
1190
+ totalUsage,
1191
+ usage: finalStep.usage,
1192
+ content: finalStep.content,
1193
+ text: finalStep.text,
1194
+ reasoningText: finalStep.reasoningText,
1195
+ reasoning: finalStep.reasoning,
1196
+ files: finalStep.files,
1197
+ sources: finalStep.sources,
1198
+ toolCalls: finalStep.toolCalls,
1199
+ staticToolCalls: finalStep.staticToolCalls,
1200
+ dynamicToolCalls: finalStep.dynamicToolCalls,
1201
+ toolResults: finalStep.toolResults,
1202
+ staticToolResults: finalStep.staticToolResults,
1203
+ dynamicToolResults: finalStep.dynamicToolResults,
1204
+ request: finalStep.request,
1205
+ response: finalStep.response,
1206
+ warnings: finalStep.warnings,
1207
+ providerMetadata: finalStep.providerMetadata,
1208
+ steps: recordedSteps,
1209
+ },
1210
+ callbacks: [
1211
+ onFinish,
1212
+ telemetryDispatcher.onFinish as
1213
+ | undefined
1214
+ | StreamTextOnFinishCallback<
1215
+ NoInfer<TOOLS>,
1216
+ NoInfer<RUNTIME_CONTEXT>
1217
+ >,
1218
+ ],
1219
+ });
1220
+ } catch (error) {
1221
+ controller.error(error);
1222
+ }
1223
+ },
1224
+ });
1225
+
1226
+ // initialize the stitchable stream and the transformed stream:
1227
+ const stitchableStream = createStitchableStream<TextStreamPart<TOOLS>>();
1228
+ this.addStream = stitchableStream.addStream;
1229
+ this.closeStream = stitchableStream.close;
1230
+
1231
+ // resilient stream that handles abort signals and errors:
1232
+ const reader = stitchableStream.stream.getReader();
1233
+ let stream = new ReadableStream<TextStreamPart<TOOLS>>({
1234
+ async start(controller) {
1235
+ // send start event:
1236
+ controller.enqueue({ type: 'start' });
1237
+ },
1238
+
1239
+ async pull(controller) {
1240
+ // abort handling:
1241
+ function abort() {
1242
+ onAbort?.({ steps: recordedSteps });
1243
+ controller.enqueue({
1244
+ type: 'abort',
1245
+ // The `reason` is usually of type DOMException, but it can also be of any type,
1246
+ // so we use getErrorMessage for serialization because it is already designed to accept values of the unknown type.
1247
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason
1248
+ ...(abortSignal?.reason !== undefined
1249
+ ? { reason: getErrorMessage(abortSignal.reason) }
1250
+ : {}),
1251
+ });
1252
+ controller.close();
1253
+ }
1254
+
1255
+ try {
1256
+ const { done, value } = await reader.read();
1257
+
1258
+ if (done) {
1259
+ controller.close();
1260
+ return;
1261
+ }
1262
+
1263
+ if (abortSignal?.aborted) {
1264
+ abort();
1265
+ return;
1266
+ }
1267
+
1268
+ controller.enqueue(value);
1269
+ } catch (error) {
1270
+ if (isAbortError(error) && abortSignal?.aborted) {
1271
+ abort();
1272
+ } else {
1273
+ controller.error(error);
1274
+ }
1275
+ }
1276
+ },
1277
+
1278
+ cancel(reason) {
1279
+ return stitchableStream.stream.cancel(reason);
1280
+ },
1281
+ });
1282
+
1283
+ // introduce a gate that prevent further tokens from
1284
+ // being emitted after a transform calls stopStream
1285
+ let isRunning = true;
1286
+ stream = stream.pipeThrough(
1287
+ new TransformStream({
1288
+ async transform(chunk, controller) {
1289
+ if (isRunning) {
1290
+ controller.enqueue(chunk);
1291
+ }
1292
+ },
1293
+ }),
1294
+ );
1295
+
1296
+ // transform the stream before output parsing
1297
+ // to enable replacement of stream segments:
1298
+ for (const transform of transforms) {
1299
+ stream = stream.pipeThrough(
1300
+ transform({
1301
+ tools: tools as TOOLS,
1302
+ stopStream() {
1303
+ stitchableStream.terminate();
1304
+ isRunning = false;
1305
+ },
1306
+ }),
1307
+ );
1308
+ }
1309
+
1310
+ this.baseStream = stream
1311
+ .pipeThrough(createOutputTransformStream(output ?? text()))
1312
+ .pipeThrough(eventProcessor);
1313
+
1314
+ const { maxRetries } = prepareRetries({
1315
+ maxRetries: maxRetriesArg,
1316
+ abortSignal,
1317
+ });
1318
+
1319
+ const callSettings = prepareLanguageModelCallOptions(settings);
1320
+
1321
+ const self = this;
1322
+
1323
+ const callId = generateCallId();
1324
+
1325
+ (async () => {
1326
+ const initialPrompt = await standardizePrompt({
1327
+ system,
1328
+ prompt,
1329
+ messages,
1330
+ } as Prompt);
1331
+
1332
+ await notify({
1333
+ event: {
1334
+ callId,
1335
+ operationId: 'ai.streamText',
1336
+ provider: model.provider,
1337
+ modelId: model.modelId,
1338
+ system,
1339
+ messages: initialPrompt.messages,
1340
+ tools,
1341
+ toolChoice,
1342
+ activeTools,
1343
+ maxOutputTokens: callSettings.maxOutputTokens,
1344
+ temperature: callSettings.temperature,
1345
+ topP: callSettings.topP,
1346
+ topK: callSettings.topK,
1347
+ presencePenalty: callSettings.presencePenalty,
1348
+ frequencyPenalty: callSettings.frequencyPenalty,
1349
+ stopSequences: callSettings.stopSequences,
1350
+ seed: callSettings.seed,
1351
+ reasoning: callSettings.reasoning,
1352
+ maxRetries,
1353
+ timeout,
1354
+ headers,
1355
+ providerOptions,
1356
+ stopWhen,
1357
+ output,
1358
+ runtimeContext,
1359
+ toolsContext,
1360
+ },
1361
+ callbacks: [
1362
+ onStart,
1363
+ telemetryDispatcher.onStart as
1364
+ | undefined
1365
+ | StreamTextOnStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>,
1366
+ ],
1367
+ });
1368
+
1369
+ const initialMessages = initialPrompt.messages;
1370
+ const initialResponseMessages: Array<ResponseMessage> = [];
1371
+
1372
+ const { approvedToolApprovals, deniedToolApprovals } =
1373
+ collectToolApprovals<TOOLS>({ messages: initialMessages });
1374
+
1375
+ // initial tool execution step stream
1376
+ if (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {
1377
+ const localApprovedToolApprovals = approvedToolApprovals.filter(
1378
+ toolApproval => !toolApproval.toolCall.providerExecuted,
1379
+ );
1380
+ const localDeniedToolApprovals = deniedToolApprovals.filter(
1381
+ toolApproval => !toolApproval.toolCall.providerExecuted,
1382
+ );
1383
+
1384
+ const deniedProviderExecutedToolApprovals = deniedToolApprovals.filter(
1385
+ toolApproval => toolApproval.toolCall.providerExecuted,
1386
+ );
1387
+
1388
+ let toolExecutionStepStreamController:
1389
+ | ReadableStreamDefaultController<TextStreamPart<TOOLS>>
1390
+ | undefined;
1391
+ const toolExecutionStepStream = new ReadableStream<
1392
+ TextStreamPart<TOOLS>
1393
+ >({
1394
+ start(controller) {
1395
+ toolExecutionStepStreamController = controller;
1396
+ },
1397
+ });
1398
+
1399
+ self.addStream(toolExecutionStepStream);
1400
+
1401
+ try {
1402
+ for (const toolApproval of [
1403
+ ...localDeniedToolApprovals,
1404
+ ...deniedProviderExecutedToolApprovals,
1405
+ ]) {
1406
+ toolExecutionStepStreamController?.enqueue({
1407
+ type: 'tool-output-denied',
1408
+ toolCallId: toolApproval.toolCall.toolCallId,
1409
+ toolName: toolApproval.toolCall.toolName,
1410
+ } as StaticToolOutputDenied<TOOLS>);
1411
+ }
1412
+
1413
+ const toolOutputs: Array<ToolOutput<TOOLS>> = [];
1414
+
1415
+ await Promise.all(
1416
+ localApprovedToolApprovals.map(async toolApproval => {
1417
+ const result = await executeToolCall({
1418
+ toolCall: toolApproval.toolCall,
1419
+ tools,
1420
+ callId,
1421
+ messages: initialMessages,
1422
+ abortSignal,
1423
+ timeout,
1424
+ toolsContext,
1425
+ onToolExecutionStart: filterNullable(
1426
+ onToolExecutionStart,
1427
+ telemetryDispatcher.onToolExecutionStart as
1428
+ | OnToolExecutionStartCallback<TOOLS>
1429
+ | undefined,
1430
+ ),
1431
+ onToolExecutionEnd: filterNullable(
1432
+ onToolExecutionEnd,
1433
+ telemetryDispatcher.onToolExecutionEnd as
1434
+ | OnToolExecutionEndCallback<TOOLS>
1435
+ | undefined,
1436
+ ),
1437
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool,
1438
+ onPreliminaryToolResult: result => {
1439
+ toolExecutionStepStreamController?.enqueue(result);
1440
+ },
1441
+ });
1442
+
1443
+ if (result != null) {
1444
+ toolExecutionStepStreamController?.enqueue(result);
1445
+ toolOutputs.push(result);
1446
+ }
1447
+ }),
1448
+ );
1449
+
1450
+ // Local tool results (approved + denied) are sent as tool results:
1451
+ if (toolOutputs.length > 0 || localDeniedToolApprovals.length > 0) {
1452
+ const localToolContent: ToolContent = [];
1453
+
1454
+ // add regular tool results for approved tool calls:
1455
+ for (const output of toolOutputs) {
1456
+ localToolContent.push({
1457
+ type: 'tool-result' as const,
1458
+ toolCallId: output.toolCallId,
1459
+ toolName: output.toolName,
1460
+ output: await createToolModelOutput({
1461
+ toolCallId: output.toolCallId,
1462
+ input: output.input,
1463
+ tool: tools?.[output.toolName],
1464
+ output:
1465
+ output.type === 'tool-result'
1466
+ ? output.output
1467
+ : output.error,
1468
+ errorMode: output.type === 'tool-error' ? 'text' : 'none',
1469
+ }),
1470
+ });
1471
+ }
1472
+
1473
+ // add execution denied tool results for denied local tool approvals:
1474
+ for (const toolApproval of localDeniedToolApprovals) {
1475
+ localToolContent.push({
1476
+ type: 'tool-result' as const,
1477
+ toolCallId: toolApproval.toolCall.toolCallId,
1478
+ toolName: toolApproval.toolCall.toolName,
1479
+ output: {
1480
+ type: 'execution-denied' as const,
1481
+ reason: toolApproval.approvalResponse.reason,
1482
+ },
1483
+ });
1484
+ }
1485
+
1486
+ initialResponseMessages.push({
1487
+ role: 'tool',
1488
+ content: localToolContent,
1489
+ });
1490
+ }
1491
+ } finally {
1492
+ toolExecutionStepStreamController?.close();
1493
+ }
1494
+ }
1495
+
1496
+ recordedResponseMessages.push(...initialResponseMessages);
1497
+
1498
+ async function streamStep({
1499
+ currentStep,
1500
+ responseMessages,
1501
+ usage,
1502
+ }: {
1503
+ currentStep: number;
1504
+ responseMessages: Array<ResponseMessage>;
1505
+ usage: LanguageModelUsage;
1506
+ }) {
1507
+ const includeRawChunks = self.includeRawChunks;
1508
+
1509
+ // Set up step timeout if configured
1510
+ const stepTimeoutId =
1511
+ stepTimeoutMs != null
1512
+ ? setTimeout(() => stepAbortController!.abort(), stepTimeoutMs)
1513
+ : undefined;
1514
+
1515
+ // Set up chunk timeout tracking (will be reset on each chunk)
1516
+ let chunkTimeoutId: ReturnType<typeof setTimeout> | undefined =
1517
+ undefined;
1518
+
1519
+ function resetChunkTimeout() {
1520
+ if (chunkTimeoutMs != null) {
1521
+ if (chunkTimeoutId != null) {
1522
+ clearTimeout(chunkTimeoutId);
1523
+ }
1524
+ chunkTimeoutId = setTimeout(
1525
+ () => chunkAbortController!.abort(),
1526
+ chunkTimeoutMs,
1527
+ );
1528
+ }
1529
+ }
1530
+
1531
+ function clearChunkTimeout() {
1532
+ if (chunkTimeoutId != null) {
1533
+ clearTimeout(chunkTimeoutId);
1534
+ chunkTimeoutId = undefined;
1535
+ }
1536
+ }
1537
+
1538
+ function clearStepTimeout() {
1539
+ if (stepTimeoutId != null) {
1540
+ clearTimeout(stepTimeoutId);
1541
+ }
1542
+ }
1543
+
1544
+ try {
1545
+ stepFinish = new DelayedPromise<void>();
1546
+
1547
+ const stepInputMessages = [...initialMessages, ...responseMessages];
1548
+
1549
+ const prepareStepResult = await prepareStep?.({
1550
+ model,
1551
+ steps: recordedSteps,
1552
+ stepNumber: recordedSteps.length,
1553
+ messages: stepInputMessages,
1554
+ toolsContext,
1555
+ runtimeContext,
1556
+ });
1557
+
1558
+ const stepModel = resolveLanguageModel(
1559
+ prepareStepResult?.model ?? model,
1560
+ );
1561
+
1562
+ const stepActiveTools = filterActiveTools({
1563
+ tools,
1564
+ activeTools: prepareStepResult?.activeTools ?? activeTools,
1565
+ });
1566
+
1567
+ const stepTools = await prepareTools({
1568
+ tools: stepActiveTools,
1569
+ });
1570
+
1571
+ const stepToolChoice = prepareToolChoice({
1572
+ toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1573
+ });
1574
+
1575
+ runtimeContext = prepareStepResult?.runtimeContext ?? runtimeContext;
1576
+ toolsContext = prepareStepResult?.toolsContext ?? toolsContext;
1577
+
1578
+ const stepMessages = prepareStepResult?.messages ?? stepInputMessages;
1579
+ const stepSystem = prepareStepResult?.system ?? initialPrompt.system;
1580
+
1581
+ const stepProviderOptions = mergeObjects(
1582
+ providerOptions,
1583
+ prepareStepResult?.providerOptions,
1584
+ );
1585
+
1586
+ const stepStartTimestampMs = now();
1587
+
1588
+ const { retry } = prepareRetries({ maxRetries, abortSignal });
1589
+
1590
+ const {
1591
+ stream: languageModelStream,
1592
+ request,
1593
+ response,
1594
+ } = await retry(async () =>
1595
+ streamLanguageModelCall({
1596
+ model: prepareStepResult?.model ?? model,
1597
+ tools: stepActiveTools,
1598
+ toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1599
+ system: stepSystem,
1600
+ messages: stepMessages,
1601
+ repairToolCall,
1602
+ abortSignal,
1603
+ headers,
1604
+ includeRawChunks,
1605
+ providerOptions: stepProviderOptions,
1606
+ download,
1607
+ output,
1608
+ callId,
1609
+ onLanguageModelCallStart: filterNullable(
1610
+ onLanguageModelCallStart,
1611
+ telemetryDispatcher.onLanguageModelCallStart as
1612
+ | undefined
1613
+ | OnLanguageModelCallStartCallback,
1614
+ ),
1615
+ onLanguageModelCallEnd: filterNullable(
1616
+ onLanguageModelCallEnd,
1617
+ telemetryDispatcher.onLanguageModelCallEnd as
1618
+ | undefined
1619
+ | OnLanguageModelCallEndCallback<TOOLS>,
1620
+ ),
1621
+ onStart: async ({ promptMessages }) => {
1622
+ await notify({
1623
+ event: {
1624
+ callId,
1625
+ provider: stepModel.provider,
1626
+ modelId: stepModel.modelId,
1627
+ stepNumber: recordedSteps.length,
1628
+ system: stepSystem,
1629
+ messages: stepMessages,
1630
+ tools,
1631
+ toolChoice: prepareStepResult?.toolChoice ?? toolChoice,
1632
+ activeTools: prepareStepResult?.activeTools ?? activeTools,
1633
+ steps: [...recordedSteps],
1634
+ providerOptions: stepProviderOptions,
1635
+ runtimeContext,
1636
+ toolsContext,
1637
+ output,
1638
+ promptMessages,
1639
+ stepTools,
1640
+ stepToolChoice,
1641
+ },
1642
+ callbacks: [
1643
+ onStepStart,
1644
+ telemetryDispatcher.onStepStart as
1645
+ | undefined
1646
+ | StreamTextOnStepStartCallback<
1647
+ TOOLS,
1648
+ RUNTIME_CONTEXT,
1649
+ OUTPUT
1650
+ >,
1651
+ ],
1652
+ });
1653
+ },
1654
+ ...callSettings,
1655
+ }),
1656
+ );
1657
+
1658
+ const stream2 = invokeToolCallbacksFromStream({
1659
+ stream: languageModelStream,
1660
+ tools,
1661
+ stepInputMessages,
1662
+ abortSignal,
1663
+ runtimeContext,
1664
+ });
1665
+
1666
+ const streamWithToolResults = stream2.pipeThrough(
1667
+ createExecuteToolsTransformation({
1668
+ tools,
1669
+ callId,
1670
+ messages: stepInputMessages,
1671
+ abortSignal,
1672
+ timeout,
1673
+ toolsContext,
1674
+ toolApproval,
1675
+ runtimeContext,
1676
+ generateId,
1677
+ onToolExecutionStart: filterNullable(
1678
+ onToolExecutionStart,
1679
+ telemetryDispatcher.onToolExecutionStart as
1680
+ | OnToolExecutionStartCallback<TOOLS>
1681
+ | undefined,
1682
+ ),
1683
+ onToolExecutionEnd: filterNullable(
1684
+ onToolExecutionEnd,
1685
+ telemetryDispatcher.onToolExecutionEnd as
1686
+ | OnToolExecutionEndCallback<TOOLS>
1687
+ | undefined,
1688
+ ),
1689
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool,
1690
+ }),
1691
+ );
1692
+
1693
+ // Conditionally include request.body based on include settings.
1694
+ // Large payloads (e.g., base64-encoded images) can cause memory issues.
1695
+ const stepRequest: LanguageModelRequestMetadata =
1696
+ (include?.requestBody ?? true)
1697
+ ? (request ?? {})
1698
+ : { ...request, body: undefined };
1699
+ const stepToolCalls: TypedToolCall<TOOLS>[] = [];
1700
+ const stepToolOutputs: ToolOutput<TOOLS>[] = [];
1701
+ const stepToolApprovalResponses: ToolApprovalResponse[] = [];
1702
+ let warnings: SharedV4Warning[] | undefined;
1703
+
1704
+ let stepFinishReason: FinishReason = 'other';
1705
+ let stepRawFinishReason: string | undefined = undefined;
1706
+
1707
+ let stepUsage: LanguageModelUsage = createNullLanguageModelUsage();
1708
+ let stepProviderMetadata: ProviderMetadata | undefined;
1709
+ let stepFirstChunk = true;
1710
+ let stepResponse: { id: string; timestamp: Date; modelId: string } = {
1711
+ id: generateId(),
1712
+ timestamp: new Date(),
1713
+ modelId: model.modelId,
1714
+ };
1715
+
1716
+ self.addStream(
1717
+ streamWithToolResults.pipeThrough(
1718
+ new TransformStream<
1719
+ LanguageModelStreamPart<TOOLS>,
1720
+ TextStreamPart<TOOLS>
1721
+ >({
1722
+ async transform(chunk, controller): Promise<void> {
1723
+ resetChunkTimeout();
1724
+
1725
+ if (chunk.type === 'model-call-start') {
1726
+ warnings = chunk.warnings;
1727
+ return; // stream start chunks are sent immediately and do not count as first chunk
1728
+ }
1729
+
1730
+ if (stepFirstChunk) {
1731
+ const msToFirstChunk = now() - stepStartTimestampMs;
1732
+ stepFirstChunk = false;
1733
+
1734
+ // Step start:
1735
+ controller.enqueue({
1736
+ type: 'start-step',
1737
+ request: stepRequest,
1738
+ warnings: warnings ?? [],
1739
+ });
1740
+
1741
+ void telemetryDispatcher.onChunk?.({
1742
+ chunk: {
1743
+ type: 'ai.stream.firstChunk',
1744
+ callId,
1745
+ stepNumber: recordedSteps.length,
1746
+ attributes: {
1747
+ 'ai.response.msToFirstChunk': msToFirstChunk,
1748
+ },
1749
+ },
1750
+ });
1751
+ }
1752
+
1753
+ const chunkType = chunk.type;
1754
+ switch (chunkType) {
1755
+ case 'file':
1756
+ case 'custom':
1757
+ case 'source':
1758
+ case 'text-start':
1759
+ case 'text-end':
1760
+ case 'reasoning-start':
1761
+ case 'reasoning-end':
1762
+ case 'reasoning-delta':
1763
+ case 'reasoning-file':
1764
+ case 'tool-input-start':
1765
+ case 'tool-input-end':
1766
+ case 'tool-input-delta':
1767
+ case 'tool-approval-request': {
1768
+ controller.enqueue(chunk);
1769
+ break;
1770
+ }
1771
+
1772
+ case 'text-delta': {
1773
+ if (chunk.text.length > 0) {
1774
+ controller.enqueue(chunk);
1775
+ }
1776
+ break;
1777
+ }
1778
+
1779
+ case 'tool-call': {
1780
+ controller.enqueue(chunk);
1781
+ // store tool calls for onFinish callback and toolCalls promise:
1782
+ stepToolCalls.push(chunk);
1783
+ break;
1784
+ }
1785
+
1786
+ case 'tool-approval-response': {
1787
+ controller.enqueue(chunk);
1788
+ stepToolApprovalResponses.push(chunk);
1789
+ break;
1790
+ }
1791
+
1792
+ case 'tool-result': {
1793
+ controller.enqueue(chunk);
1794
+
1795
+ if (!chunk.preliminary) {
1796
+ stepToolOutputs.push(chunk);
1797
+ }
1798
+
1799
+ break;
1800
+ }
1801
+
1802
+ case 'tool-error': {
1803
+ controller.enqueue(chunk);
1804
+ stepToolOutputs.push(chunk);
1805
+ break;
1806
+ }
1807
+
1808
+ case 'model-call-response-metadata': {
1809
+ stepResponse = {
1810
+ id: chunk.id ?? stepResponse.id,
1811
+ timestamp: chunk.timestamp ?? stepResponse.timestamp,
1812
+ modelId: chunk.modelId ?? stepResponse.modelId,
1813
+ };
1814
+ break;
1815
+ }
1816
+
1817
+ case 'model-call-end': {
1818
+ // Note: tool executions might not be finished yet when the finish event is emitted.
1819
+ // store usage and finish reason for promises and onFinish callback:
1820
+ stepUsage = chunk.usage;
1821
+ stepFinishReason = chunk.finishReason;
1822
+ stepRawFinishReason = chunk.rawFinishReason;
1823
+ stepProviderMetadata = chunk.providerMetadata;
1824
+ const msToFinish = now() - stepStartTimestampMs;
1825
+ void telemetryDispatcher.onChunk?.({
1826
+ chunk: {
1827
+ type: 'ai.stream.finish',
1828
+ callId,
1829
+ stepNumber: recordedSteps.length,
1830
+ attributes: {
1831
+ 'ai.response.msToFinish': msToFinish,
1832
+ 'ai.response.avgOutputTokensPerSecond':
1833
+ (1000 * (stepUsage.outputTokens ?? 0)) /
1834
+ msToFinish,
1835
+ },
1836
+ },
1837
+ });
1838
+
1839
+ break;
1840
+ }
1841
+
1842
+ case 'error': {
1843
+ controller.enqueue(chunk);
1844
+ stepFinishReason = 'error';
1845
+ break;
1846
+ }
1847
+
1848
+ case 'raw': {
1849
+ if (includeRawChunks) {
1850
+ controller.enqueue(chunk);
1851
+ }
1852
+ break;
1853
+ }
1854
+
1855
+ default: {
1856
+ const exhaustiveCheck: never = chunkType;
1857
+ throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
1858
+ }
1859
+ }
1860
+
1861
+ if (
1862
+ chunkType !== 'model-call-end' &&
1863
+ chunkType !== 'model-call-response-metadata'
1864
+ ) {
1865
+ void telemetryDispatcher.onChunk?.({ chunk });
1866
+ }
1867
+ },
1868
+
1869
+ // invoke onFinish callback and resolve toolResults promise when the stream is about to close:
1870
+ async flush(controller) {
1871
+ controller.enqueue({
1872
+ type: 'finish-step',
1873
+ finishReason: stepFinishReason,
1874
+ rawFinishReason: stepRawFinishReason,
1875
+ usage: stepUsage,
1876
+ providerMetadata: stepProviderMetadata,
1877
+ response: {
1878
+ ...stepResponse,
1879
+ headers: response?.headers,
1880
+ },
1881
+ });
1882
+
1883
+ const combinedUsage = addLanguageModelUsage(usage, stepUsage);
1884
+
1885
+ // wait for the step to be fully processed by the event processor
1886
+ // to ensure that the recorded steps are complete:
1887
+ await stepFinish.promise;
1888
+
1889
+ const clientToolCalls = stepToolCalls.filter(
1890
+ toolCall => toolCall.providerExecuted !== true,
1891
+ );
1892
+ const clientToolOutputs = stepToolOutputs.filter(
1893
+ toolOutput => toolOutput.providerExecuted !== true,
1894
+ );
1895
+ const deniedToolApprovalResponses =
1896
+ stepToolApprovalResponses.filter(
1897
+ toolApprovalResponse =>
1898
+ toolApprovalResponse.approved === false,
1899
+ );
1900
+
1901
+ // Track provider-executed tool calls that support deferred results.
1902
+ // In programmatic tool calling, a server tool (e.g., code_execution) may
1903
+ // trigger a client tool, and the server tool's result is deferred until
1904
+ // the client tool's result is sent back.
1905
+ for (const toolCall of stepToolCalls) {
1906
+ if (toolCall.providerExecuted !== true) continue;
1907
+ const tool = tools?.[toolCall.toolName];
1908
+ if (
1909
+ tool?.type === 'provider' &&
1910
+ tool.supportsDeferredResults
1911
+ ) {
1912
+ // Check if this tool call already has a result in the current step
1913
+ const hasResultInStep = stepToolOutputs.some(
1914
+ output =>
1915
+ (output.type === 'tool-result' ||
1916
+ output.type === 'tool-error') &&
1917
+ output.toolCallId === toolCall.toolCallId,
1918
+ );
1919
+ if (!hasResultInStep) {
1920
+ pendingDeferredToolCalls.set(toolCall.toolCallId, {
1921
+ toolName: toolCall.toolName,
1922
+ });
1923
+ }
1924
+ }
1925
+ }
1926
+
1927
+ // Mark deferred tool calls as resolved when we receive their results
1928
+ for (const output of stepToolOutputs) {
1929
+ if (
1930
+ output.type === 'tool-result' ||
1931
+ output.type === 'tool-error'
1932
+ ) {
1933
+ pendingDeferredToolCalls.delete(output.toolCallId);
1934
+ }
1935
+ }
1936
+
1937
+ // Clear the step and chunk timeouts before the next step is started
1938
+ clearStepTimeout();
1939
+ clearChunkTimeout();
1940
+
1941
+ if (
1942
+ // Continue if:
1943
+ // 1. There are client tool calls that have all been executed or denied, OR
1944
+ // 2. There are pending deferred results from provider-executed tools, OR
1945
+ ((clientToolCalls.length > 0 &&
1946
+ clientToolCalls.length ===
1947
+ clientToolOutputs.length +
1948
+ deniedToolApprovalResponses.length) ||
1949
+ pendingDeferredToolCalls.size > 0) &&
1950
+ // continue until a stop condition is met:
1951
+ !(await isStopConditionMet({
1952
+ stopConditions,
1953
+ steps: recordedSteps,
1954
+ }))
1955
+ ) {
1956
+ // append to messages for the next step:
1957
+ responseMessages.push(
1958
+ ...(await toResponseMessages({
1959
+ content:
1960
+ // use transformed content to create the messages for the next step:
1961
+ recordedSteps[recordedSteps.length - 1].content,
1962
+ tools,
1963
+ })),
1964
+ );
1965
+
1966
+ try {
1967
+ await streamStep({
1968
+ currentStep: currentStep + 1,
1969
+ responseMessages,
1970
+ usage: combinedUsage,
1971
+ });
1972
+ } catch (error) {
1973
+ controller.enqueue({
1974
+ type: 'error',
1975
+ error,
1976
+ });
1977
+
1978
+ self.closeStream();
1979
+ }
1980
+ } else {
1981
+ controller.enqueue({
1982
+ type: 'finish',
1983
+ finishReason: stepFinishReason,
1984
+ rawFinishReason: stepRawFinishReason,
1985
+ totalUsage: combinedUsage,
1986
+ });
1987
+
1988
+ self.closeStream(); // close the stitchable stream
1989
+ }
1990
+ },
1991
+ }),
1992
+ ),
1993
+ );
1994
+ } finally {
1995
+ clearStepTimeout();
1996
+ clearChunkTimeout();
1997
+ }
1998
+ }
1999
+
2000
+ // add the initial stream to the stitchable stream
2001
+ await streamStep({
2002
+ currentStep: 0,
2003
+ responseMessages: initialResponseMessages,
2004
+ usage: createNullLanguageModelUsage(),
2005
+ });
2006
+ })().catch(async error => {
2007
+ await telemetryDispatcher.onError?.({ callId, error });
2008
+
2009
+ // add an error stream part and close the streams:
2010
+ self.addStream(
2011
+ new ReadableStream({
2012
+ start(controller) {
2013
+ controller.enqueue({ type: 'error', error });
2014
+ controller.close();
2015
+ },
2016
+ }),
2017
+ );
2018
+ self.closeStream();
2019
+ });
2020
+ }
2021
+
2022
+ get steps() {
2023
+ // when any of the promises are accessed, the stream is consumed
2024
+ // so it resolves without needing to consume the stream separately
2025
+ this.consumeStream();
2026
+
2027
+ return this._steps.promise;
2028
+ }
2029
+
2030
+ private get finalStep() {
2031
+ return this.steps.then(steps => steps[steps.length - 1]);
2032
+ }
2033
+
2034
+ get content() {
2035
+ return this.finalStep.then(step => step.content);
2036
+ }
2037
+
2038
+ get warnings() {
2039
+ return this.finalStep.then(step => step.warnings);
2040
+ }
2041
+
2042
+ get providerMetadata() {
2043
+ return this.finalStep.then(step => step.providerMetadata);
2044
+ }
2045
+
2046
+ get text() {
2047
+ return this.finalStep.then(step => step.text);
2048
+ }
2049
+
2050
+ get reasoningText() {
2051
+ return this.finalStep.then(step => step.reasoningText);
2052
+ }
2053
+
2054
+ get reasoning() {
2055
+ return this.finalStep.then(step =>
2056
+ convertToReasoningOutputs(step.reasoning),
2057
+ );
2058
+ }
2059
+
2060
+ get sources() {
2061
+ return this.finalStep.then(step => step.sources);
2062
+ }
2063
+
2064
+ get files() {
2065
+ return this.finalStep.then(step => step.files);
2066
+ }
2067
+
2068
+ get toolCalls() {
2069
+ return this.finalStep.then(step => step.toolCalls);
2070
+ }
2071
+
2072
+ get staticToolCalls() {
2073
+ return this.finalStep.then(step => step.staticToolCalls);
2074
+ }
2075
+
2076
+ get dynamicToolCalls() {
2077
+ return this.finalStep.then(step => step.dynamicToolCalls);
2078
+ }
2079
+
2080
+ get toolResults() {
2081
+ return this.finalStep.then(step => step.toolResults);
2082
+ }
2083
+
2084
+ get staticToolResults() {
2085
+ return this.finalStep.then(step => step.staticToolResults);
2086
+ }
2087
+
2088
+ get dynamicToolResults() {
2089
+ return this.finalStep.then(step => step.dynamicToolResults);
2090
+ }
2091
+
2092
+ get usage() {
2093
+ return this.finalStep.then(step => step.usage);
2094
+ }
2095
+
2096
+ get request() {
2097
+ return this.finalStep.then(step => step.request);
2098
+ }
2099
+
2100
+ get response() {
2101
+ return this.finalStep.then(step => step.response);
2102
+ }
2103
+
2104
+ get totalUsage() {
2105
+ // when any of the promises are accessed, the stream is consumed
2106
+ // so it resolves without needing to consume the stream separately
2107
+ this.consumeStream();
2108
+
2109
+ return this._totalUsage.promise;
2110
+ }
2111
+
2112
+ get finishReason() {
2113
+ // when any of the promises are accessed, the stream is consumed
2114
+ // so it resolves without needing to consume the stream separately
2115
+ this.consumeStream();
2116
+
2117
+ return this._finishReason.promise;
2118
+ }
2119
+
2120
+ get rawFinishReason() {
2121
+ // when any of the promises are accessed, the stream is consumed
2122
+ // so it resolves without needing to consume the stream separately
2123
+ this.consumeStream();
2124
+
2125
+ return this._rawFinishReason.promise;
2126
+ }
2127
+
2128
+ /**
2129
+ * Split out a new stream from the original stream.
2130
+ * The original stream is replaced to allow for further splitting,
2131
+ * since we do not know how many times the stream will be split.
2132
+ *
2133
+ * Note: this leads to buffering the stream content on the server.
2134
+ * However, the LLM results are expected to be small enough to not cause issues.
2135
+ */
2136
+ private teeStream() {
2137
+ const [stream1, stream2] = this.baseStream.tee();
2138
+ this.baseStream = stream2;
2139
+ return stream1;
2140
+ }
2141
+
2142
+ get textStream(): AsyncIterableStream<string> {
2143
+ return createAsyncIterableStream(
2144
+ this.teeStream().pipeThrough(
2145
+ new TransformStream<
2146
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,
2147
+ string
2148
+ >({
2149
+ transform({ part }, controller) {
2150
+ if (part.type === 'text-delta') {
2151
+ controller.enqueue(part.text);
2152
+ }
2153
+ },
2154
+ }),
2155
+ ),
2156
+ );
2157
+ }
2158
+
2159
+ get fullStream(): AsyncIterableStream<TextStreamPart<TOOLS>> {
2160
+ return createAsyncIterableStream(
2161
+ this.teeStream().pipeThrough(
2162
+ new TransformStream<
2163
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,
2164
+ TextStreamPart<TOOLS>
2165
+ >({
2166
+ transform({ part }, controller) {
2167
+ controller.enqueue(part);
2168
+ },
2169
+ }),
2170
+ ),
2171
+ );
2172
+ }
2173
+
2174
+ async consumeStream(options?: ConsumeStreamOptions): Promise<void> {
2175
+ try {
2176
+ await consumeStream({
2177
+ stream: this.fullStream,
2178
+ onError: options?.onError,
2179
+ });
2180
+ } catch (error) {
2181
+ options?.onError?.(error);
2182
+ }
2183
+ }
2184
+
2185
+ get experimental_partialOutputStream(): AsyncIterableStream<
2186
+ InferPartialOutput<OUTPUT>
2187
+ > {
2188
+ return this.partialOutputStream;
2189
+ }
2190
+
2191
+ get partialOutputStream(): AsyncIterableStream<InferPartialOutput<OUTPUT>> {
2192
+ return createAsyncIterableStream(
2193
+ this.teeStream().pipeThrough(
2194
+ new TransformStream<
2195
+ EnrichedStreamPart<TOOLS, InferPartialOutput<OUTPUT>>,
2196
+ InferPartialOutput<OUTPUT>
2197
+ >({
2198
+ transform({ partialOutput }, controller) {
2199
+ if (partialOutput != null) {
2200
+ controller.enqueue(partialOutput);
2201
+ }
2202
+ },
2203
+ }),
2204
+ ),
2205
+ );
2206
+ }
2207
+
2208
+ get elementStream(): AsyncIterableStream<InferElementOutput<OUTPUT>> {
2209
+ const transform = this.outputSpecification?.createElementStreamTransform();
2210
+
2211
+ if (transform == null) {
2212
+ throw new UnsupportedFunctionalityError({
2213
+ functionality: `element streams in ${this.outputSpecification?.name ?? 'text'} mode`,
2214
+ });
2215
+ }
2216
+
2217
+ return createAsyncIterableStream(this.teeStream().pipeThrough(transform));
2218
+ }
2219
+
2220
+ get output(): Promise<InferCompleteOutput<OUTPUT>> {
2221
+ return this.finalStep.then(step => {
2222
+ const output = this.outputSpecification ?? text();
2223
+ return output.parseCompleteOutput(
2224
+ { text: step.text },
2225
+ {
2226
+ response: step.response,
2227
+ usage: step.usage,
2228
+ finishReason: step.finishReason,
2229
+ },
2230
+ );
2231
+ });
2232
+ }
2233
+
2234
+ toUIMessageStream<UI_MESSAGE extends UIMessage>({
2235
+ originalMessages,
2236
+ generateMessageId,
2237
+ onFinish,
2238
+ messageMetadata,
2239
+ sendReasoning = true,
2240
+ sendSources = false,
2241
+ sendStart = true,
2242
+ sendFinish = true,
2243
+ onError = getErrorMessage,
2244
+ }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<
2245
+ InferUIMessageChunk<UI_MESSAGE>
2246
+ > {
2247
+ const responseMessageId =
2248
+ generateMessageId != null
2249
+ ? getResponseUIMessageId({
2250
+ originalMessages,
2251
+ responseMessageId: generateMessageId,
2252
+ })
2253
+ : undefined;
2254
+
2255
+ // TODO simplify once dynamic is no longer needed for invalid tool inputs
2256
+ const isDynamic = (part: { toolName: string; dynamic?: boolean }) => {
2257
+ const tool = this.tools?.[part.toolName];
2258
+
2259
+ // provider-executed, dynamic tools are not listed in the tools object
2260
+ if (tool == null) {
2261
+ return part.dynamic;
2262
+ }
2263
+
2264
+ return tool?.type === 'dynamic' ? true : undefined;
2265
+ };
2266
+
2267
+ const baseStream = this.fullStream.pipeThrough(
2268
+ new TransformStream<
2269
+ TextStreamPart<TOOLS>,
2270
+ UIMessageChunk<
2271
+ InferUIMessageMetadata<UI_MESSAGE>,
2272
+ InferUIMessageData<UI_MESSAGE>
2273
+ >
2274
+ >({
2275
+ transform: async (part, controller) => {
2276
+ const messageMetadataValue = messageMetadata?.({ part });
2277
+
2278
+ const partType = part.type;
2279
+ switch (partType) {
2280
+ case 'text-start': {
2281
+ controller.enqueue({
2282
+ type: 'text-start',
2283
+ id: part.id,
2284
+ ...(part.providerMetadata != null
2285
+ ? { providerMetadata: part.providerMetadata }
2286
+ : {}),
2287
+ });
2288
+ break;
2289
+ }
2290
+
2291
+ case 'text-delta': {
2292
+ controller.enqueue({
2293
+ type: 'text-delta',
2294
+ id: part.id,
2295
+ delta: part.text,
2296
+ ...(part.providerMetadata != null
2297
+ ? { providerMetadata: part.providerMetadata }
2298
+ : {}),
2299
+ });
2300
+ break;
2301
+ }
2302
+
2303
+ case 'text-end': {
2304
+ controller.enqueue({
2305
+ type: 'text-end',
2306
+ id: part.id,
2307
+ ...(part.providerMetadata != null
2308
+ ? { providerMetadata: part.providerMetadata }
2309
+ : {}),
2310
+ });
2311
+ break;
2312
+ }
2313
+
2314
+ case 'reasoning-start':
2315
+ case 'reasoning-end': {
2316
+ if (sendReasoning) {
2317
+ controller.enqueue({
2318
+ type: partType,
2319
+ id: part.id,
2320
+ ...(part.providerMetadata != null
2321
+ ? { providerMetadata: part.providerMetadata }
2322
+ : {}),
2323
+ });
2324
+ }
2325
+ break;
2326
+ }
2327
+
2328
+ case 'reasoning-delta': {
2329
+ if (sendReasoning) {
2330
+ controller.enqueue({
2331
+ type: 'reasoning-delta',
2332
+ id: part.id,
2333
+ delta: part.text,
2334
+ ...(part.providerMetadata != null
2335
+ ? { providerMetadata: part.providerMetadata }
2336
+ : {}),
2337
+ });
2338
+ }
2339
+ break;
2340
+ }
2341
+
2342
+ case 'file':
2343
+ case 'reasoning-file': {
2344
+ if (partType !== 'reasoning-file' || sendReasoning) {
2345
+ controller.enqueue({
2346
+ type: part.type,
2347
+ mediaType: part.file.mediaType,
2348
+ url: `data:${part.file.mediaType};base64,${part.file.base64}`,
2349
+ ...(part.providerMetadata != null
2350
+ ? { providerMetadata: part.providerMetadata }
2351
+ : {}),
2352
+ });
2353
+ }
2354
+ break;
2355
+ }
2356
+
2357
+ case 'source': {
2358
+ if (sendSources && part.sourceType === 'url') {
2359
+ controller.enqueue({
2360
+ type: 'source-url',
2361
+ sourceId: part.id,
2362
+ url: part.url,
2363
+ title: part.title,
2364
+ ...(part.providerMetadata != null
2365
+ ? { providerMetadata: part.providerMetadata }
2366
+ : {}),
2367
+ });
2368
+ }
2369
+
2370
+ if (sendSources && part.sourceType === 'document') {
2371
+ controller.enqueue({
2372
+ type: 'source-document',
2373
+ sourceId: part.id,
2374
+ mediaType: part.mediaType,
2375
+ title: part.title,
2376
+ filename: part.filename,
2377
+ ...(part.providerMetadata != null
2378
+ ? { providerMetadata: part.providerMetadata }
2379
+ : {}),
2380
+ });
2381
+ }
2382
+ break;
2383
+ }
2384
+
2385
+ case 'custom': {
2386
+ controller.enqueue({
2387
+ type: 'custom',
2388
+ kind: part.kind,
2389
+ ...(part.providerMetadata != null
2390
+ ? { providerMetadata: part.providerMetadata }
2391
+ : {}),
2392
+ });
2393
+ break;
2394
+ }
2395
+
2396
+ case 'tool-input-start': {
2397
+ const dynamic = isDynamic(part);
2398
+
2399
+ controller.enqueue({
2400
+ type: 'tool-input-start',
2401
+ toolCallId: part.id,
2402
+ toolName: part.toolName,
2403
+ ...(part.providerExecuted != null
2404
+ ? { providerExecuted: part.providerExecuted }
2405
+ : {}),
2406
+ ...(part.providerMetadata != null
2407
+ ? { providerMetadata: part.providerMetadata }
2408
+ : {}),
2409
+ ...(dynamic != null ? { dynamic } : {}),
2410
+ ...(part.title != null ? { title: part.title } : {}),
2411
+ });
2412
+ break;
2413
+ }
2414
+
2415
+ case 'tool-input-delta': {
2416
+ controller.enqueue({
2417
+ type: 'tool-input-delta',
2418
+ toolCallId: part.id,
2419
+ inputTextDelta: part.delta,
2420
+ });
2421
+ break;
2422
+ }
2423
+
2424
+ case 'tool-call': {
2425
+ const dynamic = isDynamic(part);
2426
+
2427
+ if (part.invalid) {
2428
+ controller.enqueue({
2429
+ type: 'tool-input-error',
2430
+ toolCallId: part.toolCallId,
2431
+ toolName: part.toolName,
2432
+ input: part.input,
2433
+ ...(part.providerExecuted != null
2434
+ ? { providerExecuted: part.providerExecuted }
2435
+ : {}),
2436
+ ...(part.providerMetadata != null
2437
+ ? { providerMetadata: part.providerMetadata }
2438
+ : {}),
2439
+ ...(dynamic != null ? { dynamic } : {}),
2440
+ errorText: onError(part.error),
2441
+ ...(part.title != null ? { title: part.title } : {}),
2442
+ });
2443
+ } else {
2444
+ controller.enqueue({
2445
+ type: 'tool-input-available',
2446
+ toolCallId: part.toolCallId,
2447
+ toolName: part.toolName,
2448
+ input: part.input,
2449
+ ...(part.providerExecuted != null
2450
+ ? { providerExecuted: part.providerExecuted }
2451
+ : {}),
2452
+ ...(part.providerMetadata != null
2453
+ ? { providerMetadata: part.providerMetadata }
2454
+ : {}),
2455
+ ...(dynamic != null ? { dynamic } : {}),
2456
+ ...(part.title != null ? { title: part.title } : {}),
2457
+ });
2458
+ }
2459
+
2460
+ break;
2461
+ }
2462
+
2463
+ case 'tool-approval-request': {
2464
+ controller.enqueue({
2465
+ type: 'tool-approval-request',
2466
+ approvalId: part.approvalId,
2467
+ toolCallId: part.toolCall.toolCallId,
2468
+ ...(part.isAutomatic != null
2469
+ ? { isAutomatic: part.isAutomatic }
2470
+ : {}),
2471
+ });
2472
+ break;
2473
+ }
2474
+
2475
+ case 'tool-approval-response': {
2476
+ controller.enqueue({
2477
+ type: 'tool-approval-response',
2478
+ approvalId: part.approvalId,
2479
+ approved: part.approved,
2480
+ ...(part.reason != null ? { reason: part.reason } : {}),
2481
+ ...(part.providerExecuted != null
2482
+ ? { providerExecuted: part.providerExecuted }
2483
+ : {}),
2484
+ });
2485
+ break;
2486
+ }
2487
+
2488
+ case 'tool-result': {
2489
+ const dynamic = isDynamic(part);
2490
+
2491
+ controller.enqueue({
2492
+ type: 'tool-output-available',
2493
+ toolCallId: part.toolCallId,
2494
+ output: part.output,
2495
+ ...(part.providerExecuted != null
2496
+ ? { providerExecuted: part.providerExecuted }
2497
+ : {}),
2498
+ ...(part.providerMetadata != null
2499
+ ? { providerMetadata: part.providerMetadata }
2500
+ : {}),
2501
+ ...(part.preliminary != null
2502
+ ? { preliminary: part.preliminary }
2503
+ : {}),
2504
+ ...(dynamic != null ? { dynamic } : {}),
2505
+ });
2506
+ break;
2507
+ }
2508
+
2509
+ case 'tool-error': {
2510
+ const dynamic = isDynamic(part);
2511
+
2512
+ controller.enqueue({
2513
+ type: 'tool-output-error',
2514
+ toolCallId: part.toolCallId,
2515
+ errorText: part.providerExecuted
2516
+ ? typeof part.error === 'string'
2517
+ ? part.error
2518
+ : JSON.stringify(part.error)
2519
+ : onError(part.error),
2520
+ ...(part.providerExecuted != null
2521
+ ? { providerExecuted: part.providerExecuted }
2522
+ : {}),
2523
+ ...(part.providerMetadata != null
2524
+ ? { providerMetadata: part.providerMetadata }
2525
+ : {}),
2526
+ ...(dynamic != null ? { dynamic } : {}),
2527
+ });
2528
+ break;
2529
+ }
2530
+
2531
+ case 'tool-output-denied': {
2532
+ controller.enqueue({
2533
+ type: 'tool-output-denied',
2534
+ toolCallId: part.toolCallId,
2535
+ });
2536
+ break;
2537
+ }
2538
+
2539
+ case 'error': {
2540
+ controller.enqueue({
2541
+ type: 'error',
2542
+ errorText: onError(part.error),
2543
+ });
2544
+ break;
2545
+ }
2546
+
2547
+ case 'start-step': {
2548
+ controller.enqueue({ type: 'start-step' });
2549
+ break;
2550
+ }
2551
+
2552
+ case 'finish-step': {
2553
+ controller.enqueue({ type: 'finish-step' });
2554
+ break;
2555
+ }
2556
+
2557
+ case 'start': {
2558
+ if (sendStart) {
2559
+ controller.enqueue({
2560
+ type: 'start',
2561
+ ...(messageMetadataValue != null
2562
+ ? { messageMetadata: messageMetadataValue }
2563
+ : {}),
2564
+ ...(responseMessageId != null
2565
+ ? { messageId: responseMessageId }
2566
+ : {}),
2567
+ });
2568
+ }
2569
+ break;
2570
+ }
2571
+
2572
+ case 'finish': {
2573
+ if (sendFinish) {
2574
+ controller.enqueue({
2575
+ type: 'finish',
2576
+ finishReason: part.finishReason,
2577
+ ...(messageMetadataValue != null
2578
+ ? { messageMetadata: messageMetadataValue }
2579
+ : {}),
2580
+ });
2581
+ }
2582
+ break;
2583
+ }
2584
+
2585
+ case 'abort': {
2586
+ controller.enqueue(part);
2587
+ break;
2588
+ }
2589
+
2590
+ case 'tool-input-end': {
2591
+ break;
2592
+ }
2593
+
2594
+ case 'raw': {
2595
+ // Raw chunks are not included in UI message streams
2596
+ // as they contain provider-specific data for developer use
2597
+ break;
2598
+ }
2599
+
2600
+ default: {
2601
+ const exhaustiveCheck: never = partType;
2602
+ throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
2603
+ }
2604
+ }
2605
+
2606
+ // start and finish events already have metadata
2607
+ // so we only need to send metadata for other parts
2608
+ if (
2609
+ messageMetadataValue != null &&
2610
+ partType !== 'start' &&
2611
+ partType !== 'finish'
2612
+ ) {
2613
+ controller.enqueue({
2614
+ type: 'message-metadata',
2615
+ messageMetadata: messageMetadataValue,
2616
+ });
2617
+ }
2618
+ },
2619
+ }),
2620
+ );
2621
+
2622
+ return createAsyncIterableStream(
2623
+ handleUIMessageStreamFinish<UI_MESSAGE>({
2624
+ stream: baseStream,
2625
+ messageId: responseMessageId ?? generateMessageId?.(),
2626
+ originalMessages,
2627
+ onFinish,
2628
+ onError,
2629
+ }),
2630
+ );
2631
+ }
2632
+
2633
+ pipeUIMessageStreamToResponse<UI_MESSAGE extends UIMessage>(
2634
+ response: ServerResponse,
2635
+ {
2636
+ originalMessages,
2637
+ generateMessageId,
2638
+ onFinish,
2639
+ messageMetadata,
2640
+ sendReasoning,
2641
+ sendSources,
2642
+ sendFinish,
2643
+ sendStart,
2644
+ onError,
2645
+ ...init
2646
+ }: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE> = {},
2647
+ ) {
2648
+ pipeUIMessageStreamToResponse({
2649
+ response,
2650
+ stream: this.toUIMessageStream({
2651
+ originalMessages,
2652
+ generateMessageId,
2653
+ onFinish,
2654
+ messageMetadata,
2655
+ sendReasoning,
2656
+ sendSources,
2657
+ sendFinish,
2658
+ sendStart,
2659
+ onError,
2660
+ }),
2661
+ ...init,
2662
+ });
2663
+ }
2664
+
2665
+ pipeTextStreamToResponse(response: ServerResponse, init?: ResponseInit) {
2666
+ pipeTextStreamToResponse({
2667
+ response,
2668
+ textStream: this.textStream,
2669
+ ...init,
2670
+ });
2671
+ }
2672
+
2673
+ toUIMessageStreamResponse<UI_MESSAGE extends UIMessage>({
2674
+ originalMessages,
2675
+ generateMessageId,
2676
+ onFinish,
2677
+ messageMetadata,
2678
+ sendReasoning,
2679
+ sendSources,
2680
+ sendFinish,
2681
+ sendStart,
2682
+ onError,
2683
+ ...init
2684
+ }: UIMessageStreamResponseInit &
2685
+ UIMessageStreamOptions<UI_MESSAGE> = {}): Response {
2686
+ return createUIMessageStreamResponse({
2687
+ stream: this.toUIMessageStream({
2688
+ originalMessages,
2689
+ generateMessageId,
2690
+ onFinish,
2691
+ messageMetadata,
2692
+ sendReasoning,
2693
+ sendSources,
2694
+ sendFinish,
2695
+ sendStart,
2696
+ onError,
2697
+ }),
2698
+ ...init,
2699
+ });
2700
+ }
2701
+
2702
+ toTextStreamResponse(init?: ResponseInit): Response {
2703
+ return createTextStreamResponse({
2704
+ textStream: this.textStream,
2705
+ ...init,
2706
+ });
2707
+ }
2708
+ }