@neurocode-ai/core 1.18.8

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 (490) hide show
  1. package/bin/neurocode +199 -0
  2. package/bunfig.toml +2 -0
  3. package/drizzle.config.ts +10 -0
  4. package/package.json +131 -0
  5. package/schema.json +2071 -0
  6. package/script/fix-node-pty.ts +28 -0
  7. package/script/migration.ts +196 -0
  8. package/src/account/sql.ts +39 -0
  9. package/src/account.ts +101 -0
  10. package/src/agent.ts +111 -0
  11. package/src/aisdk.ts +235 -0
  12. package/src/background-job.ts +365 -0
  13. package/src/catalog.ts +301 -0
  14. package/src/command.ts +64 -0
  15. package/src/config/agent.ts +25 -0
  16. package/src/config/attachments.ts +15 -0
  17. package/src/config/command.ts +12 -0
  18. package/src/config/compaction.ts +15 -0
  19. package/src/config/experimental.ts +18 -0
  20. package/src/config/formatter.ts +12 -0
  21. package/src/config/lsp.ts +18 -0
  22. package/src/config/markdown.ts +36 -0
  23. package/src/config/mcp.ts +48 -0
  24. package/src/config/plugin/agent.ts +179 -0
  25. package/src/config/plugin/command.ts +83 -0
  26. package/src/config/plugin/external.ts +91 -0
  27. package/src/config/plugin/provider.ts +113 -0
  28. package/src/config/plugin/reference.ts +70 -0
  29. package/src/config/plugin/skill.ts +50 -0
  30. package/src/config/plugin.ts +13 -0
  31. package/src/config/provider.ts +71 -0
  32. package/src/config/reference.ts +22 -0
  33. package/src/config/tool-output.ts +9 -0
  34. package/src/config/watcher.ts +7 -0
  35. package/src/config.ts +227 -0
  36. package/src/control-plane/move-session.ts +148 -0
  37. package/src/control-plane/workspace.sql.ts +20 -0
  38. package/src/credential/sql.ts +14 -0
  39. package/src/credential.ts +138 -0
  40. package/src/cross-spawn-spawner.ts +507 -0
  41. package/src/data-migration.sql.ts +6 -0
  42. package/src/database/database.ts +57 -0
  43. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +107 -0
  44. package/src/database/migration/20260211171708_add_project_commands.ts +11 -0
  45. package/src/database/migration/20260213144116_wakeful_the_professor.ts +23 -0
  46. package/src/database/migration/20260225215848_workspace.ts +19 -0
  47. package/src/database/migration/20260227213759_add_session_workspace_id.ts +12 -0
  48. package/src/database/migration/20260228203230_blue_harpoon.ts +30 -0
  49. package/src/database/migration/20260303231226_add_workspace_fields.ts +15 -0
  50. package/src/database/migration/20260309230000_move_org_to_state.ts +15 -0
  51. package/src/database/migration/20260312043431_session_message_cursor.ts +16 -0
  52. package/src/database/migration/20260323234822_events.ts +26 -0
  53. package/src/database/migration/20260410174513_workspace-name.ts +29 -0
  54. package/src/database/migration/20260413175956_chief_energizer.ts +24 -0
  55. package/src/database/migration/20260423070820_add_icon_url_override.ts +14 -0
  56. package/src/database/migration/20260427172553_slow_nightmare.ts +30 -0
  57. package/src/database/migration/20260428004200_add_session_path.ts +11 -0
  58. package/src/database/migration/20260501142318_next_venus.ts +12 -0
  59. package/src/database/migration/20260504145000_add_sync_owner.ts +11 -0
  60. package/src/database/migration/20260507164347_add_workspace_time.ts +11 -0
  61. package/src/database/migration/20260510033149_session_usage.ts +56 -0
  62. package/src/database/migration/20260511000411_data_migration_state.ts +16 -0
  63. package/src/database/migration/20260511173437_session-metadata.ts +16 -0
  64. package/src/database/migration/20260601010001_normalize_storage_paths.ts +22 -0
  65. package/src/database/migration/20260601202201_amazing_prowler.ts +11 -0
  66. package/src/database/migration/20260602002951_lowly_union_jack.ts +24 -0
  67. package/src/database/migration/20260602182828_add_project_directories.ts +20 -0
  68. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +19 -0
  69. package/src/database/migration/20260603040000_session_message_projection_order.ts +19 -0
  70. package/src/database/migration/20260603141458_session_input_inbox.ts +25 -0
  71. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +20 -0
  72. package/src/database/migration/20260604172448_event_sourced_session_input.ts +47 -0
  73. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +21 -0
  74. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +11 -0
  75. package/src/database/migration/20260611035744_credential.ts +25 -0
  76. package/src/database/migration/20260611192811_lush_chimera.ts +25 -0
  77. package/src/database/migration/20260612174303_project_dir_strategy.ts +29 -0
  78. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +13 -0
  79. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -0
  80. package/src/database/migration/20260622202450_simplify_session_input.ts +17 -0
  81. package/src/database/migration.gen.ts +44 -0
  82. package/src/database/migration.ts +81 -0
  83. package/src/database/path.ts +91 -0
  84. package/src/database/schema.gen.ts +274 -0
  85. package/src/database/schema.sql.ts +10 -0
  86. package/src/database/sqlite.bun.ts +183 -0
  87. package/src/database/sqlite.node.ts +178 -0
  88. package/src/database/sqlite.ts +8 -0
  89. package/src/effect/app-node-builder.ts +23 -0
  90. package/src/effect/app-node-platform.ts +18 -0
  91. package/src/effect/app-node.ts +14 -0
  92. package/src/effect/dfdf +1 -0
  93. package/src/effect/keyed-mutex.ts +45 -0
  94. package/src/effect/layer-node.ts +333 -0
  95. package/src/effect/memo-map.ts +3 -0
  96. package/src/effect/runtime.ts +21 -0
  97. package/src/effect/service-use.ts +43 -0
  98. package/src/event/sql.ts +25 -0
  99. package/src/event.ts +638 -0
  100. package/src/file-mutation.ts +207 -0
  101. package/src/file.ts +6 -0
  102. package/src/filesystem/fff.bun.ts +140 -0
  103. package/src/filesystem/fff.node.ts +138 -0
  104. package/src/filesystem/ignore.ts +67 -0
  105. package/src/filesystem/protected.ts +53 -0
  106. package/src/filesystem/search.ts +239 -0
  107. package/src/filesystem/watcher.ts +140 -0
  108. package/src/filesystem.ts +118 -0
  109. package/src/flag/flag.ts +78 -0
  110. package/src/fs-util.ts +274 -0
  111. package/src/git.ts +987 -0
  112. package/src/github-copilot/README.md +5 -0
  113. package/src/github-copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  114. package/src/github-copilot/chat/get-response-metadata.ts +15 -0
  115. package/src/github-copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  116. package/src/github-copilot/chat/openai-compatible-api-types.ts +64 -0
  117. package/src/github-copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  118. package/src/github-copilot/chat/openai-compatible-chat-options.ts +28 -0
  119. package/src/github-copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  120. package/src/github-copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  121. package/src/github-copilot/copilot-provider.ts +100 -0
  122. package/src/github-copilot/openai-compatible-error.ts +27 -0
  123. package/src/github-copilot/responses/convert-to-openai-responses-input.ts +335 -0
  124. package/src/github-copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  125. package/src/github-copilot/responses/openai-config.ts +18 -0
  126. package/src/github-copilot/responses/openai-error.ts +22 -0
  127. package/src/github-copilot/responses/openai-responses-api-types.ts +214 -0
  128. package/src/github-copilot/responses/openai-responses-language-model.ts +1770 -0
  129. package/src/github-copilot/responses/openai-responses-prepare-tools.ts +173 -0
  130. package/src/github-copilot/responses/openai-responses-settings.ts +1 -0
  131. package/src/github-copilot/responses/tool/code-interpreter.ts +87 -0
  132. package/src/github-copilot/responses/tool/file-search.ts +127 -0
  133. package/src/github-copilot/responses/tool/image-generation.ts +114 -0
  134. package/src/github-copilot/responses/tool/local-shell.ts +64 -0
  135. package/src/github-copilot/responses/tool/web-search-preview.ts +103 -0
  136. package/src/github-copilot/responses/tool/web-search.ts +102 -0
  137. package/src/global.ts +87 -0
  138. package/src/id/id.ts +47 -0
  139. package/src/image/photon.ts +94 -0
  140. package/src/image.ts +81 -0
  141. package/src/installation/version.ts +8 -0
  142. package/src/instruction-context.ts +101 -0
  143. package/src/integration/connection.ts +12 -0
  144. package/src/integration.ts +520 -0
  145. package/src/location-mutation.ts +162 -0
  146. package/src/location-service-map.ts +18 -0
  147. package/src/location-services.ts +115 -0
  148. package/src/location.ts +39 -0
  149. package/src/markdown.d.ts +4 -0
  150. package/src/model.ts +41 -0
  151. package/src/models-dev.ts +260 -0
  152. package/src/npm-config.ts +40 -0
  153. package/src/npm.ts +269 -0
  154. package/src/oauth/page.ts +276 -0
  155. package/src/observability/logging.ts +71 -0
  156. package/src/observability/otlp.ts +79 -0
  157. package/src/observability/shared.ts +1 -0
  158. package/src/observability.ts +24 -0
  159. package/src/patch.ts +197 -0
  160. package/src/permission/saved.ts +79 -0
  161. package/src/permission/sql.ts +20 -0
  162. package/src/permission.ts +310 -0
  163. package/src/plugin/agent.ts +206 -0
  164. package/src/plugin/command/initialize.txt +65 -0
  165. package/src/plugin/command/review.txt +100 -0
  166. package/src/plugin/command.ts +25 -0
  167. package/src/plugin/host.ts +219 -0
  168. package/src/plugin/internal.ts +153 -0
  169. package/src/plugin/layer-map.example.ts +94 -0
  170. package/src/plugin/models-dev.ts +183 -0
  171. package/src/plugin/promise.ts +93 -0
  172. package/src/plugin/provider/alibaba.ts +15 -0
  173. package/src/plugin/provider/amazon-bedrock.ts +126 -0
  174. package/src/plugin/provider/anthropic.ts +27 -0
  175. package/src/plugin/provider/azure.ts +82 -0
  176. package/src/plugin/provider/cerebras.ts +26 -0
  177. package/src/plugin/provider/cloudflare-ai-gateway.ts +81 -0
  178. package/src/plugin/provider/cloudflare-workers-ai.ts +81 -0
  179. package/src/plugin/provider/cohere.ts +15 -0
  180. package/src/plugin/provider/deepinfra.ts +15 -0
  181. package/src/plugin/provider/dynamic.ts +31 -0
  182. package/src/plugin/provider/gateway.ts +15 -0
  183. package/src/plugin/provider/github-copilot.ts +52 -0
  184. package/src/plugin/provider/gitlab.ts +65 -0
  185. package/src/plugin/provider/google-vertex.ts +173 -0
  186. package/src/plugin/provider/google.ts +15 -0
  187. package/src/plugin/provider/groq.ts +15 -0
  188. package/src/plugin/provider/kilo.ts +21 -0
  189. package/src/plugin/provider/llmgateway.ts +26 -0
  190. package/src/plugin/provider/mistral.ts +15 -0
  191. package/src/plugin/provider/nvidia.ts +22 -0
  192. package/src/plugin/provider/openai-compatible.ts +17 -0
  193. package/src/plugin/provider/openai.ts +292 -0
  194. package/src/plugin/provider/opencode.ts +311 -0
  195. package/src/plugin/provider/openrouter.ts +36 -0
  196. package/src/plugin/provider/perplexity.ts +15 -0
  197. package/src/plugin/provider/sap-ai-core.ts +46 -0
  198. package/src/plugin/provider/snowflake-cortex.ts +89 -0
  199. package/src/plugin/provider/togetherai.ts +15 -0
  200. package/src/plugin/provider/venice.ts +15 -0
  201. package/src/plugin/provider/vercel.ts +27 -0
  202. package/src/plugin/provider/xai.ts +22 -0
  203. package/src/plugin/provider/zenmux.ts +21 -0
  204. package/src/plugin/provider.ts +71 -0
  205. package/src/plugin/skill/customize-neurocode.md +452 -0
  206. package/src/plugin/skill.ts +31 -0
  207. package/src/plugin/variant.ts +39 -0
  208. package/src/plugin.ts +167 -0
  209. package/src/policy.ts +49 -0
  210. package/src/process.ts +261 -0
  211. package/src/project/copy-strategies.ts +35 -0
  212. package/src/project/copy.ts +292 -0
  213. package/src/project/directories.ts +158 -0
  214. package/src/project/schema.ts +16 -0
  215. package/src/project/sql.ts +35 -0
  216. package/src/project.ts +136 -0
  217. package/src/provider.ts +25 -0
  218. package/src/pty/protocol.ts +37 -0
  219. package/src/pty/pty.bun.ts +26 -0
  220. package/src/pty/pty.node.ts +29 -0
  221. package/src/pty/pty.ts +25 -0
  222. package/src/pty/schema.ts +1 -0
  223. package/src/pty/ticket.ts +56 -0
  224. package/src/pty.ts +318 -0
  225. package/src/public-event-manifest.ts +7 -0
  226. package/src/question.ts +153 -0
  227. package/src/reference/guidance.ts +69 -0
  228. package/src/reference.ts +125 -0
  229. package/src/repository-cache.ts +259 -0
  230. package/src/repository.ts +214 -0
  231. package/src/ripgrep/binary.ts +132 -0
  232. package/src/ripgrep.ts +281 -0
  233. package/src/schema.ts +79 -0
  234. package/src/session/compaction.ts +241 -0
  235. package/src/session/context-epoch.ts +174 -0
  236. package/src/session/error.ts +24 -0
  237. package/src/session/event.ts +2 -0
  238. package/src/session/execution/local.ts +46 -0
  239. package/src/session/execution.ts +34 -0
  240. package/src/session/history.ts +101 -0
  241. package/src/session/info.ts +50 -0
  242. package/src/session/input.ts +288 -0
  243. package/src/session/message-updater.ts +397 -0
  244. package/src/session/message.ts +2 -0
  245. package/src/session/projector.ts +458 -0
  246. package/src/session/prompt.ts +1 -0
  247. package/src/session/revert.ts +121 -0
  248. package/src/session/run-coordinator.ts +104 -0
  249. package/src/session/runner/index.ts +28 -0
  250. package/src/session/runner/llm.ts +432 -0
  251. package/src/session/runner/max-steps.ts +16 -0
  252. package/src/session/runner/model.ts +218 -0
  253. package/src/session/runner/publish-llm-event.ts +423 -0
  254. package/src/session/runner/to-llm-message.ts +171 -0
  255. package/src/session/schema.ts +9 -0
  256. package/src/session/sql.ts +176 -0
  257. package/src/session/store.ts +63 -0
  258. package/src/session/todo.ts +78 -0
  259. package/src/session.ts +486 -0
  260. package/src/share/sql.ts +13 -0
  261. package/src/shell.ts +226 -0
  262. package/src/skill/discovery.ts +213 -0
  263. package/src/skill/guidance.ts +76 -0
  264. package/src/skill.ts +132 -0
  265. package/src/snapshot.ts +266 -0
  266. package/src/state.ts +128 -0
  267. package/src/system-context/builtins.ts +50 -0
  268. package/src/system-context/index.ts +320 -0
  269. package/src/system-context/registry.ts +49 -0
  270. package/src/tool/AGENTS.md +59 -0
  271. package/src/tool/application-tools.ts +57 -0
  272. package/src/tool/apply-patch.ts +219 -0
  273. package/src/tool/bash.ts +207 -0
  274. package/src/tool/builtins.ts +48 -0
  275. package/src/tool/edit.ts +223 -0
  276. package/src/tool/glob.ts +105 -0
  277. package/src/tool/grep.ts +137 -0
  278. package/src/tool/http-body.ts +30 -0
  279. package/src/tool/question.ts +94 -0
  280. package/src/tool/read-filesystem.ts +366 -0
  281. package/src/tool/read.ts +117 -0
  282. package/src/tool/registry.ts +147 -0
  283. package/src/tool/skill.ts +109 -0
  284. package/src/tool/todowrite.ts +62 -0
  285. package/src/tool/tool.ts +162 -0
  286. package/src/tool/tools.ts +13 -0
  287. package/src/tool/webfetch.ts +218 -0
  288. package/src/tool/websearch.ts +260 -0
  289. package/src/tool/write.ts +101 -0
  290. package/src/tool-output-store.ts +211 -0
  291. package/src/util/array.ts +10 -0
  292. package/src/util/binary.ts +41 -0
  293. package/src/util/effect-flock.ts +284 -0
  294. package/src/util/encode.ts +51 -0
  295. package/src/util/error.ts +70 -0
  296. package/src/util/flock.ts +358 -0
  297. package/src/util/glob.ts +34 -0
  298. package/src/util/hash.ts +11 -0
  299. package/src/util/identifier.ts +1 -0
  300. package/src/util/iife.ts +3 -0
  301. package/src/util/lazy.ts +11 -0
  302. package/src/util/module.ts +10 -0
  303. package/src/util/path.ts +37 -0
  304. package/src/util/retry.ts +42 -0
  305. package/src/util/slug.ts +74 -0
  306. package/src/util/token.ts +5 -0
  307. package/src/util/which.ts +14 -0
  308. package/src/util/wildcard.ts +14 -0
  309. package/src/v1/config/agent.ts +89 -0
  310. package/src/v1/config/attachment.ts +25 -0
  311. package/src/v1/config/command.ts +13 -0
  312. package/src/v1/config/config.ts +192 -0
  313. package/src/v1/config/console-state.ts +16 -0
  314. package/src/v1/config/error.ts +39 -0
  315. package/src/v1/config/formatter.ts +13 -0
  316. package/src/v1/config/layout.ts +6 -0
  317. package/src/v1/config/lsp.ts +80 -0
  318. package/src/v1/config/mcp.ts +63 -0
  319. package/src/v1/config/migrate.ts +254 -0
  320. package/src/v1/config/permission.ts +50 -0
  321. package/src/v1/config/plugin.ts +9 -0
  322. package/src/v1/config/provider-options.ts +227 -0
  323. package/src/v1/config/provider.ts +121 -0
  324. package/src/v1/config/server.ts +19 -0
  325. package/src/v1/config/skills.ts +13 -0
  326. package/src/v1/permission.ts +33 -0
  327. package/src/v1/session.ts +68 -0
  328. package/src/v2-schema.ts +3 -0
  329. package/src/workspace.ts +6 -0
  330. package/sst-env.d.ts +10 -0
  331. package/test/agent.test.ts +131 -0
  332. package/test/application-tools.test.ts +287 -0
  333. package/test/background-job.test.ts +106 -0
  334. package/test/catalog.test.ts +353 -0
  335. package/test/command.test.ts +56 -0
  336. package/test/config/agent.test.ts +349 -0
  337. package/test/config/command.test.ts +83 -0
  338. package/test/config/config.test.ts +798 -0
  339. package/test/config/fixtures/plugin/directory-plugin.ts +13 -0
  340. package/test/config/plugin.test.ts +248 -0
  341. package/test/config/provider-options.test.ts +224 -0
  342. package/test/config/provider.test.ts +269 -0
  343. package/test/config/skill.test.ts +80 -0
  344. package/test/credential.test.ts +36 -0
  345. package/test/database-migration.test.ts +644 -0
  346. package/test/effect/cross-spawn-spawner.test.ts +426 -0
  347. package/test/effect/keyed-mutex.test.ts +73 -0
  348. package/test/effect/layer-node/layer-node-types.test.ts +143 -0
  349. package/test/effect/layer-node/layer-node.test.ts +261 -0
  350. package/test/effect/layer-node/node-build.test.ts +125 -0
  351. package/test/effect/observability.test.ts +109 -0
  352. package/test/event.test.ts +1124 -0
  353. package/test/file-mutation.test.ts +368 -0
  354. package/test/filesystem/filesystem.test.ts +387 -0
  355. package/test/filesystem/ignore.test.ts +10 -0
  356. package/test/filesystem/search.test.ts +44 -0
  357. package/test/filesystem/watcher.test.ts +266 -0
  358. package/test/fixture/effect-flock-worker.ts +60 -0
  359. package/test/fixture/flock-worker.ts +72 -0
  360. package/test/fixture/git.ts +49 -0
  361. package/test/fixture/location.ts +26 -0
  362. package/test/fixture/tmpdir.ts +25 -0
  363. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -0
  364. package/test/git.test.ts +164 -0
  365. package/test/github-copilot/convert-to-copilot-messages.test.ts +523 -0
  366. package/test/github-copilot/copilot-chat-model.test.ts +592 -0
  367. package/test/github-copilot/openai-responses-language-model.test.ts +206 -0
  368. package/test/global.test.ts +16 -0
  369. package/test/instruction-context.test.ts +323 -0
  370. package/test/integration.test.ts +349 -0
  371. package/test/legacy-event-schema.test.ts +16 -0
  372. package/test/lib/effect.ts +53 -0
  373. package/test/lib/tool.ts +20 -0
  374. package/test/location-filesystem.test.ts +69 -0
  375. package/test/location-layer.test.ts +226 -0
  376. package/test/location-mutation.test.ts +178 -0
  377. package/test/location.test.ts +42 -0
  378. package/test/model.test.ts +23 -0
  379. package/test/models.test.ts +290 -0
  380. package/test/move-session.test.ts +235 -0
  381. package/test/npm-config.test.ts +51 -0
  382. package/test/npm.test.ts +84 -0
  383. package/test/oauth-page.test.ts +15 -0
  384. package/test/patch.test.ts +68 -0
  385. package/test/permission.test.ts +315 -0
  386. package/test/plugin/command.test.ts +47 -0
  387. package/test/plugin/fixture.ts +52 -0
  388. package/test/plugin/fixtures/config-effect-plugin.ts +15 -0
  389. package/test/plugin/fixtures/config-promise-plugin.ts +13 -0
  390. package/test/plugin/fixtures/invalid-plugin.ts +1 -0
  391. package/test/plugin/fixtures/models-dev.json +14 -0
  392. package/test/plugin/fixtures/provider-factory.ts +9 -0
  393. package/test/plugin/host.ts +303 -0
  394. package/test/plugin/models-dev.test.ts +170 -0
  395. package/test/plugin/promise.test.ts +67 -0
  396. package/test/plugin/provider-alibaba.test.ts +92 -0
  397. package/test/plugin/provider-amazon-bedrock.test.ts +622 -0
  398. package/test/plugin/provider-anthropic.test.ts +94 -0
  399. package/test/plugin/provider-azure-cognitive-services.test.ts +199 -0
  400. package/test/plugin/provider-azure.test.ts +293 -0
  401. package/test/plugin/provider-cerebras.test.ts +136 -0
  402. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +426 -0
  403. package/test/plugin/provider-cloudflare-workers-ai.test.ts +279 -0
  404. package/test/plugin/provider-cohere.test.ts +123 -0
  405. package/test/plugin/provider-deepinfra.test.ts +159 -0
  406. package/test/plugin/provider-dynamic.test.ts +184 -0
  407. package/test/plugin/provider-gateway.test.ts +115 -0
  408. package/test/plugin/provider-github-copilot.test.ts +278 -0
  409. package/test/plugin/provider-gitlab.test.ts +308 -0
  410. package/test/plugin/provider-google-vertex-anthropic.test.ts +264 -0
  411. package/test/plugin/provider-google-vertex.test.ts +387 -0
  412. package/test/plugin/provider-google.test.ts +80 -0
  413. package/test/plugin/provider-groq.test.ts +121 -0
  414. package/test/plugin/provider-kilo.test.ts +99 -0
  415. package/test/plugin/provider-llmgateway.test.ts +80 -0
  416. package/test/plugin/provider-mistral.test.ts +129 -0
  417. package/test/plugin/provider-nvidia.test.ts +97 -0
  418. package/test/plugin/provider-openai-compatible.test.ts +107 -0
  419. package/test/plugin/provider-openai.test.ts +176 -0
  420. package/test/plugin/provider-opencode.test.ts +423 -0
  421. package/test/plugin/provider-openrouter.test.ts +113 -0
  422. package/test/plugin/provider-perplexity.test.ts +122 -0
  423. package/test/plugin/provider-sap-ai-core.test.ts +159 -0
  424. package/test/plugin/provider-snowflake-cortex.test.ts +261 -0
  425. package/test/plugin/provider-togetherai.test.ts +129 -0
  426. package/test/plugin/provider-venice.test.ts +115 -0
  427. package/test/plugin/provider-vercel.test.ts +83 -0
  428. package/test/plugin/provider-xai.test.ts +125 -0
  429. package/test/plugin/provider-zenmux.test.ts +110 -0
  430. package/test/plugin/skill.test.ts +25 -0
  431. package/test/plugin/variant.test.ts +67 -0
  432. package/test/plugin.test.ts +71 -0
  433. package/test/policy.test.ts +85 -0
  434. package/test/preload.ts +5 -0
  435. package/test/process/process.test.ts +368 -0
  436. package/test/project-copy.test.ts +400 -0
  437. package/test/project-directories.test.ts +61 -0
  438. package/test/project.test.ts +221 -0
  439. package/test/provider-mistral.test.ts +282 -0
  440. package/test/provider-xai-responses.test.ts +32 -0
  441. package/test/pty/info-schema.test.ts +32 -0
  442. package/test/pty/protocol.test.ts +27 -0
  443. package/test/pty/pty-session.test.ts +240 -0
  444. package/test/pty/ticket.test.ts +62 -0
  445. package/test/question.test.ts +114 -0
  446. package/test/reference-guidance.test.ts +76 -0
  447. package/test/reference.test.ts +78 -0
  448. package/test/repository-cache.test.ts +153 -0
  449. package/test/repository.test.ts +71 -0
  450. package/test/ripgrep.test.ts +65 -0
  451. package/test/session-compaction.test.ts +27 -0
  452. package/test/session-create.test.ts +425 -0
  453. package/test/session-history.test.ts +165 -0
  454. package/test/session-projector.test.ts +533 -0
  455. package/test/session-prompt.test.ts +584 -0
  456. package/test/session-run-coordinator.test.ts +418 -0
  457. package/test/session-runner-message.test.ts +501 -0
  458. package/test/session-runner-model.test.ts +347 -0
  459. package/test/session-runner-recorded.test.ts +193 -0
  460. package/test/session-runner-tool-events.test.ts +136 -0
  461. package/test/session-runner-tool-registry.test.ts +452 -0
  462. package/test/session-runner.test.ts +3365 -0
  463. package/test/session-todo.test.ts +94 -0
  464. package/test/session-tool-progress.test.ts +158 -0
  465. package/test/shared-schema.test.ts +206 -0
  466. package/test/shell.test.ts +108 -0
  467. package/test/skill/guidance.test.ts +144 -0
  468. package/test/skill-discovery.test.ts +165 -0
  469. package/test/skill.test.ts +125 -0
  470. package/test/snapshot.test.ts +178 -0
  471. package/test/state.test.ts +115 -0
  472. package/test/system-context/builtins.test.ts +129 -0
  473. package/test/system-context/index.test.ts +307 -0
  474. package/test/system-context/registry.test.ts +114 -0
  475. package/test/tool-apply-patch.test.ts +436 -0
  476. package/test/tool-bash.test.ts +437 -0
  477. package/test/tool-edit.test.ts +434 -0
  478. package/test/tool-output-store.test.ts +247 -0
  479. package/test/tool-question.test.ts +162 -0
  480. package/test/tool-read-filesystem.test.ts +118 -0
  481. package/test/tool-read.test.ts +674 -0
  482. package/test/tool-skill.test.ts +149 -0
  483. package/test/tool-todowrite.test.ts +125 -0
  484. package/test/tool-webfetch.test.ts +281 -0
  485. package/test/tool-websearch.test.ts +316 -0
  486. package/test/tool-write.test.ts +305 -0
  487. package/test/util/effect-flock.test.ts +392 -0
  488. package/test/util/flock.test.ts +428 -0
  489. package/test/util/which.test.ts +100 -0
  490. package/tsconfig.json +7 -0
