@farhanic017/octocode 3.5.0

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 (716) hide show
  1. package/.swarm_lessons.json +85 -0
  2. package/AGENTS.md +151 -0
  3. package/BUN_SHELL_MIGRATION_PLAN.md +136 -0
  4. package/Dockerfile +18 -0
  5. package/README.md +15 -0
  6. package/bin/octocode +31 -0
  7. package/bunfig.toml +7 -0
  8. package/git +0 -0
  9. package/package.json +151 -0
  10. package/parsers-config.ts +1 -0
  11. package/script/bench-search.ts +115 -0
  12. package/script/bench-test-suite.ts +52 -0
  13. package/script/build.ts +243 -0
  14. package/script/generate.ts +14 -0
  15. package/script/httpapi-exercise.ts +1 -0
  16. package/script/octo-shim.mjs +34 -0
  17. package/script/postinstall.mjs +198 -0
  18. package/script/profile-test-files.ts +42 -0
  19. package/script/publish.ts +211 -0
  20. package/script/run-workspace-server +106 -0
  21. package/script/schema.ts +77 -0
  22. package/script/time.ts +6 -0
  23. package/script/trace-imports.ts +154 -0
  24. package/specs/effect/error-boundaries-plan.md +235 -0
  25. package/specs/effect/errors.md +207 -0
  26. package/specs/effect/facades.md +218 -0
  27. package/specs/effect/guide.md +247 -0
  28. package/specs/effect/instance-context.md +13 -0
  29. package/specs/effect/loose-ends.md +30 -0
  30. package/specs/effect/migration.md +62 -0
  31. package/specs/effect/routes.md +61 -0
  32. package/specs/effect/schema.md +88 -0
  33. package/specs/effect/server-package.md +58 -0
  34. package/specs/effect/todo.md +241 -0
  35. package/specs/effect/tools.md +88 -0
  36. package/specs/openapi-translation-cleanup.md +204 -0
  37. package/specs/tui-plugins.md +544 -0
  38. package/specs/v2/api.ts +67 -0
  39. package/specs/v2/message-shape.md +136 -0
  40. package/specs/v2/notifications.md +13 -0
  41. package/specs/v2/tui-command-shim.md +67 -0
  42. package/src/account/account.ts +459 -0
  43. package/src/account/repo.ts +170 -0
  44. package/src/account/schema.ts +99 -0
  45. package/src/account/url.ts +8 -0
  46. package/src/acp/agent.ts +95 -0
  47. package/src/acp/config-option.ts +203 -0
  48. package/src/acp/content.ts +250 -0
  49. package/src/acp/directory.ts +210 -0
  50. package/src/acp/error.ts +90 -0
  51. package/src/acp/event.ts +345 -0
  52. package/src/acp/permission.ts +145 -0
  53. package/src/acp/profile.ts +42 -0
  54. package/src/acp/service.ts +1062 -0
  55. package/src/acp/tool.ts +321 -0
  56. package/src/acp/usage.ts +239 -0
  57. package/src/agent/agent.ts +451 -0
  58. package/src/agent/generate.txt +75 -0
  59. package/src/agent/prompt/compaction.txt +30 -0
  60. package/src/agent/prompt/explore.txt +18 -0
  61. package/src/agent/prompt/summary.txt +11 -0
  62. package/src/agent/prompt/title.txt +50 -0
  63. package/src/agent/subagent-permissions.ts +35 -0
  64. package/src/audio.d.ts +14 -0
  65. package/src/auth/index.ts +96 -0
  66. package/src/background/job.ts +36 -0
  67. package/src/bus/global.ts +22 -0
  68. package/src/cli/bootstrap.ts +11 -0
  69. package/src/cli/cmd/account.ts +264 -0
  70. package/src/cli/cmd/acp.ts +76 -0
  71. package/src/cli/cmd/agent.ts +259 -0
  72. package/src/cli/cmd/attach.ts +97 -0
  73. package/src/cli/cmd/cmd.ts +7 -0
  74. package/src/cli/cmd/db.ts +62 -0
  75. package/src/cli/cmd/debug/agent.handler.ts +188 -0
  76. package/src/cli/cmd/debug/agent.ts +27 -0
  77. package/src/cli/cmd/debug/config.ts +14 -0
  78. package/src/cli/cmd/debug/file.ts +87 -0
  79. package/src/cli/cmd/debug/index.ts +87 -0
  80. package/src/cli/cmd/debug/lsp.ts +51 -0
  81. package/src/cli/cmd/debug/ripgrep.ts +99 -0
  82. package/src/cli/cmd/debug/scrap.ts +18 -0
  83. package/src/cli/cmd/debug/skill.ts +15 -0
  84. package/src/cli/cmd/debug/snapshot.ts +50 -0
  85. package/src/cli/cmd/debug/startup.ts +11 -0
  86. package/src/cli/cmd/debug/v2.ts +46 -0
  87. package/src/cli/cmd/export.ts +292 -0
  88. package/src/cli/cmd/generate.ts +54 -0
  89. package/src/cli/cmd/github.handler.ts +1594 -0
  90. package/src/cli/cmd/github.shared.ts +30 -0
  91. package/src/cli/cmd/github.ts +42 -0
  92. package/src/cli/cmd/import.ts +224 -0
  93. package/src/cli/cmd/mcp.ts +859 -0
  94. package/src/cli/cmd/models.ts +66 -0
  95. package/src/cli/cmd/plug.ts +230 -0
  96. package/src/cli/cmd/pr.ts +115 -0
  97. package/src/cli/cmd/prompt-display.ts +1 -0
  98. package/src/cli/cmd/providers.ts +550 -0
  99. package/src/cli/cmd/run/demo.ts +1274 -0
  100. package/src/cli/cmd/run/entry.body.ts +205 -0
  101. package/src/cli/cmd/run/footer.command.tsx +1088 -0
  102. package/src/cli/cmd/run/footer.menu.tsx +353 -0
  103. package/src/cli/cmd/run/footer.permission.tsx +482 -0
  104. package/src/cli/cmd/run/footer.prompt.tsx +1351 -0
  105. package/src/cli/cmd/run/footer.question.tsx +580 -0
  106. package/src/cli/cmd/run/footer.subagent.tsx +180 -0
  107. package/src/cli/cmd/run/footer.ts +1153 -0
  108. package/src/cli/cmd/run/footer.view.tsx +992 -0
  109. package/src/cli/cmd/run/footer.width.ts +27 -0
  110. package/src/cli/cmd/run/otel.ts +117 -0
  111. package/src/cli/cmd/run/permission.shared.ts +256 -0
  112. package/src/cli/cmd/run/prompt.editor.ts +157 -0
  113. package/src/cli/cmd/run/prompt.shared.ts +153 -0
  114. package/src/cli/cmd/run/question.shared.ts +340 -0
  115. package/src/cli/cmd/run/runtime.boot.ts +202 -0
  116. package/src/cli/cmd/run/runtime.lifecycle.ts +431 -0
  117. package/src/cli/cmd/run/runtime.queue.ts +349 -0
  118. package/src/cli/cmd/run/runtime.shared.ts +17 -0
  119. package/src/cli/cmd/run/runtime.stdin.ts +37 -0
  120. package/src/cli/cmd/run/runtime.ts +905 -0
  121. package/src/cli/cmd/run/scrollback.shared.ts +92 -0
  122. package/src/cli/cmd/run/scrollback.surface.ts +448 -0
  123. package/src/cli/cmd/run/scrollback.writer.tsx +353 -0
  124. package/src/cli/cmd/run/splash.ts +284 -0
  125. package/src/cli/cmd/run/stream.transport.ts +1465 -0
  126. package/src/cli/cmd/run/stream.ts +175 -0
  127. package/src/cli/cmd/run/subagent-data.ts +876 -0
  128. package/src/cli/cmd/run/theme.ts +690 -0
  129. package/src/cli/cmd/run/tool.ts +1489 -0
  130. package/src/cli/cmd/run/trace.ts +94 -0
  131. package/src/cli/cmd/run/turn-summary.ts +47 -0
  132. package/src/cli/cmd/run/types.ts +350 -0
  133. package/src/cli/cmd/run/variant.shared.ts +215 -0
  134. package/src/cli/cmd/run.ts +897 -0
  135. package/src/cli/cmd/serve.ts +24 -0
  136. package/src/cli/cmd/stats.ts +393 -0
  137. package/src/cli/cmd/tui.ts +264 -0
  138. package/src/cli/cmd/uninstall.ts +353 -0
  139. package/src/cli/cmd/upgrade.ts +74 -0
  140. package/src/cli/cmd/web.ts +84 -0
  141. package/src/cli/effect/prompt.ts +37 -0
  142. package/src/cli/effect-cmd.ts +96 -0
  143. package/src/cli/error.ts +118 -0
  144. package/src/cli/heap.ts +66 -0
  145. package/src/cli/logo.ts +1 -0
  146. package/src/cli/network.ts +64 -0
  147. package/src/cli/tui/layer.ts +7 -0
  148. package/src/cli/tui/photon_rs_bg-bq08arze.wasm +0 -0
  149. package/src/cli/tui/tree-sitter-3jzf13jk.wasm +0 -0
  150. package/src/cli/tui/tree-sitter-bash-hq5s6fxb.wasm +0 -0
  151. package/src/cli/tui/tree-sitter-powershell-ryb2ffqs.wasm +0 -0
  152. package/src/cli/tui/worker.ts +99 -0
  153. package/src/cli/ui.ts +144 -0
  154. package/src/cli/upgrade.ts +53 -0
  155. package/src/command/index.ts +189 -0
  156. package/src/command/template/initialize.txt +66 -0
  157. package/src/command/template/review.txt +101 -0
  158. package/src/command/terminal-ai-commands.ts +567 -0
  159. package/src/config/agent.ts +68 -0
  160. package/src/config/command.ts +45 -0
  161. package/src/config/config.ts +686 -0
  162. package/src/config/entry-name.ts +19 -0
  163. package/src/config/managed.ts +77 -0
  164. package/src/config/markdown.ts +36 -0
  165. package/src/config/parse.ts +79 -0
  166. package/src/config/paths.ts +47 -0
  167. package/src/config/plugin.ts +79 -0
  168. package/src/config/reference.ts +48 -0
  169. package/src/config/tui-cwd.ts +5 -0
  170. package/src/config/tui-host-attention.ts +21 -0
  171. package/src/config/tui-migrate.ts +156 -0
  172. package/src/config/tui.ts +294 -0
  173. package/src/config/variable.ts +91 -0
  174. package/src/control-plane/adapters/index.ts +41 -0
  175. package/src/control-plane/adapters/worktree.ts +96 -0
  176. package/src/control-plane/dev/README.md +19 -0
  177. package/src/control-plane/dev/debug-workspace-plugin.ts +73 -0
  178. package/src/control-plane/types.ts +59 -0
  179. package/src/control-plane/util.ts +39 -0
  180. package/src/control-plane/workspace-adapter-runtime.ts +51 -0
  181. package/src/control-plane/workspace-context.ts +26 -0
  182. package/src/control-plane/workspace.ts +1075 -0
  183. package/src/desktop/agent.ts +147 -0
  184. package/src/desktop/index.ts +247 -0
  185. package/src/desktop/platform.ts +97 -0
  186. package/src/desktop/stream.ts +64 -0
  187. package/src/desktop/vision.ts +52 -0
  188. package/src/desktop/websocket.ts +120 -0
  189. package/src/effect/app-runtime.ts +133 -0
  190. package/src/effect/bootstrap-runtime.ts +23 -0
  191. package/src/effect/bridge.ts +84 -0
  192. package/src/effect/config-service.ts +67 -0
  193. package/src/effect/instance-ref.ts +11 -0
  194. package/src/effect/instance-registry.ts +12 -0
  195. package/src/effect/instance-state.ts +72 -0
  196. package/src/effect/promise.ts +17 -0
  197. package/src/effect/run-service.ts +47 -0
  198. package/src/effect/runner.ts +217 -0
  199. package/src/effect/runtime-flags.ts +76 -0
  200. package/src/env/index.ts +40 -0
  201. package/src/event-v2-bridge.ts +76 -0
  202. package/src/format/formatter.ts +404 -0
  203. package/src/format/index.ts +212 -0
  204. package/src/git/index.ts +347 -0
  205. package/src/id/id.ts +80 -0
  206. package/src/ide/index.ts +70 -0
  207. package/src/image/image.ts +177 -0
  208. package/src/index.ts +208 -0
  209. package/src/installation/index.ts +350 -0
  210. package/src/lsp/client.ts +686 -0
  211. package/src/lsp/diagnostic.ts +29 -0
  212. package/src/lsp/language.ts +121 -0
  213. package/src/lsp/launch.ts +21 -0
  214. package/src/lsp/lsp.ts +517 -0
  215. package/src/lsp/server.ts +2116 -0
  216. package/src/markdown.d.ts +4 -0
  217. package/src/mcp/auth.ts +171 -0
  218. package/src/mcp/builtin.ts +92 -0
  219. package/src/mcp/index.ts +1000 -0
  220. package/src/mcp/oauth-callback.ts +232 -0
  221. package/src/mcp/oauth-provider.ts +217 -0
  222. package/src/node.ts +5 -0
  223. package/src/patch/index.ts +689 -0
  224. package/src/permission/arity.ts +163 -0
  225. package/src/permission/evaluate.ts +1 -0
  226. package/src/permission/index.ts +230 -0
  227. package/src/plugin/azure.ts +26 -0
  228. package/src/plugin/cloudflare.ts +76 -0
  229. package/src/plugin/digitalocean.ts +391 -0
  230. package/src/plugin/github-copilot/copilot.ts +417 -0
  231. package/src/plugin/github-copilot/models.ts +246 -0
  232. package/src/plugin/index.ts +320 -0
  233. package/src/plugin/install.ts +439 -0
  234. package/src/plugin/loader.ts +237 -0
  235. package/src/plugin/meta.ts +188 -0
  236. package/src/plugin/openai/README.md +31 -0
  237. package/src/plugin/openai/codex.ts +647 -0
  238. package/src/plugin/openai/ws-pool.ts +290 -0
  239. package/src/plugin/openai/ws.ts +381 -0
  240. package/src/plugin/shared.ts +323 -0
  241. package/src/plugin/tui/internal.ts +12 -0
  242. package/src/plugin/tui/runtime.ts +1174 -0
  243. package/src/plugin/xai.ts +742 -0
  244. package/src/project/bootstrap-service.ts +9 -0
  245. package/src/project/bootstrap.ts +80 -0
  246. package/src/project/instance-context.ts +24 -0
  247. package/src/project/instance-layer.ts +11 -0
  248. package/src/project/instance-runtime.ts +16 -0
  249. package/src/project/instance-store.ts +207 -0
  250. package/src/project/project.ts +520 -0
  251. package/src/project/vcs.ts +435 -0
  252. package/src/provider/auth.ts +230 -0
  253. package/src/provider/error.ts +188 -0
  254. package/src/provider/model-status.ts +8 -0
  255. package/src/provider/provider.ts +2037 -0
  256. package/src/provider/transform.ts +1367 -0
  257. package/src/pty-preparation.ts +30 -0
  258. package/src/question/index.ts +229 -0
  259. package/src/question/schema.ts +10 -0
  260. package/src/reference/reference.ts +239 -0
  261. package/src/reference/repository-cache.ts +320 -0
  262. package/src/server/auth.ts +48 -0
  263. package/src/server/cors.ts +34 -0
  264. package/src/server/event.ts +13 -0
  265. package/src/server/global-lifecycle.ts +37 -0
  266. package/src/server/init-projectors.ts +3 -0
  267. package/src/server/mdns.ts +60 -0
  268. package/src/server/projectors.ts +1 -0
  269. package/src/server/proxy-util.ts +48 -0
  270. package/src/server/routes/instance/httpapi/AGENTS.md +39 -0
  271. package/src/server/routes/instance/httpapi/api.ts +80 -0
  272. package/src/server/routes/instance/httpapi/errors.ts +193 -0
  273. package/src/server/routes/instance/httpapi/groups/config.ts +65 -0
  274. package/src/server/routes/instance/httpapi/groups/control-plane.ts +35 -0
  275. package/src/server/routes/instance/httpapi/groups/control.ts +76 -0
  276. package/src/server/routes/instance/httpapi/groups/event.ts +29 -0
  277. package/src/server/routes/instance/httpapi/groups/experimental.ts +260 -0
  278. package/src/server/routes/instance/httpapi/groups/file.ts +172 -0
  279. package/src/server/routes/instance/httpapi/groups/global.ts +138 -0
  280. package/src/server/routes/instance/httpapi/groups/instance.ts +206 -0
  281. package/src/server/routes/instance/httpapi/groups/mcp.ts +156 -0
  282. package/src/server/routes/instance/httpapi/groups/metadata.ts +18 -0
  283. package/src/server/routes/instance/httpapi/groups/permission.ts +61 -0
  284. package/src/server/routes/instance/httpapi/groups/project-copy.ts +88 -0
  285. package/src/server/routes/instance/httpapi/groups/project.ts +93 -0
  286. package/src/server/routes/instance/httpapi/groups/provider.ts +101 -0
  287. package/src/server/routes/instance/httpapi/groups/pty.ts +172 -0
  288. package/src/server/routes/instance/httpapi/groups/query.ts +12 -0
  289. package/src/server/routes/instance/httpapi/groups/question.ts +74 -0
  290. package/src/server/routes/instance/httpapi/groups/reference.ts +60 -0
  291. package/src/server/routes/instance/httpapi/groups/sync.ts +113 -0
  292. package/src/server/routes/instance/httpapi/groups/tui.ts +208 -0
  293. package/src/server/routes/instance/httpapi/groups/workspace.ts +141 -0
  294. package/src/server/routes/instance/httpapi/handlers/config.ts +34 -0
  295. package/src/server/routes/instance/httpapi/handlers/control-plane.ts +37 -0
  296. package/src/server/routes/instance/httpapi/handlers/control.ts +37 -0
  297. package/src/server/routes/instance/httpapi/handlers/event.ts +102 -0
  298. package/src/server/routes/instance/httpapi/handlers/experimental.ts +187 -0
  299. package/src/server/routes/instance/httpapi/handlers/file.ts +128 -0
  300. package/src/server/routes/instance/httpapi/handlers/global.ts +157 -0
  301. package/src/server/routes/instance/httpapi/handlers/instance.ts +110 -0
  302. package/src/server/routes/instance/httpapi/handlers/mcp.ts +111 -0
  303. package/src/server/routes/instance/httpapi/handlers/permission.ts +41 -0
  304. package/src/server/routes/instance/httpapi/handlers/project-copy.ts +157 -0
  305. package/src/server/routes/instance/httpapi/handlers/project.ts +63 -0
  306. package/src/server/routes/instance/httpapi/handlers/provider.ts +113 -0
  307. package/src/server/routes/instance/httpapi/handlers/pty.ts +258 -0
  308. package/src/server/routes/instance/httpapi/handlers/question.ts +54 -0
  309. package/src/server/routes/instance/httpapi/handlers/reference.ts +27 -0
  310. package/src/server/routes/instance/httpapi/handlers/sync.ts +95 -0
  311. package/src/server/routes/instance/httpapi/handlers/tui.ts +131 -0
  312. package/src/server/routes/instance/httpapi/handlers/workspace.ts +102 -0
  313. package/src/server/routes/instance/httpapi/lifecycle.ts +57 -0
  314. package/src/server/routes/instance/httpapi/middleware/authorization.ts +150 -0
  315. package/src/server/routes/instance/httpapi/middleware/compression.ts +64 -0
  316. package/src/server/routes/instance/httpapi/middleware/cors-vary.ts +29 -0
  317. package/src/server/routes/instance/httpapi/middleware/error.ts +36 -0
  318. package/src/server/routes/instance/httpapi/middleware/fence.ts +25 -0
  319. package/src/server/routes/instance/httpapi/middleware/instance-context.ts +43 -0
  320. package/src/server/routes/instance/httpapi/middleware/proxy.ts +108 -0
  321. package/src/server/routes/instance/httpapi/middleware/schema-error.ts +42 -0
  322. package/src/server/routes/instance/httpapi/middleware/workspace-routing.ts +250 -0
  323. package/src/server/routes/instance/httpapi/public.ts +535 -0
  324. package/src/server/routes/instance/httpapi/server.ts +281 -0
  325. package/src/server/routes/instance/httpapi/websocket-tracker.ts +57 -0
  326. package/src/server/server.ts +218 -0
  327. package/src/server/shared/fence.ts +68 -0
  328. package/src/server/shared/pty-ticket.ts +15 -0
  329. package/src/server/shared/public-ui.ts +12 -0
  330. package/src/server/shared/tui-control.ts +28 -0
  331. package/src/server/shared/ui.ts +108 -0
  332. package/src/server/shared/workspace-routing.ts +38 -0
  333. package/src/server/tui-event.ts +53 -0
  334. package/src/share/share-next.ts +379 -0
  335. package/src/shell/shell.ts +215 -0
  336. package/src/skill/discovery.ts +115 -0
  337. package/src/skill/index.ts +382 -0
  338. package/src/snapshot/index.ts +762 -0
  339. package/src/sql.d.ts +4 -0
  340. package/src/storage/schema.ts +5 -0
  341. package/src/storage/storage.ts +329 -0
  342. package/src/swarm/evolution.ts +304 -0
  343. package/src/swarm/index.ts +7 -0
  344. package/src/swarm/learning.ts +736 -0
  345. package/src/swarm/vision.ts +131 -0
  346. package/src/sync/README.md +179 -0
  347. package/src/sync/schema.ts +11 -0
  348. package/src/temporary.ts +33 -0
  349. package/src/tool/apply_patch.ts +313 -0
  350. package/src/tool/apply_patch.txt +33 -0
  351. package/src/tool/browser_click.ts +51 -0
  352. package/src/tool/browser_drag.ts +76 -0
  353. package/src/tool/browser_evaluate.ts +51 -0
  354. package/src/tool/browser_hover.ts +51 -0
  355. package/src/tool/browser_navigate.ts +45 -0
  356. package/src/tool/browser_screenshot.ts +66 -0
  357. package/src/tool/browser_select.ts +52 -0
  358. package/src/tool/browser_type.ts +52 -0
  359. package/src/tool/browser_wait.ts +60 -0
  360. package/src/tool/desktop_clipboard.ts +82 -0
  361. package/src/tool/desktop_control.ts +160 -0
  362. package/src/tool/desktop_record.ts +93 -0
  363. package/src/tool/desktop_replay.ts +99 -0
  364. package/src/tool/desktop_screen_record.ts +143 -0
  365. package/src/tool/desktop_window.ts +142 -0
  366. package/src/tool/desktop_workflow.ts +81 -0
  367. package/src/tool/edit.ts +737 -0
  368. package/src/tool/edit.txt +10 -0
  369. package/src/tool/external-directory.ts +49 -0
  370. package/src/tool/glob.ts +84 -0
  371. package/src/tool/glob.txt +6 -0
  372. package/src/tool/grep.ts +140 -0
  373. package/src/tool/grep.txt +8 -0
  374. package/src/tool/invalid.ts +21 -0
  375. package/src/tool/json-schema.ts +164 -0
  376. package/src/tool/lsp.ts +113 -0
  377. package/src/tool/lsp.txt +24 -0
  378. package/src/tool/mcp-websearch.ts +96 -0
  379. package/src/tool/open_app.ts +55 -0
  380. package/src/tool/open_terminal.ts +69 -0
  381. package/src/tool/plan-enter.txt +14 -0
  382. package/src/tool/plan-exit.txt +13 -0
  383. package/src/tool/plan.ts +79 -0
  384. package/src/tool/question.ts +44 -0
  385. package/src/tool/question.txt +10 -0
  386. package/src/tool/read.ts +392 -0
  387. package/src/tool/read.txt +14 -0
  388. package/src/tool/registry.ts +527 -0
  389. package/src/tool/schema.ts +14 -0
  390. package/src/tool/screenshot.ts +72 -0
  391. package/src/tool/shell/id.ts +19 -0
  392. package/src/tool/shell/prompt.ts +307 -0
  393. package/src/tool/shell/shell.txt +21 -0
  394. package/src/tool/shell.ts +669 -0
  395. package/src/tool/skill.ts +72 -0
  396. package/src/tool/skill.txt +5 -0
  397. package/src/tool/task.ts +339 -0
  398. package/src/tool/task.txt +19 -0
  399. package/src/tool/todo.ts +57 -0
  400. package/src/tool/todowrite.txt +44 -0
  401. package/src/tool/tool.ts +180 -0
  402. package/src/tool/truncate.ts +160 -0
  403. package/src/tool/truncation-dir.ts +4 -0
  404. package/src/tool/visual_qa.ts +77 -0
  405. package/src/tool/webfetch.ts +192 -0
  406. package/src/tool/webfetch.txt +13 -0
  407. package/src/tool/websearch.ts +143 -0
  408. package/src/tool/websearch.txt +14 -0
  409. package/src/tool/write.ts +104 -0
  410. package/src/tool/write.txt +8 -0
  411. package/src/util/archive.ts +17 -0
  412. package/src/util/bom.ts +27 -0
  413. package/src/util/data-url.ts +9 -0
  414. package/src/util/defer.ts +10 -0
  415. package/src/util/effect-http-client.ts +11 -0
  416. package/src/util/error.ts +1 -0
  417. package/src/util/filesystem.ts +251 -0
  418. package/src/util/iife.ts +3 -0
  419. package/src/util/lazy.ts +20 -0
  420. package/src/util/local-context.ts +25 -0
  421. package/src/util/locale.ts +2 -0
  422. package/src/util/media.ts +26 -0
  423. package/src/util/process.ts +177 -0
  424. package/src/util/proxy-env.ts +72 -0
  425. package/src/util/queue.ts +32 -0
  426. package/src/util/record.ts +1 -0
  427. package/src/util/repository.ts +232 -0
  428. package/src/util/rpc.ts +66 -0
  429. package/src/util/signal.ts +12 -0
  430. package/src/util/sys-monitor.ts +223 -0
  431. package/src/util/timeout.ts +13 -0
  432. package/src/util/wildcard.ts +59 -0
  433. package/src/worktree/index.ts +645 -0
  434. package/sst-env.d.ts +10 -0
  435. package/test/AGENTS.md +204 -0
  436. package/test/EFFECT_TEST_MIGRATION.md +169 -0
  437. package/test/account/repo.test.ts +353 -0
  438. package/test/account/service.test.ts +453 -0
  439. package/test/acp/config-option.test.ts +229 -0
  440. package/test/acp/content.test.ts +201 -0
  441. package/test/acp/directory.test.ts +186 -0
  442. package/test/acp/error.test.ts +67 -0
  443. package/test/acp/event.test.ts +743 -0
  444. package/test/acp/permission.test.ts +273 -0
  445. package/test/acp/tool.test.ts +210 -0
  446. package/test/acp/usage.test.ts +315 -0
  447. package/test/agent/agent.test.ts +711 -0
  448. package/test/agent/plan-mode-subagent-bypass.test.ts +213 -0
  449. package/test/agent/plugin-agent-regression.test.ts +62 -0
  450. package/test/auth/auth.test.ts +77 -0
  451. package/test/background/job.test.ts +243 -0
  452. package/test/cli/account.test.ts +30 -0
  453. package/test/cli/acp/acp-test-client.ts +97 -0
  454. package/test/cli/acp/config-options.test.ts +103 -0
  455. package/test/cli/acp/helpers.ts +96 -0
  456. package/test/cli/acp/initialize-auth.test.ts +61 -0
  457. package/test/cli/acp/lifecycle.test.ts +118 -0
  458. package/test/cli/acp/prompt-content.test.ts +97 -0
  459. package/test/cli/acp/skills.test.ts +38 -0
  460. package/test/cli/cmd/tui/attention.test.ts +484 -0
  461. package/test/cli/effect-cmd-instance-als.test.ts +39 -0
  462. package/test/cli/error.test.ts +95 -0
  463. package/test/cli/github-action.test.ts +199 -0
  464. package/test/cli/github-remote.test.ts +90 -0
  465. package/test/cli/help/__snapshots__/help-snapshots.test.ts.snap +631 -0
  466. package/test/cli/help/help-snapshots.test.ts +137 -0
  467. package/test/cli/import.test.ts +54 -0
  468. package/test/cli/mcp-add.test.ts +74 -0
  469. package/test/cli/plugin-auth-picker.test.ts +120 -0
  470. package/test/cli/run/entry.body.test.ts +536 -0
  471. package/test/cli/run/footer.menu.test.ts +43 -0
  472. package/test/cli/run/footer.view.test.tsx +1336 -0
  473. package/test/cli/run/footer.width.test.ts +35 -0
  474. package/test/cli/run/permission.shared.test.ts +144 -0
  475. package/test/cli/run/prompt.editor.test.ts +101 -0
  476. package/test/cli/run/prompt.shared.test.ts +101 -0
  477. package/test/cli/run/question.shared.test.ts +115 -0
  478. package/test/cli/run/run-process.test.ts +84 -0
  479. package/test/cli/run/runtime.boot.test.ts +283 -0
  480. package/test/cli/run/runtime.queue.test.ts +481 -0
  481. package/test/cli/run/runtime.stdin.test.ts +71 -0
  482. package/test/cli/run/runtime.test.ts +238 -0
  483. package/test/cli/run/scrollback.surface.test.ts +1065 -0
  484. package/test/cli/run/stream.test.ts +56 -0
  485. package/test/cli/run/stream.transport.test.ts +2363 -0
  486. package/test/cli/run/subagent-data.test.ts +547 -0
  487. package/test/cli/run/theme.test.ts +177 -0
  488. package/test/cli/run/variant.shared.test.ts +217 -0
  489. package/test/cli/serve/serve-process.test.ts +61 -0
  490. package/test/cli/smokes/read-only.test.ts +115 -0
  491. package/test/cli/tui/attach.test.ts +11 -0
  492. package/test/cli/tui/editor-context-zed.test.ts +379 -0
  493. package/test/cli/tui/editor-context.test.tsx +297 -0
  494. package/test/cli/tui/plugin-add.test.ts +110 -0
  495. package/test/cli/tui/plugin-install.test.ts +87 -0
  496. package/test/cli/tui/plugin-lifecycle.test.ts +224 -0
  497. package/test/cli/tui/plugin-loader-entrypoint.test.ts +485 -0
  498. package/test/cli/tui/plugin-loader-pure.test.ts +72 -0
  499. package/test/cli/tui/plugin-loader.test.ts +1332 -0
  500. package/test/cli/tui/plugin-toggle.test.ts +264 -0
  501. package/test/cli/tui/thread.test.ts +36 -0
  502. package/test/cli.test.ts +7 -0
  503. package/test/command/acp-slash-detect.test.ts +202 -0
  504. package/test/command/demo-slash.test.ts +213 -0
  505. package/test/command/slash-head.test.ts +232 -0
  506. package/test/command/slash-parsing.test.ts +193 -0
  507. package/test/command/terminal-ai-commands.test.ts +536 -0
  508. package/test/config/agent-color.test.ts +47 -0
  509. package/test/config/config.test.ts +1994 -0
  510. package/test/config/entry-name.test.ts +57 -0
  511. package/test/config/fixtures/empty-frontmatter.md +4 -0
  512. package/test/config/fixtures/frontmatter.md +28 -0
  513. package/test/config/fixtures/markdown-header.md +11 -0
  514. package/test/config/fixtures/no-frontmatter.md +1 -0
  515. package/test/config/fixtures/weird-model-id.md +13 -0
  516. package/test/config/lsp.test.ts +69 -0
  517. package/test/config/markdown.test.ts +228 -0
  518. package/test/config/plugin.test.ts +0 -0
  519. package/test/config/tui.test.ts +886 -0
  520. package/test/control-plane/adapters.test.ts +71 -0
  521. package/test/control-plane/workspace.test.ts +1704 -0
  522. package/test/effect/app-runtime-logger.test.ts +105 -0
  523. package/test/effect/config-service.test.ts +65 -0
  524. package/test/effect/instance-state.test.ts +391 -0
  525. package/test/effect/run-service.test.ts +89 -0
  526. package/test/effect/runner.test.ts +514 -0
  527. package/test/effect/runtime-flags.test.ts +373 -0
  528. package/test/fake/account.ts +9 -0
  529. package/test/fake/auth.ts +8 -0
  530. package/test/fake/npm.ts +8 -0
  531. package/test/fake/provider.ts +82 -0
  532. package/test/fake/skill.ts +8 -0
  533. package/test/filesystem/filesystem.test.ts +319 -0
  534. package/test/fixture/agent-plugin.constants.ts +6 -0
  535. package/test/fixture/agent-plugin.ts +12 -0
  536. package/test/fixture/config.ts +23 -0
  537. package/test/fixture/db.ts +11 -0
  538. package/test/fixture/fixture.test.ts +26 -0
  539. package/test/fixture/fixture.ts +224 -0
  540. package/test/fixture/flag.ts +20 -0
  541. package/test/fixture/flock-worker.ts +72 -0
  542. package/test/fixture/lsp/fake-lsp-server.js +249 -0
  543. package/test/fixture/plug-worker.ts +96 -0
  544. package/test/fixture/plugin-meta-worker.ts +19 -0
  545. package/test/fixture/plugin.ts +10 -0
  546. package/test/fixture/skills/agents-sdk/SKILL.md +152 -0
  547. package/test/fixture/skills/agents-sdk/references/callable.md +92 -0
  548. package/test/fixture/skills/cloudflare/SKILL.md +211 -0
  549. package/test/fixture/skills/index.json +6 -0
  550. package/test/fixture/tui-environment.tsx +32 -0
  551. package/test/fixture/tui-plugin.ts +357 -0
  552. package/test/fixture/tui-runtime.ts +56 -0
  553. package/test/fixture/tui-sdk.ts +82 -0
  554. package/test/fixture/workspace.ts +30 -0
  555. package/test/format/format.test.ts +228 -0
  556. package/test/git/git.test.ts +178 -0
  557. package/test/ide/ide.test.ts +82 -0
  558. package/test/image/fixtures/picture-5mb-base64.png +0 -0
  559. package/test/image/image.test.ts +123 -0
  560. package/test/installation/installation.test.ts +231 -0
  561. package/test/lib/cli-process.ts +459 -0
  562. package/test/lib/effect.ts +177 -0
  563. package/test/lib/filesystem.ts +10 -0
  564. package/test/lib/llm-server.ts +771 -0
  565. package/test/lib/snapshot.ts +73 -0
  566. package/test/lib/test-provider.ts +37 -0
  567. package/test/lib/websocket.ts +46 -0
  568. package/test/lsp/client.test.ts +493 -0
  569. package/test/lsp/index.test.ts +232 -0
  570. package/test/lsp/jdtls-root.test.ts +459 -0
  571. package/test/lsp/launch.test.ts +22 -0
  572. package/test/lsp/lifecycle.test.ts +160 -0
  573. package/test/mcp/auth.test.ts +78 -0
  574. package/test/mcp/builtin.test.ts +95 -0
  575. package/test/mcp/headers.test.ts +126 -0
  576. package/test/mcp/lifecycle.test.ts +999 -0
  577. package/test/mcp/oauth-auto-connect.test.ts +274 -0
  578. package/test/mcp/oauth-browser.test.ts +232 -0
  579. package/test/mcp/oauth-callback.test.ts +34 -0
  580. package/test/mcp/oauth-provider.test.ts +61 -0
  581. package/test/patch/patch.test.ts +383 -0
  582. package/test/permission/arity.test.ts +33 -0
  583. package/test/permission/next.test.ts +1176 -0
  584. package/test/permission-task.test.ts +318 -0
  585. package/test/plugin/auth-override.test.ts +105 -0
  586. package/test/plugin/cloudflare.test.ts +68 -0
  587. package/test/plugin/codex.test.ts +247 -0
  588. package/test/plugin/github-copilot-models.test.ts +332 -0
  589. package/test/plugin/install-concurrency.test.ts +140 -0
  590. package/test/plugin/install.test.ts +573 -0
  591. package/test/plugin/loader-shared.test.ts +1303 -0
  592. package/test/plugin/meta.test.ts +137 -0
  593. package/test/plugin/openai-rollout.test.ts +17 -0
  594. package/test/plugin/openai-ws.test.ts +877 -0
  595. package/test/plugin/shared.test.ts +88 -0
  596. package/test/plugin/trigger.test.ts +120 -0
  597. package/test/plugin/workspace-adapter.test.ts +137 -0
  598. package/test/plugin/xai.test.ts +634 -0
  599. package/test/preload.ts +99 -0
  600. package/test/project/instance-bootstrap.test.ts +110 -0
  601. package/test/project/instance.test.ts +245 -0
  602. package/test/project/migrate-global.test.ts +170 -0
  603. package/test/project/project-directory.test.ts +169 -0
  604. package/test/project/project.test.ts +818 -0
  605. package/test/project/vcs.test.ts +336 -0
  606. package/test/project/worktree-remove.test.ts +126 -0
  607. package/test/project/worktree.test.ts +320 -0
  608. package/test/provider/amazon-bedrock.test.ts +360 -0
  609. package/test/provider/cf-ai-gateway-e2e.test.ts +132 -0
  610. package/test/provider/digitalocean.test.ts +123 -0
  611. package/test/provider/gitlab-duo.test.ts +412 -0
  612. package/test/provider/header-timeout.test.ts +233 -0
  613. package/test/provider/model-status.test.ts +61 -0
  614. package/test/provider/provider.test.ts +1795 -0
  615. package/test/provider/transform.test.ts +3937 -0
  616. package/test/pty/pty-shell.test.ts +102 -0
  617. package/test/question/question.test.ts +465 -0
  618. package/test/reference/reference.test.ts +311 -0
  619. package/test/server/AGENTS.md +15 -0
  620. package/test/server/auth.test.ts +59 -0
  621. package/test/server/global-bus.ts +31 -0
  622. package/test/server/httpapi-authorization.test.ts +174 -0
  623. package/test/server/httpapi-compression.test.ts +154 -0
  624. package/test/server/httpapi-config.test.ts +113 -0
  625. package/test/server/httpapi-control-plane.test.ts +63 -0
  626. package/test/server/httpapi-cors-vary.test.ts +66 -0
  627. package/test/server/httpapi-cors.test.ts +122 -0
  628. package/test/server/httpapi-error-middleware.test.ts +96 -0
  629. package/test/server/httpapi-event.test.ts +97 -0
  630. package/test/server/httpapi-exercise/assertions.ts +64 -0
  631. package/test/server/httpapi-exercise/backend.ts +144 -0
  632. package/test/server/httpapi-exercise/dsl.ts +210 -0
  633. package/test/server/httpapi-exercise/environment.ts +40 -0
  634. package/test/server/httpapi-exercise/index.ts +1538 -0
  635. package/test/server/httpapi-exercise/report.ts +66 -0
  636. package/test/server/httpapi-exercise/routing.ts +96 -0
  637. package/test/server/httpapi-exercise/runner.ts +267 -0
  638. package/test/server/httpapi-exercise/runtime.ts +52 -0
  639. package/test/server/httpapi-exercise/types.ts +123 -0
  640. package/test/server/httpapi-experimental.test.ts +300 -0
  641. package/test/server/httpapi-file.test.ts +76 -0
  642. package/test/server/httpapi-global.test.ts +66 -0
  643. package/test/server/httpapi-instance-context.test.ts +347 -0
  644. package/test/server/httpapi-instance-route-auth.test.ts +84 -0
  645. package/test/server/httpapi-instance.test.ts +265 -0
  646. package/test/server/httpapi-layer.ts +33 -0
  647. package/test/server/httpapi-listen.test.ts +415 -0
  648. package/test/server/httpapi-mcp-oauth.test.ts +73 -0
  649. package/test/server/httpapi-mcp.test.ts +234 -0
  650. package/test/server/httpapi-mdns.test.ts +82 -0
  651. package/test/server/httpapi-promptasync-context.test.ts +222 -0
  652. package/test/server/httpapi-provider.test.ts +403 -0
  653. package/test/server/httpapi-pty.test.ts +275 -0
  654. package/test/server/httpapi-public-openapi.test.ts +297 -0
  655. package/test/server/httpapi-query-schema-drift.test.ts +330 -0
  656. package/test/server/httpapi-reference.test.ts +56 -0
  657. package/test/server/httpapi-schema-error-body.test.ts +165 -0
  658. package/test/server/httpapi-sdk.test.ts +909 -0
  659. package/test/server/httpapi-sync.test.ts +154 -0
  660. package/test/server/httpapi-ui.test.ts +456 -0
  661. package/test/server/httpapi-v2-location.test.ts +85 -0
  662. package/test/server/httpapi-workspace-routing.test.ts +554 -0
  663. package/test/server/httpapi-workspace.test.ts +515 -0
  664. package/test/server/project-copy.test.ts +101 -0
  665. package/test/server/project-init-git.test.ts +117 -0
  666. package/test/server/proxy-util.test.ts +113 -0
  667. package/test/server/sdk-error-shape.test.ts +84 -0
  668. package/test/server/sdk-v1-smoke.test.ts +60 -0
  669. package/test/server/workspace-proxy.test.ts +181 -0
  670. package/test/server/workspace-routing.test.ts +94 -0
  671. package/test/server/worktree-endpoint-repro.test.ts +307 -0
  672. package/test/share/share-next.test.ts +344 -0
  673. package/test/shell/shell.test.ts +99 -0
  674. package/test/skill/discovery.test.ts +139 -0
  675. package/test/skill/skill.test.ts +571 -0
  676. package/test/snapshot/snapshot.test.ts +1121 -0
  677. package/test/storage/storage.test.ts +296 -0
  678. package/test/storage/workspace-time-migration.test.ts +50 -0
  679. package/test/tool/__snapshots__/parameters.test.ts.snap +484 -0
  680. package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
  681. package/test/tool/apply_patch.test.ts +533 -0
  682. package/test/tool/browser.integration.test.ts +141 -0
  683. package/test/tool/desktop.integration.test.ts +129 -0
  684. package/test/tool/desktop.test.ts +85 -0
  685. package/test/tool/edit.test.ts +578 -0
  686. package/test/tool/external-directory.test.ts +167 -0
  687. package/test/tool/fixtures/large-image.png +0 -0
  688. package/test/tool/fixtures/models-api.json +117299 -0
  689. package/test/tool/glob.test.ts +188 -0
  690. package/test/tool/grep.test.ts +266 -0
  691. package/test/tool/lsp.test.ts +181 -0
  692. package/test/tool/parameters.test.ts +293 -0
  693. package/test/tool/question.test.ts +138 -0
  694. package/test/tool/read.test.ts +659 -0
  695. package/test/tool/registry.test.ts +539 -0
  696. package/test/tool/shell.test.ts +1256 -0
  697. package/test/tool/skill.test.ts +135 -0
  698. package/test/tool/task.test.ts +901 -0
  699. package/test/tool/tool-define.test.ts +153 -0
  700. package/test/tool/truncation.test.ts +266 -0
  701. package/test/tool/webfetch.test.ts +113 -0
  702. package/test/tool/websearch.test.ts +99 -0
  703. package/test/tool/write.test.ts +276 -0
  704. package/test/util/data-url.test.ts +14 -0
  705. package/test/util/error.test.ts +16 -0
  706. package/test/util/filesystem.test.ts +656 -0
  707. package/test/util/glob.test.ts +164 -0
  708. package/test/util/iife.test.ts +36 -0
  709. package/test/util/lazy.test.ts +50 -0
  710. package/test/util/log.test.ts +77 -0
  711. package/test/util/module.test.ts +59 -0
  712. package/test/util/process.test.ts +128 -0
  713. package/test/util/repository.test.ts +93 -0
  714. package/test/util/timeout.test.ts +21 -0
  715. package/test/util/wildcard.test.ts +90 -0
  716. package/tsconfig.json +16 -0
