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