@@ -0,0 +1,815 @@
1
+ import {
2
+ APICallError,
3
+ InvalidResponseDataError,
4
+ type LanguageModelV3,
5
+ type LanguageModelV3CallOptions,
6
+ type LanguageModelV3Content,
7
+ type LanguageModelV3StreamPart,
8
+ type SharedV3ProviderMetadata,
9
+ type SharedV3Warning,
10
+ } from "@ai-sdk/provider"
11
+ import {
12
+ combineHeaders,
13
+ createEventSourceResponseHandler,
14
+ createJsonErrorResponseHandler,
15
+ createJsonResponseHandler,
16
+ type FetchFunction,
17
+ generateId,
18
+ isParsableJson,
19
+ parseProviderOptions,
20
+ type ParseResult,
21
+ postJsonToApi,
22
+ type ResponseHandler,
23
+ } from "@ai-sdk/provider-utils"
24
+ import { z } from "zod/v4"
25
+ import { convertToOpenAICompatibleChatMessages } from "./convert-to-openai-compatible-chat-messages"
26
+ import { getResponseMetadata } from "./get-response-metadata"
27
+ import { mapOpenAICompatibleFinishReason } from "./map-openai-compatible-finish-reason"
28
+ import { type OpenAICompatibleChatModelId, openaiCompatibleProviderOptions } from "./openai-compatible-chat-options"
29
+ import { defaultOpenAICompatibleErrorStructure, type ProviderErrorStructure } from "../openai-compatible-error"
30
+ import type { MetadataExtractor } from "./openai-compatible-metadata-extractor"
31
+ import { prepareTools } from "./openai-compatible-prepare-tools"
32
+
33
+ export type OpenAICompatibleChatConfig = {
34
+ provider: string
35
+ headers: () => Record<string, string | undefined>
36
+ url: (options: { modelId: string; path: string }) => string
37
+ fetch?: FetchFunction
38
+ includeUsage?: boolean
39
+ errorStructure?: ProviderErrorStructure<any>
40
+ metadataExtractor?: MetadataExtractor
41
+
42
+ /**
43
+ * Whether the model supports structured outputs.
44
+ */
45
+ supportsStructuredOutputs?: boolean
46
+
47
+ /**
48
+ * The supported URLs for the model.
49
+ */
50
+ supportedUrls?: () => LanguageModelV3["supportedUrls"]
51
+ }
52
+
53
+ export class OpenAICompatibleChatLanguageModel implements LanguageModelV3 {
54
+ readonly specificationVersion = "v3"
55
+
56
+ readonly supportsStructuredOutputs: boolean
57
+
58
+ readonly modelId: OpenAICompatibleChatModelId
59
+ private readonly config: OpenAICompatibleChatConfig
60
+ private readonly failedResponseHandler: ResponseHandler<APICallError>
61
+ private readonly chunkSchema // type inferred via constructor
62
+
63
+ constructor(modelId: OpenAICompatibleChatModelId, config: OpenAICompatibleChatConfig) {
64
+ this.modelId = modelId
65
+ this.config = config
66
+
67
+ // initialize error handling:
68
+ const errorStructure = config.errorStructure ?? defaultOpenAICompatibleErrorStructure
69
+ this.chunkSchema = createOpenAICompatibleChatChunkSchema(errorStructure.errorSchema)
70
+ this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure)
71
+
72
+ this.supportsStructuredOutputs = config.supportsStructuredOutputs ?? false
73
+ }
74
+
75
+ get provider(): string {
76
+ return this.config.provider
77
+ }
78
+
79
+ private get providerOptionsName(): string {
80
+ return this.config.provider.split(".")[0].trim()
81
+ }
82
+
83
+ get supportedUrls() {
84
+ return this.config.supportedUrls?.() ?? {}
85
+ }
86
+
87
+ private async getArgs({
88
+ prompt,
89
+ maxOutputTokens,
90
+ temperature,
91
+ topP,
92
+ topK,
93
+ frequencyPenalty,
94
+ presencePenalty,
95
+ providerOptions,
96
+ stopSequences,
97
+ responseFormat,
98
+ seed,
99
+ toolChoice,
100
+ tools,
101
+ }: LanguageModelV3CallOptions) {
102
+ const warnings: SharedV3Warning[] = []
103
+
104
+ // Parse provider options
105
+ const compatibleOptions = Object.assign(
106
+ (await parseProviderOptions({
107
+ provider: "copilot",
108
+ providerOptions,
109
+ schema: openaiCompatibleProviderOptions,
110
+ })) ?? {},
111
+ (await parseProviderOptions({
112
+ provider: this.providerOptionsName,
113
+ providerOptions,
114
+ schema: openaiCompatibleProviderOptions,
115
+ })) ?? {},
116
+ )
117
+
118
+ if (topK != null) {
119
+ warnings.push({ type: "unsupported", feature: "topK" })
120
+ }
121
+
122
+ if (responseFormat?.type === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) {
123
+ warnings.push({
124
+ type: "unsupported",
125
+ feature: "responseFormat",
126
+ details: "JSON response format schema is only supported with structuredOutputs",
127
+ })
128
+ }
129
+
130
+ const {
131
+ tools: openaiTools,
132
+ toolChoice: openaiToolChoice,
133
+ toolWarnings,
134
+ } = prepareTools({
135
+ tools,
136
+ toolChoice,
137
+ })
138
+
139
+ return {
140
+ args: {
141
+ // model id:
142
+ model: this.modelId,
143
+
144
+ // model specific settings:
145
+ user: compatibleOptions.user,
146
+
147
+ // standardized settings:
148
+ max_tokens: maxOutputTokens,
149
+ temperature,
150
+ top_p: topP,
151
+ frequency_penalty: frequencyPenalty,
152
+ presence_penalty: presencePenalty,
153
+ response_format:
154
+ responseFormat?.type === "json"
155
+ ? this.supportsStructuredOutputs === true && responseFormat.schema != null
156
+ ? {
157
+ type: "json_schema",
158
+ json_schema: {
159
+ schema: responseFormat.schema,
160
+ name: responseFormat.name ?? "response",
161
+ description: responseFormat.description,
162
+ },
163
+ }
164
+ : { type: "json_object" }
165
+ : undefined,
166
+
167
+ stop: stopSequences,
168
+ seed,
169
+ ...Object.fromEntries(
170
+ Object.entries(providerOptions?.[this.providerOptionsName] ?? {}).filter(
171
+ ([key]) => !Object.keys(openaiCompatibleProviderOptions.shape).includes(key),
172
+ ),
173
+ ),
174
+
175
+ reasoning_effort: compatibleOptions.reasoningEffort,
176
+ verbosity: compatibleOptions.textVerbosity,
177
+
178
+ // messages:
179
+ messages: convertToOpenAICompatibleChatMessages(prompt),
180
+
181
+ // tools:
182
+ tools: openaiTools,
183
+ tool_choice: openaiToolChoice,
184
+
185
+ // thinking_budget
186
+ thinking_budget: compatibleOptions.thinking_budget,
187
+ },
188
+ warnings: [...warnings, ...toolWarnings],
189
+ }
190
+ }
191
+
192
+ async doGenerate(options: LanguageModelV3CallOptions) {
193
+ const { args, warnings } = await this.getArgs({ ...options })
194
+
195
+ const body = JSON.stringify(args)
196
+
197
+ const {
198
+ responseHeaders,
199
+ value: responseBody,
200
+ rawValue: rawResponse,
201
+ } = await postJsonToApi({
202
+ url: this.config.url({
203
+ path: "/chat/completions",
204
+ modelId: this.modelId,
205
+ }),
206
+ headers: combineHeaders(this.config.headers(), options.headers),
207
+ body: args,
208
+ failedResponseHandler: this.failedResponseHandler,
209
+ successfulResponseHandler: createJsonResponseHandler(OpenAICompatibleChatResponseSchema),
210
+ abortSignal: options.abortSignal,
211
+ fetch: this.config.fetch,
212
+ })
213
+
214
+ const choice = responseBody.choices[0]
215
+ const content: Array<LanguageModelV3Content> = []
216
+
217
+ // text content:
218
+ const text = choice.message.content
219
+ if (text != null && text.length > 0) {
220
+ content.push({
221
+ type: "text",
222
+ text,
223
+ providerMetadata: choice.message.reasoning_opaque
224
+ ? { copilot: { reasoningOpaque: choice.message.reasoning_opaque } }
225
+ : undefined,
226
+ })
227
+ }
228
+
229
+ // reasoning content (Copilot uses reasoning_text):
230
+ const reasoning = choice.message.reasoning_text
231
+ if (reasoning != null && reasoning.length > 0) {
232
+ content.push({
233
+ type: "reasoning",
234
+ text: reasoning,
235
+ // Include reasoning_opaque for Copilot multi-turn reasoning
236
+ providerMetadata: choice.message.reasoning_opaque
237
+ ? { copilot: { reasoningOpaque: choice.message.reasoning_opaque } }
238
+ : undefined,
239
+ })
240
+ }
241
+
242
+ // tool calls:
243
+ if (choice.message.tool_calls != null) {
244
+ for (const toolCall of choice.message.tool_calls) {
245
+ content.push({
246
+ type: "tool-call",
247
+ toolCallId: toolCall.id ?? generateId(),
248
+ toolName: toolCall.function.name,
249
+ input: toolCall.function.arguments!,
250
+ providerMetadata: choice.message.reasoning_opaque
251
+ ? { copilot: { reasoningOpaque: choice.message.reasoning_opaque } }
252
+ : undefined,
253
+ })
254
+ }
255
+ }
256
+
257
+ // provider metadata:
258
+ const providerMetadata: SharedV3ProviderMetadata = {
259
+ [this.providerOptionsName]: {},
260
+ ...(await this.config.metadataExtractor?.extractMetadata?.({
261
+ parsedBody: rawResponse,
262
+ })),
263
+ }
264
+ const completionTokenDetails = responseBody.usage?.completion_tokens_details
265
+ if (completionTokenDetails?.accepted_prediction_tokens != null) {
266
+ providerMetadata[this.providerOptionsName].acceptedPredictionTokens =
267
+ completionTokenDetails?.accepted_prediction_tokens
268
+ }
269
+ if (completionTokenDetails?.rejected_prediction_tokens != null) {
270
+ providerMetadata[this.providerOptionsName].rejectedPredictionTokens =
271
+ completionTokenDetails?.rejected_prediction_tokens
272
+ }
273
+
274
+ return {
275
+ content,
276
+ finishReason: {
277
+ unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
278
+ raw: choice.finish_reason ?? undefined,
279
+ },
280
+ usage: {
281
+ inputTokens: {
282
+ total: responseBody.usage?.prompt_tokens ?? undefined,
283
+ noCache: undefined,
284
+ cacheRead: responseBody.usage?.prompt_tokens_details?.cached_tokens ?? undefined,
285
+ cacheWrite: undefined,
286
+ },
287
+ outputTokens: {
288
+ total: responseBody.usage?.completion_tokens ?? undefined,
289
+ text: undefined,
290
+ reasoning: responseBody.usage?.completion_tokens_details?.reasoning_tokens ?? undefined,
291
+ },
292
+ raw: responseBody.usage ?? undefined,
293
+ },
294
+ providerMetadata,
295
+ request: { body },
296
+ response: {
297
+ ...getResponseMetadata(responseBody),
298
+ headers: responseHeaders,
299
+ body: rawResponse,
300
+ },
301
+ warnings,
302
+ }
303
+ }
304
+
305
+ async doStream(options: LanguageModelV3CallOptions) {
306
+ const { args, warnings } = await this.getArgs({ ...options })
307
+
308
+ const body = {
309
+ ...args,
310
+ stream: true,
311
+
312
+ // only include stream_options when in strict compatibility mode:
313
+ stream_options: this.config.includeUsage ? { include_usage: true } : undefined,
314
+ }
315
+
316
+ const metadataExtractor = this.config.metadataExtractor?.createStreamExtractor()
317
+
318
+ const { responseHeaders, value: response } = await postJsonToApi({
319
+ url: this.config.url({
320
+ path: "/chat/completions",
321
+ modelId: this.modelId,
322
+ }),
323
+ headers: combineHeaders(this.config.headers(), options.headers),
324
+ body,
325
+ failedResponseHandler: this.failedResponseHandler,
326
+ successfulResponseHandler: createEventSourceResponseHandler(this.chunkSchema),
327
+ abortSignal: options.abortSignal,
328
+ fetch: this.config.fetch,
329
+ })
330
+
331
+ const toolCalls: Array<{
332
+ id: string
333
+ type: "function"
334
+ function: {
335
+ name: string
336
+ arguments: string
337
+ }
338
+ hasFinished: boolean
339
+ }> = []
340
+
341
+ let finishReason: {
342
+ unified: ReturnType<typeof mapOpenAICompatibleFinishReason>
343
+ raw: string | undefined
344
+ } = {
345
+ unified: "other",
346
+ raw: undefined,
347
+ }
348
+ const usage: {
349
+ completionTokens: number | undefined
350
+ completionTokensDetails: {
351
+ reasoningTokens: number | undefined
352
+ acceptedPredictionTokens: number | undefined
353
+ rejectedPredictionTokens: number | undefined
354
+ }
355
+ promptTokens: number | undefined
356
+ promptTokensDetails: {
357
+ cachedTokens: number | undefined
358
+ }
359
+ totalTokens: number | undefined
360
+ } = {
361
+ completionTokens: undefined,
362
+ completionTokensDetails: {
363
+ reasoningTokens: undefined,
364
+ acceptedPredictionTokens: undefined,
365
+ rejectedPredictionTokens: undefined,
366
+ },
367
+ promptTokens: undefined,
368
+ promptTokensDetails: {
369
+ cachedTokens: undefined,
370
+ },
371
+ totalTokens: undefined,
372
+ }
373
+ let isFirstChunk = true
374
+ const providerOptionsName = this.providerOptionsName
375
+ let isActiveReasoning = false
376
+ let isActiveText = false
377
+ let reasoningOpaque: string | undefined
378
+
379
+ return {
380
+ stream: response.pipeThrough(
381
+ new TransformStream<ParseResult<z.infer<typeof this.chunkSchema>>, LanguageModelV3StreamPart>({
382
+ start(controller) {
383
+ controller.enqueue({ type: "stream-start", warnings })
384
+ },
385
+
386
+ // TODO we lost type safety on Chunk, most likely due to the error schema. MUST FIX
387
+ transform(chunk, controller) {
388
+ // Emit raw chunk if requested (before anything else)
389
+ if (options.includeRawChunks) {
390
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue })
391
+ }
392
+
393
+ // handle failed chunk parsing / validation:
394
+ if (!chunk.success) {
395
+ finishReason = {
396
+ unified: "error",
397
+ raw: undefined,
398
+ }
399
+ controller.enqueue({ type: "error", error: chunk.error })
400
+ return
401
+ }
402
+ const value = chunk.value
403
+
404
+ metadataExtractor?.processChunk(chunk.rawValue)
405
+
406
+ // handle error chunks:
407
+ if ("error" in value) {
408
+ finishReason = {
409
+ unified: "error",
410
+ raw: undefined,
411
+ }
412
+ controller.enqueue({ type: "error", error: value.error.message })
413
+ return
414
+ }
415
+
416
+ if (isFirstChunk) {
417
+ isFirstChunk = false
418
+
419
+ controller.enqueue({
420
+ type: "response-metadata",
421
+ ...getResponseMetadata(value),
422
+ })
423
+ }
424
+
425
+ if (value.usage != null) {
426
+ const {
427
+ prompt_tokens,
428
+ completion_tokens,
429
+ total_tokens,
430
+ prompt_tokens_details,
431
+ completion_tokens_details,
432
+ } = value.usage
433
+
434
+ usage.promptTokens = prompt_tokens ?? undefined
435
+ usage.completionTokens = completion_tokens ?? undefined
436
+ usage.totalTokens = total_tokens ?? undefined
437
+ if (completion_tokens_details?.reasoning_tokens != null) {
438
+ usage.completionTokensDetails.reasoningTokens = completion_tokens_details?.reasoning_tokens
439
+ }
440
+ if (completion_tokens_details?.accepted_prediction_tokens != null) {
441
+ usage.completionTokensDetails.acceptedPredictionTokens =
442
+ completion_tokens_details?.accepted_prediction_tokens
443
+ }
444
+ if (completion_tokens_details?.rejected_prediction_tokens != null) {
445
+ usage.completionTokensDetails.rejectedPredictionTokens =
446
+ completion_tokens_details?.rejected_prediction_tokens
447
+ }
448
+ if (prompt_tokens_details?.cached_tokens != null) {
449
+ usage.promptTokensDetails.cachedTokens = prompt_tokens_details?.cached_tokens
450
+ }
451
+ }
452
+
453
+ const choice = value.choices[0]
454
+
455
+ if (choice?.finish_reason != null) {
456
+ finishReason = {
457
+ unified: mapOpenAICompatibleFinishReason(choice.finish_reason),
458
+ raw: choice.finish_reason ?? undefined,
459
+ }
460
+ }
461
+
462
+ if (choice?.delta == null) {
463
+ return
464
+ }
465
+
466
+ const delta = choice.delta
467
+
468
+ // Capture reasoning_opaque for Copilot multi-turn reasoning
469
+ if (delta.reasoning_opaque) {
470
+ if (reasoningOpaque != null) {
471
+ throw new InvalidResponseDataError({
472
+ data: delta,
473
+ message:
474
+ "Multiple reasoning_opaque values received in a single response. Only one thinking part per response is supported.",
475
+ })
476
+ }
477
+ reasoningOpaque = delta.reasoning_opaque
478
+ }
479
+
480
+ // enqueue reasoning before text deltas (Copilot uses reasoning_text):
481
+ const reasoningContent = delta.reasoning_text
482
+ if (reasoningContent) {
483
+ if (!isActiveReasoning) {
484
+ controller.enqueue({
485
+ type: "reasoning-start",
486
+ id: "reasoning-0",
487
+ })
488
+ isActiveReasoning = true
489
+ }
490
+
491
+ controller.enqueue({
492
+ type: "reasoning-delta",
493
+ id: "reasoning-0",
494
+ delta: reasoningContent,
495
+ })
496
+ }
497
+
498
+ if (delta.content) {
499
+ // If reasoning was active and we're starting text, end reasoning first
500
+ // This handles the case where reasoning_opaque and content come in the same chunk
501
+ if (isActiveReasoning && !isActiveText) {
502
+ controller.enqueue({
503
+ type: "reasoning-end",
504
+ id: "reasoning-0",
505
+ providerMetadata: reasoningOpaque ? { copilot: { reasoningOpaque } } : undefined,
506
+ })
507
+ isActiveReasoning = false
508
+ }
509
+
510
+ if (!isActiveText) {
511
+ controller.enqueue({
512
+ type: "text-start",
513
+ id: "txt-0",
514
+ providerMetadata: reasoningOpaque ? { copilot: { reasoningOpaque } } : undefined,
515
+ })
516
+ isActiveText = true
517
+ }
518
+
519
+ controller.enqueue({
520
+ type: "text-delta",
521
+ id: "txt-0",
522
+ delta: delta.content,
523
+ })
524
+ }
525
+
526
+ if (delta.tool_calls != null) {
527
+ // If reasoning was active and we're starting tool calls, end reasoning first
528
+ // This handles the case where reasoning goes directly to tool calls with no content
529
+ if (isActiveReasoning) {
530
+ controller.enqueue({
531
+ type: "reasoning-end",
532
+ id: "reasoning-0",
533
+ providerMetadata: reasoningOpaque ? { copilot: { reasoningOpaque } } : undefined,
534
+ })
535
+ isActiveReasoning = false
536
+ }
537
+ for (const toolCallDelta of delta.tool_calls) {
538
+ const index = toolCallDelta.index
539
+
540
+ if (toolCalls[index] == null) {
541
+ if (toolCallDelta.id == null) {
542
+ throw new InvalidResponseDataError({
543
+ data: toolCallDelta,
544
+ message: `Expected 'id' to be a string.`,
545
+ })
546
+ }
547
+
548
+ if (toolCallDelta.function?.name == null) {
549
+ throw new InvalidResponseDataError({
550
+ data: toolCallDelta,
551
+ message: `Expected 'function.name' to be a string.`,
552
+ })
553
+ }
554
+
555
+ controller.enqueue({
556
+ type: "tool-input-start",
557
+ id: toolCallDelta.id,
558
+ toolName: toolCallDelta.function.name,
559
+ })
560
+
561
+ toolCalls[index] = {
562
+ id: toolCallDelta.id,
563
+ type: "function",
564
+ function: {
565
+ name: toolCallDelta.function.name,
566
+ arguments: toolCallDelta.function.arguments ?? "",
567
+ },
568
+ hasFinished: false,
569
+ }
570
+
571
+ const toolCall = toolCalls[index]
572
+
573
+ if (toolCall.function?.name != null && toolCall.function?.arguments != null) {
574
+ // send delta if the argument text has already started:
575
+ if (toolCall.function.arguments.length > 0) {
576
+ controller.enqueue({
577
+ type: "tool-input-delta",
578
+ id: toolCall.id,
579
+ delta: toolCall.function.arguments,
580
+ })
581
+ }
582
+
583
+ // check if tool call is complete
584
+ // (some providers send the full tool call in one chunk):
585
+ if (isParsableJson(toolCall.function.arguments)) {
586
+ controller.enqueue({
587
+ type: "tool-input-end",
588
+ id: toolCall.id,
589
+ })
590
+
591
+ controller.enqueue({
592
+ type: "tool-call",
593
+ toolCallId: toolCall.id ?? generateId(),
594
+ toolName: toolCall.function.name,
595
+ input: toolCall.function.arguments,
596
+ providerMetadata: reasoningOpaque ? { copilot: { reasoningOpaque } } : undefined,
597
+ })
598
+ toolCall.hasFinished = true
599
+ }
600
+ }
601
+
602
+ continue
603
+ }
604
+
605
+ // existing tool call, merge if not finished
606
+ const toolCall = toolCalls[index]
607
+
608
+ if (toolCall.hasFinished) {
609
+ continue
610
+ }
611
+
612
+ if (toolCallDelta.function?.arguments != null) {
613
+ toolCall.function!.arguments += toolCallDelta.function?.arguments ?? ""
614
+ }
615
+
616
+ // send delta
617
+ controller.enqueue({
618
+ type: "tool-input-delta",
619
+ id: toolCall.id,
620
+ delta: toolCallDelta.function.arguments ?? "",
621
+ })
622
+
623
+ // check if tool call is complete
624
+ if (
625
+ toolCall.function?.name != null &&
626
+ toolCall.function?.arguments != null &&
627
+ isParsableJson(toolCall.function.arguments)
628
+ ) {
629
+ controller.enqueue({
630
+ type: "tool-input-end",
631
+ id: toolCall.id,
632
+ })
633
+
634
+ controller.enqueue({
635
+ type: "tool-call",
636
+ toolCallId: toolCall.id ?? generateId(),
637
+ toolName: toolCall.function.name,
638
+ input: toolCall.function.arguments,
639
+ providerMetadata: reasoningOpaque ? { copilot: { reasoningOpaque } } : undefined,
640
+ })
641
+ toolCall.hasFinished = true
642
+ }
643
+ }
644
+ }
645
+ },
646
+
647
+ flush(controller) {
648
+ if (isActiveReasoning) {
649
+ controller.enqueue({
650
+ type: "reasoning-end",
651
+ id: "reasoning-0",
652
+ // Include reasoning_opaque for Copilot multi-turn reasoning
653
+ providerMetadata: reasoningOpaque ? { copilot: { reasoningOpaque } } : undefined,
654
+ })
655
+ }
656
+
657
+ if (isActiveText) {
658
+ controller.enqueue({ type: "text-end", id: "txt-0" })
659
+ }
660
+
661
+ // go through all tool calls and send the ones that are not finished
662
+ for (const toolCall of toolCalls.filter((toolCall) => !toolCall.hasFinished)) {
663
+ controller.enqueue({
664
+ type: "tool-input-end",
665
+ id: toolCall.id,
666
+ })
667
+
668
+ controller.enqueue({
669
+ type: "tool-call",
670
+ toolCallId: toolCall.id ?? generateId(),
671
+ toolName: toolCall.function.name,
672
+ input: toolCall.function.arguments,
673
+ })
674
+ }
675
+
676
+ const providerMetadata: SharedV3ProviderMetadata = {
677
+ [providerOptionsName]: {},
678
+ // Include reasoning_opaque for Copilot multi-turn reasoning
679
+ ...(reasoningOpaque ? { copilot: { reasoningOpaque } } : {}),
680
+ ...metadataExtractor?.buildMetadata(),
681
+ }
682
+ if (usage.completionTokensDetails.acceptedPredictionTokens != null) {
683
+ providerMetadata[providerOptionsName].acceptedPredictionTokens =
684
+ usage.completionTokensDetails.acceptedPredictionTokens
685
+ }
686
+ if (usage.completionTokensDetails.rejectedPredictionTokens != null) {
687
+ providerMetadata[providerOptionsName].rejectedPredictionTokens =
688
+ usage.completionTokensDetails.rejectedPredictionTokens
689
+ }
690
+
691
+ controller.enqueue({
692
+ type: "finish",
693
+ finishReason,
694
+ usage: {
695
+ inputTokens: {
696
+ total: usage.promptTokens,
697
+ noCache:
698
+ usage.promptTokens != undefined && usage.promptTokensDetails.cachedTokens != undefined
699
+ ? usage.promptTokens - usage.promptTokensDetails.cachedTokens
700
+ : undefined,
701
+ cacheRead: usage.promptTokensDetails.cachedTokens,
702
+ cacheWrite: undefined,
703
+ },
704
+ outputTokens: {
705
+ total: usage.completionTokens,
706
+ text: undefined,
707
+ reasoning: usage.completionTokensDetails.reasoningTokens,
708
+ },
709
+ raw: {
710
+ prompt_tokens: usage.promptTokens ?? null,
711
+ completion_tokens: usage.completionTokens ?? null,
712
+ total_tokens: usage.totalTokens ?? null,
713
+ },
714
+ },
715
+ providerMetadata,
716
+ })
717
+ },
718
+ }),
719
+ ),
720
+ request: { body },
721
+ response: { headers: responseHeaders },
722
+ }
723
+ }
724
+ }
725
+
726
+ const openaiCompatibleTokenUsageSchema = z
727
+ .object({
728
+ prompt_tokens: z.number().nullish(),
729
+ completion_tokens: z.number().nullish(),
730
+ total_tokens: z.number().nullish(),
731
+ prompt_tokens_details: z
732
+ .object({
733
+ cached_tokens: z.number().nullish(),
734
+ })
735
+ .nullish(),
736
+ completion_tokens_details: z
737
+ .object({
738
+ reasoning_tokens: z.number().nullish(),
739
+ accepted_prediction_tokens: z.number().nullish(),
740
+ rejected_prediction_tokens: z.number().nullish(),
741
+ })
742
+ .nullish(),
743
+ })
744
+ .nullish()
745
+
746
+ // limited version of the schema, focussed on what is needed for the implementation
747
+ // this approach limits breakages when the API changes and increases efficiency
748
+ const OpenAICompatibleChatResponseSchema = z.object({
749
+ id: z.string().nullish(),
750
+ created: z.number().nullish(),
751
+ model: z.string().nullish(),
752
+ choices: z.array(
753
+ z.object({
754
+ message: z.object({
755
+ role: z.literal("assistant").nullish(),
756
+ content: z.string().nullish(),
757
+ // Copilot-specific reasoning fields
758
+ reasoning_text: z.string().nullish(),
759
+ reasoning_opaque: z.string().nullish(),
760
+ tool_calls: z
761
+ .array(
762
+ z.object({
763
+ id: z.string().nullish(),
764
+ function: z.object({
765
+ name: z.string(),
766
+ arguments: z.string(),
767
+ }),
768
+ }),
769
+ )
770
+ .nullish(),
771
+ }),
772
+ finish_reason: z.string().nullish(),
773
+ }),
774
+ ),
775
+ usage: openaiCompatibleTokenUsageSchema,
776
+ })
777
+
778
+ // limited version of the schema, focussed on what is needed for the implementation
779
+ // this approach limits breakages when the API changes and increases efficiency
780
+ const createOpenAICompatibleChatChunkSchema = <ERROR_SCHEMA extends z.core.$ZodType>(errorSchema: ERROR_SCHEMA) =>
781
+ z.union([
782
+ z.object({
783
+ id: z.string().nullish(),
784
+ created: z.number().nullish(),
785
+ model: z.string().nullish(),
786
+ choices: z.array(
787
+ z.object({
788
+ delta: z
789
+ .object({
790
+ role: z.enum(["assistant"]).nullish(),
791
+ content: z.string().nullish(),
792
+ // Copilot-specific reasoning fields
793
+ reasoning_text: z.string().nullish(),
794
+ reasoning_opaque: z.string().nullish(),
795
+ tool_calls: z
796
+ .array(
797
+ z.object({
798
+ index: z.number(),
799
+ id: z.string().nullish(),
800
+ function: z.object({
801
+ name: z.string().nullish(),
802
+ arguments: z.string().nullish(),
803
+ }),
804
+ }),
805
+ )
806
+ .nullish(),
807
+ })
808
+ .nullish(),
809
+ finish_reason: z.string().nullish(),
810
+ }),
811
+ ),
812
+ usage: openaiCompatibleTokenUsageSchema,
813
+ }),
814
+ errorSchema,
815
+ ])