@@ -0,0 +1,2037 @@
1
+ import os from "os"
2
+ import { ConfigV1 } from "@octocode-ai/core/v1/config/config"
3
+ import fuzzysort from "fuzzysort"
4
+ import { Config } from "@/config/config"
5
+ import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda"
6
+ import { NoSuchModelError, type Provider as SDK } from "ai"
7
+ import { Log } from "@octocode-ai/core/util/log"
8
+ import { Npm } from "@octocode-ai/core/npm"
9
+ import { Hash } from "@octocode-ai/core/util/hash"
10
+ import { Plugin } from "../plugin"
11
+ import { serviceUse } from "@octocode-ai/core/effect/service-use"
12
+ import { type LanguageModelV3 } from "@ai-sdk/provider"
13
+ import { ModelsDev } from "@octocode-ai/core/models-dev"
14
+ import { Auth } from "../auth"
15
+ import { Env } from "../env"
16
+ import { InstallationVersion } from "@octocode-ai/core/installation/version"
17
+ import { iife } from "@/util/iife"
18
+ import { Global } from "@octocode-ai/core/global"
19
+ import path from "path"
20
+ import { pathToFileURL } from "url"
21
+ import { Effect, Layer, Context, Schema, Types } from "effect"
22
+ import { EffectBridge } from "@/effect/bridge"
23
+ import { InstanceState } from "@/effect/instance-state"
24
+ import { EffectPromise } from "@/effect/promise"
25
+ import { FSUtil } from "@octocode-ai/core/fs-util"
26
+ import { isRecord } from "@/util/record"
27
+ import { optionalOmitUndefined } from "@octocode-ai/core/schema"
28
+ import { ProviderTransform } from "./transform"
29
+ import { ProviderV2 } from "@octocode-ai/core/provider"
30
+ import { ModelV2 } from "@octocode-ai/core/model"
31
+ import { ModelStatus } from "./model-status"
32
+ import { RuntimeFlags } from "@/effect/runtime-flags"
33
+ import { ProviderError } from "./error"
34
+
35
+ const log = Log.create({ service: "provider" })
36
+ const OPENAI_HEADER_TIMEOUT_DEFAULT = 10_000
37
+
38
+ // Provider ID aliases: maps user-facing provider IDs to their models.dev equivalents.
39
+ // This allows users to use custom provider names (e.g. "google-ai") while still
40
+ // getting correct model limits, capabilities, and pricing from models.dev.
41
+ const PROVIDER_ALIASES: Record<string, string> = {
42
+ "google-ai": "google",
43
+ "google-gemini": "google",
44
+ "google-vertex-ai": "google-vertex",
45
+ "anthropic-claude": "anthropic",
46
+ "openai-chatgpt": "openai",
47
+ "azure-openai": "azure",
48
+ "github-ai": "github-copilot",
49
+ "hf": "huggingface",
50
+ "hf-inference": "huggingface",
51
+ "deepseek-ai": "deepseek",
52
+ "mistral-ai": "mistral",
53
+ "cohere-ai": "cohere",
54
+ "nvidia-nim": "nvidia",
55
+ "xai-grok": "xai",
56
+ "x-ai": "xai",
57
+ "meta-llama": "llama",
58
+ "amazon-aws": "amazon-bedrock",
59
+ "cloudflare": "cloudflare-workers-ai",
60
+ }
61
+
62
+ function resolveProviderID(providerID: string, database: Record<string, Info>): string {
63
+ if (database[providerID]) return providerID
64
+ const alias = PROVIDER_ALIASES[providerID]
65
+ if (alias && database[alias]) return alias
66
+ return providerID
67
+ }
68
+
69
+ function wrapSSE(res: Response, ms: number, ctl: AbortController) {
70
+ if (typeof ms !== "number" || ms <= 0) return res
71
+ if (!res.body) return res
72
+ if (!res.headers.get("content-type")?.includes("text/event-stream")) return res
73
+
74
+ const reader = res.body.getReader()
75
+ const body = new ReadableStream<Uint8Array>({
76
+ async pull(ctrl) {
77
+ const part = await new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => {
78
+ const id = setTimeout(() => {
79
+ const err = new ProviderError.ResponseStreamError("SSE read timed out")
80
+ ctl.abort(err)
81
+ void reader.cancel(err)
82
+ reject(err)
83
+ }, ms)
84
+
85
+ reader.read().then(
86
+ (part) => {
87
+ clearTimeout(id)
88
+ resolve(part)
89
+ },
90
+ (err) => {
91
+ clearTimeout(id)
92
+ reject(err)
93
+ },
94
+ )
95
+ })
96
+
97
+ if (part.done) {
98
+ ctrl.close()
99
+ return
100
+ }
101
+
102
+ ctrl.enqueue(part.value)
103
+ },
104
+ async cancel(reason) {
105
+ ctl.abort(reason)
106
+ await reader.cancel(reason)
107
+ },
108
+ })
109
+
110
+ return new Response(body, {
111
+ headers: new Headers(res.headers),
112
+ status: res.status,
113
+ statusText: res.statusText,
114
+ })
115
+ }
116
+
117
+ function timeoutController(ms: number) {
118
+ const ctl = new AbortController()
119
+ const id = setTimeout(() => ctl.abort(new ProviderError.HeaderTimeoutError(ms)), ms)
120
+ return {
121
+ signal: ctl.signal,
122
+ clear: () => clearTimeout(id),
123
+ }
124
+ }
125
+
126
+ function googleVertexAnthropicBaseURL(project: string | undefined, location: string | undefined) {
127
+ if (!project) return
128
+ if (location !== "eu" && location !== "us") return
129
+ // Continental multi-regions require Regional Endpoint Platform domains.
130
+ return `https://aiplatform.${location}.rep.googleapis.com/v1/projects/${project}/locations/${location}/publishers/anthropic/models`
131
+ }
132
+
133
+ type BundledSDK = {
134
+ languageModel(modelId: string): LanguageModelV3
135
+ chat?: (modelId: string) => LanguageModelV3
136
+ responses?: (modelId: string) => LanguageModelV3
137
+ }
138
+
139
+ const BUNDLED_PROVIDERS: Record<string, () => Promise<(opts: any) => BundledSDK>> = {
140
+ "@ai-sdk/amazon-bedrock": () => import("@ai-sdk/amazon-bedrock").then((m) => m.createAmazonBedrock),
141
+ "@ai-sdk/amazon-bedrock/mantle": () => import("@ai-sdk/amazon-bedrock/mantle").then((m) => m.createBedrockMantle),
142
+ "@ai-sdk/anthropic": () => import("@ai-sdk/anthropic").then((m) => m.createAnthropic),
143
+ "@ai-sdk/azure": () => import("@ai-sdk/azure").then((m) => m.createAzure),
144
+ "@ai-sdk/google": () => import("@ai-sdk/google").then((m) => m.createGoogleGenerativeAI),
145
+ "@ai-sdk/google-vertex": () => import("@ai-sdk/google-vertex").then((m) => m.createVertex),
146
+ "@ai-sdk/google-vertex/anthropic": () =>
147
+ import("@ai-sdk/google-vertex/anthropic").then((m) => m.createVertexAnthropic),
148
+ "@ai-sdk/openai": () => import("@ai-sdk/openai").then((m) => m.createOpenAI),
149
+ "@ai-sdk/openai-compatible": () => import("@ai-sdk/openai-compatible").then((m) => m.createOpenAICompatible),
150
+ "@openrouter/ai-sdk-provider": () => import("@openrouter/ai-sdk-provider").then((m) => m.createOpenRouter),
151
+ "@ai-sdk/xai": () => import("@ai-sdk/xai").then((m) => m.createXai),
152
+ "@ai-sdk/mistral": () => import("@ai-sdk/mistral").then((m) => m.createMistral),
153
+ "@ai-sdk/groq": () => import("@ai-sdk/groq").then((m) => m.createGroq),
154
+ "@ai-sdk/deepinfra": () => import("@ai-sdk/deepinfra").then((m) => m.createDeepInfra),
155
+ "@ai-sdk/cerebras": () => import("@ai-sdk/cerebras").then((m) => m.createCerebras),
156
+ "@ai-sdk/cohere": () => import("@ai-sdk/cohere").then((m) => m.createCohere),
157
+ "@ai-sdk/gateway": () => import("@ai-sdk/gateway").then((m) => m.createGateway),
158
+ "@ai-sdk/togetherai": () => import("@ai-sdk/togetherai").then((m) => m.createTogetherAI),
159
+ "@ai-sdk/perplexity": () => import("@ai-sdk/perplexity").then((m) => m.createPerplexity),
160
+ "@ai-sdk/vercel": () => import("@ai-sdk/vercel").then((m) => m.createVercel),
161
+ "@ai-sdk/alibaba": () => import("@ai-sdk/alibaba").then((m) => m.createAlibaba),
162
+ "gitlab-ai-provider": () => import("gitlab-ai-provider").then((m) => m.createGitLab),
163
+ "@ai-sdk/github-copilot": () =>
164
+ import("@octocode-ai/core/github-copilot/copilot-provider").then((m) => m.createOpenaiCompatible),
165
+ "venice-ai-sdk-provider": () => import("venice-ai-sdk-provider").then((m) => m.createVenice),
166
+ }
167
+
168
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>, model?: Model) => Promise<any>
169
+ type CustomVarsLoader = (options: Record<string, any>) => Record<string, string>
170
+ type CustomDiscoverModels = () => Promise<Record<string, Model>>
171
+ type CustomLoader = (provider: Info) => Effect.Effect<{
172
+ autoload: boolean
173
+ getModel?: CustomModelLoader
174
+ vars?: CustomVarsLoader
175
+ options?: Record<string, any>
176
+ discoverModels?: CustomDiscoverModels
177
+ }>
178
+
179
+ type CustomDep = {
180
+ auth: (id: string) => Effect.Effect<Auth.Info | undefined>
181
+ config: () => Effect.Effect<ConfigV1.Info>
182
+ env: () => Effect.Effect<Record<string, string | undefined>>
183
+ get: (key: string) => Effect.Effect<string | undefined>
184
+ }
185
+
186
+ function selectAzureLanguageModel(sdk: any, modelID: string, useChat: boolean) {
187
+ if (useChat && sdk.chat) return sdk.chat(modelID)
188
+ if (sdk.responses) return sdk.responses(modelID)
189
+ if (sdk.messages) return sdk.messages(modelID)
190
+ if (sdk.chat) return sdk.chat(modelID)
191
+ return sdk.languageModel(modelID)
192
+ }
193
+
194
+ function selectBedrockMantleLanguageModel(sdk: BundledSDK, modelID: string) {
195
+ if (modelID === "openai.gpt-oss-safeguard-20b" || modelID === "openai.gpt-oss-safeguard-120b")
196
+ return sdk.chat?.(modelID) ?? sdk.languageModel(modelID)
197
+ return sdk.responses?.(modelID) ?? sdk.languageModel(modelID)
198
+ }
199
+
200
+ function custom(dep: CustomDep): Record<string, CustomLoader> {
201
+ return {
202
+ anthropic: () =>
203
+ Effect.succeed({
204
+ autoload: false,
205
+ options: {
206
+ headers: {
207
+ "anthropic-beta": "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
208
+ },
209
+ },
210
+ }),
211
+ octocode: Effect.fnUntraced(function* (input: Info) {
212
+ const env = yield* dep.env()
213
+ const hasKey = iife(() => {
214
+ if (input.env.some((item) => env[item])) return true
215
+ return false
216
+ })
217
+ const ok =
218
+ hasKey ||
219
+ Boolean(yield* dep.auth(input.id)) ||
220
+ Boolean((yield* dep.config()).provider?.["octo"]?.options?.apiKey)
221
+
222
+ if (!ok) {
223
+ for (const [key, value] of Object.entries(input.models)) {
224
+ if (value.cost.input === 0) continue
225
+ delete input.models[key]
226
+ }
227
+ }
228
+
229
+ return {
230
+ autoload: Object.keys(input.models).length > 0,
231
+ options: ok ? {} : { apiKey: "public" },
232
+ }
233
+ }),
234
+ openai: () =>
235
+ Effect.succeed({
236
+ autoload: false,
237
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
238
+ return sdk.responses(modelID)
239
+ },
240
+ options: { headerTimeout: OPENAI_HEADER_TIMEOUT_DEFAULT },
241
+ }),
242
+ xai: () =>
243
+ Effect.succeed({
244
+ autoload: false,
245
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
246
+ return sdk.responses(modelID)
247
+ },
248
+ options: {},
249
+ }),
250
+ "github-copilot": () =>
251
+ Effect.succeed({
252
+ autoload: false,
253
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
254
+ if (sdk.responses === undefined && sdk.chat === undefined) return sdk.languageModel(modelID)
255
+ const match = /^gpt-(\d+)/.exec(modelID)
256
+ if (match && Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")) return sdk.responses(modelID)
257
+ return sdk.chat(modelID)
258
+ },
259
+ options: {},
260
+ }),
261
+ azure: Effect.fnUntraced(function* (provider: Info) {
262
+ const env = yield* dep.env()
263
+ const auth = yield* dep.auth(provider.id)
264
+ const resource = iife(() => {
265
+ return [
266
+ provider.options?.resourceName,
267
+ auth?.type === "api" ? auth.metadata?.resourceName : undefined,
268
+ env["AZURE_RESOURCE_NAME"],
269
+ ].find((name) => typeof name === "string" && name.trim() !== "")
270
+ })
271
+
272
+ if (!resource && !provider.options?.baseURL) {
273
+ return {
274
+ autoload: false,
275
+ async getModel() {
276
+ throw new Error(
277
+ "AZURE_RESOURCE_NAME is missing, set it using env var or reconnecting the azure provider and setting it",
278
+ )
279
+ },
280
+ }
281
+ }
282
+
283
+ return {
284
+ autoload: false,
285
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
286
+ return selectAzureLanguageModel(sdk, modelID, Boolean(options?.["useCompletionUrls"]))
287
+ },
288
+ options: {
289
+ resourceName: resource,
290
+ },
291
+ vars(_options): Record<string, string> {
292
+ if (resource) {
293
+ return {
294
+ AZURE_RESOURCE_NAME: resource,
295
+ }
296
+ }
297
+ return {}
298
+ },
299
+ }
300
+ }),
301
+ "azure-cognitive-services": Effect.fnUntraced(function* () {
302
+ const resourceName = yield* dep.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
303
+ return {
304
+ autoload: false,
305
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
306
+ return selectAzureLanguageModel(sdk, modelID, Boolean(options?.["useCompletionUrls"]))
307
+ },
308
+ options: {
309
+ baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
310
+ },
311
+ }
312
+ }),
313
+ "amazon-bedrock": Effect.fnUntraced(function* () {
314
+ const providerConfig = (yield* dep.config()).provider?.["amazon-bedrock"]
315
+ const auth = yield* dep.auth("amazon-bedrock")
316
+ const env = yield* dep.env()
317
+
318
+ // Region precedence: 1) config file, 2) env var, 3) default
319
+ const configRegion = providerConfig?.options?.region
320
+ const envRegion = env["AWS_REGION"]
321
+ const defaultRegion = configRegion ?? envRegion ?? "us-east-1"
322
+
323
+ // Profile: config file takes precedence over env var
324
+ const configProfile = providerConfig?.options?.profile
325
+ const envProfile = env["AWS_PROFILE"]
326
+ const profile = configProfile ?? envProfile
327
+
328
+ const awsAccessKeyId = env["AWS_ACCESS_KEY_ID"]
329
+ const configApiKey = providerConfig?.options?.apiKey
330
+
331
+ // TODO: Using process.env directly because Env.set only updates a process.env shallow copy,
332
+ // until the scope of the Env API is clarified (test only or runtime?)
333
+ const awsBearerToken = iife(() => {
334
+ const envToken = process.env.AWS_BEARER_TOKEN_BEDROCK
335
+ if (envToken) return envToken
336
+ if (auth?.type === "api") {
337
+ process.env.AWS_BEARER_TOKEN_BEDROCK = auth.key
338
+ return auth.key
339
+ }
340
+ return undefined
341
+ })
342
+
343
+ const awsWebIdentityTokenFile = env["AWS_WEB_IDENTITY_TOKEN_FILE"]
344
+
345
+ const containerCreds = Boolean(
346
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,
347
+ )
348
+
349
+ if (
350
+ !profile &&
351
+ !awsAccessKeyId &&
352
+ !awsBearerToken &&
353
+ !configApiKey &&
354
+ !awsWebIdentityTokenFile &&
355
+ !containerCreds
356
+ )
357
+ return { autoload: false }
358
+
359
+ const { fromNodeProviderChain } = yield* Effect.promise(() => import("@aws-sdk/credential-providers"))
360
+
361
+ const providerOptions: Record<string, any> = {
362
+ region: defaultRegion,
363
+ }
364
+
365
+ // Only use credential chain if no bearer token exists
366
+ // Bearer token takes precedence over credential chain (profiles, access keys, IAM roles, web identity tokens)
367
+ if (!awsBearerToken && !configApiKey) {
368
+ // Build credential provider options (only pass profile if specified)
369
+ const credentialProviderOptions = profile ? { profile } : {}
370
+
371
+ providerOptions.credentialProvider = fromNodeProviderChain(credentialProviderOptions)
372
+ }
373
+
374
+ // Add custom endpoint if specified (endpoint takes precedence over baseURL)
375
+ const endpoint = providerConfig?.options?.endpoint ?? providerConfig?.options?.baseURL
376
+ if (endpoint) {
377
+ providerOptions.baseURL = endpoint
378
+ }
379
+
380
+ return {
381
+ autoload: true,
382
+ options: providerOptions,
383
+ vars(options: Record<string, any>) {
384
+ return { AWS_REGION: options.region ?? defaultRegion }
385
+ },
386
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>, model?: Model) {
387
+ if (model?.api.npm === "@ai-sdk/amazon-bedrock/mantle") return selectBedrockMantleLanguageModel(sdk, modelID)
388
+
389
+ // Skip region prefixing if model already has a cross-region inference profile prefix
390
+ // Models from models.dev may already include prefixes like us., eu., global., etc.
391
+ const crossRegionPrefixes = ["global.", "us.", "eu.", "jp.", "apac.", "au."]
392
+ if (crossRegionPrefixes.some((prefix) => modelID.startsWith(prefix))) {
393
+ return sdk.languageModel(modelID)
394
+ }
395
+
396
+ // Region resolution precedence (highest to lowest):
397
+ // 1. options.region from octo.json provider config
398
+ // 2. defaultRegion from AWS_REGION environment variable
399
+ // 3. Default "us-east-1" (baked into defaultRegion)
400
+ const region = options?.region ?? defaultRegion
401
+
402
+ let regionPrefix = region.split("-")[0]
403
+
404
+ switch (regionPrefix) {
405
+ case "us": {
406
+ const modelRequiresPrefix = [
407
+ "nova-micro",
408
+ "nova-lite",
409
+ "nova-pro",
410
+ "nova-premier",
411
+ "nova-2",
412
+ "claude",
413
+ "deepseek",
414
+ ].some((m) => modelID.includes(m))
415
+ const isGovCloud = region.startsWith("us-gov")
416
+ if (modelRequiresPrefix && !isGovCloud) {
417
+ modelID = `${regionPrefix}.${modelID}`
418
+ }
419
+ break
420
+ }
421
+ case "eu": {
422
+ const regionRequiresPrefix = [
423
+ "eu-west-1",
424
+ "eu-west-2",
425
+ "eu-west-3",
426
+ "eu-north-1",
427
+ "eu-central-1",
428
+ "eu-south-1",
429
+ "eu-south-2",
430
+ ].some((r) => region.includes(r))
431
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
432
+ modelID.includes(m),
433
+ )
434
+ if (regionRequiresPrefix && modelRequiresPrefix) {
435
+ modelID = `${regionPrefix}.${modelID}`
436
+ }
437
+ break
438
+ }
439
+ case "ap": {
440
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
441
+ const isTokyoRegion = region === "ap-northeast-1"
442
+ if (
443
+ isAustraliaRegion &&
444
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
445
+ ) {
446
+ regionPrefix = "au"
447
+ modelID = `${regionPrefix}.${modelID}`
448
+ } else if (isTokyoRegion) {
449
+ // Tokyo region uses jp. prefix for cross-region inference
450
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
451
+ modelID.includes(m),
452
+ )
453
+ if (modelRequiresPrefix) {
454
+ regionPrefix = "jp"
455
+ modelID = `${regionPrefix}.${modelID}`
456
+ }
457
+ } else {
458
+ // Other APAC regions use apac. prefix
459
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
460
+ modelID.includes(m),
461
+ )
462
+ if (modelRequiresPrefix) {
463
+ regionPrefix = "apac"
464
+ modelID = `${regionPrefix}.${modelID}`
465
+ }
466
+ }
467
+ break
468
+ }
469
+ }
470
+
471
+ return sdk.languageModel(modelID)
472
+ },
473
+ }
474
+ }),
475
+ llmgateway: () =>
476
+ Effect.succeed({
477
+ autoload: false,
478
+ options: {
479
+ headers: {
480
+ "HTTP-Referer": "https://octocode.ai/",
481
+ "X-Title": "octo",
482
+ "X-Source": "octo",
483
+ },
484
+ },
485
+ }),
486
+ openrouter: () =>
487
+ Effect.succeed({
488
+ autoload: false,
489
+ options: {
490
+ headers: {
491
+ "HTTP-Referer": "https://octocode.ai/",
492
+ "X-Title": "octo",
493
+ },
494
+ },
495
+ }),
496
+ nvidia: (provider) =>
497
+ Effect.succeed({
498
+ autoload: provider.source === "config",
499
+ options: {
500
+ headers: {
501
+ "HTTP-Referer": "https://octocode.ai/",
502
+ "X-Title": "octo",
503
+ "X-BILLING-INVOKE-ORIGIN": "OctoCode",
504
+ },
505
+ },
506
+ }),
507
+ vercel: () =>
508
+ Effect.succeed({
509
+ autoload: false,
510
+ options: {
511
+ headers: {
512
+ "http-referer": "https://octocode.ai/",
513
+ "x-title": "octo",
514
+ },
515
+ },
516
+ }),
517
+ "google-vertex": Effect.fnUntraced(function* (provider: Info) {
518
+ const env = yield* dep.env()
519
+ // models.dev advertises GOOGLE_VERTEX_PROJECT for Vertex; keep the wider
520
+ // Google Cloud project env names as fallbacks for existing ADC setups.
521
+ const project =
522
+ provider.options?.project ??
523
+ env["GOOGLE_VERTEX_PROJECT"] ??
524
+ env["GOOGLE_CLOUD_PROJECT"] ??
525
+ env["GCP_PROJECT"] ??
526
+ env["GCLOUD_PROJECT"]
527
+
528
+ const location = String(
529
+ provider.options?.location ??
530
+ env["GOOGLE_VERTEX_LOCATION"] ??
531
+ env["GOOGLE_CLOUD_LOCATION"] ??
532
+ env["VERTEX_LOCATION"] ??
533
+ "us-central1",
534
+ )
535
+
536
+ const autoload = Boolean(project)
537
+ if (!autoload) return { autoload: false }
538
+ return {
539
+ autoload: true,
540
+ vars(_options: Record<string, any>) {
541
+ const endpoint = location === "global" ? "aiplatform.googleapis.com" : `${location}-aiplatform.googleapis.com`
542
+ return {
543
+ ...(project && { GOOGLE_VERTEX_PROJECT: project }),
544
+ GOOGLE_VERTEX_LOCATION: location,
545
+ GOOGLE_VERTEX_ENDPOINT: endpoint,
546
+ }
547
+ },
548
+ options: {
549
+ project,
550
+ location,
551
+ fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
552
+ const { GoogleAuth } = await import("google-auth-library")
553
+ const auth = new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] })
554
+ const client = await auth.getClient()
555
+ const token = await client.getAccessToken()
556
+
557
+ const headers = new Headers(init?.headers)
558
+ headers.set("Authorization", `Bearer ${token.token}`)
559
+
560
+ return fetch(input, { ...init, headers })
561
+ },
562
+ },
563
+ async getModel(sdk: any, modelID: string) {
564
+ const id = String(modelID).trim()
565
+ return sdk.languageModel(id)
566
+ },
567
+ }
568
+ }),
569
+ "google-vertex-anthropic": Effect.fnUntraced(function* () {
570
+ const env = yield* dep.env()
571
+ const project = env["GOOGLE_CLOUD_PROJECT"] ?? env["GCP_PROJECT"] ?? env["GCLOUD_PROJECT"]
572
+ const location = env["GOOGLE_CLOUD_LOCATION"] ?? env["VERTEX_LOCATION"] ?? "global"
573
+ const autoload = Boolean(project)
574
+ if (!autoload) return { autoload: false }
575
+ const baseURL = googleVertexAnthropicBaseURL(project, location)
576
+ return {
577
+ autoload: true,
578
+ options: {
579
+ project,
580
+ location,
581
+ ...(baseURL && { baseURL }),
582
+ },
583
+ async getModel(sdk: any, modelID) {
584
+ const id = String(modelID).trim()
585
+ return sdk.languageModel(id)
586
+ },
587
+ }
588
+ }),
589
+ "sap-ai-core": Effect.fnUntraced(function* () {
590
+ const auth = yield* dep.auth("sap-ai-core")
591
+ // TODO: Using process.env directly because Env.set only updates a shallow copy (not process.env),
592
+ // until the scope of the Env API is clarified (test only or runtime?)
593
+ const envServiceKey = iife(() => {
594
+ const envAICoreServiceKey = process.env.AICORE_SERVICE_KEY
595
+ if (envAICoreServiceKey) return envAICoreServiceKey
596
+ if (auth?.type === "api") {
597
+ process.env.AICORE_SERVICE_KEY = auth.key
598
+ return auth.key
599
+ }
600
+ return undefined
601
+ })
602
+ const deploymentId = process.env.AICORE_DEPLOYMENT_ID
603
+ const resourceGroup = process.env.AICORE_RESOURCE_GROUP
604
+
605
+ return {
606
+ autoload: !!envServiceKey,
607
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
608
+ async getModel(sdk: any, modelID: string) {
609
+ return sdk(modelID)
610
+ },
611
+ }
612
+ }),
613
+ zenmux: () =>
614
+ Effect.succeed({
615
+ autoload: false,
616
+ options: {
617
+ headers: {
618
+ "HTTP-Referer": "https://octocode.ai/",
619
+ "X-Title": "octo",
620
+ },
621
+ },
622
+ }),
623
+ gitlab: Effect.fnUntraced(function* (input: Info) {
624
+ const {
625
+ VERSION: GITLAB_PROVIDER_VERSION,
626
+ isWorkflowModel,
627
+ discoverWorkflowModels,
628
+ } = yield* Effect.promise(() => import("gitlab-ai-provider"))
629
+
630
+ const instanceUrl = (yield* dep.get("GITLAB_INSTANCE_URL")) || "https://gitlab.com"
631
+
632
+ const auth = yield* dep.auth(input.id)
633
+ const apiKey = auth?.type === "oauth" ? auth.access : auth?.type === "api" ? auth.key : undefined
634
+ const token = apiKey ?? (yield* dep.get("GITLAB_TOKEN"))
635
+
636
+ const providerConfig = (yield* dep.config()).provider?.["gitlab"]
637
+ const directory = yield* InstanceState.directory
638
+
639
+ const aiGatewayHeaders = {
640
+ "User-Agent": `octocode/${InstallationVersion} gitlab-ai-provider/${GITLAB_PROVIDER_VERSION} (${os.platform()} ${os.release()}; ${os.arch()})`,
641
+ "anthropic-beta": "context-1m-2025-08-07",
642
+ ...providerConfig?.options?.aiGatewayHeaders,
643
+ }
644
+
645
+ const featureFlags = {
646
+ duo_agent_platform_agentic_chat: true,
647
+ duo_agent_platform: true,
648
+ ...providerConfig?.options?.featureFlags,
649
+ }
650
+
651
+ return {
652
+ autoload: !!token,
653
+ options: {
654
+ instanceUrl,
655
+ apiKey: token,
656
+ aiGatewayHeaders,
657
+ featureFlags,
658
+ },
659
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
660
+ if (modelID.startsWith("duo-workflow-")) {
661
+ const workflowRef = typeof options?.workflowRef === "string" ? options.workflowRef : undefined
662
+ // Use the static mapping if it exists, otherwise use duo-workflow with selectedModelRef
663
+ const sdkModelID = isWorkflowModel(modelID) ? modelID : "duo-workflow"
664
+ const workflowDefinition =
665
+ typeof options?.workflowDefinition === "string" ? options.workflowDefinition : undefined
666
+ const model = sdk.workflowChat(sdkModelID, {
667
+ featureFlags,
668
+ workflowDefinition,
669
+ })
670
+ if (workflowRef) {
671
+ model.selectedModelRef = workflowRef
672
+ }
673
+ return model
674
+ }
675
+ return sdk.agenticChat(modelID, {
676
+ aiGatewayHeaders,
677
+ featureFlags,
678
+ })
679
+ },
680
+ async discoverModels(): Promise<Record<string, Model>> {
681
+ if (!apiKey) {
682
+ log.info("gitlab model discovery skipped: no apiKey")
683
+ return {}
684
+ }
685
+
686
+ try {
687
+ const token = apiKey
688
+ const getHeaders = (): Record<string, string> =>
689
+ auth?.type === "api" ? { "PRIVATE-TOKEN": token } : { Authorization: `Bearer ${token}` }
690
+
691
+ log.info("gitlab model discovery starting", { instanceUrl })
692
+ const result = await discoverWorkflowModels({ instanceUrl, getHeaders }, { workingDirectory: directory })
693
+
694
+ if (!result.models.length) {
695
+ log.info("gitlab model discovery skipped: no models found", {
696
+ project: result.project
697
+ ? {
698
+ id: result.project.id,
699
+ path: result.project.pathWithNamespace,
700
+ }
701
+ : null,
702
+ })
703
+ return {}
704
+ }
705
+
706
+ const models: Record<string, Model> = {}
707
+ for (const m of result.models) {
708
+ if (!input.models[m.id]) {
709
+ models[m.id] = {
710
+ id: ModelV2.ID.make(m.id),
711
+ providerID: ProviderV2.ID.make("gitlab"),
712
+ name: `Agent Platform (${m.name})`,
713
+ family: "",
714
+ api: {
715
+ id: m.id,
716
+ url: instanceUrl,
717
+ npm: "gitlab-ai-provider",
718
+ },
719
+ status: "active",
720
+ headers: {},
721
+ options: { workflowRef: m.ref },
722
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
723
+ limit: { context: m.context, output: m.output },
724
+ capabilities: {
725
+ temperature: false,
726
+ reasoning: true,
727
+ attachment: true,
728
+ toolcall: true,
729
+ input: {
730
+ text: true,
731
+ audio: false,
732
+ image: true,
733
+ video: false,
734
+ pdf: true,
735
+ },
736
+ output: {
737
+ text: true,
738
+ audio: false,
739
+ image: false,
740
+ video: false,
741
+ pdf: false,
742
+ },
743
+ interleaved: false,
744
+ },
745
+ release_date: "",
746
+ variants: {},
747
+ }
748
+ }
749
+ }
750
+
751
+ log.info("gitlab model discovery complete", {
752
+ count: Object.keys(models).length,
753
+ models: Object.keys(models),
754
+ })
755
+ return models
756
+ } catch (e) {
757
+ log.warn("gitlab model discovery failed", { error: e })
758
+ return {}
759
+ }
760
+ },
761
+ }
762
+ }),
763
+ "cloudflare-workers-ai": Effect.fnUntraced(function* (input: Info) {
764
+ // When baseURL is already configured (e.g. corporate config routing through a proxy/gateway),
765
+ // skip the account ID check because the URL is already fully specified.
766
+ if (input.options?.baseURL) return { autoload: false }
767
+
768
+ const auth = yield* dep.auth(input.id)
769
+ const env = yield* dep.env()
770
+ const accountId = env["CLOUDFLARE_ACCOUNT_ID"] || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
771
+ if (!accountId)
772
+ return {
773
+ autoload: false,
774
+ async getModel() {
775
+ throw new Error(
776
+ "CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>",
777
+ )
778
+ },
779
+ }
780
+
781
+ const apiKey = env["CLOUDFLARE_API_KEY"] || (auth?.type === "api" ? auth.key : undefined)
782
+
783
+ return {
784
+ autoload: !!apiKey,
785
+ options: {
786
+ apiKey,
787
+ headers: {
788
+ "User-Agent": `octocode/${InstallationVersion} cloudflare-workers-ai (${os.platform()} ${os.release()}; ${os.arch()})`,
789
+ },
790
+ },
791
+ async getModel(sdk: any, modelID: string) {
792
+ return sdk.languageModel(modelID)
793
+ },
794
+ vars(_options) {
795
+ return {
796
+ CLOUDFLARE_ACCOUNT_ID: accountId,
797
+ }
798
+ },
799
+ }
800
+ }),
801
+ "cloudflare-ai-gateway": Effect.fnUntraced(function* (input: Info) {
802
+ // When baseURL is already configured (e.g. corporate config), skip the ID checks.
803
+ if (input.options?.baseURL) return { autoload: false }
804
+
805
+ const auth = yield* dep.auth(input.id)
806
+ const env = yield* dep.env()
807
+ const accountId = env["CLOUDFLARE_ACCOUNT_ID"] || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
808
+ // The Cloudflare auth prompt stores this value as gatewayId metadata.
809
+ const gateway = env["CLOUDFLARE_GATEWAY_ID"] || (auth?.type === "api" ? auth.metadata?.gatewayId : undefined)
810
+
811
+ if (!accountId || !gateway) {
812
+ const missing = [
813
+ !accountId ? "CLOUDFLARE_ACCOUNT_ID" : undefined,
814
+ !gateway ? "CLOUDFLARE_GATEWAY_ID" : undefined,
815
+ ].filter((x): x is string => Boolean(x))
816
+ return {
817
+ autoload: false,
818
+ async getModel() {
819
+ throw new Error(
820
+ `${missing.join(" and ")} missing. Set with: ${missing.map((x) => `export ${x}=<value>`).join(" && ")}`,
821
+ )
822
+ },
823
+ }
824
+ }
825
+
826
+ // Get API token from env or auth - required for authenticated gateways
827
+ const apiToken =
828
+ env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"] || (auth?.type === "api" ? auth.key : undefined)
829
+
830
+ if (!apiToken) {
831
+ throw new Error(
832
+ "CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. " +
833
+ "Set it via environment variable or run `octo auth cloudflare-ai-gateway`.",
834
+ )
835
+ }
836
+
837
+ // Use official ai-gateway-provider package (v2.x for AI SDK v5 compatibility)
838
+ const { createAiGateway } = yield* Effect.promise(() => import("ai-gateway-provider"))
839
+ const { createUnified } = yield* Effect.promise(() => import("ai-gateway-provider/providers/unified"))
840
+
841
+ const metadata = iife(() => {
842
+ if (input.options?.metadata) return input.options.metadata
843
+ try {
844
+ return JSON.parse(input.options?.headers?.["cf-aig-metadata"])
845
+ } catch {
846
+ return undefined
847
+ }
848
+ })
849
+ const opts = {
850
+ metadata,
851
+ cacheTtl: input.options?.cacheTtl,
852
+ cacheKey: input.options?.cacheKey,
853
+ skipCache: input.options?.skipCache,
854
+ collectLog: input.options?.collectLog,
855
+ headers: {
856
+ "User-Agent": `octocode/${InstallationVersion} cloudflare-ai-gateway (${os.platform()} ${os.release()}; ${os.arch()})`,
857
+ },
858
+ }
859
+
860
+ const aigateway = createAiGateway({
861
+ accountId,
862
+ gateway,
863
+ apiKey: apiToken,
864
+ ...(Object.values(opts).some((v) => v !== undefined) ? { options: opts } : {}),
865
+ })
866
+ const unified = createUnified()
867
+
868
+ return {
869
+ autoload: true,
870
+ async getModel(_sdk: any, modelID: string, _options?: Record<string, any>) {
871
+ // Model IDs use Unified API format: provider/model (e.g., "anthropic/claude-sonnet-4-5")
872
+ return aigateway(unified(modelID))
873
+ },
874
+ options: {},
875
+ }
876
+ }),
877
+ cerebras: () =>
878
+ Effect.succeed({
879
+ autoload: false,
880
+ options: {
881
+ headers: {
882
+ "X-Cerebras-3rd-Party-Integration": "octo",
883
+ },
884
+ },
885
+ }),
886
+ kilo: () =>
887
+ Effect.succeed({
888
+ autoload: false,
889
+ options: {
890
+ headers: {
891
+ "HTTP-Referer": "https://octocode.ai/",
892
+ "X-Title": "octo",
893
+ },
894
+ },
895
+ }),
896
+ "snowflake-cortex": Effect.fnUntraced(function* (input: Info) {
897
+ const env = yield* dep.env()
898
+ const auth = yield* dep.auth(input.id)
899
+
900
+ const account =
901
+ env["SNOWFLAKE_ACCOUNT"] ??
902
+ (auth?.type === "api" ? auth.metadata?.account : undefined) ??
903
+ input.options?.account
904
+
905
+ const pat = env["SNOWFLAKE_CORTEX_PAT"] ?? (auth?.type === "api" ? auth.key : undefined) ?? input.options?.apiKey
906
+
907
+ if (!account || !pat) {
908
+ const missing = [!account && "SNOWFLAKE_ACCOUNT", !pat && "SNOWFLAKE_CORTEX_PAT"].filter(Boolean).join(", ")
909
+ return {
910
+ autoload: false,
911
+ async getModel() {
912
+ throw new Error(
913
+ `Snowflake Cortex: missing credentials (${missing}). Set via env var, octo auth, or provider options.`,
914
+ )
915
+ },
916
+ }
917
+ }
918
+
919
+ const baseURL = `https://${account}.snowflakecomputing.com/api/v2/cortex/v1`
920
+
921
+ return {
922
+ autoload: input.source === "config",
923
+ options: {
924
+ baseURL,
925
+ apiKey: pat,
926
+ fetch: async (url: RequestInfo | URL, init?: RequestInit) => {
927
+ if (init?.body && typeof init.body === "string") {
928
+ try {
929
+ const body = JSON.parse(init.body)
930
+ if ("max_tokens" in body) {
931
+ body.max_completion_tokens = body.max_tokens
932
+ delete body.max_tokens
933
+ init = { ...init, body: JSON.stringify(body) }
934
+ }
935
+ } catch {}
936
+ }
937
+
938
+ const response = await fetch(url, init)
939
+
940
+ // Cortex returns 400 "conversation complete" as a normal stop condition
941
+ if (!response.ok && response.status === 400) {
942
+ try {
943
+ const errorData = await response.clone().json()
944
+ const errorMessage = String(errorData.message || errorData.error || "")
945
+ if (errorMessage.toLowerCase().includes("conversation complete")) {
946
+ return new Response(
947
+ JSON.stringify({
948
+ choices: [{ finish_reason: "stop", message: { content: "", role: "assistant" } }],
949
+ }),
950
+ { status: 200, headers: new Headers({ "content-type": "application/json" }) },
951
+ )
952
+ }
953
+ } catch {}
954
+ }
955
+
956
+ // Cortex returns role:"" in streaming deltas; the AI SDK schema requires "assistant"
957
+ if (response.body && response.headers.get("content-type")?.includes("text/event-stream")) {
958
+ const reader = response.body.getReader()
959
+ const encoder = new TextEncoder()
960
+ const decoder = new TextDecoder()
961
+ const stream = new ReadableStream({
962
+ async pull(ctrl) {
963
+ const { done, value } = await reader.read()
964
+ if (done) {
965
+ ctrl.close()
966
+ return
967
+ }
968
+ const text = decoder.decode(value, { stream: true })
969
+ ctrl.enqueue(encoder.encode(text.replace(/"role"\s*:\s*""/g, '"role":"assistant"')))
970
+ },
971
+ cancel() {
972
+ reader.cancel()
973
+ },
974
+ })
975
+ return new Response(stream, { headers: response.headers, status: response.status })
976
+ }
977
+
978
+ return response
979
+ },
980
+ },
981
+ }
982
+ }),
983
+ }
984
+ }
985
+
986
+ const ProviderApiInfo = Schema.Struct({
987
+ id: Schema.String,
988
+ url: Schema.String,
989
+ npm: Schema.String,
990
+ })
991
+
992
+ const ProviderModalities = Schema.Struct({
993
+ text: Schema.Boolean,
994
+ audio: Schema.Boolean,
995
+ image: Schema.Boolean,
996
+ video: Schema.Boolean,
997
+ pdf: Schema.Boolean,
998
+ })
999
+
1000
+ const ProviderInterleaved = Schema.Union([
1001
+ Schema.Boolean,
1002
+ Schema.Struct({
1003
+ field: Schema.Literals(["reasoning_content", "reasoning_details"]),
1004
+ }),
1005
+ ])
1006
+
1007
+ const ProviderCapabilities = Schema.Struct({
1008
+ temperature: Schema.Boolean,
1009
+ reasoning: Schema.Boolean,
1010
+ attachment: Schema.Boolean,
1011
+ toolcall: Schema.Boolean,
1012
+ input: ProviderModalities,
1013
+ output: ProviderModalities,
1014
+ interleaved: ProviderInterleaved,
1015
+ })
1016
+
1017
+ const ProviderCacheCost = Schema.Struct({
1018
+ read: Schema.Finite,
1019
+ write: Schema.Finite,
1020
+ })
1021
+
1022
+ const ProviderCostTier = Schema.Struct({
1023
+ input: Schema.Finite,
1024
+ output: Schema.Finite,
1025
+ cache: ProviderCacheCost,
1026
+ tier: Schema.Struct({
1027
+ type: Schema.Literal("context"),
1028
+ size: Schema.Finite,
1029
+ }),
1030
+ })
1031
+
1032
+ const ProviderCost = Schema.Struct({
1033
+ input: Schema.Finite,
1034
+ output: Schema.Finite,
1035
+ cache: ProviderCacheCost,
1036
+ tiers: optionalOmitUndefined(Schema.Array(ProviderCostTier)),
1037
+ experimentalOver200K: optionalOmitUndefined(
1038
+ Schema.Struct({
1039
+ input: Schema.Finite,
1040
+ output: Schema.Finite,
1041
+ cache: ProviderCacheCost,
1042
+ }),
1043
+ ),
1044
+ })
1045
+
1046
+ const ProviderLimit = Schema.Struct({
1047
+ context: Schema.Finite,
1048
+ input: optionalOmitUndefined(Schema.Finite),
1049
+ output: Schema.Finite,
1050
+ })
1051
+
1052
+ export const Model = Schema.Struct({
1053
+ id: ModelV2.ID,
1054
+ providerID: ProviderV2.ID,
1055
+ api: ProviderApiInfo,
1056
+ name: Schema.String,
1057
+ family: optionalOmitUndefined(Schema.String),
1058
+ capabilities: ProviderCapabilities,
1059
+ cost: ProviderCost,
1060
+ limit: ProviderLimit,
1061
+ status: ModelStatus,
1062
+ options: Schema.Record(Schema.String, Schema.Any),
1063
+ headers: Schema.Record(Schema.String, Schema.String),
1064
+ release_date: Schema.String,
1065
+ variants: optionalOmitUndefined(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Any))),
1066
+ }).annotate({ identifier: "Model" })
1067
+ export type Model = Types.DeepMutable<Schema.Schema.Type<typeof Model>>
1068
+
1069
+ export const Info = Schema.Struct({
1070
+ id: ProviderV2.ID,
1071
+ name: Schema.String,
1072
+ source: Schema.Literals(["env", "config", "custom", "api"]),
1073
+ env: Schema.Array(Schema.String),
1074
+ key: optionalOmitUndefined(Schema.String),
1075
+ options: Schema.Record(Schema.String, Schema.Any),
1076
+ models: Schema.Record(Schema.String, Model),
1077
+ }).annotate({ identifier: "Provider" })
1078
+ export type Info = Types.DeepMutable<Schema.Schema.Type<typeof Info>>
1079
+
1080
+ const DefaultModelIDs = Schema.Record(Schema.String, Schema.String)
1081
+
1082
+ export const ListResult = Schema.Struct({
1083
+ all: Schema.Array(Info),
1084
+ default: DefaultModelIDs,
1085
+ connected: Schema.Array(Schema.String),
1086
+ })
1087
+ export type ListResult = Types.DeepMutable<Schema.Schema.Type<typeof ListResult>>
1088
+
1089
+ export const ConfigProvidersResult = Schema.Struct({
1090
+ providers: Schema.Array(Info),
1091
+ default: DefaultModelIDs,
1092
+ })
1093
+ export type ConfigProvidersResult = Types.DeepMutable<Schema.Schema.Type<typeof ConfigProvidersResult>>
1094
+
1095
+ export function toPublicInfo(provider: Info): Info {
1096
+ return JSON.parse(
1097
+ JSON.stringify(provider, (_, value) => {
1098
+ if (typeof value === "function" || typeof value === "symbol" || value === undefined) return undefined
1099
+ if (typeof value === "bigint") return value.toString()
1100
+ return value
1101
+ }),
1102
+ )
1103
+ }
1104
+
1105
+ export function defaultModelIDs<T extends { models: Record<string, { id: string }> }>(providers: Record<string, T>) {
1106
+ return mapValues(providers, (item) => sort(Object.values(item.models))[0].id)
1107
+ }
1108
+
1109
+ export class ModelNotFoundError extends Schema.TaggedErrorClass<ModelNotFoundError>()("ProviderModelNotFoundError", {
1110
+ providerID: ProviderV2.ID,
1111
+ modelID: ModelV2.ID,
1112
+ suggestions: Schema.optional(Schema.Array(Schema.String)),
1113
+ cause: Schema.optional(Schema.Defect),
1114
+ }) {
1115
+ static isInstance(input: unknown): input is ModelNotFoundError {
1116
+ return input instanceof ModelNotFoundError
1117
+ }
1118
+ }
1119
+
1120
+ export class InitError extends Schema.TaggedErrorClass<InitError>()("ProviderInitError", {
1121
+ providerID: ProviderV2.ID,
1122
+ cause: Schema.optional(Schema.Defect),
1123
+ }) {
1124
+ static isInstance(input: unknown): input is InitError {
1125
+ return input instanceof InitError
1126
+ }
1127
+ }
1128
+
1129
+ export class NoProvidersError extends Schema.TaggedErrorClass<NoProvidersError>()("ProviderNoProvidersError", {}) {
1130
+ static isInstance(input: unknown): input is NoProvidersError {
1131
+ return input instanceof NoProvidersError
1132
+ }
1133
+ }
1134
+
1135
+ export class NoModelsError extends Schema.TaggedErrorClass<NoModelsError>()("ProviderNoModelsError", {
1136
+ providerID: ProviderV2.ID,
1137
+ }) {
1138
+ static isInstance(input: unknown): input is NoModelsError {
1139
+ return input instanceof NoModelsError
1140
+ }
1141
+ }
1142
+
1143
+ export type DefaultModelError = ModelNotFoundError | NoProvidersError | NoModelsError
1144
+ export type Error = ModelNotFoundError | InitError | NoProvidersError | NoModelsError
1145
+
1146
+ export interface Interface {
1147
+ readonly list: () => Effect.Effect<Record<ProviderV2.ID, Info>>
1148
+ readonly getProvider: (providerID: ProviderV2.ID) => Effect.Effect<Info>
1149
+ readonly getModel: (providerID: ProviderV2.ID, modelID: ModelV2.ID) => Effect.Effect<Model, ModelNotFoundError>
1150
+ readonly getLanguage: (model: Model) => Effect.Effect<LanguageModelV3, ModelNotFoundError>
1151
+ readonly closest: (
1152
+ providerID: ProviderV2.ID,
1153
+ query: string[],
1154
+ ) => Effect.Effect<{ providerID: ProviderV2.ID; modelID: string } | undefined>
1155
+ readonly getSmallModel: (providerID: ProviderV2.ID) => Effect.Effect<Model | undefined>
1156
+ readonly defaultModel: () => Effect.Effect<{ providerID: ProviderV2.ID; modelID: ModelV2.ID }, DefaultModelError>
1157
+ }
1158
+
1159
+ interface State {
1160
+ models: Map<string, LanguageModelV3>
1161
+ providers: Record<ProviderV2.ID, Info>
1162
+ catalog: Record<ProviderV2.ID, Info>
1163
+ sdk: Map<string, BundledSDK>
1164
+ modelLoaders: Record<string, CustomModelLoader>
1165
+ varsLoaders: Record<string, CustomVarsLoader>
1166
+ }
1167
+
1168
+ export class Service extends Context.Service<Service, Interface>()("@octocode/Provider") {}
1169
+
1170
+ export const use = serviceUse(Service)
1171
+
1172
+ function cost(c: ModelsDev.Model["cost"]): Model["cost"] {
1173
+ const result: Model["cost"] = {
1174
+ input: c?.input ?? 0,
1175
+ output: c?.output ?? 0,
1176
+ cache: {
1177
+ read: c?.cache_read ?? 0,
1178
+ write: c?.cache_write ?? 0,
1179
+ },
1180
+ }
1181
+ if (c?.tiers) {
1182
+ result.tiers = c.tiers.map((item) => ({
1183
+ input: item.input,
1184
+ output: item.output,
1185
+ cache: {
1186
+ read: item.cache_read ?? 0,
1187
+ write: item.cache_write ?? 0,
1188
+ },
1189
+ tier: item.tier,
1190
+ }))
1191
+ }
1192
+ if (c?.context_over_200k) {
1193
+ result.experimentalOver200K = {
1194
+ cache: {
1195
+ read: c.context_over_200k.cache_read ?? 0,
1196
+ write: c.context_over_200k.cache_write ?? 0,
1197
+ },
1198
+ input: c.context_over_200k.input,
1199
+ output: c.context_over_200k.output,
1200
+ }
1201
+ }
1202
+ return result
1203
+ }
1204
+
1205
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
1206
+ const base: Model = {
1207
+ id: ModelV2.ID.make(model.id),
1208
+ providerID: ProviderV2.ID.make(provider.id),
1209
+ name: model.name,
1210
+ family: model.family,
1211
+ api: {
1212
+ id: model.id,
1213
+ url: model.provider?.api ?? provider.api ?? "",
1214
+ npm: model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible",
1215
+ },
1216
+ status: model.status ?? "active",
1217
+ headers: {},
1218
+ options: {},
1219
+ cost: cost(model.cost),
1220
+ limit: {
1221
+ context: model.limit.context,
1222
+ input: model.limit.input,
1223
+ output: model.limit.output,
1224
+ },
1225
+ capabilities: {
1226
+ temperature: model.temperature ?? false,
1227
+ reasoning: model.reasoning ?? false,
1228
+ attachment: model.attachment ?? false,
1229
+ toolcall: model.tool_call ?? true,
1230
+ input: {
1231
+ text: model.modalities?.input?.includes("text") ?? false,
1232
+ audio: model.modalities?.input?.includes("audio") ?? false,
1233
+ image: model.modalities?.input?.includes("image") ?? false,
1234
+ video: model.modalities?.input?.includes("video") ?? false,
1235
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
1236
+ },
1237
+ output: {
1238
+ text: model.modalities?.output?.includes("text") ?? false,
1239
+ audio: model.modalities?.output?.includes("audio") ?? false,
1240
+ image: model.modalities?.output?.includes("image") ?? false,
1241
+ video: model.modalities?.output?.includes("video") ?? false,
1242
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
1243
+ },
1244
+ interleaved: model.interleaved ?? false,
1245
+ },
1246
+ release_date: model.release_date ?? "",
1247
+ variants: {},
1248
+ }
1249
+
1250
+ return {
1251
+ ...base,
1252
+ variants: mapValues(ProviderTransform.variants(base), (v) => v),
1253
+ }
1254
+ }
1255
+
1256
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
1257
+ const models: Record<string, Model> = {}
1258
+ for (const [key, model] of Object.entries(provider.models)) {
1259
+ models[key] = fromModelsDevModel(provider, model)
1260
+ for (const [mode, opts] of Object.entries(model.experimental?.modes ?? {})) {
1261
+ const id = `${model.id}-${mode}`
1262
+ const base = fromModelsDevModel(provider, model)
1263
+ models[id] = {
1264
+ ...base,
1265
+ id: ModelV2.ID.make(id),
1266
+ name: `${model.name} ${mode[0].toUpperCase()}${mode.slice(1)}`,
1267
+ cost: opts.cost ? mergeDeep(base.cost, cost(opts.cost)) : base.cost,
1268
+ options: opts.provider?.body
1269
+ ? Object.fromEntries(
1270
+ Object.entries(opts.provider.body).map(([k, v]) => [
1271
+ k.replace(/_([a-z])/g, (_, c) => c.toUpperCase()),
1272
+ v,
1273
+ ]),
1274
+ )
1275
+ : base.options,
1276
+ headers: opts.provider?.headers ?? base.headers,
1277
+ }
1278
+ }
1279
+ }
1280
+ return {
1281
+ id: ProviderV2.ID.make(provider.id),
1282
+ source: "custom",
1283
+ name: provider.name,
1284
+ env: [...(provider.env ?? [])],
1285
+ options: {},
1286
+ models,
1287
+ }
1288
+ }
1289
+
1290
+ function modelSuggestions(provider: Info | undefined, modelID: ModelV2.ID, enableExperimentalModels: boolean) {
1291
+ const available = provider
1292
+ ? Object.keys(provider.models).filter((id) => {
1293
+ const model = provider.models[id]
1294
+ if (model.status === "deprecated") return false
1295
+ if (model.status === "alpha" && !enableExperimentalModels) return false
1296
+ return true
1297
+ })
1298
+ : []
1299
+ const fuzzy = fuzzysort.go(modelID, available, { limit: 3, threshold: -10000 }).map((m) => m.target)
1300
+ if (fuzzy.length) return fuzzy
1301
+ const query = modelID
1302
+ .toLowerCase()
1303
+ .split(/[^a-z0-9]+/)
1304
+ .filter((part) => part.length > 1)
1305
+ return sortBy(
1306
+ available
1307
+ .map((id) => ({
1308
+ id,
1309
+ score: query.filter((part) => id.toLowerCase().includes(part)).length,
1310
+ }))
1311
+ .filter((item) => item.score > 0),
1312
+ [(item) => item.score, "desc"],
1313
+ [(item) => item.id, "asc"],
1314
+ )
1315
+ .slice(0, 3)
1316
+ .map((item) => item.id)
1317
+ }
1318
+
1319
+ export const layer = Layer.effect(
1320
+ Service,
1321
+ Effect.gen(function* () {
1322
+ const fs = yield* FSUtil.Service
1323
+ const config = yield* Config.Service
1324
+ const auth = yield* Auth.Service
1325
+ const env = yield* Env.Service
1326
+ const plugin = yield* Plugin.Service
1327
+ const modelsDevSvc = yield* ModelsDev.Service
1328
+ const runtimeFlags = yield* RuntimeFlags.Service
1329
+
1330
+ const state = yield* InstanceState.make<State>(() =>
1331
+ Effect.gen(function* () {
1332
+ using _ = log.time("state")
1333
+ const bridge = yield* EffectBridge.make()
1334
+ const cfg = yield* config.get()
1335
+ const modelsDev = yield* modelsDevSvc.get()
1336
+ const catalog = mapValues(modelsDev, fromModelsDevProvider)
1337
+ const database = mapValues(catalog, toPublicInfo)
1338
+
1339
+ const providers: Record<ProviderV2.ID, Info> = {} as Record<ProviderV2.ID, Info>
1340
+ const languages = new Map<string, LanguageModelV3>()
1341
+ const modelLoaders: {
1342
+ [providerID: string]: CustomModelLoader
1343
+ } = {}
1344
+ const varsLoaders: {
1345
+ [providerID: string]: CustomVarsLoader
1346
+ } = {}
1347
+ const sdk = new Map<string, BundledSDK>()
1348
+ const discoveryLoaders: {
1349
+ [providerID: string]: CustomDiscoverModels
1350
+ } = {}
1351
+ const dep = {
1352
+ auth: (id: string) => auth.get(id).pipe(Effect.orDie),
1353
+ config: () => config.get(),
1354
+ env: () => env.all(),
1355
+ get: (key: string) => env.get(key),
1356
+ }
1357
+
1358
+ log.info("init")
1359
+
1360
+ function mergeProvider(providerID: ProviderV2.ID, provider: Partial<Info>) {
1361
+ const existing = providers[providerID]
1362
+ if (existing) {
1363
+ // @ts-expect-error
1364
+ providers[providerID] = mergeDeep(existing, provider)
1365
+ return
1366
+ }
1367
+ const resolvedID = resolveProviderID(providerID, database)
1368
+ const match = database[resolvedID]
1369
+ if (!match) return
1370
+ // @ts-expect-error
1371
+ providers[providerID] = mergeDeep(match, provider)
1372
+ }
1373
+
1374
+ // load plugins first so config() hook runs before reading cfg.provider
1375
+ const plugins = yield* plugin.list()
1376
+
1377
+ // now read config providers - includes any modifications from plugin config() hook
1378
+ const configProviders = Object.entries(cfg.provider ?? {})
1379
+ const disabled = new Set(cfg.disabled_providers ?? [])
1380
+ const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : null
1381
+
1382
+ function isProviderAllowed(providerID: ProviderV2.ID): boolean {
1383
+ if (enabled && !enabled.has(providerID)) return false
1384
+ if (disabled.has(providerID)) return false
1385
+ return true
1386
+ }
1387
+
1388
+ for (const hook of plugins) {
1389
+ const p = hook.provider
1390
+ const models = p?.models
1391
+ if (!p || !models) continue
1392
+
1393
+ const providerID = ProviderV2.ID.make(p.id)
1394
+ if (disabled.has(providerID)) continue
1395
+
1396
+ const provider = database[providerID]
1397
+ if (!provider) continue
1398
+ const pluginAuth = yield* auth.get(providerID).pipe(Effect.orDie)
1399
+
1400
+ provider.models = yield* Effect.promise(async () => {
1401
+ const next = await models(toPublicInfo(provider), { auth: pluginAuth })
1402
+ return Object.fromEntries(
1403
+ Object.entries(next).map(([id, model]) => [
1404
+ id,
1405
+ {
1406
+ ...model,
1407
+ id: ModelV2.ID.make(id),
1408
+ providerID,
1409
+ },
1410
+ ]),
1411
+ )
1412
+ })
1413
+ }
1414
+
1415
+ // extend database from config
1416
+ for (const [providerID, provider] of configProviders) {
1417
+ const resolvedID = resolveProviderID(providerID, database)
1418
+ const existing = database[resolvedID]
1419
+ const parsed: Info = {
1420
+ id: ProviderV2.ID.make(providerID),
1421
+ name: provider.name ?? existing?.name ?? providerID,
1422
+ env: provider.env ?? existing?.env ?? [],
1423
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
1424
+ source: "config",
1425
+ models: existing?.models ?? {},
1426
+ }
1427
+
1428
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
1429
+ const existingModel = parsed.models[model.id ?? modelID]
1430
+ const apiID = model.id ?? existingModel?.api.id ?? modelID
1431
+ const apiNpm =
1432
+ model.provider?.npm ??
1433
+ provider.npm ??
1434
+ existingModel?.api.npm ??
1435
+ modelsDev[providerID]?.npm ??
1436
+ "@ai-sdk/openai-compatible"
1437
+ const name = iife(() => {
1438
+ if (model.name) return model.name
1439
+ if (model.id && model.id !== modelID) return modelID
1440
+ return existingModel?.name ?? modelID
1441
+ })
1442
+ const parsedModel: Model = {
1443
+ id: ModelV2.ID.make(modelID),
1444
+ api: {
1445
+ id: apiID,
1446
+ npm: apiNpm,
1447
+ url: model.provider?.api ?? provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api ?? "",
1448
+ },
1449
+ status: model.status ?? existingModel?.status ?? "active",
1450
+ name,
1451
+ providerID: ProviderV2.ID.make(providerID),
1452
+ capabilities: {
1453
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
1454
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
1455
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
1456
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
1457
+ input: {
1458
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
1459
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
1460
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
1461
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
1462
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
1463
+ },
1464
+ output: {
1465
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
1466
+ audio:
1467
+ model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
1468
+ image:
1469
+ model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
1470
+ video:
1471
+ model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
1472
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
1473
+ },
1474
+ interleaved:
1475
+ model.interleaved ??
1476
+ existingModel?.capabilities.interleaved ??
1477
+ (!existingModel && apiNpm === "@ai-sdk/openai-compatible" && apiID.includes("deepseek")
1478
+ ? { field: "reasoning_content" }
1479
+ : false),
1480
+ },
1481
+ cost: {
1482
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
1483
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
1484
+ cache: {
1485
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
1486
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
1487
+ },
1488
+ },
1489
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
1490
+ limit: {
1491
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
1492
+ input: model.limit?.input ?? existingModel?.limit?.input,
1493
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
1494
+ },
1495
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
1496
+ family: model.family ?? existingModel?.family ?? "",
1497
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
1498
+ variants: {},
1499
+ }
1500
+ const merged = mergeDeep(ProviderTransform.variants(parsedModel), model.variants ?? {})
1501
+ parsedModel.variants = mapValues(
1502
+ pickBy(merged, (v) => !v.disabled),
1503
+ (v) => omit(v, ["disabled"]),
1504
+ )
1505
+ parsed.models[modelID] = parsedModel
1506
+ }
1507
+ database[providerID] = parsed
1508
+ }
1509
+
1510
+ // load env
1511
+ const envs = yield* env.all()
1512
+ for (const [id, provider] of Object.entries(database)) {
1513
+ const providerID = ProviderV2.ID.make(id)
1514
+ if (disabled.has(providerID)) continue
1515
+ const apiKey = provider.env.map((item) => envs[item]).find(Boolean)
1516
+ if (!apiKey) continue
1517
+ mergeProvider(providerID, {
1518
+ source: "env",
1519
+ key: provider.env.length === 1 ? apiKey : undefined,
1520
+ })
1521
+ }
1522
+
1523
+ // load apikeys
1524
+ const auths = yield* auth.all().pipe(Effect.orDie)
1525
+ for (const [id, provider] of Object.entries(auths)) {
1526
+ const providerID = ProviderV2.ID.make(id)
1527
+ if (disabled.has(providerID)) continue
1528
+ if (provider.type === "api") {
1529
+ mergeProvider(providerID, {
1530
+ source: "api",
1531
+ key: provider.key,
1532
+ })
1533
+ }
1534
+ }
1535
+
1536
+ // plugin auth loader - database now has entries for config providers
1537
+ for (const plugin of plugins) {
1538
+ if (!plugin.auth) continue
1539
+ const providerID = ProviderV2.ID.make(plugin.auth.provider)
1540
+ if (disabled.has(providerID)) continue
1541
+
1542
+ const stored = yield* auth.get(providerID).pipe(Effect.orDie)
1543
+ if (!stored) continue
1544
+ if (!plugin.auth.loader) continue
1545
+
1546
+ const options = yield* Effect.promise(() =>
1547
+ plugin.auth!.loader!(
1548
+ () => bridge.promise(auth.get(providerID).pipe(Effect.orDie)) as any,
1549
+ toPublicInfo(database[plugin.auth!.provider]),
1550
+ ),
1551
+ )
1552
+ const opts = options ?? {}
1553
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1554
+ mergeProvider(providerID, patch)
1555
+ }
1556
+
1557
+ for (const [id, fn] of Object.entries(custom(dep))) {
1558
+ const providerID = ProviderV2.ID.make(id)
1559
+ if (disabled.has(providerID)) continue
1560
+ const data = database[providerID]
1561
+ if (!data) {
1562
+ log.error("Provider does not exist in model list " + providerID)
1563
+ continue
1564
+ }
1565
+ const result = yield* fn(data)
1566
+ if (result && (result.autoload || providers[providerID])) {
1567
+ if (result.getModel) modelLoaders[providerID] = result.getModel
1568
+ if (result.vars) varsLoaders[providerID] = result.vars
1569
+ if (result.discoverModels) discoveryLoaders[providerID] = result.discoverModels
1570
+ const opts = result.options ?? {}
1571
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1572
+ mergeProvider(providerID, patch)
1573
+ }
1574
+ }
1575
+
1576
+ // load config - re-apply with updated data
1577
+ for (const [id, provider] of configProviders) {
1578
+ const providerID = ProviderV2.ID.make(id)
1579
+ const partial: Partial<Info> = { source: "config" }
1580
+ if (provider.env) partial.env = provider.env
1581
+ if (provider.name) partial.name = provider.name
1582
+ if (provider.options) partial.options = provider.options
1583
+ mergeProvider(providerID, partial)
1584
+ }
1585
+
1586
+ const gitlab = ProviderV2.ID.make("gitlab")
1587
+ if (discoveryLoaders[gitlab] && providers[gitlab] && isProviderAllowed(gitlab)) {
1588
+ yield* Effect.promise(async () => {
1589
+ try {
1590
+ const discovered = await discoveryLoaders[gitlab]()
1591
+ for (const [modelID, model] of Object.entries(discovered)) {
1592
+ if (!providers[gitlab].models[modelID]) {
1593
+ providers[gitlab].models[modelID] = model
1594
+ }
1595
+ }
1596
+ } catch (e) {
1597
+ log.warn("state discovery error", { id: "gitlab", error: e })
1598
+ }
1599
+ })
1600
+ }
1601
+
1602
+ for (const [id, provider] of Object.entries(providers)) {
1603
+ const providerID = ProviderV2.ID.make(id)
1604
+ if (!isProviderAllowed(providerID)) {
1605
+ delete providers[providerID]
1606
+ continue
1607
+ }
1608
+
1609
+ const configProvider = cfg.provider?.[providerID]
1610
+
1611
+ for (const [modelID, model] of Object.entries(provider.models)) {
1612
+ model.api.id = model.api.id ?? model.id ?? modelID
1613
+ if (
1614
+ // These chat aliases are invalid for the special handling in the
1615
+ // built-in providers below, but custom providers may support them.
1616
+ (modelID === "gpt-5-chat-latest" &&
1617
+ (providerID === ProviderV2.ID.openai ||
1618
+ providerID === ProviderV2.ID.githubCopilot ||
1619
+ providerID === ProviderV2.ID.openrouter)) ||
1620
+ (providerID === ProviderV2.ID.openrouter && modelID === "openai/gpt-5-chat")
1621
+ )
1622
+ delete provider.models[modelID]
1623
+ if (model.status === "alpha" && !runtimeFlags.enableExperimentalModels) delete provider.models[modelID]
1624
+ if (model.status === "deprecated") delete provider.models[modelID]
1625
+ if (
1626
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
1627
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
1628
+ )
1629
+ delete provider.models[modelID]
1630
+
1631
+ if (!model.variants || Object.keys(model.variants).length === 0) {
1632
+ model.variants = mapValues(ProviderTransform.variants(model), (v) => v)
1633
+ }
1634
+
1635
+ const configVariants = configProvider?.models?.[modelID]?.variants
1636
+ if (configVariants && model.variants) {
1637
+ const merged = mergeDeep(model.variants, configVariants)
1638
+ model.variants = mapValues(
1639
+ pickBy(merged, (v) => !v.disabled),
1640
+ (v) => omit(v, ["disabled"]),
1641
+ )
1642
+ }
1643
+ }
1644
+
1645
+ if (Object.keys(provider.models).length === 0) {
1646
+ delete providers[providerID]
1647
+ continue
1648
+ }
1649
+
1650
+ log.info("found", { providerID })
1651
+ }
1652
+
1653
+ return {
1654
+ models: languages,
1655
+ providers,
1656
+ catalog,
1657
+ sdk,
1658
+ modelLoaders,
1659
+ varsLoaders,
1660
+ }
1661
+ }),
1662
+ )
1663
+
1664
+ const list = Effect.fn("Provider.list")(() => InstanceState.use(state, (s) => s.providers))
1665
+
1666
+ async function resolveSDK(model: Model, s: State, envs: Record<string, string | undefined>) {
1667
+ try {
1668
+ using _ = log.time("getSDK", {
1669
+ providerID: model.providerID,
1670
+ })
1671
+ const provider = s.providers[model.providerID]
1672
+ const options = { ...provider.options }
1673
+
1674
+ if (
1675
+ model.providerID === "google-vertex" &&
1676
+ model.api.npm === "@ai-sdk/google-vertex/anthropic" &&
1677
+ !options.baseURL
1678
+ ) {
1679
+ const baseURL = googleVertexAnthropicBaseURL(
1680
+ typeof options.project === "string" ? options.project : undefined,
1681
+ typeof options.location === "string" ? options.location : undefined,
1682
+ )
1683
+ if (baseURL) options.baseURL = baseURL
1684
+ }
1685
+
1686
+ if (model.providerID === "google-vertex" && !model.api.npm.includes("@ai-sdk/openai-compatible")) {
1687
+ delete options.fetch
1688
+ }
1689
+
1690
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
1691
+ options["includeUsage"] = true
1692
+ }
1693
+
1694
+ const baseURL = iife(() => {
1695
+ let url =
1696
+ typeof options["baseURL"] === "string" && options["baseURL"] !== "" ? options["baseURL"] : model.api.url
1697
+ if (!url) return
1698
+
1699
+ const loader = s.varsLoaders[model.providerID]
1700
+ if (loader) {
1701
+ const vars = loader(options)
1702
+ for (const [key, value] of Object.entries(vars)) {
1703
+ const field = "${" + key + "}"
1704
+ url = url.replaceAll(field, value)
1705
+ }
1706
+ }
1707
+
1708
+ url = url.replace(/\$\{([^}]+)\}/g, (item, key) => {
1709
+ const val = envs[String(key)]
1710
+ return val ?? item
1711
+ })
1712
+ return url
1713
+ })
1714
+
1715
+ if (baseURL !== undefined) options["baseURL"] = baseURL
1716
+ if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
1717
+ if (model.headers)
1718
+ options["headers"] = {
1719
+ ...options["headers"],
1720
+ ...model.headers,
1721
+ }
1722
+
1723
+ const key = Hash.fast(
1724
+ JSON.stringify({
1725
+ providerID: model.providerID,
1726
+ npm: model.api.npm,
1727
+ options,
1728
+ }),
1729
+ )
1730
+ const existing = s.sdk.get(key)
1731
+ if (existing) return existing
1732
+
1733
+ const customFetch = options["fetch"]
1734
+ const chunkTimeout = options["chunkTimeout"]
1735
+ const headerTimeout = options["headerTimeout"]
1736
+ delete options["chunkTimeout"]
1737
+ delete options["headerTimeout"]
1738
+
1739
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
1740
+ const fetchFn = customFetch ?? fetch
1741
+ const opts = init ?? {}
1742
+ const chunkAbortCtl = typeof chunkTimeout === "number" && chunkTimeout > 0 ? new AbortController() : undefined
1743
+ const headerTimeoutMs = headerTimeout === false ? undefined : headerTimeout
1744
+ const headerTimeoutCtl = typeof headerTimeoutMs === "number" ? timeoutController(headerTimeoutMs) : undefined
1745
+ const signals: AbortSignal[] = []
1746
+
1747
+ if (opts.signal) signals.push(opts.signal)
1748
+ if (chunkAbortCtl) signals.push(chunkAbortCtl.signal)
1749
+ if (headerTimeoutCtl) signals.push(headerTimeoutCtl.signal)
1750
+ if (options["timeout"] !== undefined && options["timeout"] !== null && options["timeout"] !== false)
1751
+ signals.push(AbortSignal.timeout(options["timeout"]))
1752
+
1753
+ const combined = signals.length === 0 ? null : signals.length === 1 ? signals[0] : AbortSignal.any(signals)
1754
+ if (combined) opts.signal = combined
1755
+
1756
+ // Strip openai itemId metadata following what codex does
1757
+ if (
1758
+ (model.api.npm === "@ai-sdk/openai" ||
1759
+ model.api.npm === "@ai-sdk/azure" ||
1760
+ model.api.npm === "@ai-sdk/amazon-bedrock/mantle") &&
1761
+ opts.body &&
1762
+ opts.method === "POST"
1763
+ ) {
1764
+ const body = JSON.parse(opts.body as string)
1765
+ const keepIds = body.store === true
1766
+ if (!keepIds && Array.isArray(body.input)) {
1767
+ for (const item of body.input) {
1768
+ if ("id" in item) {
1769
+ delete item.id
1770
+ }
1771
+ }
1772
+ opts.body = JSON.stringify(body)
1773
+ }
1774
+ }
1775
+
1776
+ const res = await fetchFn(input, {
1777
+ ...opts,
1778
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
1779
+ timeout: options["timeout"] !== undefined && options["timeout"] !== null && options["timeout"] !== false ? options["timeout"] : 120_000,
1780
+ }).finally(() => headerTimeoutCtl?.clear())
1781
+
1782
+ if (!chunkAbortCtl) return res
1783
+ return wrapSSE(res, chunkTimeout, chunkAbortCtl)
1784
+ }
1785
+
1786
+ const bundledLoader = BUNDLED_PROVIDERS[model.api.npm]
1787
+ if (bundledLoader) {
1788
+ log.info("using bundled provider", {
1789
+ providerID: model.providerID,
1790
+ pkg: model.api.npm,
1791
+ })
1792
+ const factory = await bundledLoader()
1793
+ const loaded = factory({
1794
+ name: model.providerID,
1795
+ ...options,
1796
+ })
1797
+ s.sdk.set(key, loaded)
1798
+ return loaded as SDK
1799
+ }
1800
+
1801
+ const installedPath = await (async () => {
1802
+ if (model.api.npm.startsWith("file://")) {
1803
+ log.info("loading local provider", { pkg: model.api.npm })
1804
+ return model.api.npm
1805
+ }
1806
+ const item = await Npm.add(model.api.npm)
1807
+ if (!item.entrypoint) throw new Error(`Package ${model.api.npm} has no import entrypoint`)
1808
+ return item.entrypoint
1809
+ })()
1810
+
1811
+ // `installedPath` is a local entry path or an existing `file://` URL. Normalize
1812
+ // only path inputs so Node on Windows accepts the dynamic import.
1813
+ const importSpec = installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href
1814
+ const mod = await import(importSpec)
1815
+
1816
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
1817
+ const loaded = fn({
1818
+ name: model.providerID,
1819
+ ...options,
1820
+ })
1821
+ s.sdk.set(key, loaded)
1822
+ return loaded as SDK
1823
+ } catch (e) {
1824
+ throw new InitError({ providerID: model.providerID, cause: e })
1825
+ }
1826
+ }
1827
+
1828
+ const getProvider = Effect.fn("Provider.getProvider")((providerID: ProviderV2.ID) =>
1829
+ InstanceState.use(state, (s) => s.providers[providerID]),
1830
+ )
1831
+
1832
+ const getModel = Effect.fn("Provider.getModel")(function* (providerID: ProviderV2.ID, modelID: ModelV2.ID) {
1833
+ const s = yield* InstanceState.get(state)
1834
+ const provider = s.providers[providerID]
1835
+ if (!provider) {
1836
+ const catalogProvider = s.catalog[providerID]
1837
+ const suggestions = catalogProvider
1838
+ ? modelSuggestions(catalogProvider, modelID, runtimeFlags.enableExperimentalModels)
1839
+ : fuzzysort
1840
+ .go(providerID, Object.keys({ ...s.catalog, ...s.providers }), { limit: 3, threshold: -10000 })
1841
+ .map((m) => m.target)
1842
+ return yield* new ModelNotFoundError({ providerID, modelID, suggestions })
1843
+ }
1844
+
1845
+ const info = provider.models[modelID]
1846
+ if (!info) {
1847
+ const current = modelSuggestions(provider, modelID, runtimeFlags.enableExperimentalModels)
1848
+ const suggestions = current.length
1849
+ ? current
1850
+ : modelSuggestions(s.catalog[providerID], modelID, runtimeFlags.enableExperimentalModels)
1851
+ return yield* new ModelNotFoundError({ providerID, modelID, suggestions })
1852
+ }
1853
+ return info
1854
+ })
1855
+
1856
+ const getLanguage = Effect.fn("Provider.getLanguage")(function* (model: Model) {
1857
+ const s = yield* InstanceState.get(state)
1858
+ const envs = yield* env.all()
1859
+ const key = `${model.providerID}/${model.id}`
1860
+ if (s.models.has(key)) return s.models.get(key)!
1861
+
1862
+ const provider = s.providers[model.providerID]
1863
+ return yield* EffectPromise.refineRejection(
1864
+ async () => {
1865
+ const sdk = await resolveSDK(model, s, envs)
1866
+ const language = s.modelLoaders[model.providerID]
1867
+ ? await s.modelLoaders[model.providerID](
1868
+ sdk,
1869
+ model.api.id,
1870
+ {
1871
+ ...provider.options,
1872
+ ...model.options,
1873
+ },
1874
+ model,
1875
+ )
1876
+ : sdk.languageModel(model.api.id)
1877
+ s.models.set(key, language)
1878
+ return language
1879
+ },
1880
+ (cause) =>
1881
+ cause instanceof NoSuchModelError
1882
+ ? new ModelNotFoundError({ modelID: model.id, providerID: model.providerID, cause })
1883
+ : undefined,
1884
+ )
1885
+ })
1886
+
1887
+ const closest = Effect.fn("Provider.closest")(function* (providerID: ProviderV2.ID, query: string[]) {
1888
+ const s = yield* InstanceState.get(state)
1889
+ const provider = s.providers[providerID]
1890
+ if (!provider) return undefined
1891
+ for (const item of query) {
1892
+ for (const modelID of Object.keys(provider.models)) {
1893
+ if (modelID.includes(item)) return { providerID, modelID }
1894
+ }
1895
+ }
1896
+ return undefined
1897
+ })
1898
+
1899
+ const getSmallModel = Effect.fn("Provider.getSmallModel")(function* (providerID: ProviderV2.ID) {
1900
+ const cfg = yield* config.get()
1901
+
1902
+ if (cfg.small_model) {
1903
+ const parsed = parseModel(cfg.small_model)
1904
+ return yield* getModel(parsed.providerID, parsed.modelID).pipe(
1905
+ Effect.catchTag("ProviderModelNotFoundError", () => Effect.succeed(undefined)),
1906
+ )
1907
+ }
1908
+
1909
+ const s = yield* InstanceState.get(state)
1910
+ const provider = s.providers[providerID]
1911
+ if (!provider) return undefined
1912
+
1913
+ const experimental = yield* plugin.trigger<"experimental.provider.small_model">(
1914
+ "experimental.provider.small_model",
1915
+ { provider: toPublicInfo(provider) },
1916
+ { model: undefined },
1917
+ )
1918
+ if (experimental.model) {
1919
+ return {
1920
+ ...experimental.model,
1921
+ id: ModelV2.ID.make(experimental.model.id),
1922
+ providerID: ProviderV2.ID.make(experimental.model.providerID),
1923
+ }
1924
+ }
1925
+
1926
+ const defaultPriority = [
1927
+ "claude-haiku-4-5",
1928
+ "claude-haiku-4.5",
1929
+ "3-5-haiku",
1930
+ "3.5-haiku",
1931
+ "gemini-3-flash",
1932
+ "gemini-2.5-flash",
1933
+ "gpt-5-nano",
1934
+ ]
1935
+ const priority = providerID.startsWith("octo")
1936
+ ? ["gpt-5-nano"]
1937
+ : providerID.startsWith("github-copilot")
1938
+ ? ["gpt-5-mini", "claude-haiku-4.5", ...defaultPriority]
1939
+ : defaultPriority
1940
+ for (const item of priority) {
1941
+ if (providerID === ProviderV2.ID.amazonBedrock) {
1942
+ const crossRegionPrefixes = ["global.", "us.", "eu."]
1943
+ const candidates = Object.keys(provider.models).filter((m) => m.includes(item))
1944
+
1945
+ const globalMatch = candidates.find((m) => m.startsWith("global."))
1946
+ if (globalMatch) return provider.models[globalMatch]
1947
+
1948
+ const region = provider.options?.region
1949
+ if (region) {
1950
+ const regionPrefix = region.split("-")[0]
1951
+ if (regionPrefix === "us" || regionPrefix === "eu") {
1952
+ const regionalMatch = candidates.find((m) => m.startsWith(`${regionPrefix}.`))
1953
+ if (regionalMatch) return provider.models[regionalMatch]
1954
+ }
1955
+ }
1956
+
1957
+ const unprefixed = candidates.find((m) => !crossRegionPrefixes.some((p) => m.startsWith(p)))
1958
+ if (unprefixed) return provider.models[unprefixed]
1959
+ } else {
1960
+ for (const model of Object.keys(provider.models)) {
1961
+ if (model.includes(item)) return provider.models[model]
1962
+ }
1963
+ }
1964
+ }
1965
+
1966
+ return undefined
1967
+ })
1968
+
1969
+ const defaultModel = Effect.fn("Provider.defaultModel")(function* () {
1970
+ const cfg = yield* config.get()
1971
+ if (cfg.model) return parseModel(cfg.model)
1972
+
1973
+ const s = yield* InstanceState.get(state)
1974
+ const recent = yield* fs.readJson(path.join(Global.Path.state, "model.json")).pipe(
1975
+ Effect.map((x): { providerID: ProviderV2.ID; modelID: ModelV2.ID }[] => {
1976
+ if (!isRecord(x) || !Array.isArray(x.recent)) return []
1977
+ return x.recent.flatMap((item) => {
1978
+ if (!isRecord(item)) return []
1979
+ if (typeof item.providerID !== "string") return []
1980
+ if (typeof item.modelID !== "string") return []
1981
+ return [{ providerID: ProviderV2.ID.make(item.providerID), modelID: ModelV2.ID.make(item.modelID) }]
1982
+ })
1983
+ }),
1984
+ Effect.catch(() => Effect.succeed([] as { providerID: ProviderV2.ID; modelID: ModelV2.ID }[])),
1985
+ )
1986
+ for (const entry of recent) {
1987
+ const provider = s.providers[entry.providerID]
1988
+ if (!provider) continue
1989
+ if (!provider.models[entry.modelID]) continue
1990
+ return { providerID: entry.providerID, modelID: entry.modelID }
1991
+ }
1992
+
1993
+ const provider = Object.values(s.providers).find((p) => !cfg.provider || Object.keys(cfg.provider).includes(p.id))
1994
+ if (!provider) return yield* new NoProvidersError()
1995
+ const [model] = sort(Object.values(provider.models))
1996
+ if (!model) return yield* new NoModelsError({ providerID: provider.id })
1997
+ return {
1998
+ providerID: provider.id,
1999
+ modelID: model.id,
2000
+ }
2001
+ })
2002
+
2003
+ return Service.of({ list, getProvider, getModel, getLanguage, closest, getSmallModel, defaultModel })
2004
+ }),
2005
+ )
2006
+
2007
+ export const defaultLayer = Layer.suspend(() =>
2008
+ layer.pipe(
2009
+ Layer.provide(FSUtil.defaultLayer),
2010
+ Layer.provide(Env.defaultLayer),
2011
+ Layer.provide(Config.defaultLayer),
2012
+ Layer.provide(Auth.defaultLayer),
2013
+ Layer.provide(Plugin.defaultLayer),
2014
+ Layer.provide(ModelsDev.defaultLayer),
2015
+ Layer.provide(RuntimeFlags.defaultLayer),
2016
+ ),
2017
+ )
2018
+
2019
+ const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
2020
+ export function sort<T extends { id: string }>(models: T[]) {
2021
+ return sortBy(
2022
+ models,
2023
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
2024
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
2025
+ [(model) => model.id, "desc"],
2026
+ )
2027
+ }
2028
+
2029
+ export function parseModel(model: string) {
2030
+ const [providerID, ...rest] = model.split("/")
2031
+ return {
2032
+ providerID: ProviderV2.ID.make(providerID),
2033
+ modelID: ModelV2.ID.make(rest.join("/")),
2034
+ }
2035
+ }
2036
+
2037
+ export * as Provider from "./provider"