@sleepy-ai/cli 0.1.14 → 0.1.16

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 (806) hide show
  1. package/.sleepycode-test-fixtures-50158/sleepycode-test-eqsxv84ythu/.watcher-b67v64k2mnv +1 -0
  2. package/.sleepycode-test-fixtures-66172/sleepycode-test-x1ymo4kksaa/sleepycode.json +1 -0
  3. package/Dockerfile +18 -0
  4. package/README.md +6 -139
  5. package/drizzle.config.ts +10 -0
  6. package/git +0 -0
  7. package/migration/20260127222353_familiar_lady_ursula/migration.sql +90 -0
  8. package/migration/20260127222353_familiar_lady_ursula/snapshot.json +796 -0
  9. package/migration/20260211171708_add_project_commands/migration.sql +1 -0
  10. package/migration/20260211171708_add_project_commands/snapshot.json +806 -0
  11. package/migration/20260213144116_wakeful_the_professor/migration.sql +11 -0
  12. package/migration/20260213144116_wakeful_the_professor/snapshot.json +897 -0
  13. package/migration/20260225215848_workspace/migration.sql +7 -0
  14. package/migration/20260225215848_workspace/snapshot.json +959 -0
  15. package/migration/20260227213759_add_session_workspace_id/migration.sql +2 -0
  16. package/migration/20260227213759_add_session_workspace_id/snapshot.json +983 -0
  17. package/migration/20260228203230_blue_harpoon/migration.sql +17 -0
  18. package/migration/20260228203230_blue_harpoon/snapshot.json +1102 -0
  19. package/migration/20260303231226_add_workspace_fields/migration.sql +5 -0
  20. package/migration/20260303231226_add_workspace_fields/snapshot.json +1013 -0
  21. package/migration/20260309230000_move_org_to_state/migration.sql +3 -0
  22. package/migration/20260309230000_move_org_to_state/snapshot.json +1156 -0
  23. package/migration/20260312043431_session_message_cursor/migration.sql +4 -0
  24. package/migration/20260312043431_session_message_cursor/snapshot.json +1168 -0
  25. package/migration/20260323234822_events/migration.sql +13 -0
  26. package/migration/20260323234822_events/snapshot.json +1271 -0
  27. package/migration/20260410174513_workspace-name/migration.sql +16 -0
  28. package/migration/20260410174513_workspace-name/snapshot.json +1271 -0
  29. package/migration/20260413175956_chief_energizer/migration.sql +13 -0
  30. package/migration/20260413175956_chief_energizer/snapshot.json +1399 -0
  31. package/migration/20260422160000_context_inheritance/migration.sql +3 -0
  32. package/migration/20260422170000_task_registry/migration.sql +18 -0
  33. package/migration/20260423145421_remove_session_entry/migration.sql +4 -0
  34. package/migration/20260515000000_actor_rename/migration.sql +7 -0
  35. package/migration/20260515010000_memory_fts/migration.sql +33 -0
  36. package/migration/20260515020000_user_task/migration.sql +29 -0
  37. package/migration/20260519000000_last_checkpoint_message_id/migration.sql +1 -0
  38. package/migration/20260521000000_message_agent_id/migration.sql +2 -0
  39. package/migration/20260521000100_actor_registry_v6/migration.sql +25 -0
  40. package/migration/20260521010000_memory_fts_v6/migration.sql +33 -0
  41. package/migration/20260521020000_memory_fts_triggers/migration.sql +17 -0
  42. package/migration/20260526000000_agent_id_main/migration.sql +14 -0
  43. package/migration/20260527000000_actor_lifecycle/migration.sql +8 -0
  44. package/migration/20260527000100_inbox/migration.sql +12 -0
  45. package/migration/20260529000000_task_todo_redesign/migration.sql +16 -0
  46. package/migration/20260603000000_task_in_progress_owner/migration.sql +1 -0
  47. package/migration/20260603000000_workflow_run/migration.sql +17 -0
  48. package/migration/20260604000000_workflow_script_sha/migration.sql +1 -0
  49. package/migration/20260608000000_claude_import/migration.sql +7 -0
  50. package/migration/20260608010000_claude_import_message_ids/migration.sql +1 -0
  51. package/migration/20260609000000_history_fts/migration.sql +29 -0
  52. package/migration/20260609230000_workflow_agent_timeout/migration.sql +1 -0
  53. package/migration/20260612000000_external_import/migration.sql +16 -0
  54. package/package.json +199 -19
  55. package/parsers-config.ts +290 -0
  56. package/src/account/account.sql.ts +39 -0
  57. package/src/account/account.ts +456 -0
  58. package/src/account/repo.ts +166 -0
  59. package/src/account/schema.ts +99 -0
  60. package/src/account/url.ts +8 -0
  61. package/src/acp/README.md +174 -0
  62. package/src/acp/agent.ts +1787 -0
  63. package/src/acp/session.ts +116 -0
  64. package/src/acp/types.ts +24 -0
  65. package/src/actor/actor.sql.ts +38 -0
  66. package/src/actor/events.ts +67 -0
  67. package/src/actor/index.ts +2 -0
  68. package/src/actor/registry.ts +412 -0
  69. package/src/actor/return-header.ts +24 -0
  70. package/src/actor/schema.ts +47 -0
  71. package/src/actor/spawn-ref.ts +16 -0
  72. package/src/actor/spawn.ts +756 -0
  73. package/src/actor/turn.ts +49 -0
  74. package/src/actor/waiter.ts +166 -0
  75. package/src/agent/agent.ts +645 -0
  76. package/src/agent/config.ts +5 -0
  77. package/src/agent/generate.txt +75 -0
  78. package/src/agent/prompt/apex.txt +363 -0
  79. package/src/agent/prompt/checkpoint-writer.txt +167 -0
  80. package/src/agent/prompt/compaction.txt +9 -0
  81. package/src/agent/prompt/distill.txt +199 -0
  82. package/src/agent/prompt/dream.txt +155 -0
  83. package/src/agent/prompt/explore.txt +18 -0
  84. package/src/agent/prompt/forge.txt +491 -0
  85. package/src/agent/prompt/phantom.txt +491 -0
  86. package/src/agent/prompt/pivot.txt +460 -0
  87. package/src/agent/prompt/stack.txt +472 -0
  88. package/src/agent/prompt/summary.txt +11 -0
  89. package/src/agent/prompt/title.txt +44 -0
  90. package/src/audio.d.ts +9 -0
  91. package/src/auth/index.ts +97 -0
  92. package/src/bus/bus-event.ts +33 -0
  93. package/src/bus/global.ts +12 -0
  94. package/src/bus/index.ts +193 -0
  95. package/src/cli/bootstrap.ts +33 -0
  96. package/src/cli/cmd/account.ts +258 -0
  97. package/src/cli/cmd/acp.ts +70 -0
  98. package/src/cli/cmd/agent.ts +248 -0
  99. package/src/cli/cmd/cmd.ts +7 -0
  100. package/src/cli/cmd/db.ts +120 -0
  101. package/src/cli/cmd/debug/agent.ts +192 -0
  102. package/src/cli/cmd/debug/config.ts +17 -0
  103. package/src/cli/cmd/debug/file.ts +100 -0
  104. package/src/cli/cmd/debug/index.ts +48 -0
  105. package/src/cli/cmd/debug/lsp.ts +61 -0
  106. package/src/cli/cmd/debug/ripgrep.ts +105 -0
  107. package/src/cli/cmd/debug/scrap.ts +16 -0
  108. package/src/cli/cmd/debug/skill.ts +23 -0
  109. package/src/cli/cmd/debug/snapshot.ts +53 -0
  110. package/src/cli/cmd/doctor.ts +116 -0
  111. package/src/cli/cmd/export.ts +306 -0
  112. package/src/cli/cmd/generate.ts +50 -0
  113. package/src/cli/cmd/github.ts +1647 -0
  114. package/src/cli/cmd/import.ts +208 -0
  115. package/src/cli/cmd/init.ts +97 -0
  116. package/src/cli/cmd/login.ts +402 -0
  117. package/src/cli/cmd/mcp.ts +812 -0
  118. package/src/cli/cmd/models.ts +88 -0
  119. package/src/cli/cmd/plug.ts +233 -0
  120. package/src/cli/cmd/pr.ts +138 -0
  121. package/src/cli/cmd/providers.ts +713 -0
  122. package/src/cli/cmd/run-completion.ts +77 -0
  123. package/src/cli/cmd/run.ts +694 -0
  124. package/src/cli/cmd/serve.ts +30 -0
  125. package/src/cli/cmd/session.ts +181 -0
  126. package/src/cli/cmd/stats.ts +413 -0
  127. package/src/cli/cmd/tui/app.tsx +1161 -0
  128. package/src/cli/cmd/tui/asset/TEN_VAD_LICENSE +12 -0
  129. package/src/cli/cmd/tui/asset/charge.wav +0 -0
  130. package/src/cli/cmd/tui/asset/pulse-a.wav +0 -0
  131. package/src/cli/cmd/tui/asset/pulse-b.wav +0 -0
  132. package/src/cli/cmd/tui/asset/pulse-c.wav +0 -0
  133. package/src/cli/cmd/tui/asset/ten_vad.wasm +0 -0
  134. package/src/cli/cmd/tui/asset/ten_vad_loader.js +30 -0
  135. package/src/cli/cmd/tui/attach.ts +84 -0
  136. package/src/cli/cmd/tui/component/background-image.tsx +150 -0
  137. package/src/cli/cmd/tui/component/banner-session-expired.tsx +48 -0
  138. package/src/cli/cmd/tui/component/bg-pulse.tsx +130 -0
  139. package/src/cli/cmd/tui/component/border.tsx +21 -0
  140. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  141. package/src/cli/cmd/tui/component/dialog-agreement.tsx +111 -0
  142. package/src/cli/cmd/tui/component/dialog-command.tsx +219 -0
  143. package/src/cli/cmd/tui/component/dialog-console-org.tsx +103 -0
  144. package/src/cli/cmd/tui/component/dialog-go-upsell.tsx +150 -0
  145. package/src/cli/cmd/tui/component/dialog-image-list.tsx +111 -0
  146. package/src/cli/cmd/tui/component/dialog-logo-design.tsx +37 -0
  147. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  148. package/src/cli/cmd/tui/component/dialog-model.tsx +299 -0
  149. package/src/cli/cmd/tui/component/dialog-provider.tsx +449 -0
  150. package/src/cli/cmd/tui/component/dialog-session-delete-failed.tsx +101 -0
  151. package/src/cli/cmd/tui/component/dialog-session-list.tsx +269 -0
  152. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  153. package/src/cli/cmd/tui/component/dialog-skill.tsx +42 -0
  154. package/src/cli/cmd/tui/component/dialog-sleepy-login.tsx +167 -0
  155. package/src/cli/cmd/tui/component/dialog-stash.tsx +87 -0
  156. package/src/cli/cmd/tui/component/dialog-status.tsx +170 -0
  157. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  158. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  159. package/src/cli/cmd/tui/component/dialog-token-plan.tsx +77 -0
  160. package/src/cli/cmd/tui/component/dialog-variant.tsx +39 -0
  161. package/src/cli/cmd/tui/component/dialog-workflows.tsx +51 -0
  162. package/src/cli/cmd/tui/component/dialog-workspace-create.tsx +289 -0
  163. package/src/cli/cmd/tui/component/dialog-workspace-unavailable.tsx +81 -0
  164. package/src/cli/cmd/tui/component/dialog-worktree.tsx +90 -0
  165. package/src/cli/cmd/tui/component/error-component.tsx +92 -0
  166. package/src/cli/cmd/tui/component/logo.tsx +961 -0
  167. package/src/cli/cmd/tui/component/plugin-route-missing.tsx +14 -0
  168. package/src/cli/cmd/tui/component/prompt/autocomplete-detect.ts +34 -0
  169. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +668 -0
  170. package/src/cli/cmd/tui/component/prompt/cwd.ts +0 -0
  171. package/src/cli/cmd/tui/component/prompt/frecency.tsx +90 -0
  172. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  173. package/src/cli/cmd/tui/component/prompt/index.tsx +1869 -0
  174. package/src/cli/cmd/tui/component/prompt/offset.ts +45 -0
  175. package/src/cli/cmd/tui/component/prompt/part.ts +36 -0
  176. package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
  177. package/src/cli/cmd/tui/component/spinner.tsx +24 -0
  178. package/src/cli/cmd/tui/component/starry-background.tsx +305 -0
  179. package/src/cli/cmd/tui/component/startup-loading.tsx +67 -0
  180. package/src/cli/cmd/tui/component/task-item.tsx +63 -0
  181. package/src/cli/cmd/tui/component/textarea-keybindings.ts +73 -0
  182. package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
  183. package/src/cli/cmd/tui/component/workflow-tree.tsx +177 -0
  184. package/src/cli/cmd/tui/config/cwd.ts +5 -0
  185. package/src/cli/cmd/tui/config/tui-migrate.ts +151 -0
  186. package/src/cli/cmd/tui/config/tui-schema.ts +38 -0
  187. package/src/cli/cmd/tui/config/tui.ts +219 -0
  188. package/src/cli/cmd/tui/context/args.tsx +16 -0
  189. package/src/cli/cmd/tui/context/directory.ts +15 -0
  190. package/src/cli/cmd/tui/context/event.ts +45 -0
  191. package/src/cli/cmd/tui/context/exit.tsx +65 -0
  192. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  193. package/src/cli/cmd/tui/context/keybind.tsx +105 -0
  194. package/src/cli/cmd/tui/context/kv.tsx +86 -0
  195. package/src/cli/cmd/tui/context/language.tsx +91 -0
  196. package/src/cli/cmd/tui/context/local.tsx +458 -0
  197. package/src/cli/cmd/tui/context/plugin-keybinds.ts +41 -0
  198. package/src/cli/cmd/tui/context/project.tsx +109 -0
  199. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  200. package/src/cli/cmd/tui/context/route.tsx +68 -0
  201. package/src/cli/cmd/tui/context/sdk.tsx +150 -0
  202. package/src/cli/cmd/tui/context/sync.tsx +884 -0
  203. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  204. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  205. package/src/cli/cmd/tui/context/theme/carbonfox.json +248 -0
  206. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +230 -0
  207. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +230 -0
  208. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  209. package/src/cli/cmd/tui/context/theme/cobalt2.json +225 -0
  210. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  211. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  212. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  213. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  214. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  215. package/src/cli/cmd/tui/context/theme/gruvbox.json +242 -0
  216. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  217. package/src/cli/cmd/tui/context/theme/lucent-orng.json +234 -0
  218. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  219. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  220. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  221. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  222. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  223. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  224. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  225. package/src/cli/cmd/tui/context/theme/orng.json +249 -0
  226. package/src/cli/cmd/tui/context/theme/osaka-jade.json +93 -0
  227. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  228. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  229. package/src/cli/cmd/tui/context/theme/sleepycode.json +245 -0
  230. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  231. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  232. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  233. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  234. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  235. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  236. package/src/cli/cmd/tui/context/theme.tsx +1298 -0
  237. package/src/cli/cmd/tui/context/thinking.ts +48 -0
  238. package/src/cli/cmd/tui/context/tui-config.tsx +9 -0
  239. package/src/cli/cmd/tui/event.ts +62 -0
  240. package/src/cli/cmd/tui/feature-plugins/home/footer.tsx +93 -0
  241. package/src/cli/cmd/tui/feature-plugins/home/tips-view.tsx +193 -0
  242. package/src/cli/cmd/tui/feature-plugins/home/tips.tsx +54 -0
  243. package/src/cli/cmd/tui/feature-plugins/sidebar/context.tsx +287 -0
  244. package/src/cli/cmd/tui/feature-plugins/sidebar/cwd.tsx +45 -0
  245. package/src/cli/cmd/tui/feature-plugins/sidebar/files.tsx +62 -0
  246. package/src/cli/cmd/tui/feature-plugins/sidebar/footer.tsx +93 -0
  247. package/src/cli/cmd/tui/feature-plugins/sidebar/goal.tsx +84 -0
  248. package/src/cli/cmd/tui/feature-plugins/sidebar/instructions.tsx +54 -0
  249. package/src/cli/cmd/tui/feature-plugins/sidebar/lsp.tsx +66 -0
  250. package/src/cli/cmd/tui/feature-plugins/sidebar/mascot.tsx +69 -0
  251. package/src/cli/cmd/tui/feature-plugins/sidebar/mcp.tsx +98 -0
  252. package/src/cli/cmd/tui/feature-plugins/sidebar/task.tsx +95 -0
  253. package/src/cli/cmd/tui/feature-plugins/sidebar/todo.tsx +51 -0
  254. package/src/cli/cmd/tui/feature-plugins/sidebar/tps.ts +31 -0
  255. package/src/cli/cmd/tui/feature-plugins/system/plugins.tsx +274 -0
  256. package/src/cli/cmd/tui/i18n/en.ts +454 -0
  257. package/src/cli/cmd/tui/i18n/es.ts +508 -0
  258. package/src/cli/cmd/tui/i18n/fr.ts +515 -0
  259. package/src/cli/cmd/tui/i18n/ja.ts +463 -0
  260. package/src/cli/cmd/tui/i18n/locales.ts +82 -0
  261. package/src/cli/cmd/tui/i18n/ru.ts +527 -0
  262. package/src/cli/cmd/tui/i18n/slash-command.ts +11 -0
  263. package/src/cli/cmd/tui/i18n/zh.ts +454 -0
  264. package/src/cli/cmd/tui/i18n/zht.ts +430 -0
  265. package/src/cli/cmd/tui/layer.ts +6 -0
  266. package/src/cli/cmd/tui/plugin/api.tsx +402 -0
  267. package/src/cli/cmd/tui/plugin/index.ts +3 -0
  268. package/src/cli/cmd/tui/plugin/internal.ts +37 -0
  269. package/src/cli/cmd/tui/plugin/runtime.ts +1057 -0
  270. package/src/cli/cmd/tui/plugin/slots.tsx +60 -0
  271. package/src/cli/cmd/tui/routes/home.tsx +223 -0
  272. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +76 -0
  273. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +116 -0
  274. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +47 -0
  275. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  276. package/src/cli/cmd/tui/routes/session/footer.tsx +91 -0
  277. package/src/cli/cmd/tui/routes/session/index.tsx +3068 -0
  278. package/src/cli/cmd/tui/routes/session/permission.tsx +697 -0
  279. package/src/cli/cmd/tui/routes/session/question.tsx +488 -0
  280. package/src/cli/cmd/tui/routes/session/sidebar.tsx +97 -0
  281. package/src/cli/cmd/tui/routes/session/subagent-footer.tsx +143 -0
  282. package/src/cli/cmd/tui/thread.ts +324 -0
  283. package/src/cli/cmd/tui/ui/dialog-alert.tsx +61 -0
  284. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +95 -0
  285. package/src/cli/cmd/tui/ui/dialog-export-options.tsx +223 -0
  286. package/src/cli/cmd/tui/ui/dialog-help.tsx +42 -0
  287. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +123 -0
  288. package/src/cli/cmd/tui/ui/dialog-select.tsx +467 -0
  289. package/src/cli/cmd/tui/ui/dialog.tsx +207 -0
  290. package/src/cli/cmd/tui/ui/link.tsx +28 -0
  291. package/src/cli/cmd/tui/ui/spinner.ts +378 -0
  292. package/src/cli/cmd/tui/ui/toast.tsx +102 -0
  293. package/src/cli/cmd/tui/util/clipboard.ts +197 -0
  294. package/src/cli/cmd/tui/util/editor.ts +41 -0
  295. package/src/cli/cmd/tui/util/image-protocol.ts +35 -0
  296. package/src/cli/cmd/tui/util/index.ts +6 -0
  297. package/src/cli/cmd/tui/util/model.ts +23 -0
  298. package/src/cli/cmd/tui/util/pinyin.ts +20 -0
  299. package/src/cli/cmd/tui/util/provider-origin.ts +7 -0
  300. package/src/cli/cmd/tui/util/revert-diff.ts +18 -0
  301. package/src/cli/cmd/tui/util/scroll.ts +23 -0
  302. package/src/cli/cmd/tui/util/selection.ts +23 -0
  303. package/src/cli/cmd/tui/util/signal.ts +41 -0
  304. package/src/cli/cmd/tui/util/sound.ts +154 -0
  305. package/src/cli/cmd/tui/util/system-locale.ts +209 -0
  306. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  307. package/src/cli/cmd/tui/util/transcript.ts +112 -0
  308. package/src/cli/cmd/tui/util/vad.ts +229 -0
  309. package/src/cli/cmd/tui/util/voice.ts +450 -0
  310. package/src/cli/cmd/tui/win32.ts +130 -0
  311. package/src/cli/cmd/tui/worker.ts +104 -0
  312. package/src/cli/cmd/uninstall.ts +351 -0
  313. package/src/cli/cmd/upgrade.ts +79 -0
  314. package/src/cli/cmd/web.ts +96 -0
  315. package/src/cli/effect/prompt.ts +25 -0
  316. package/src/cli/error.ts +82 -0
  317. package/src/cli/heap.ts +59 -0
  318. package/src/cli/i18n.ts +15 -0
  319. package/src/cli/logo.ts +53 -0
  320. package/src/cli/network.ts +68 -0
  321. package/src/cli/ui.ts +133 -0
  322. package/src/cli/upgrade.ts +41 -0
  323. package/src/command/index.ts +276 -0
  324. package/src/command/template/initialize.txt +66 -0
  325. package/src/command/template/review.txt +101 -0
  326. package/src/config/agent.ts +197 -0
  327. package/src/config/command.ts +69 -0
  328. package/src/config/compose.ts +26 -0
  329. package/src/config/config.ts +1047 -0
  330. package/src/config/console-state.ts +16 -0
  331. package/src/config/entry-name.ts +16 -0
  332. package/src/config/error.ts +21 -0
  333. package/src/config/formatter.ts +17 -0
  334. package/src/config/history.ts +21 -0
  335. package/src/config/index.ts +17 -0
  336. package/src/config/keybinds.ts +127 -0
  337. package/src/config/layout.ts +10 -0
  338. package/src/config/lsp.ts +45 -0
  339. package/src/config/managed.ts +70 -0
  340. package/src/config/markdown.ts +97 -0
  341. package/src/config/mcp.ts +172 -0
  342. package/src/config/model-id.ts +14 -0
  343. package/src/config/parse.ts +44 -0
  344. package/src/config/paths.ts +85 -0
  345. package/src/config/permission.ts +76 -0
  346. package/src/config/plugin.ts +88 -0
  347. package/src/config/provider.ts +118 -0
  348. package/src/config/server.ts +20 -0
  349. package/src/config/skills.ts +16 -0
  350. package/src/config/variable.ts +90 -0
  351. package/src/control-plane/adaptors/index.ts +52 -0
  352. package/src/control-plane/adaptors/worktree.ts +47 -0
  353. package/src/control-plane/dev/debug-workspace-plugin.ts +73 -0
  354. package/src/control-plane/schema.ts +19 -0
  355. package/src/control-plane/sse.ts +66 -0
  356. package/src/control-plane/types.ts +34 -0
  357. package/src/control-plane/util.ts +37 -0
  358. package/src/control-plane/workspace-context.ts +26 -0
  359. package/src/control-plane/workspace.sql.ts +17 -0
  360. package/src/control-plane/workspace.ts +615 -0
  361. package/src/effect/app-runtime.ts +146 -0
  362. package/src/effect/bootstrap-runtime.ts +33 -0
  363. package/src/effect/bridge.ts +48 -0
  364. package/src/effect/cross-spawn-spawner.ts +514 -0
  365. package/src/effect/index.ts +5 -0
  366. package/src/effect/instance-ref.ts +11 -0
  367. package/src/effect/instance-registry.ts +12 -0
  368. package/src/effect/instance-state.ts +81 -0
  369. package/src/effect/logger.ts +73 -0
  370. package/src/effect/memo-map.ts +3 -0
  371. package/src/effect/observability.ts +107 -0
  372. package/src/effect/run-service.ts +52 -0
  373. package/src/effect/runner.ts +210 -0
  374. package/src/effect/runtime.ts +19 -0
  375. package/src/env/index.ts +37 -0
  376. package/src/file/ignore.ts +81 -0
  377. package/src/file/index.ts +664 -0
  378. package/src/file/protected.ts +59 -0
  379. package/src/file/ripgrep.ts +485 -0
  380. package/src/file/watcher.ts +163 -0
  381. package/src/flag/flag.ts +185 -0
  382. package/src/format/formatter.ts +403 -0
  383. package/src/format/index.ts +203 -0
  384. package/src/git/index.ts +260 -0
  385. package/src/global/index.ts +54 -0
  386. package/src/history/backfill.ts +162 -0
  387. package/src/history/extract.ts +67 -0
  388. package/src/history/fts-query.ts +15 -0
  389. package/src/history/fts.sql.ts +20 -0
  390. package/src/history/index.ts +10 -0
  391. package/src/history/resolve.ts +65 -0
  392. package/src/history/service.ts +258 -0
  393. package/src/history/writer.ts +112 -0
  394. package/src/id/id.ts +87 -0
  395. package/src/ide/index.ts +73 -0
  396. package/src/inbox/inbox-ref.ts +38 -0
  397. package/src/inbox/inbox.sql.ts +26 -0
  398. package/src/inbox/inbox.ts +223 -0
  399. package/src/inbox/index.ts +3 -0
  400. package/src/inbox/render.ts +40 -0
  401. package/src/index.ts +268 -0
  402. package/src/installation/index.ts +362 -0
  403. package/src/installation/version.ts +8 -0
  404. package/src/lsp/client.ts +249 -0
  405. package/src/lsp/diagnostic.ts +29 -0
  406. package/src/lsp/index.ts +3 -0
  407. package/src/lsp/language.ts +120 -0
  408. package/src/lsp/launch.ts +21 -0
  409. package/src/lsp/lsp.ts +519 -0
  410. package/src/lsp/server.ts +1956 -0
  411. package/src/mcp/auth.ts +144 -0
  412. package/src/mcp/index.ts +939 -0
  413. package/src/mcp/oauth-callback.ts +236 -0
  414. package/src/mcp/oauth-provider.ts +214 -0
  415. package/src/memory/fts-query.ts +37 -0
  416. package/src/memory/fts.sql.ts +19 -0
  417. package/src/memory/index.ts +1 -0
  418. package/src/memory/paths.ts +116 -0
  419. package/src/memory/reconcile.ts +144 -0
  420. package/src/memory/service.ts +144 -0
  421. package/src/metrics/client.ts +40 -0
  422. package/src/metrics/event.ts +43 -0
  423. package/src/metrics/index.ts +5 -0
  424. package/src/metrics/installation.ts +18 -0
  425. package/src/metrics/subscriber.ts +58 -0
  426. package/src/metrics/util.ts +9 -0
  427. package/src/node.ts +6 -0
  428. package/src/npm/config.ts +0 -0
  429. package/src/npm/index.ts +293 -0
  430. package/src/npmcli-config.d.ts +43 -0
  431. package/src/patch/index.ts +680 -0
  432. package/src/permission/arity.ts +163 -0
  433. package/src/permission/evaluate.ts +15 -0
  434. package/src/permission/index.ts +382 -0
  435. package/src/permission/schema.ts +17 -0
  436. package/src/plugin/checkpoint-splitover.ts +60 -0
  437. package/src/plugin/cloudflare.ts +76 -0
  438. package/src/plugin/codex.ts +611 -0
  439. package/src/plugin/github-copilot/copilot.ts +368 -0
  440. package/src/plugin/github-copilot/models.ts +153 -0
  441. package/src/plugin/index.ts +637 -0
  442. package/src/plugin/install.ts +439 -0
  443. package/src/plugin/loader.ts +216 -0
  444. package/src/plugin/matcher.ts +33 -0
  445. package/src/plugin/meta.ts +188 -0
  446. package/src/plugin/shared.ts +323 -0
  447. package/src/plugin/sleepy.ts +232 -0
  448. package/src/plugin/subagent-progress-checker.ts +147 -0
  449. package/src/project/bootstrap.ts +59 -0
  450. package/src/project/index.ts +2 -0
  451. package/src/project/instance.ts +215 -0
  452. package/src/project/project-id.ts +48 -0
  453. package/src/project/project.sql.ts +16 -0
  454. package/src/project/project.ts +522 -0
  455. package/src/project/schema.ts +15 -0
  456. package/src/project/vcs.ts +227 -0
  457. package/src/project/workspace-trust.ts +67 -0
  458. package/src/provider/auth.ts +234 -0
  459. package/src/provider/error.ts +216 -0
  460. package/src/provider/index.ts +5 -0
  461. package/src/provider/models-snapshot.d.ts +2 -0
  462. package/src/provider/models-snapshot.js +3 -0
  463. package/src/provider/models.ts +180 -0
  464. package/src/provider/provider.ts +2030 -0
  465. package/src/provider/schema.ts +36 -0
  466. package/src/provider/sdk/copilot/README.md +5 -0
  467. package/src/provider/sdk/copilot/chat/convert-to-openai-compatible-chat-messages.ts +170 -0
  468. package/src/provider/sdk/copilot/chat/get-response-metadata.ts +15 -0
  469. package/src/provider/sdk/copilot/chat/map-openai-compatible-finish-reason.ts +19 -0
  470. package/src/provider/sdk/copilot/chat/openai-compatible-api-types.ts +64 -0
  471. package/src/provider/sdk/copilot/chat/openai-compatible-chat-language-model.ts +815 -0
  472. package/src/provider/sdk/copilot/chat/openai-compatible-chat-options.ts +28 -0
  473. package/src/provider/sdk/copilot/chat/openai-compatible-metadata-extractor.ts +44 -0
  474. package/src/provider/sdk/copilot/chat/openai-compatible-prepare-tools.ts +83 -0
  475. package/src/provider/sdk/copilot/copilot-provider.ts +100 -0
  476. package/src/provider/sdk/copilot/index.ts +2 -0
  477. package/src/provider/sdk/copilot/openai-compatible-error.ts +27 -0
  478. package/src/provider/sdk/copilot/responses/convert-to-openai-responses-input.ts +335 -0
  479. package/src/provider/sdk/copilot/responses/map-openai-responses-finish-reason.ts +22 -0
  480. package/src/provider/sdk/copilot/responses/openai-config.ts +18 -0
  481. package/src/provider/sdk/copilot/responses/openai-error.ts +22 -0
  482. package/src/provider/sdk/copilot/responses/openai-responses-api-types.ts +214 -0
  483. package/src/provider/sdk/copilot/responses/openai-responses-language-model.ts +1770 -0
  484. package/src/provider/sdk/copilot/responses/openai-responses-prepare-tools.ts +173 -0
  485. package/src/provider/sdk/copilot/responses/openai-responses-settings.ts +1 -0
  486. package/src/provider/sdk/copilot/responses/tool/code-interpreter.ts +87 -0
  487. package/src/provider/sdk/copilot/responses/tool/file-search.ts +127 -0
  488. package/src/provider/sdk/copilot/responses/tool/image-generation.ts +114 -0
  489. package/src/provider/sdk/copilot/responses/tool/local-shell.ts +64 -0
  490. package/src/provider/sdk/copilot/responses/tool/web-search-preview.ts +103 -0
  491. package/src/provider/sdk/copilot/responses/tool/web-search.ts +102 -0
  492. package/src/provider/session-check.ts +178 -0
  493. package/src/provider/transform.ts +1393 -0
  494. package/src/pty/index.ts +364 -0
  495. package/src/pty/pty.bun.ts +26 -0
  496. package/src/pty/pty.node.ts +27 -0
  497. package/src/pty/pty.ts +25 -0
  498. package/src/pty/schema.ts +17 -0
  499. package/src/question/index.ts +252 -0
  500. package/src/question/schema.ts +17 -0
  501. package/src/server/adapter.bun.ts +40 -0
  502. package/src/server/adapter.node.ts +66 -0
  503. package/src/server/adapter.ts +21 -0
  504. package/src/server/auth.ts +16 -0
  505. package/src/server/error.ts +53 -0
  506. package/src/server/event.ts +7 -0
  507. package/src/server/fence.ts +81 -0
  508. package/src/server/mdns.ts +60 -0
  509. package/src/server/middleware.ts +94 -0
  510. package/src/server/projectors.ts +28 -0
  511. package/src/server/proxy.ts +171 -0
  512. package/src/server/pty-ticket.ts +42 -0
  513. package/src/server/rate-limit.ts +38 -0
  514. package/src/server/routes/control/index.ts +160 -0
  515. package/src/server/routes/control/workspace.ts +203 -0
  516. package/src/server/routes/global.ts +367 -0
  517. package/src/server/routes/instance/bash-interactive.ts +82 -0
  518. package/src/server/routes/instance/config.ts +89 -0
  519. package/src/server/routes/instance/event.ts +108 -0
  520. package/src/server/routes/instance/experimental.ts +408 -0
  521. package/src/server/routes/instance/file.ts +190 -0
  522. package/src/server/routes/instance/httpapi/config.ts +51 -0
  523. package/src/server/routes/instance/httpapi/permission.ts +72 -0
  524. package/src/server/routes/instance/httpapi/project.ts +62 -0
  525. package/src/server/routes/instance/httpapi/provider.ts +142 -0
  526. package/src/server/routes/instance/httpapi/question.ts +121 -0
  527. package/src/server/routes/instance/httpapi/server.ts +153 -0
  528. package/src/server/routes/instance/index.ts +301 -0
  529. package/src/server/routes/instance/mcp.ts +260 -0
  530. package/src/server/routes/instance/middleware.ts +44 -0
  531. package/src/server/routes/instance/permission.ts +73 -0
  532. package/src/server/routes/instance/project.ts +122 -0
  533. package/src/server/routes/instance/provider.ts +158 -0
  534. package/src/server/routes/instance/pty.ts +302 -0
  535. package/src/server/routes/instance/question.ts +162 -0
  536. package/src/server/routes/instance/session.ts +1328 -0
  537. package/src/server/routes/instance/sync.ts +143 -0
  538. package/src/server/routes/instance/trace.ts +59 -0
  539. package/src/server/routes/instance/tui.ts +384 -0
  540. package/src/server/routes/instance/workflows.ts +142 -0
  541. package/src/server/routes/ui.ts +37 -0
  542. package/src/server/server.ts +146 -0
  543. package/src/server/workspace.ts +122 -0
  544. package/src/session/auto-dream.ts +123 -0
  545. package/src/session/boundary.ts +77 -0
  546. package/src/session/budgeted-read.ts +118 -0
  547. package/src/session/checkpoint-align.ts +29 -0
  548. package/src/session/checkpoint-context.ts +36 -0
  549. package/src/session/checkpoint-paths.ts +86 -0
  550. package/src/session/checkpoint-progress-reconcile.ts +111 -0
  551. package/src/session/checkpoint-retry.ts +192 -0
  552. package/src/session/checkpoint-templates.ts +114 -0
  553. package/src/session/checkpoint-validator.ts +259 -0
  554. package/src/session/checkpoint.ts +1560 -0
  555. package/src/session/classify.ts +120 -0
  556. package/src/session/claude-import.ts +381 -0
  557. package/src/session/codex-import.ts +416 -0
  558. package/src/session/compaction.ts +545 -0
  559. package/src/session/external-import.sql.ts +18 -0
  560. package/src/session/external-import.ts +136 -0
  561. package/src/session/goal.ts +232 -0
  562. package/src/session/index.ts +1 -0
  563. package/src/session/instruction.ts +276 -0
  564. package/src/session/last-message-info.ts +32 -0
  565. package/src/session/llm-request-prefix.ts +82 -0
  566. package/src/session/llm.ts +739 -0
  567. package/src/session/max-mode.ts +410 -0
  568. package/src/session/message-v2.ts +1146 -0
  569. package/src/session/message.ts +191 -0
  570. package/src/session/opencode-import.ts +281 -0
  571. package/src/session/overflow.ts +53 -0
  572. package/src/session/prefix-capture-ref.ts +48 -0
  573. package/src/session/processor.ts +983 -0
  574. package/src/session/projectors.ts +137 -0
  575. package/src/session/prompt/anthropic.txt +154 -0
  576. package/src/session/prompt/beast.txt +155 -0
  577. package/src/session/prompt/build-switch.txt +5 -0
  578. package/src/session/prompt/codex.txt +79 -0
  579. package/src/session/prompt/compose.txt +119 -0
  580. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  581. package/src/session/prompt/deepseek.txt +131 -0
  582. package/src/session/prompt/default.old.txt +151 -0
  583. package/src/session/prompt/default.txt +172 -0
  584. package/src/session/prompt/gemini.txt +155 -0
  585. package/src/session/prompt/glm.txt +51 -0
  586. package/src/session/prompt/gpt.txt +107 -0
  587. package/src/session/prompt/kimi.txt +95 -0
  588. package/src/session/prompt/max-steps.txt +16 -0
  589. package/src/session/prompt/minimax.txt +140 -0
  590. package/src/session/prompt/text-loop-recovery.ts +40 -0
  591. package/src/session/prompt/text-ngram-detection.ts +87 -0
  592. package/src/session/prompt/trinity.txt +97 -0
  593. package/src/session/prompt.ts +3879 -0
  594. package/src/session/prune.ts +481 -0
  595. package/src/session/retry.ts +178 -0
  596. package/src/session/revert.ts +161 -0
  597. package/src/session/run-state.ts +135 -0
  598. package/src/session/schema.ts +36 -0
  599. package/src/session/session.sql.ts +110 -0
  600. package/src/session/session.ts +908 -0
  601. package/src/session/status.ts +89 -0
  602. package/src/session/summary.ts +163 -0
  603. package/src/session/system.ts +96 -0
  604. package/src/session/todo.ts +77 -0
  605. package/src/session/trajectory.ts +98 -0
  606. package/src/share/index.ts +2 -0
  607. package/src/share/session.ts +57 -0
  608. package/src/share/share-next.ts +381 -0
  609. package/src/share/share.sql.ts +13 -0
  610. package/src/shell/shell.ts +124 -0
  611. package/src/skill/builtin/.bundle/self-extend/SKILL.md +131 -0
  612. package/src/skill/builtin/.bundle/self-extend/reference/hook-api.md +242 -0
  613. package/src/skill/builtin/.bundle/self-extend/reference/skill-api.md +114 -0
  614. package/src/skill/builtin/.bundle/self-extend/reference/tool-api.md +115 -0
  615. package/src/skill/builtin/.bundle/self-extend/reference/tui-api.md +258 -0
  616. package/src/skill/builtin/bundle.macro.ts +30 -0
  617. package/src/skill/builtin/extract.ts +41 -0
  618. package/src/skill/compose/.bundle/ask/SKILL.md +58 -0
  619. package/src/skill/compose/.bundle/brainstorm/SKILL.md +200 -0
  620. package/src/skill/compose/.bundle/brainstorm/scripts/frame-template.html +214 -0
  621. package/src/skill/compose/.bundle/brainstorm/scripts/helper.js +88 -0
  622. package/src/skill/compose/.bundle/brainstorm/scripts/server.cjs +354 -0
  623. package/src/skill/compose/.bundle/brainstorm/scripts/start-server.sh +148 -0
  624. package/src/skill/compose/.bundle/brainstorm/scripts/stop-server.sh +56 -0
  625. package/src/skill/compose/.bundle/brainstorm/spec-document-reviewer-prompt.md +50 -0
  626. package/src/skill/compose/.bundle/brainstorm/visual-companion.md +258 -0
  627. package/src/skill/compose/.bundle/debug/CREATION-LOG.md +119 -0
  628. package/src/skill/compose/.bundle/debug/SKILL.md +297 -0
  629. package/src/skill/compose/.bundle/debug/condition-based-waiting-example.ts +158 -0
  630. package/src/skill/compose/.bundle/debug/condition-based-waiting.md +106 -0
  631. package/src/skill/compose/.bundle/debug/defense-in-depth.md +122 -0
  632. package/src/skill/compose/.bundle/debug/find-polluter.sh +63 -0
  633. package/src/skill/compose/.bundle/debug/root-cause-tracing.md +144 -0
  634. package/src/skill/compose/.bundle/debug/test-academic.md +14 -0
  635. package/src/skill/compose/.bundle/debug/test-pressure-1.md +58 -0
  636. package/src/skill/compose/.bundle/debug/test-pressure-2.md +68 -0
  637. package/src/skill/compose/.bundle/debug/test-pressure-3.md +69 -0
  638. package/src/skill/compose/.bundle/execute/SKILL.md +71 -0
  639. package/src/skill/compose/.bundle/feedback/SKILL.md +214 -0
  640. package/src/skill/compose/.bundle/merge/SKILL.md +252 -0
  641. package/src/skill/compose/.bundle/new-skill/SKILL.md +211 -0
  642. package/src/skill/compose/.bundle/parallel/SKILL.md +168 -0
  643. package/src/skill/compose/.bundle/plan/SKILL.md +183 -0
  644. package/src/skill/compose/.bundle/plan/plan-document-reviewer-prompt.md +50 -0
  645. package/src/skill/compose/.bundle/report/SKILL.md +180 -0
  646. package/src/skill/compose/.bundle/review/SKILL.md +104 -0
  647. package/src/skill/compose/.bundle/review/code-reviewer.md +178 -0
  648. package/src/skill/compose/.bundle/subagent/SKILL.md +325 -0
  649. package/src/skill/compose/.bundle/subagent/code-quality-reviewer-prompt.md +26 -0
  650. package/src/skill/compose/.bundle/subagent/implementer-prompt.md +128 -0
  651. package/src/skill/compose/.bundle/subagent/spec-reviewer-prompt.md +118 -0
  652. package/src/skill/compose/.bundle/tdd/SKILL.md +360 -0
  653. package/src/skill/compose/.bundle/tdd/testing-anti-patterns.md +299 -0
  654. package/src/skill/compose/.bundle/verify/SKILL.md +140 -0
  655. package/src/skill/compose/.bundle/worktree/SKILL.md +234 -0
  656. package/src/skill/compose/LICENSE-karpathy +28 -0
  657. package/{LICENSE → src/skill/compose/LICENSE-superpowers} +6 -3
  658. package/src/skill/compose/bundle.macro.ts +30 -0
  659. package/src/skill/compose/extract.ts +85 -0
  660. package/src/skill/discovery.ts +118 -0
  661. package/src/skill/index.ts +328 -0
  662. package/src/snapshot/index.ts +777 -0
  663. package/src/sql.d.ts +4 -0
  664. package/src/storage/db.bun.ts +8 -0
  665. package/src/storage/db.node.ts +8 -0
  666. package/src/storage/db.ts +172 -0
  667. package/src/storage/index.ts +26 -0
  668. package/src/storage/json-migration.ts +426 -0
  669. package/src/storage/read-sqlite.bun.ts +11 -0
  670. package/src/storage/read-sqlite.node.ts +13 -0
  671. package/src/storage/read-sqlite.ts +10 -0
  672. package/src/storage/schema.sql.ts +10 -0
  673. package/src/storage/schema.ts +7 -0
  674. package/src/storage/storage.ts +331 -0
  675. package/src/sync/README.md +179 -0
  676. package/src/sync/event.sql.ts +16 -0
  677. package/src/sync/index.ts +278 -0
  678. package/src/sync/schema.ts +14 -0
  679. package/src/task/events.ts +28 -0
  680. package/src/task/gate-state.ts +54 -0
  681. package/src/task/gate.ts +116 -0
  682. package/src/task/index.ts +1 -0
  683. package/src/task/registry.ts +394 -0
  684. package/src/task/schema.ts +43 -0
  685. package/src/task/task.sql.ts +50 -0
  686. package/src/team/events.ts +22 -0
  687. package/src/team/index.ts +113 -0
  688. package/src/team/schema.ts +31 -0
  689. package/src/temporary.ts +33 -0
  690. package/src/tool/actor.shell.txt +72 -0
  691. package/src/tool/actor.ts +804 -0
  692. package/src/tool/actor.txt +103 -0
  693. package/src/tool/apply_patch.ts +308 -0
  694. package/src/tool/apply_patch.txt +33 -0
  695. package/src/tool/bash-interactive.ts +183 -0
  696. package/src/tool/bash.ts +704 -0
  697. package/src/tool/bash.txt +123 -0
  698. package/src/tool/change-directory.ts +91 -0
  699. package/src/tool/codesearch.ts +63 -0
  700. package/src/tool/codesearch.txt +12 -0
  701. package/src/tool/edit.ts +693 -0
  702. package/src/tool/edit.txt +10 -0
  703. package/src/tool/external-directory.ts +132 -0
  704. package/src/tool/glob.ts +100 -0
  705. package/src/tool/glob.txt +6 -0
  706. package/src/tool/grep.ts +145 -0
  707. package/src/tool/grep.txt +8 -0
  708. package/src/tool/history.ts +146 -0
  709. package/src/tool/history.txt +17 -0
  710. package/src/tool/index.ts +4 -0
  711. package/src/tool/invalid.ts +20 -0
  712. package/src/tool/invocation-style.ts +17 -0
  713. package/src/tool/lsp.ts +91 -0
  714. package/src/tool/lsp.txt +19 -0
  715. package/src/tool/mcp-exa.ts +78 -0
  716. package/src/tool/memory-path-guard.ts +162 -0
  717. package/src/tool/memory.ts +81 -0
  718. package/src/tool/memory.txt +69 -0
  719. package/src/tool/multiedit.ts +54 -0
  720. package/src/tool/multiedit.txt +41 -0
  721. package/src/tool/notebook-edit.ts +225 -0
  722. package/src/tool/notebook-edit.txt +10 -0
  723. package/src/tool/plan-enter.txt +16 -0
  724. package/src/tool/plan-exit.txt +14 -0
  725. package/src/tool/plan.ts +194 -0
  726. package/src/tool/question.ts +67 -0
  727. package/src/tool/question.txt +10 -0
  728. package/src/tool/read-state.ts +44 -0
  729. package/src/tool/read.ts +327 -0
  730. package/src/tool/read.txt +14 -0
  731. package/src/tool/recoverable.ts +35 -0
  732. package/src/tool/registry.ts +429 -0
  733. package/src/tool/schema.ts +17 -0
  734. package/src/tool/session-cwd.ts +35 -0
  735. package/src/tool/shell-tokenize.ts +374 -0
  736. package/src/tool/shell-wrap.ts +235 -0
  737. package/src/tool/skill.ts +76 -0
  738. package/src/tool/skill.txt +5 -0
  739. package/src/tool/task.shell.txt +57 -0
  740. package/src/tool/task.ts +456 -0
  741. package/src/tool/task.txt +56 -0
  742. package/src/tool/tool.ts +166 -0
  743. package/src/tool/truncate.ts +201 -0
  744. package/src/tool/truncation-dir.ts +4 -0
  745. package/src/tool/webfetch.ts +208 -0
  746. package/src/tool/webfetch.txt +13 -0
  747. package/src/tool/websearch/index.ts +104 -0
  748. package/src/tool/websearch/sleepy.ts +118 -0
  749. package/src/tool/websearch/websearch.txt +14 -0
  750. package/src/tool/workflow.ts +357 -0
  751. package/src/tool/workflow.txt +25 -0
  752. package/src/tool/write.ts +88 -0
  753. package/src/tool/write.txt +10 -0
  754. package/src/util/abort.ts +35 -0
  755. package/src/util/archive.ts +15 -0
  756. package/src/util/color.ts +17 -0
  757. package/src/util/data-url.ts +9 -0
  758. package/src/util/defer.ts +10 -0
  759. package/src/util/effect-http-client.ts +11 -0
  760. package/src/util/effect-zod.ts +367 -0
  761. package/src/util/env-info.ts +62 -0
  762. package/src/util/error.ts +78 -0
  763. package/src/util/filesystem.ts +243 -0
  764. package/src/util/fn.ts +21 -0
  765. package/src/util/format.ts +20 -0
  766. package/src/util/iife.ts +3 -0
  767. package/src/util/index.ts +14 -0
  768. package/src/util/keybind.ts +101 -0
  769. package/src/util/lazy.ts +18 -0
  770. package/src/util/local-context.ts +23 -0
  771. package/src/util/locale.ts +79 -0
  772. package/src/util/lock.ts +96 -0
  773. package/src/util/log.ts +234 -0
  774. package/src/util/media.ts +26 -0
  775. package/src/util/network.ts +9 -0
  776. package/src/util/process.ts +174 -0
  777. package/src/util/provider-priority.ts +48 -0
  778. package/src/util/queue.ts +60 -0
  779. package/src/util/record.ts +3 -0
  780. package/src/util/rpc.ts +64 -0
  781. package/src/util/schema.ts +53 -0
  782. package/src/util/scrap.ts +10 -0
  783. package/src/util/signal.ts +12 -0
  784. package/src/util/sleepy-process.ts +24 -0
  785. package/src/util/ssrf.ts +116 -0
  786. package/src/util/timeout.ts +14 -0
  787. package/src/util/token.ts +5 -0
  788. package/src/util/tool-compat.ts +144 -0
  789. package/src/util/update-schema.ts +13 -0
  790. package/src/util/which.ts +14 -0
  791. package/src/util/wildcard.ts +57 -0
  792. package/src/workflow/builtin/compose.js +749 -0
  793. package/src/workflow/builtin/deep-research.js +397 -0
  794. package/src/workflow/builtin.ts +59 -0
  795. package/src/workflow/events.ts +72 -0
  796. package/src/workflow/meta.ts +335 -0
  797. package/src/workflow/persistence.ts +312 -0
  798. package/src/workflow/resolve.ts +45 -0
  799. package/src/workflow/runtime-ref.ts +18 -0
  800. package/src/workflow/runtime.ts +1447 -0
  801. package/src/workflow/sandbox.ts +286 -0
  802. package/src/workflow/workflow.sql.ts +31 -0
  803. package/src/workflow/workspace.ts +69 -0
  804. package/src/worktree/index.ts +629 -0
  805. package/postinstall.mjs +0 -102
  806. package/sleepy-ai-cli-0.1.14.tgz +0 -0
@@ -0,0 +1,2030 @@
1
+ import z from "zod"
2
+ import fsNode from "fs/promises"
3
+ import os from "os"
4
+ import fuzzysort from "fuzzysort"
5
+ import { Config } from "../config"
6
+ import { mapValues, mergeDeep, omit, pickBy, sortBy } from "remeda"
7
+ import { NoSuchModelError, type Provider as SDK } from "ai"
8
+ import { Log } from "../util"
9
+ import { Npm } from "../npm"
10
+ import { Hash } from "@sleepy-ai/shared/util/hash"
11
+ import { Plugin } from "../plugin"
12
+ import { NamedError } from "@sleepy-ai/shared/util/error"
13
+ import { type LanguageModelV3 } from "@ai-sdk/provider"
14
+ import * as ModelsDev from "./models"
15
+ import { Auth } from "../auth"
16
+ import { Env } from "../env"
17
+ import { InstallationVersion } from "../installation/version"
18
+ import { Flag } from "../flag/flag"
19
+ import { zod } from "@/util/effect-zod"
20
+ import { iife } from "@/util/iife"
21
+ import { Global } from "../global"
22
+ import path from "path"
23
+ import { pathToFileURL } from "url"
24
+ import { Effect, Layer, Context, Schema, Types } from "effect"
25
+ import { EffectBridge } from "@/effect"
26
+ import { InstanceState } from "@/effect"
27
+ import { AppFileSystem } from "@sleepy-ai/shared/filesystem"
28
+ import { isRecord } from "@/util/record"
29
+ import { withStatics } from "@/util/schema"
30
+
31
+ import * as ProviderTransform from "./transform"
32
+ import { ModelID, ProviderID } from "./schema"
33
+ import { createSessionChecker } from "./session-check"
34
+
35
+ const log = Log.create({ service: "provider" })
36
+ const DEFAULT_CONTEXT_WINDOW = 1_000_000
37
+ // Reserved built-in model tiers: always resolve, falling back to the default
38
+ // model when not configured in `model_groups` (zero-config never errors).
39
+ const BUILTIN_TIERS = new Set(["ultra", "standard", "lite"])
40
+ // F41: warn once per (providerID, modelID) when limit.context falls back to default
41
+ const warnedContextDefaults = new Set<string>()
42
+
43
+ export const DEFAULT_CHUNK_TIMEOUT = 480_000 // 8 minutes — bounds single-attempt SSE stall.
44
+ // Tuned for sleepy-v2.5-pro on Sleepy Router whose cold-path TTFT after context
45
+ // rebuild can dip to ~5 minutes silent. Reasoning models with multi-minute
46
+ // thinking still emit partial chunks / heartbeats within this window. Override
47
+ // per-provider via sleepycode.json's `chunkTimeout` config for tighter or looser
48
+ // bounds.
49
+
50
+ function shouldUseCopilotResponsesApi(modelID: string): boolean {
51
+ const match = /^gpt-(\d+)/.exec(modelID)
52
+ if (!match) return false
53
+ return Number(match[1]) >= 5 && !modelID.startsWith("gpt-5-mini")
54
+ }
55
+
56
+ function wrapSSE(res: Response, ms: number, ctl: AbortController) {
57
+ if (typeof ms !== "number" || ms <= 0) return res
58
+ if (!res.body) return res
59
+ if (!res.headers.get("content-type")?.includes("text/event-stream")) return res
60
+
61
+ const reader = res.body.getReader()
62
+ const body = new ReadableStream<Uint8Array>({
63
+ async pull(ctrl) {
64
+ const part = await new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => {
65
+ const id = setTimeout(() => {
66
+ const err = new Error("SSE read timed out")
67
+ ctl.abort(err)
68
+ void reader.cancel(err)
69
+ reject(err)
70
+ }, ms)
71
+
72
+ reader.read().then(
73
+ (part) => {
74
+ clearTimeout(id)
75
+ resolve(part)
76
+ },
77
+ (err) => {
78
+ clearTimeout(id)
79
+ reject(err)
80
+ },
81
+ )
82
+ })
83
+
84
+ if (part.done) {
85
+ ctrl.close()
86
+ return
87
+ }
88
+
89
+ ctrl.enqueue(part.value)
90
+ },
91
+ async cancel(reason) {
92
+ ctl.abort(reason)
93
+ await reader.cancel(reason)
94
+ },
95
+ })
96
+
97
+ return new Response(body, {
98
+ headers: new Headers(res.headers),
99
+ status: res.status,
100
+ statusText: res.statusText,
101
+ })
102
+ }
103
+
104
+ interface GatewayModel {
105
+ modelId: string
106
+ name: string
107
+ omniRouteModelId?: string
108
+ contextWindow?: number
109
+ maxOutputLimit?: number
110
+ inputPrice?: number
111
+ outputPrice?: number
112
+ cacheReadPrice?: number
113
+ cacheWritePrice?: number
114
+ }
115
+
116
+ async function fetchModels(endpoint: string, token: string): Promise<GatewayModel[]> {
117
+ try {
118
+ const res = await fetch(`${endpoint}/api/v1/models`, {
119
+ headers: { Authorization: `Bearer ${token}` },
120
+ })
121
+ if (!res.ok) return []
122
+ const json = await res.json()
123
+ if (json && json.data && Array.isArray(json.data)) {
124
+ return json.data as GatewayModel[]
125
+ }
126
+ return []
127
+ } catch {
128
+ return []
129
+ }
130
+ }
131
+
132
+ async function tryRefreshStartup(
133
+ dashboardUrl: string,
134
+ refreshToken: string,
135
+ ): Promise<{ access_token: string; refresh_token: string; expires_in: number } | null> {
136
+ const res = await fetch(`${dashboardUrl}/api/auth/token/refresh`, {
137
+ method: "POST",
138
+ headers: { "Content-Type": "application/json" },
139
+ body: JSON.stringify({ refresh_token: refreshToken }),
140
+ })
141
+ return res.ok ? res.json() : null
142
+ }
143
+
144
+ type BundledSDK = {
145
+ languageModel(modelId: string): LanguageModelV3
146
+ }
147
+
148
+ const BUNDLED_PROVIDERS: Record<string, () => Promise<(opts: any) => BundledSDK>> = {
149
+ "@ai-sdk/amazon-bedrock": () => import("@ai-sdk/amazon-bedrock").then((m) => m.createAmazonBedrock),
150
+ "@ai-sdk/anthropic": () => import("@ai-sdk/anthropic").then((m) => m.createAnthropic),
151
+ "@ai-sdk/azure": () => import("@ai-sdk/azure").then((m) => m.createAzure),
152
+ "@ai-sdk/google": () => import("@ai-sdk/google").then((m) => m.createGoogleGenerativeAI),
153
+ "@ai-sdk/google-vertex": () => import("@ai-sdk/google-vertex").then((m) => m.createVertex),
154
+ "@ai-sdk/google-vertex/anthropic": () =>
155
+ import("@ai-sdk/google-vertex/anthropic").then((m) => m.createVertexAnthropic),
156
+ "@ai-sdk/openai": () => import("@ai-sdk/openai").then((m) => m.createOpenAI),
157
+ "@ai-sdk/openai-compatible": () => import("@ai-sdk/openai-compatible").then((m) => m.createOpenAICompatible),
158
+ "@openrouter/ai-sdk-provider": () => import("@openrouter/ai-sdk-provider").then((m) => m.createOpenRouter),
159
+ "@ai-sdk/xai": () => import("@ai-sdk/xai").then((m) => m.createXai),
160
+ "@ai-sdk/mistral": () => import("@ai-sdk/mistral").then((m) => m.createMistral),
161
+ "@ai-sdk/groq": () => import("@ai-sdk/groq").then((m) => m.createGroq),
162
+ "@ai-sdk/deepinfra": () => import("@ai-sdk/deepinfra").then((m) => m.createDeepInfra),
163
+ "@ai-sdk/cerebras": () => import("@ai-sdk/cerebras").then((m) => m.createCerebras),
164
+ "@ai-sdk/cohere": () => import("@ai-sdk/cohere").then((m) => m.createCohere),
165
+ "@ai-sdk/gateway": () => import("@ai-sdk/gateway").then((m) => m.createGateway),
166
+ "@ai-sdk/togetherai": () => import("@ai-sdk/togetherai").then((m) => m.createTogetherAI),
167
+ "@ai-sdk/perplexity": () => import("@ai-sdk/perplexity").then((m) => m.createPerplexity),
168
+ "@ai-sdk/vercel": () => import("@ai-sdk/vercel").then((m) => m.createVercel),
169
+ "@ai-sdk/alibaba": () => import("@ai-sdk/alibaba").then((m) => m.createAlibaba),
170
+ "gitlab-ai-provider": () => import("gitlab-ai-provider").then((m) => m.createGitLab),
171
+ "@ai-sdk/github-copilot": () => import("./sdk/copilot").then((m) => m.createOpenaiCompatible),
172
+ "venice-ai-sdk-provider": () => import("venice-ai-sdk-provider").then((m) => m.createVenice),
173
+ }
174
+
175
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
176
+ type CustomVarsLoader = (options: Record<string, any>) => Record<string, string>
177
+ type CustomDiscoverModels = () => Promise<Record<string, Model>>
178
+ type CustomLoader = (provider: Info) => Effect.Effect<{
179
+ autoload: boolean
180
+ getModel?: CustomModelLoader
181
+ vars?: CustomVarsLoader
182
+ options?: Record<string, any>
183
+ discoverModels?: CustomDiscoverModels
184
+ }>
185
+
186
+ type CustomDep = {
187
+ auth: (id: string) => Effect.Effect<Auth.Info | undefined>
188
+ config: () => Effect.Effect<Config.Info>
189
+ env: () => Effect.Effect<Record<string, string | undefined>>
190
+ get: (key: string) => Effect.Effect<string | undefined>
191
+ }
192
+
193
+ function useLanguageModel(sdk: any) {
194
+ return sdk.responses === undefined && sdk.chat === undefined
195
+ }
196
+
197
+ function custom(dep: CustomDep): Record<string, CustomLoader> {
198
+ return {
199
+ anthropic: () =>
200
+ Effect.succeed({
201
+ autoload: false,
202
+ options: {
203
+ headers: {
204
+ "anthropic-beta": "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
205
+ },
206
+ },
207
+ }),
208
+ opencode: Effect.fnUntraced(function* (input: Info) {
209
+ const env = yield* dep.env()
210
+ const hasKey = iife(() => {
211
+ if (input.env.some((item) => env[item])) return true
212
+ return false
213
+ })
214
+ const ok =
215
+ hasKey ||
216
+ Boolean(yield* dep.auth(input.id)) ||
217
+ Boolean((yield* dep.config()).provider?.["opencode"]?.options?.apiKey)
218
+
219
+ // Never surface the free/public tier (cost.input === 0). Without a
220
+ // subscription/key, hide the remaining (paid) models too — they can't be
221
+ // used unauthenticated. So: authenticated -> subscription models only,
222
+ // unauthenticated -> nothing.
223
+ for (const [key, value] of Object.entries(input.models)) {
224
+ if (!ok || value.cost.input === 0) delete input.models[key]
225
+ }
226
+
227
+ return {
228
+ autoload: Object.keys(input.models).length > 0,
229
+ options: {},
230
+ }
231
+ }),
232
+ openai: () =>
233
+ Effect.succeed({
234
+ autoload: false,
235
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
236
+ return sdk.responses(modelID)
237
+ },
238
+ options: {},
239
+ }),
240
+ xai: () =>
241
+ Effect.succeed({
242
+ autoload: false,
243
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
244
+ return sdk.responses(modelID)
245
+ },
246
+ options: {},
247
+ }),
248
+ "github-copilot": () =>
249
+ Effect.succeed({
250
+ autoload: false,
251
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
252
+ if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
253
+ return shouldUseCopilotResponsesApi(modelID) ? sdk.responses(modelID) : sdk.chat(modelID)
254
+ },
255
+ options: {},
256
+ }),
257
+ azure: Effect.fnUntraced(function* (provider: Info) {
258
+ const env = yield* dep.env()
259
+ const resource = iife(() => {
260
+ const name = provider.options?.resourceName
261
+ if (typeof name === "string" && name.trim() !== "") return name
262
+ return env["AZURE_RESOURCE_NAME"]
263
+ })
264
+
265
+ return {
266
+ autoload: false,
267
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
268
+ if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
269
+ if (options?.["useCompletionUrls"]) {
270
+ return sdk.chat(modelID)
271
+ } else {
272
+ return sdk.responses(modelID)
273
+ }
274
+ },
275
+ options: {},
276
+ vars(_options) {
277
+ return {
278
+ ...(resource && { AZURE_RESOURCE_NAME: resource }),
279
+ }
280
+ },
281
+ }
282
+ }),
283
+ "azure-cognitive-services": Effect.fnUntraced(function* () {
284
+ const resourceName = yield* dep.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
285
+ return {
286
+ autoload: false,
287
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
288
+ if (useLanguageModel(sdk)) return sdk.languageModel(modelID)
289
+ if (options?.["useCompletionUrls"]) {
290
+ return sdk.chat(modelID)
291
+ } else {
292
+ return sdk.responses(modelID)
293
+ }
294
+ },
295
+ options: {
296
+ baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
297
+ },
298
+ }
299
+ }),
300
+ "amazon-bedrock": Effect.fnUntraced(function* () {
301
+ const providerConfig = (yield* dep.config()).provider?.["amazon-bedrock"]
302
+ const auth = yield* dep.auth("amazon-bedrock")
303
+ const env = yield* dep.env()
304
+
305
+ // Region precedence: 1) config file, 2) env var, 3) default
306
+ const configRegion = providerConfig?.options?.region
307
+ const envRegion = env["AWS_REGION"]
308
+ const defaultRegion = configRegion ?? envRegion ?? "us-east-1"
309
+
310
+ // Profile: config file takes precedence over env var
311
+ const configProfile = providerConfig?.options?.profile
312
+ const envProfile = env["AWS_PROFILE"]
313
+ const profile = configProfile ?? envProfile
314
+
315
+ const awsAccessKeyId = env["AWS_ACCESS_KEY_ID"]
316
+
317
+ // TODO: Using process.env directly because Env.set only updates a process.env shallow copy,
318
+ // until the scope of the Env API is clarified (test only or runtime?)
319
+ const awsBearerToken = iife(() => {
320
+ const envToken = process.env.AWS_BEARER_TOKEN_BEDROCK
321
+ if (envToken) return envToken
322
+ if (auth?.type === "api") {
323
+ process.env.AWS_BEARER_TOKEN_BEDROCK = auth.key
324
+ return auth.key
325
+ }
326
+ return undefined
327
+ })
328
+
329
+ const awsWebIdentityTokenFile = env["AWS_WEB_IDENTITY_TOKEN_FILE"]
330
+
331
+ const containerCreds = Boolean(
332
+ process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI || process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI,
333
+ )
334
+
335
+ if (!profile && !awsAccessKeyId && !awsBearerToken && !awsWebIdentityTokenFile && !containerCreds)
336
+ return { autoload: false }
337
+
338
+ const { fromNodeProviderChain } = yield* Effect.promise(() => import("@aws-sdk/credential-providers"))
339
+
340
+ const providerOptions: Record<string, any> = {
341
+ region: defaultRegion,
342
+ }
343
+
344
+ // Only use credential chain if no bearer token exists
345
+ // Bearer token takes precedence over credential chain (profiles, access keys, IAM roles, web identity tokens)
346
+ if (!awsBearerToken) {
347
+ // Build credential provider options (only pass profile if specified)
348
+ const credentialProviderOptions = profile ? { profile } : {}
349
+
350
+ providerOptions.credentialProvider = fromNodeProviderChain(credentialProviderOptions)
351
+ }
352
+
353
+ // Add custom endpoint if specified (endpoint takes precedence over baseURL)
354
+ const endpoint = providerConfig?.options?.endpoint ?? providerConfig?.options?.baseURL
355
+ if (endpoint) {
356
+ providerOptions.baseURL = endpoint
357
+ }
358
+
359
+ return {
360
+ autoload: true,
361
+ options: providerOptions,
362
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
363
+ // Skip region prefixing if model already has a cross-region inference profile prefix
364
+ // Models from models.dev may already include prefixes like us., eu., global., etc.
365
+ const crossRegionPrefixes = ["global.", "us.", "eu.", "jp.", "apac.", "au."]
366
+ if (crossRegionPrefixes.some((prefix) => modelID.startsWith(prefix))) {
367
+ return sdk.languageModel(modelID)
368
+ }
369
+
370
+ // Region resolution precedence (highest to lowest):
371
+ // 1. options.region from sleepycode.json provider config
372
+ // 2. defaultRegion from AWS_REGION environment variable
373
+ // 3. Default "us-east-1" (baked into defaultRegion)
374
+ const region = options?.region ?? defaultRegion
375
+
376
+ let regionPrefix = region.split("-")[0]
377
+
378
+ switch (regionPrefix) {
379
+ case "us": {
380
+ const modelRequiresPrefix = [
381
+ "nova-micro",
382
+ "nova-lite",
383
+ "nova-pro",
384
+ "nova-premier",
385
+ "nova-2",
386
+ "claude",
387
+ "deepseek",
388
+ ].some((m) => modelID.includes(m))
389
+ const isGovCloud = region.startsWith("us-gov")
390
+ if (modelRequiresPrefix && !isGovCloud) {
391
+ modelID = `${regionPrefix}.${modelID}`
392
+ }
393
+ break
394
+ }
395
+ case "eu": {
396
+ const regionRequiresPrefix = [
397
+ "eu-west-1",
398
+ "eu-west-2",
399
+ "eu-west-3",
400
+ "eu-north-1",
401
+ "eu-central-1",
402
+ "eu-south-1",
403
+ "eu-south-2",
404
+ ].some((r) => region.includes(r))
405
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
406
+ modelID.includes(m),
407
+ )
408
+ if (regionRequiresPrefix && modelRequiresPrefix) {
409
+ modelID = `${regionPrefix}.${modelID}`
410
+ }
411
+ break
412
+ }
413
+ case "ap": {
414
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
415
+ const isTokyoRegion = region === "ap-northeast-1"
416
+ if (
417
+ isAustraliaRegion &&
418
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
419
+ ) {
420
+ regionPrefix = "au"
421
+ modelID = `${regionPrefix}.${modelID}`
422
+ } else if (isTokyoRegion) {
423
+ // Tokyo region uses jp. prefix for cross-region inference
424
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
425
+ modelID.includes(m),
426
+ )
427
+ if (modelRequiresPrefix) {
428
+ regionPrefix = "jp"
429
+ modelID = `${regionPrefix}.${modelID}`
430
+ }
431
+ } else {
432
+ // Other APAC regions use apac. prefix
433
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
434
+ modelID.includes(m),
435
+ )
436
+ if (modelRequiresPrefix) {
437
+ regionPrefix = "apac"
438
+ modelID = `${regionPrefix}.${modelID}`
439
+ }
440
+ }
441
+ break
442
+ }
443
+ }
444
+
445
+ return sdk.languageModel(modelID)
446
+ },
447
+ }
448
+ }),
449
+ llmgateway: () =>
450
+ Effect.succeed({
451
+ autoload: false,
452
+ options: {
453
+ headers: {
454
+ "HTTP-Referer": "https://www.sleepyai.org/",
455
+ "X-Title": "sleepy-code",
456
+ "X-Source": "sleepycode",
457
+ },
458
+ },
459
+ }),
460
+ openrouter: () =>
461
+ Effect.succeed({
462
+ autoload: false,
463
+ options: {
464
+ headers: {
465
+ "HTTP-Referer": "https://www.sleepyai.org/",
466
+ "X-Title": "sleepy-code",
467
+ "X-OpenRouter-Categories": "programming,programming-app,cli-agent",
468
+ },
469
+ },
470
+ }),
471
+ nvidia: () =>
472
+ Effect.succeed({
473
+ autoload: false,
474
+ options: {
475
+ headers: {
476
+ "HTTP-Referer": "https://www.sleepyai.org/",
477
+ "X-Title": "sleepy-code",
478
+ },
479
+ },
480
+ }),
481
+ vercel: () =>
482
+ Effect.succeed({
483
+ autoload: false,
484
+ options: {
485
+ headers: {
486
+ "http-referer": "https://www.sleepyai.org/",
487
+ "x-title": "sleepy-code",
488
+ },
489
+ },
490
+ }),
491
+ "google-vertex": Effect.fnUntraced(function* (provider: Info) {
492
+ const env = yield* dep.env()
493
+ const project =
494
+ provider.options?.project ?? env["GOOGLE_CLOUD_PROJECT"] ?? env["GCP_PROJECT"] ?? env["GCLOUD_PROJECT"]
495
+
496
+ const location = String(
497
+ provider.options?.location ??
498
+ env["GOOGLE_VERTEX_LOCATION"] ??
499
+ env["GOOGLE_CLOUD_LOCATION"] ??
500
+ env["VERTEX_LOCATION"] ??
501
+ "us-central1",
502
+ )
503
+
504
+ const autoload = Boolean(project)
505
+ if (!autoload) return { autoload: false }
506
+ return {
507
+ autoload: true,
508
+ vars(_options: Record<string, any>) {
509
+ const endpoint = location === "global" ? "aiplatform.googleapis.com" : `${location}-aiplatform.googleapis.com`
510
+ return {
511
+ ...(project && { GOOGLE_VERTEX_PROJECT: project }),
512
+ GOOGLE_VERTEX_LOCATION: location,
513
+ GOOGLE_VERTEX_ENDPOINT: endpoint,
514
+ }
515
+ },
516
+ options: {
517
+ project,
518
+ location,
519
+ fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
520
+ const { GoogleAuth } = await import("google-auth-library")
521
+ const auth = new GoogleAuth()
522
+ const client = await auth.getApplicationDefault()
523
+ const token = await client.credential.getAccessToken()
524
+
525
+ const headers = new Headers(init?.headers)
526
+ headers.set("Authorization", `Bearer ${token.token}`)
527
+
528
+ return fetch(input, { ...init, headers })
529
+ },
530
+ },
531
+ async getModel(sdk: any, modelID: string) {
532
+ const id = String(modelID).trim()
533
+ return sdk.languageModel(id)
534
+ },
535
+ }
536
+ }),
537
+ "google-vertex-anthropic": Effect.fnUntraced(function* () {
538
+ const env = yield* dep.env()
539
+ const project = env["GOOGLE_CLOUD_PROJECT"] ?? env["GCP_PROJECT"] ?? env["GCLOUD_PROJECT"]
540
+ const location = env["GOOGLE_CLOUD_LOCATION"] ?? env["VERTEX_LOCATION"] ?? "global"
541
+ const autoload = Boolean(project)
542
+ if (!autoload) return { autoload: false }
543
+ return {
544
+ autoload: true,
545
+ options: {
546
+ project,
547
+ location,
548
+ },
549
+ async getModel(sdk: any, modelID) {
550
+ const id = String(modelID).trim()
551
+ return sdk.languageModel(id)
552
+ },
553
+ }
554
+ }),
555
+ "sap-ai-core": Effect.fnUntraced(function* () {
556
+ const auth = yield* dep.auth("sap-ai-core")
557
+ // TODO: Using process.env directly because Env.set only updates a shallow copy (not process.env),
558
+ // until the scope of the Env API is clarified (test only or runtime?)
559
+ const envServiceKey = iife(() => {
560
+ const envAICoreServiceKey = process.env.AICORE_SERVICE_KEY
561
+ if (envAICoreServiceKey) return envAICoreServiceKey
562
+ if (auth?.type === "api") {
563
+ process.env.AICORE_SERVICE_KEY = auth.key
564
+ return auth.key
565
+ }
566
+ return undefined
567
+ })
568
+ const deploymentId = process.env.AICORE_DEPLOYMENT_ID
569
+ const resourceGroup = process.env.AICORE_RESOURCE_GROUP
570
+
571
+ return {
572
+ autoload: !!envServiceKey,
573
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
574
+ async getModel(sdk: any, modelID: string) {
575
+ return sdk(modelID)
576
+ },
577
+ }
578
+ }),
579
+ zenmux: () =>
580
+ Effect.succeed({
581
+ autoload: false,
582
+ options: {
583
+ headers: {
584
+ "HTTP-Referer": "https://www.sleepyai.org/",
585
+ "X-Title": "sleepy-code",
586
+ },
587
+ },
588
+ }),
589
+ gitlab: Effect.fnUntraced(function* (input: Info) {
590
+ const {
591
+ VERSION: GITLAB_PROVIDER_VERSION,
592
+ isWorkflowModel,
593
+ discoverWorkflowModels,
594
+ } = yield* Effect.promise(() => import("gitlab-ai-provider"))
595
+
596
+ const instanceUrl = (yield* dep.get("GITLAB_INSTANCE_URL")) || "https://gitlab.com"
597
+
598
+ const auth = yield* dep.auth(input.id)
599
+ const apiKey = yield* Effect.sync(() => {
600
+ if (auth?.type === "oauth") return auth.access
601
+ if (auth?.type === "api") return auth.key
602
+ return undefined
603
+ })
604
+ const token = apiKey ?? (yield* dep.get("GITLAB_TOKEN"))
605
+
606
+ const providerConfig = (yield* dep.config()).provider?.["gitlab"]
607
+ const directory = yield* InstanceState.directory
608
+
609
+ const aiGatewayHeaders = {
610
+ "User-Agent": `sleepycode/${InstallationVersion} gitlab-ai-provider/${GITLAB_PROVIDER_VERSION} (${os.platform()} ${os.release()}; ${os.arch()})`,
611
+ "anthropic-beta": "context-1m-2025-08-07",
612
+ ...providerConfig?.options?.aiGatewayHeaders,
613
+ }
614
+
615
+ const featureFlags = {
616
+ duo_agent_platform_agentic_chat: true,
617
+ duo_agent_platform: true,
618
+ ...providerConfig?.options?.featureFlags,
619
+ }
620
+
621
+ return {
622
+ autoload: !!token,
623
+ options: {
624
+ instanceUrl,
625
+ apiKey: token,
626
+ aiGatewayHeaders,
627
+ featureFlags,
628
+ },
629
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
630
+ if (modelID.startsWith("duo-workflow-")) {
631
+ const workflowRef = typeof options?.workflowRef === "string" ? options.workflowRef : undefined
632
+ // Use the static mapping if it exists, otherwise use duo-workflow with selectedModelRef
633
+ const sdkModelID = isWorkflowModel(modelID) ? modelID : "duo-workflow"
634
+ const workflowDefinition =
635
+ typeof options?.workflowDefinition === "string" ? options.workflowDefinition : undefined
636
+ const model = sdk.workflowChat(sdkModelID, {
637
+ featureFlags,
638
+ workflowDefinition,
639
+ })
640
+ if (workflowRef) {
641
+ model.selectedModelRef = workflowRef
642
+ }
643
+ return model
644
+ }
645
+ return sdk.agenticChat(modelID, {
646
+ aiGatewayHeaders,
647
+ featureFlags,
648
+ })
649
+ },
650
+ async discoverModels(): Promise<Record<string, Model>> {
651
+ if (!apiKey) {
652
+ log.info("gitlab model discovery skipped: no apiKey")
653
+ return {}
654
+ }
655
+
656
+ try {
657
+ const token = apiKey
658
+ const getHeaders = (): Record<string, string> =>
659
+ auth?.type === "api" ? { "PRIVATE-TOKEN": token } : { Authorization: `Bearer ${token}` }
660
+
661
+ log.info("gitlab model discovery starting", { instanceUrl })
662
+ const result = await discoverWorkflowModels({ instanceUrl, getHeaders }, { workingDirectory: directory })
663
+
664
+ if (!result.models.length) {
665
+ log.info("gitlab model discovery skipped: no models found", {
666
+ project: result.project
667
+ ? {
668
+ id: result.project.id,
669
+ path: result.project.pathWithNamespace,
670
+ }
671
+ : null,
672
+ })
673
+ return {}
674
+ }
675
+
676
+ const models: Record<string, Model> = {}
677
+ for (const m of result.models) {
678
+ if (!input.models[m.id]) {
679
+ models[m.id] = {
680
+ id: ModelID.make(m.id),
681
+ providerID: ProviderID.make("gitlab"),
682
+ name: `Agent Platform (${m.name})`,
683
+ family: "",
684
+ api: {
685
+ id: m.id,
686
+ url: instanceUrl,
687
+ npm: "gitlab-ai-provider",
688
+ },
689
+ status: "active",
690
+ headers: {},
691
+ options: { workflowRef: m.ref },
692
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
693
+ limit: { context: m.context, output: m.output },
694
+ capabilities: {
695
+ temperature: false,
696
+ reasoning: true,
697
+ attachment: true,
698
+ toolcall: true,
699
+ input: {
700
+ text: true,
701
+ audio: false,
702
+ image: true,
703
+ video: false,
704
+ pdf: true,
705
+ },
706
+ output: {
707
+ text: true,
708
+ audio: false,
709
+ image: false,
710
+ video: false,
711
+ pdf: false,
712
+ },
713
+ interleaved: false,
714
+ },
715
+ release_date: "",
716
+ variants: {},
717
+ }
718
+ }
719
+ }
720
+
721
+ log.info("gitlab model discovery complete", {
722
+ count: Object.keys(models).length,
723
+ models: Object.keys(models),
724
+ })
725
+ return models
726
+ } catch (e) {
727
+ log.warn("gitlab model discovery failed", { error: e })
728
+ return {}
729
+ }
730
+ },
731
+ }
732
+ }),
733
+ "cloudflare-workers-ai": Effect.fnUntraced(function* (input: Info) {
734
+ // When baseURL is already configured (e.g. corporate config routing through a proxy/gateway),
735
+ // skip the account ID check because the URL is already fully specified.
736
+ if (input.options?.baseURL) return { autoload: false }
737
+
738
+ const auth = yield* dep.auth(input.id)
739
+ const env = yield* dep.env()
740
+ const accountId = env["CLOUDFLARE_ACCOUNT_ID"] || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
741
+ if (!accountId)
742
+ return {
743
+ autoload: false,
744
+ async getModel() {
745
+ throw new Error(
746
+ "CLOUDFLARE_ACCOUNT_ID is missing. Set it with: export CLOUDFLARE_ACCOUNT_ID=<your-account-id>",
747
+ )
748
+ },
749
+ }
750
+
751
+ const apiKey = yield* Effect.gen(function* () {
752
+ const envToken = env["CLOUDFLARE_API_KEY"]
753
+ if (envToken) return envToken
754
+ if (auth?.type === "api") return auth.key
755
+ return undefined
756
+ })
757
+
758
+ return {
759
+ autoload: !!apiKey,
760
+ options: {
761
+ apiKey,
762
+ headers: {
763
+ "User-Agent": `sleepycode/${InstallationVersion} cloudflare-workers-ai (${os.platform()} ${os.release()}; ${os.arch()})`,
764
+ },
765
+ },
766
+ async getModel(sdk: any, modelID: string) {
767
+ return sdk.languageModel(modelID)
768
+ },
769
+ vars(_options) {
770
+ return {
771
+ CLOUDFLARE_ACCOUNT_ID: accountId,
772
+ }
773
+ },
774
+ }
775
+ }),
776
+ "cloudflare-ai-gateway": Effect.fnUntraced(function* (input: Info) {
777
+ // When baseURL is already configured (e.g. corporate config), skip the ID checks.
778
+ if (input.options?.baseURL) return { autoload: false }
779
+
780
+ const auth = yield* dep.auth(input.id)
781
+ const env = yield* dep.env()
782
+ const accountId = env["CLOUDFLARE_ACCOUNT_ID"] || (auth?.type === "api" ? auth.metadata?.accountId : undefined)
783
+ const gateway = env["CLOUDFLARE_GATEWAY_ID"] || (auth?.type === "api" ? auth.metadata?.gatewayId : undefined)
784
+
785
+ if (!accountId || !gateway) {
786
+ const missing = [
787
+ !accountId ? "CLOUDFLARE_ACCOUNT_ID" : undefined,
788
+ !gateway ? "CLOUDFLARE_GATEWAY_ID" : undefined,
789
+ ].filter((x): x is string => Boolean(x))
790
+ return {
791
+ autoload: false,
792
+ async getModel() {
793
+ throw new Error(
794
+ `${missing.join(" and ")} missing. Set with: ${missing.map((x) => `export ${x}=<value>`).join(" && ")}`,
795
+ )
796
+ },
797
+ }
798
+ }
799
+
800
+ // Get API token from env or auth - required for authenticated gateways
801
+ const apiToken = yield* Effect.gen(function* () {
802
+ const envToken = env["CLOUDFLARE_API_TOKEN"] || env["CF_AIG_TOKEN"]
803
+ if (envToken) return envToken
804
+ if (auth?.type === "api") return auth.key
805
+ return undefined
806
+ })
807
+
808
+ if (!apiToken) {
809
+ throw new Error(
810
+ "CLOUDFLARE_API_TOKEN (or CF_AIG_TOKEN) is required for Cloudflare AI Gateway. " +
811
+ "Set it via environment variable or run `sleepycode auth cloudflare-ai-gateway`.",
812
+ )
813
+ }
814
+
815
+ // Use official ai-gateway-provider package (v2.x for AI SDK v5 compatibility)
816
+ const { createAiGateway } = yield* Effect.promise(() => import("ai-gateway-provider"))
817
+ const { createUnified } = yield* Effect.promise(() => import("ai-gateway-provider/providers/unified"))
818
+
819
+ const metadata = iife(() => {
820
+ if (input.options?.metadata) return input.options.metadata
821
+ try {
822
+ return JSON.parse(input.options?.headers?.["cf-aig-metadata"])
823
+ } catch {
824
+ return undefined
825
+ }
826
+ })
827
+ const opts = {
828
+ metadata,
829
+ cacheTtl: input.options?.cacheTtl,
830
+ cacheKey: input.options?.cacheKey,
831
+ skipCache: input.options?.skipCache,
832
+ collectLog: input.options?.collectLog,
833
+ headers: {
834
+ "User-Agent": `sleepycode/${InstallationVersion} cloudflare-ai-gateway (${os.platform()} ${os.release()}; ${os.arch()})`,
835
+ },
836
+ }
837
+
838
+ const aigateway = createAiGateway({
839
+ accountId,
840
+ gateway,
841
+ apiKey: apiToken,
842
+ ...(Object.values(opts).some((v) => v !== undefined) ? { options: opts } : {}),
843
+ })
844
+ const unified = createUnified()
845
+
846
+ return {
847
+ autoload: true,
848
+ async getModel(_sdk: any, modelID: string, _options?: Record<string, any>) {
849
+ // Model IDs use Unified API format: provider/model (e.g., "anthropic/claude-sonnet-4-5")
850
+ return aigateway(unified(modelID))
851
+ },
852
+ options: {},
853
+ }
854
+ }),
855
+ cerebras: () =>
856
+ Effect.succeed({
857
+ autoload: false,
858
+ options: {
859
+ headers: {
860
+ "X-Cerebras-3rd-Party-Integration": "sleepycode",
861
+ },
862
+ },
863
+ }),
864
+ kilo: () =>
865
+ Effect.succeed({
866
+ autoload: false,
867
+ options: {
868
+ headers: {
869
+ "HTTP-Referer": "https://www.sleepyai.org/",
870
+ "X-Title": "sleepy-code",
871
+ },
872
+ },
873
+ }),
874
+ }
875
+ }
876
+
877
+ const ProviderApiInfo = Schema.Struct({
878
+ id: Schema.String,
879
+ url: Schema.String,
880
+ npm: Schema.String,
881
+ })
882
+
883
+ const ProviderModalities = Schema.Struct({
884
+ text: Schema.Boolean,
885
+ audio: Schema.Boolean,
886
+ image: Schema.Boolean,
887
+ video: Schema.Boolean,
888
+ pdf: Schema.Boolean,
889
+ })
890
+
891
+ const ProviderInterleaved = Schema.Union([
892
+ Schema.Boolean,
893
+ Schema.Struct({
894
+ field: Schema.Literals(["reasoning_content", "reasoning_details"]),
895
+ }),
896
+ ])
897
+
898
+ const ProviderCapabilities = Schema.Struct({
899
+ temperature: Schema.Boolean,
900
+ reasoning: Schema.Boolean,
901
+ attachment: Schema.Boolean,
902
+ toolcall: Schema.Boolean,
903
+ input: ProviderModalities,
904
+ output: ProviderModalities,
905
+ interleaved: ProviderInterleaved,
906
+ })
907
+
908
+ const ProviderCacheCost = Schema.Struct({
909
+ read: Schema.Number,
910
+ write: Schema.Number,
911
+ })
912
+
913
+ const ProviderCost = Schema.Struct({
914
+ input: Schema.Number,
915
+ output: Schema.Number,
916
+ cache: ProviderCacheCost,
917
+ experimentalOver200K: Schema.optional(
918
+ Schema.Struct({
919
+ input: Schema.Number,
920
+ output: Schema.Number,
921
+ cache: ProviderCacheCost,
922
+ }),
923
+ ),
924
+ })
925
+
926
+ const ProviderLimit = Schema.Struct({
927
+ context: Schema.Number,
928
+ input: Schema.optional(Schema.Number),
929
+ output: Schema.Number,
930
+ })
931
+
932
+ export const Model = Schema.Struct({
933
+ id: ModelID,
934
+ providerID: ProviderID,
935
+ api: ProviderApiInfo,
936
+ name: Schema.String,
937
+ family: Schema.optional(Schema.String),
938
+ capabilities: ProviderCapabilities,
939
+ cost: ProviderCost,
940
+ limit: ProviderLimit,
941
+ status: Schema.Literals(["alpha", "beta", "deprecated", "active"]),
942
+ options: Schema.Record(Schema.String, Schema.Any),
943
+ headers: Schema.Record(Schema.String, Schema.String),
944
+ release_date: Schema.String,
945
+ variants: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Any))),
946
+ cacheTTL: Schema.optional(Schema.Number),
947
+ cachePromptTTL: Schema.optional(Schema.Literals(["5m", "1h"])),
948
+ })
949
+ .annotate({ identifier: "Model" })
950
+ .pipe(withStatics((s) => ({ zod: zod(s) })))
951
+ export type Model = Types.DeepMutable<Schema.Schema.Type<typeof Model>>
952
+
953
+ export const Info = Schema.Struct({
954
+ id: ProviderID,
955
+ name: Schema.String,
956
+ source: Schema.Literals(["env", "config", "custom", "api"]),
957
+ env: Schema.Array(Schema.String),
958
+ key: Schema.optional(Schema.String),
959
+ options: Schema.Record(Schema.String, Schema.Any),
960
+ models: Schema.Record(Schema.String, Model),
961
+ })
962
+ .annotate({ identifier: "Provider" })
963
+ .pipe(withStatics((s) => ({ zod: zod(s) })))
964
+ export type Info = Types.DeepMutable<Schema.Schema.Type<typeof Info>>
965
+
966
+ const DefaultModelIDs = Schema.Record(Schema.String, Schema.String)
967
+
968
+ export const ListResult = Schema.Struct({
969
+ all: Schema.Array(Info),
970
+ default: DefaultModelIDs,
971
+ connected: Schema.Array(Schema.String),
972
+ }).pipe(withStatics((s) => ({ zod: zod(s) })))
973
+ export type ListResult = Types.DeepMutable<Schema.Schema.Type<typeof ListResult>>
974
+
975
+ export const ConfigProvidersResult = Schema.Struct({
976
+ providers: Schema.Array(Info),
977
+ default: DefaultModelIDs,
978
+ }).pipe(withStatics((s) => ({ zod: zod(s) })))
979
+ export type ConfigProvidersResult = Types.DeepMutable<Schema.Schema.Type<typeof ConfigProvidersResult>>
980
+
981
+ export function defaultModelIDs<T extends { models: Record<string, { id: string }> }>(providers: Record<string, T>) {
982
+ return mapValues(providers, (item) => sort(Object.values(item.models))[0].id)
983
+ }
984
+
985
+ export interface Interface {
986
+ readonly list: () => Effect.Effect<Record<ProviderID, Info>>
987
+ readonly getProvider: (providerID: ProviderID) => Effect.Effect<Info>
988
+ readonly getModel: (providerID: ProviderID, modelID: ModelID) => Effect.Effect<Model>
989
+ readonly getLanguage: (model: Model) => Effect.Effect<LanguageModelV3>
990
+ readonly closest: (
991
+ providerID: ProviderID,
992
+ query: string[],
993
+ ) => Effect.Effect<{ providerID: ProviderID; modelID: string } | undefined>
994
+ readonly getSmallModel: (providerID: ProviderID) => Effect.Effect<Model | undefined>
995
+ readonly resolveModelRef: (ref: string, contextProviderID?: ProviderID) => Effect.Effect<Model>
996
+ readonly defaultModel: () => Effect.Effect<{ providerID: ProviderID; modelID: ModelID }>
997
+ }
998
+
999
+ interface State {
1000
+ models: Map<string, LanguageModelV3>
1001
+ providers: Record<ProviderID, Info>
1002
+ sdk: Map<string, BundledSDK>
1003
+ modelLoaders: Record<string, CustomModelLoader>
1004
+ varsLoaders: Record<string, CustomVarsLoader>
1005
+ }
1006
+
1007
+ export class Service extends Context.Service<Service, Interface>()("@opencode/Provider") {}
1008
+
1009
+ function cost(c: ModelsDev.Model["cost"]): Model["cost"] {
1010
+ const result: Model["cost"] = {
1011
+ input: c?.input ?? 0,
1012
+ output: c?.output ?? 0,
1013
+ cache: {
1014
+ read: c?.cache_read ?? 0,
1015
+ write: c?.cache_write ?? 0,
1016
+ },
1017
+ }
1018
+ if (c?.context_over_200k) {
1019
+ result.experimentalOver200K = {
1020
+ cache: {
1021
+ read: c.context_over_200k.cache_read ?? 0,
1022
+ write: c.context_over_200k.cache_write ?? 0,
1023
+ },
1024
+ input: c.context_over_200k.input,
1025
+ output: c.context_over_200k.output,
1026
+ }
1027
+ }
1028
+ return result
1029
+ }
1030
+
1031
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
1032
+ const base: Model = {
1033
+ id: ModelID.make(model.id),
1034
+ providerID: ProviderID.make(provider.id),
1035
+ name: model.name,
1036
+ family: model.family,
1037
+ api: {
1038
+ id: model.id,
1039
+ url: model.provider?.api ?? provider.api ?? "",
1040
+ npm: model.provider?.npm ?? provider.npm ?? "@ai-sdk/openai-compatible",
1041
+ },
1042
+ status: model.status ?? "active",
1043
+ headers: {},
1044
+ options: {},
1045
+ cost: cost(model.cost),
1046
+ limit: {
1047
+ context: model.limit.context,
1048
+ input: model.limit.input,
1049
+ output: model.limit.output,
1050
+ },
1051
+ capabilities: {
1052
+ temperature: model.temperature ?? false,
1053
+ reasoning: model.reasoning ?? false,
1054
+ attachment: model.attachment ?? false,
1055
+ toolcall: model.tool_call ?? true,
1056
+ input: {
1057
+ text: model.modalities?.input?.includes("text") ?? false,
1058
+ audio: model.modalities?.input?.includes("audio") ?? false,
1059
+ image: model.modalities?.input?.includes("image") ?? false,
1060
+ video: model.modalities?.input?.includes("video") ?? false,
1061
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
1062
+ },
1063
+ output: {
1064
+ text: model.modalities?.output?.includes("text") ?? false,
1065
+ audio: model.modalities?.output?.includes("audio") ?? false,
1066
+ image: model.modalities?.output?.includes("image") ?? false,
1067
+ video: model.modalities?.output?.includes("video") ?? false,
1068
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
1069
+ },
1070
+ interleaved: model.interleaved ?? false,
1071
+ },
1072
+ release_date: model.release_date ?? "",
1073
+ variants: {},
1074
+ }
1075
+
1076
+ return {
1077
+ ...base,
1078
+ variants: mapValues(ProviderTransform.variants(base), (v) => v),
1079
+ }
1080
+ }
1081
+
1082
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
1083
+ const models: Record<string, Model> = {}
1084
+ for (const [key, model] of Object.entries(provider.models)) {
1085
+ models[key] = fromModelsDevModel(provider, model)
1086
+ for (const [mode, opts] of Object.entries(model.experimental?.modes ?? {})) {
1087
+ const id = `${model.id}-${mode}`
1088
+ const base = fromModelsDevModel(provider, model)
1089
+ models[id] = {
1090
+ ...base,
1091
+ id: ModelID.make(id),
1092
+ name: `${model.name} ${mode[0].toUpperCase()}${mode.slice(1)}`,
1093
+ cost: opts.cost ? mergeDeep(base.cost, cost(opts.cost)) : base.cost,
1094
+ options: opts.provider?.body
1095
+ ? Object.fromEntries(
1096
+ Object.entries(opts.provider.body).map(([k, v]) => [
1097
+ k.replace(/_([a-z])/g, (_, c) => c.toUpperCase()),
1098
+ v,
1099
+ ]),
1100
+ )
1101
+ : base.options,
1102
+ headers: opts.provider?.headers ?? base.headers,
1103
+ }
1104
+ }
1105
+ }
1106
+ return {
1107
+ id: ProviderID.make(provider.id),
1108
+ source: "custom",
1109
+ name: provider.name,
1110
+ env: provider.env ?? [],
1111
+ options: {},
1112
+ models,
1113
+ }
1114
+ }
1115
+
1116
+ const layer: Layer.Layer<
1117
+ Service,
1118
+ never,
1119
+ Config.Service | Auth.Service | Plugin.Service | AppFileSystem.Service | Env.Service
1120
+ > = Layer.effect(
1121
+ Service,
1122
+ Effect.gen(function* () {
1123
+ const fs = yield* AppFileSystem.Service
1124
+ const config = yield* Config.Service
1125
+ const auth = yield* Auth.Service
1126
+ const env = yield* Env.Service
1127
+ const plugin = yield* Plugin.Service
1128
+
1129
+ const state = yield* InstanceState.make<State>(() =>
1130
+ Effect.gen(function* () {
1131
+ using _ = log.time("state")
1132
+ const bridge = yield* EffectBridge.make()
1133
+ const cfg = yield* config.get()
1134
+ const modelsDev = yield* Effect.promise(() => ModelsDev.get())
1135
+ const database = mapValues(modelsDev, fromModelsDevProvider)
1136
+
1137
+ let sleepyCredentials: { token: string; dashboardUrl: string } | null = null
1138
+
1139
+ // Inject Sleepy Gateway provider from ~/.sleepy/gateway.json if credentials exist
1140
+ try {
1141
+ const sleepyConfigPath = path.join(Global.Path.config, "gateway.json")
1142
+ const sleepyConfigRaw = yield* Effect.promise(() =>
1143
+ fsNode.readFile(sleepyConfigPath, "utf-8").catch(() => null as string | null),
1144
+ )
1145
+ if (sleepyConfigRaw) {
1146
+ const sleepyConfig = JSON.parse(sleepyConfigRaw)
1147
+ const endpoint = sleepyConfig.endpoint
1148
+ let token = sleepyConfig.access_token || sleepyConfig.token
1149
+ const dashboardUrl = sleepyConfig.dashboard_url || "https://www.sleepyai.org"
1150
+
1151
+ if (token && sleepyConfig.refresh_token && sleepyConfig.expires_at && Date.now() > sleepyConfig.expires_at) {
1152
+ const refreshed = yield* Effect.promise(() =>
1153
+ tryRefreshStartup(dashboardUrl, sleepyConfig.refresh_token).catch(() => null),
1154
+ )
1155
+ if (refreshed) {
1156
+ token = refreshed.access_token
1157
+ const updated = {
1158
+ ...sleepyConfig,
1159
+ access_token: refreshed.access_token,
1160
+ refresh_token: refreshed.refresh_token,
1161
+ expires_at: Date.now() + (refreshed.expires_in ?? 3600) * 1000,
1162
+ }
1163
+ const tmpPath = sleepyConfigPath + ".tmp"
1164
+ yield* Effect.promise(() =>
1165
+ fsNode.writeFile(tmpPath, JSON.stringify(updated, null, 2)).then(() => fsNode.rename(tmpPath, sleepyConfigPath)).catch((err) => {
1166
+ log.error("failed to persist refreshed token — next startup will re-refresh", { error: err.message })
1167
+ }),
1168
+ )
1169
+ } else {
1170
+ yield* Effect.promise(() => fsNode.unlink(sleepyConfigPath).catch(() => {}))
1171
+ token = null
1172
+ }
1173
+ }
1174
+
1175
+ if (endpoint && token) {
1176
+ sleepyCredentials = { token, dashboardUrl }
1177
+ const sleepyProviderID = ProviderID.make("sleepy")
1178
+ const baseUrl = `${dashboardUrl}/api/v1`
1179
+ const authHeader = { Authorization: `Bearer ${token}` }
1180
+
1181
+ const fetchedModels = yield* Effect.promise(() => fetchModels(dashboardUrl, token))
1182
+
1183
+ let sleepyModels: Record<string, Model> = {}
1184
+
1185
+ if (fetchedModels.length > 0) {
1186
+ for (const m of fetchedModels) {
1187
+ sleepyModels[m.modelId] = {
1188
+ id: ModelID.make(m.modelId),
1189
+ providerID: sleepyProviderID,
1190
+ name: m.name,
1191
+ family: "sleepy",
1192
+ api: {
1193
+ id: m.omniRouteModelId || m.modelId,
1194
+ url: baseUrl,
1195
+ npm: "@ai-sdk/openai-compatible",
1196
+ },
1197
+ status: "active",
1198
+ headers: authHeader,
1199
+ options: {},
1200
+ cost: {
1201
+ input: m.inputPrice ?? 0.0015,
1202
+ output: m.outputPrice ?? 0.005,
1203
+ cache: {
1204
+ read: m.cacheReadPrice ?? 0.00075,
1205
+ write: m.cacheWritePrice ?? 0.0015,
1206
+ },
1207
+ },
1208
+ limit: {
1209
+ context: m.contextWindow ?? 128000,
1210
+ output: m.maxOutputLimit ?? 4096,
1211
+ },
1212
+ capabilities: {
1213
+ temperature: true,
1214
+ reasoning: true,
1215
+ attachment: true,
1216
+ toolcall: true,
1217
+ input: { text: true, audio: false, image: true, video: false, pdf: true },
1218
+ output: { text: true, audio: false, image: false, video: false, pdf: false },
1219
+ interleaved: false,
1220
+ },
1221
+ release_date: "",
1222
+ variants: {},
1223
+ }
1224
+ }
1225
+ } else {
1226
+ // No models fetched — provider registered but empty.
1227
+ // User must login so models can be fetched from the dashboard API.
1228
+ sleepyModels = {}
1229
+ }
1230
+
1231
+ database[sleepyProviderID] = {
1232
+ id: sleepyProviderID,
1233
+ source: "config",
1234
+ name: "Sleepy Gateway",
1235
+ env: [],
1236
+ options: {
1237
+ baseURL: baseUrl,
1238
+ headers: {
1239
+ Authorization: authHeader,
1240
+ },
1241
+ },
1242
+ models: sleepyModels,
1243
+ }
1244
+ log.info("sleepy provider injected from config", { endpoint, dashboardUrl })
1245
+
1246
+ // Start background session polling — checks every 10 minutes if the session is still valid.
1247
+ // Proactively refreshes tokens before expiry to prevent mid-session logouts.
1248
+ const checker = createSessionChecker({
1249
+ dashboardUrl,
1250
+ token,
1251
+ configPath: sleepyConfigPath,
1252
+ onRefreshed(newToken) {
1253
+ token = newToken
1254
+ authHeader.Authorization = `Bearer ${newToken}`
1255
+ },
1256
+ })
1257
+ checker.start()
1258
+ }
1259
+ }
1260
+ } catch {
1261
+ // Config file missing or malformed — silently skip sleepy provider injection
1262
+ }
1263
+
1264
+ const providers: Record<ProviderID, Info> = {} as Record<ProviderID, Info>
1265
+ const languages = new Map<string, LanguageModelV3>()
1266
+ const modelLoaders: {
1267
+ [providerID: string]: CustomModelLoader
1268
+ } = {}
1269
+ const varsLoaders: {
1270
+ [providerID: string]: CustomVarsLoader
1271
+ } = {}
1272
+ const sdk = new Map<string, BundledSDK>()
1273
+ const discoveryLoaders: {
1274
+ [providerID: string]: CustomDiscoverModels
1275
+ } = {}
1276
+ const dep = {
1277
+ auth: (id: string) => auth.get(id).pipe(Effect.orDie),
1278
+ config: () => config.get(),
1279
+ env: () => env.all(),
1280
+ get: (key: string) => env.get(key),
1281
+ }
1282
+
1283
+ log.info("init")
1284
+
1285
+ function mergeProvider(providerID: ProviderID, provider: Partial<Info>) {
1286
+ const existing = providers[providerID]
1287
+ if (existing) {
1288
+ // @ts-expect-error
1289
+ providers[providerID] = mergeDeep(existing, provider)
1290
+ return
1291
+ }
1292
+ const match = database[providerID]
1293
+ if (!match) return
1294
+ // @ts-expect-error
1295
+ providers[providerID] = mergeDeep(match, provider)
1296
+ }
1297
+
1298
+ // load plugins first so config() hook runs before reading cfg.provider
1299
+ const plugins = yield* plugin.list()
1300
+
1301
+ // promote sleepy provider from database to providers if injected
1302
+ if (database[ProviderID.make("sleepy")]) {
1303
+ mergeProvider(ProviderID.make("sleepy"), {})
1304
+ }
1305
+
1306
+ // now read config providers - includes any modifications from plugin config() hook
1307
+ const configProviders = Object.entries(cfg.provider ?? {})
1308
+ const disabled = new Set(cfg.disabled_providers ?? [])
1309
+ const enabled = cfg.enabled_providers ? new Set(cfg.enabled_providers) : null
1310
+
1311
+ function isProviderAllowed(providerID: ProviderID): boolean {
1312
+ if (enabled && !enabled.has(providerID)) return false
1313
+ if (disabled.has(providerID)) return false
1314
+ return true
1315
+ }
1316
+
1317
+ // extend database from config
1318
+ for (const [providerID, provider] of configProviders) {
1319
+ const existing = database[providerID]
1320
+ const parsed: Info = {
1321
+ id: ProviderID.make(providerID),
1322
+ name: provider.name ?? existing?.name ?? providerID,
1323
+ env: provider.env ?? existing?.env ?? [],
1324
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
1325
+ source: "config",
1326
+ models: existing?.models ?? {},
1327
+ }
1328
+
1329
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
1330
+ const existingModel = parsed.models[model.id ?? modelID]
1331
+ const apiID = model.id ?? existingModel?.api.id ?? modelID
1332
+ const apiNpm =
1333
+ model.provider?.npm ??
1334
+ provider.npm ??
1335
+ existingModel?.api.npm ??
1336
+ modelsDev[providerID]?.npm ??
1337
+ "@ai-sdk/openai-compatible"
1338
+ const name = iife(() => {
1339
+ if (model.name) return model.name
1340
+ if (model.id && model.id !== modelID) return modelID
1341
+ return existingModel?.name ?? modelID
1342
+ })
1343
+ const parsedModel: Model = {
1344
+ id: ModelID.make(modelID),
1345
+ api: {
1346
+ id: apiID,
1347
+ npm: apiNpm,
1348
+ url: model.provider?.api ?? provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api ?? "",
1349
+ },
1350
+ status: model.status ?? existingModel?.status ?? "active",
1351
+ name,
1352
+ providerID: ProviderID.make(providerID),
1353
+ capabilities: {
1354
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
1355
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
1356
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
1357
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
1358
+ input: {
1359
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
1360
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
1361
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
1362
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
1363
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
1364
+ },
1365
+ output: {
1366
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
1367
+ audio:
1368
+ model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
1369
+ image:
1370
+ model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
1371
+ video:
1372
+ model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
1373
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
1374
+ },
1375
+ interleaved:
1376
+ model.interleaved ??
1377
+ existingModel?.capabilities.interleaved ??
1378
+ (!existingModel && apiNpm === "@ai-sdk/openai-compatible" && apiID.includes("deepseek")
1379
+ ? { field: "reasoning_content" }
1380
+ : false),
1381
+ },
1382
+ cost: {
1383
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
1384
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
1385
+ cache: {
1386
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
1387
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
1388
+ },
1389
+ },
1390
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
1391
+ limit: {
1392
+ context: (() => {
1393
+ const explicit = model.limit?.context ?? existingModel?.limit?.context
1394
+ if (explicit !== undefined) return explicit
1395
+ const key = `${providerID}/${modelID}`
1396
+ if (!warnedContextDefaults.has(key)) {
1397
+ warnedContextDefaults.add(key)
1398
+ log.warn("limit.context not configured and not found in models.dev", {
1399
+ providerID,
1400
+ modelID,
1401
+ defaulting_to: DEFAULT_CONTEXT_WINDOW,
1402
+ fix: `Set limit.context explicitly in sleepycode.json under provider.${providerID}.models.${modelID}`,
1403
+ })
1404
+ }
1405
+ return DEFAULT_CONTEXT_WINDOW
1406
+ })(),
1407
+ input: model.limit?.input ?? existingModel?.limit?.input,
1408
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
1409
+ },
1410
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
1411
+ family: model.family ?? existingModel?.family ?? "",
1412
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
1413
+ cachePromptTTL: model.cachePromptTTL ?? existingModel?.cachePromptTTL,
1414
+ variants: {},
1415
+ }
1416
+ const merged = mergeDeep(ProviderTransform.variants(parsedModel), model.variants ?? {})
1417
+ parsedModel.variants = mapValues(
1418
+ pickBy(merged, (v) => !v.disabled),
1419
+ (v) => omit(v, ["disabled"]),
1420
+ )
1421
+ parsed.models[modelID] = parsedModel
1422
+ }
1423
+ database[providerID] = parsed
1424
+ }
1425
+
1426
+ // load env (skipped in sleepy-only mode so ANTHROPIC_API_KEY etc. don't auto-light other providers)
1427
+ if (!Flag.SLEEPYCODE_DISABLE_PROVIDER_ENV) {
1428
+ const envs = yield* env.all()
1429
+ for (const [id, provider] of Object.entries(database)) {
1430
+ const providerID = ProviderID.make(id)
1431
+ if (disabled.has(providerID)) continue
1432
+ const apiKey = provider.env.map((item) => envs[item]).find(Boolean)
1433
+ if (!apiKey) continue
1434
+ mergeProvider(providerID, {
1435
+ source: "env",
1436
+ key: provider.env.length === 1 ? apiKey : undefined,
1437
+ })
1438
+ }
1439
+ }
1440
+
1441
+ // load apikeys
1442
+ const auths = yield* auth.all().pipe(Effect.orDie)
1443
+ for (const [id, provider] of Object.entries(auths)) {
1444
+ const providerID = ProviderID.make(id)
1445
+ if (disabled.has(providerID)) continue
1446
+ if (provider.type === "api") {
1447
+ mergeProvider(providerID, {
1448
+ source: "api",
1449
+ key: provider.key,
1450
+ })
1451
+ }
1452
+ }
1453
+
1454
+ // plugin auth loader - database now has entries for config providers
1455
+ for (const plugin of plugins) {
1456
+ if (!plugin.auth) continue
1457
+ const providerID = ProviderID.make(plugin.auth.provider)
1458
+ if (disabled.has(providerID)) continue
1459
+
1460
+ const stored = yield* auth.get(providerID).pipe(Effect.orDie)
1461
+ if (!stored) continue
1462
+ if (!plugin.auth.loader) continue
1463
+
1464
+ const options = yield* Effect.promise(() =>
1465
+ plugin.auth!.loader!(
1466
+ () => bridge.promise(auth.get(providerID).pipe(Effect.orDie)) as any,
1467
+ database[plugin.auth!.provider],
1468
+ ),
1469
+ )
1470
+ const opts = options ?? {}
1471
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1472
+ mergeProvider(providerID, patch)
1473
+ }
1474
+
1475
+ for (const [id, fn] of Object.entries(custom(dep))) {
1476
+ const providerID = ProviderID.make(id)
1477
+ if (disabled.has(providerID)) continue
1478
+ const data = database[providerID]
1479
+ if (!data) {
1480
+ log.error("Provider does not exist in model list " + providerID)
1481
+ continue
1482
+ }
1483
+ const result = yield* fn(data)
1484
+ if (result && (result.autoload || providers[providerID])) {
1485
+ if (result.getModel) modelLoaders[providerID] = result.getModel
1486
+ if (result.vars) varsLoaders[providerID] = result.vars
1487
+ if (result.discoverModels) discoveryLoaders[providerID] = result.discoverModels
1488
+ const opts = result.options ?? {}
1489
+ const patch: Partial<Info> = providers[providerID] ? { options: opts } : { source: "custom", options: opts }
1490
+ mergeProvider(providerID, patch)
1491
+ }
1492
+ }
1493
+
1494
+ // load config - re-apply with updated data
1495
+ for (const [id, provider] of configProviders) {
1496
+ const providerID = ProviderID.make(id)
1497
+ const partial: Partial<Info> = { source: "config" }
1498
+ if (provider.env) partial.env = provider.env
1499
+ if (provider.name) partial.name = provider.name
1500
+ if (provider.options) partial.options = provider.options
1501
+ mergeProvider(providerID, partial)
1502
+ }
1503
+
1504
+ const gitlab = ProviderID.make("gitlab")
1505
+ if (discoveryLoaders[gitlab] && providers[gitlab] && isProviderAllowed(gitlab)) {
1506
+ yield* Effect.promise(async () => {
1507
+ try {
1508
+ const discovered = await discoveryLoaders[gitlab]()
1509
+ for (const [modelID, model] of Object.entries(discovered)) {
1510
+ if (!providers[gitlab].models[modelID]) {
1511
+ providers[gitlab].models[modelID] = model
1512
+ }
1513
+ }
1514
+ } catch (e) {
1515
+ log.warn("state discovery error", { id: "gitlab", error: e })
1516
+ }
1517
+ })
1518
+ }
1519
+
1520
+ for (const hook of plugins) {
1521
+ const p = hook.provider
1522
+ const models = p?.models
1523
+ if (!p || !models) continue
1524
+
1525
+ const providerID = ProviderID.make(p.id)
1526
+ if (disabled.has(providerID)) continue
1527
+
1528
+ const provider = providers[providerID]
1529
+ if (!provider) continue
1530
+ const pluginAuth = yield* auth.get(providerID).pipe(Effect.orDie)
1531
+
1532
+ provider.models = yield* Effect.promise(async () => {
1533
+ const next = await models(provider, { auth: pluginAuth })
1534
+ return Object.fromEntries(
1535
+ Object.entries(next).map(([id, model]) => [
1536
+ id,
1537
+ {
1538
+ ...model,
1539
+ id: ModelID.make(id),
1540
+ providerID,
1541
+ },
1542
+ ]),
1543
+ )
1544
+ })
1545
+ }
1546
+
1547
+ for (const [id, provider] of Object.entries(providers)) {
1548
+ const providerID = ProviderID.make(id)
1549
+ if (!isProviderAllowed(providerID)) {
1550
+ delete providers[providerID]
1551
+ continue
1552
+ }
1553
+
1554
+ const configProvider = cfg.provider?.[providerID]
1555
+
1556
+ for (const [modelID, model] of Object.entries(provider.models)) {
1557
+ model.api.id = model.api.id ?? model.id ?? modelID
1558
+ if (
1559
+ modelID === "gpt-5-chat-latest" ||
1560
+ (providerID === ProviderID.openrouter && modelID === "openai/gpt-5-chat")
1561
+ )
1562
+ delete provider.models[modelID]
1563
+ if (model.status === "alpha" && !Flag.SLEEPYCODE_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID]
1564
+ if (model.status === "deprecated") delete provider.models[modelID]
1565
+ if (
1566
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
1567
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
1568
+ )
1569
+ delete provider.models[modelID]
1570
+
1571
+ model.variants = mapValues(ProviderTransform.variants(model), (v) => v)
1572
+
1573
+ const configVariants = configProvider?.models?.[modelID]?.variants
1574
+ if (configVariants && model.variants) {
1575
+ const merged = mergeDeep(model.variants, configVariants)
1576
+ model.variants = mapValues(
1577
+ pickBy(merged, (v) => !v.disabled),
1578
+ (v) => omit(v, ["disabled"]),
1579
+ )
1580
+ }
1581
+ }
1582
+
1583
+ if (Object.keys(provider.models).length === 0) {
1584
+ delete providers[providerID]
1585
+ continue
1586
+ }
1587
+
1588
+ log.info("found", { providerID })
1589
+ }
1590
+
1591
+ if (sleepyCredentials) {
1592
+ const { token, dashboardUrl } = sleepyCredentials
1593
+ setInterval(async () => {
1594
+ const freshModels = await fetchModels(dashboardUrl, token)
1595
+ if (freshModels.length === 0) return
1596
+
1597
+ const sleepy = providers[ProviderID.make("sleepy")]
1598
+ if (!sleepy) return
1599
+
1600
+ const sleepyProviderID = ProviderID.make("sleepy")
1601
+ const baseUrl = `${dashboardUrl}/api/v1`
1602
+ const authHeader = { Authorization: `Bearer ${token}` }
1603
+
1604
+ for (const m of freshModels) {
1605
+ const existing = sleepy.models[m.modelId]
1606
+ if (existing) {
1607
+ existing.name = m.name
1608
+ existing.api.id = m.omniRouteModelId || m.modelId
1609
+ existing.cost = {
1610
+ input: m.inputPrice ?? 0.0015,
1611
+ output: m.outputPrice ?? 0.005,
1612
+ cache: {
1613
+ read: m.cacheReadPrice ?? 0.00075,
1614
+ write: m.cacheWritePrice ?? 0.0015,
1615
+ },
1616
+ }
1617
+ existing.limit = {
1618
+ context: m.contextWindow ?? 128000,
1619
+ output: m.maxOutputLimit ?? 4096,
1620
+ }
1621
+ } else {
1622
+ sleepy.models[m.modelId] = {
1623
+ id: ModelID.make(m.modelId),
1624
+ providerID: sleepyProviderID,
1625
+ name: m.name,
1626
+ family: "sleepy",
1627
+ api: {
1628
+ id: m.omniRouteModelId || m.modelId,
1629
+ url: baseUrl,
1630
+ npm: "@ai-sdk/openai-compatible",
1631
+ },
1632
+ status: "active",
1633
+ headers: authHeader,
1634
+ options: {},
1635
+ cost: {
1636
+ input: m.inputPrice ?? 0.0015,
1637
+ output: m.outputPrice ?? 0.005,
1638
+ cache: {
1639
+ read: m.cacheReadPrice ?? 0.00075,
1640
+ write: m.cacheWritePrice ?? 0.0015,
1641
+ },
1642
+ },
1643
+ limit: {
1644
+ context: m.contextWindow ?? 128000,
1645
+ output: m.maxOutputLimit ?? 4096,
1646
+ },
1647
+ capabilities: {
1648
+ temperature: true,
1649
+ reasoning: true,
1650
+ attachment: true,
1651
+ toolcall: true,
1652
+ input: { text: true, audio: false, image: true, video: false, pdf: true },
1653
+ output: { text: true, audio: false, image: false, video: false, pdf: false },
1654
+ interleaved: false,
1655
+ },
1656
+ release_date: "",
1657
+ variants: {},
1658
+ }
1659
+ }
1660
+ }
1661
+ }, 30 * 1000).unref()
1662
+ }
1663
+
1664
+ return {
1665
+ models: languages,
1666
+ providers,
1667
+ sdk,
1668
+ modelLoaders,
1669
+ varsLoaders,
1670
+ }
1671
+ }),
1672
+ )
1673
+
1674
+ const list = Effect.fn("Provider.list")(() => InstanceState.use(state, (s) => s.providers))
1675
+
1676
+ async function resolveSDK(model: Model, s: State, envs: Record<string, string | undefined>) {
1677
+ try {
1678
+ using _ = log.time("getSDK", {
1679
+ providerID: model.providerID,
1680
+ })
1681
+ const provider = s.providers[model.providerID]
1682
+ const options = { ...provider.options }
1683
+
1684
+ if (model.providerID === "google-vertex" && !model.api.npm.includes("@ai-sdk/openai-compatible")) {
1685
+ delete options.fetch
1686
+ }
1687
+
1688
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
1689
+ options["includeUsage"] = true
1690
+ }
1691
+
1692
+ const baseURL = iife(() => {
1693
+ let url =
1694
+ typeof options["baseURL"] === "string" && options["baseURL"] !== "" ? options["baseURL"] : model.api.url
1695
+ if (!url) return
1696
+
1697
+ const loader = s.varsLoaders[model.providerID]
1698
+ if (loader) {
1699
+ const vars = loader(options)
1700
+ for (const [key, value] of Object.entries(vars)) {
1701
+ const field = "${" + key + "}"
1702
+ url = url.replaceAll(field, value)
1703
+ }
1704
+ }
1705
+
1706
+ url = url.replace(/\$\{([^}]+)\}/g, (item, key) => {
1707
+ const val = envs[String(key)]
1708
+ return val ?? item
1709
+ })
1710
+ return url
1711
+ })
1712
+
1713
+ if (baseURL !== undefined) options["baseURL"] = baseURL
1714
+ if (options["apiKey"] === undefined && provider.key) options["apiKey"] = provider.key
1715
+ if (model.headers)
1716
+ options["headers"] = {
1717
+ ...options["headers"],
1718
+ ...model.headers,
1719
+ }
1720
+
1721
+ const key = Hash.fast(
1722
+ JSON.stringify({
1723
+ providerID: model.providerID,
1724
+ npm: model.api.npm,
1725
+ options,
1726
+ }),
1727
+ )
1728
+ const existing = s.sdk.get(key)
1729
+ if (existing) return existing
1730
+
1731
+ const customFetch = options["fetch"]
1732
+ const userChunkTimeout = options["chunkTimeout"]
1733
+ const chunkTimeout =
1734
+ typeof userChunkTimeout === "number"
1735
+ ? userChunkTimeout // user-set value (incl. 0 / negative to disable)
1736
+ : DEFAULT_CHUNK_TIMEOUT
1737
+ delete options["chunkTimeout"]
1738
+
1739
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
1740
+ const fetchFn = customFetch ?? fetch
1741
+ const opts = init ?? {}
1742
+ const chunkAbortCtl = typeof chunkTimeout === "number" && chunkTimeout > 0 ? new AbortController() : undefined
1743
+ const signals: AbortSignal[] = []
1744
+
1745
+ if (opts.signal) signals.push(opts.signal)
1746
+ if (chunkAbortCtl) signals.push(chunkAbortCtl.signal)
1747
+ if (options["timeout"] !== undefined && options["timeout"] !== null && options["timeout"] !== false)
1748
+ signals.push(AbortSignal.timeout(options["timeout"]))
1749
+
1750
+ const combined = signals.length === 0 ? null : signals.length === 1 ? signals[0] : AbortSignal.any(signals)
1751
+ if (combined) opts.signal = combined
1752
+
1753
+ // Strip openai itemId metadata following what codex does
1754
+ if (model.api.npm === "@ai-sdk/openai" && opts.body && opts.method === "POST") {
1755
+ const body = JSON.parse(opts.body as string)
1756
+ const isAzure = model.providerID.includes("azure")
1757
+ const keepIds = isAzure && body.store === true
1758
+ if (!keepIds && Array.isArray(body.input)) {
1759
+ for (const item of body.input) {
1760
+ if ("id" in item) {
1761
+ delete item.id
1762
+ }
1763
+ }
1764
+ opts.body = JSON.stringify(body)
1765
+ }
1766
+ }
1767
+
1768
+ const res = await fetchFn(input, {
1769
+ ...opts,
1770
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
1771
+ timeout: false,
1772
+ })
1773
+
1774
+ if (!chunkAbortCtl) return res
1775
+ return wrapSSE(res, chunkTimeout, chunkAbortCtl)
1776
+ }
1777
+
1778
+ const bundledLoader = BUNDLED_PROVIDERS[model.api.npm]
1779
+ if (bundledLoader) {
1780
+ log.info("using bundled provider", {
1781
+ providerID: model.providerID,
1782
+ pkg: model.api.npm,
1783
+ })
1784
+ const factory = await bundledLoader()
1785
+ const loaded = factory({
1786
+ name: model.providerID,
1787
+ ...options,
1788
+ })
1789
+ s.sdk.set(key, loaded)
1790
+ return loaded as SDK
1791
+ }
1792
+
1793
+ let installedPath: string
1794
+ if (!model.api.npm.startsWith("file://")) {
1795
+ const item = await Npm.add(model.api.npm)
1796
+ if (!item.entrypoint) throw new Error(`Package ${model.api.npm} has no import entrypoint`)
1797
+ installedPath = item.entrypoint
1798
+ } else {
1799
+ log.info("loading local provider", { pkg: model.api.npm })
1800
+ installedPath = model.api.npm
1801
+ }
1802
+
1803
+ // `installedPath` is a local entry path or an existing `file://` URL. Normalize
1804
+ // only path inputs so Node on Windows accepts the dynamic import.
1805
+ const importSpec = installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href
1806
+ const mod = await import(importSpec)
1807
+
1808
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
1809
+ const loaded = fn({
1810
+ name: model.providerID,
1811
+ ...options,
1812
+ })
1813
+ s.sdk.set(key, loaded)
1814
+ return loaded as SDK
1815
+ } catch (e) {
1816
+ throw new InitError({ providerID: model.providerID }, { cause: e })
1817
+ }
1818
+ }
1819
+
1820
+ const getProvider = Effect.fn("Provider.getProvider")((providerID: ProviderID) =>
1821
+ InstanceState.use(state, (s) => s.providers[providerID]),
1822
+ )
1823
+
1824
+ const getModel = Effect.fn("Provider.getModel")(function* (providerID: ProviderID, modelID: ModelID) {
1825
+ const s = yield* InstanceState.get(state)
1826
+ const provider = s.providers[providerID]
1827
+ if (!provider) {
1828
+ const available = Object.keys(s.providers)
1829
+ const matches = fuzzysort.go(providerID, available, { limit: 3, threshold: -10000 })
1830
+ throw new ModelNotFoundError({ providerID, modelID, suggestions: matches.map((m) => m.target) })
1831
+ }
1832
+
1833
+ const info = provider.models[modelID]
1834
+ if (!info) {
1835
+ const available = Object.keys(provider.models)
1836
+ const matches = fuzzysort.go(modelID, available, { limit: 3, threshold: -10000 })
1837
+ throw new ModelNotFoundError({ providerID, modelID, suggestions: matches.map((m) => m.target) })
1838
+ }
1839
+ return info
1840
+ })
1841
+
1842
+ const getLanguage = Effect.fn("Provider.getLanguage")(function* (model: Model) {
1843
+ const s = yield* InstanceState.get(state)
1844
+ const envs = yield* env.all()
1845
+ const key = `${model.providerID}/${model.id}`
1846
+ if (s.models.has(key)) return s.models.get(key)!
1847
+
1848
+ return yield* Effect.promise(async () => {
1849
+ const provider = s.providers[model.providerID]
1850
+ const sdk = await resolveSDK(model, s, envs)
1851
+
1852
+ try {
1853
+ const language = s.modelLoaders[model.providerID]
1854
+ ? await s.modelLoaders[model.providerID](sdk, model.api.id, {
1855
+ ...provider.options,
1856
+ ...model.options,
1857
+ })
1858
+ : sdk.languageModel(model.api.id)
1859
+ s.models.set(key, language)
1860
+ return language
1861
+ } catch (e) {
1862
+ if (e instanceof NoSuchModelError)
1863
+ throw new ModelNotFoundError(
1864
+ {
1865
+ modelID: model.id,
1866
+ providerID: model.providerID,
1867
+ },
1868
+ { cause: e },
1869
+ )
1870
+ throw e
1871
+ }
1872
+ })
1873
+ })
1874
+
1875
+ const closest = Effect.fn("Provider.closest")(function* (providerID: ProviderID, query: string[]) {
1876
+ const s = yield* InstanceState.get(state)
1877
+ const provider = s.providers[providerID]
1878
+ if (!provider) return undefined
1879
+ for (const item of query) {
1880
+ for (const modelID of Object.keys(provider.models)) {
1881
+ if (modelID.includes(item)) return { providerID, modelID }
1882
+ }
1883
+ }
1884
+ return undefined
1885
+ })
1886
+
1887
+ const resolveModelRef = Effect.fn("Provider.resolveModelRef")(function* (
1888
+ ref: string,
1889
+ contextProviderID?: ProviderID,
1890
+ ) {
1891
+ // Literal "provider/model" — unchanged path.
1892
+ if (ref.includes("/")) {
1893
+ const parsed = parseModel(ref)
1894
+ return yield* getModel(parsed.providerID, parsed.modelID)
1895
+ }
1896
+
1897
+ // Otherwise it's a group name.
1898
+ const cfg = yield* config.get()
1899
+ const group = cfg.model_groups?.[ref]
1900
+ if (!group) {
1901
+ if (BUILTIN_TIERS.has(ref)) {
1902
+ const fallback = yield* defaultModel()
1903
+ return yield* getModel(fallback.providerID, fallback.modelID)
1904
+ }
1905
+ const names = Object.keys(cfg.model_groups ?? {})
1906
+ const matches = fuzzysort.go(ref, names, { limit: 3, threshold: -10000 })
1907
+ throw new ModelGroupNotFoundError({ group: ref, suggestions: matches.map((m) => m.target) })
1908
+ }
1909
+
1910
+ const def = typeof group === "string" ? group : group.default
1911
+ const members = typeof group === "string" ? [group] : (group.models ?? [group.default])
1912
+
1913
+ // Provider-aware: prefer a member on the caller's provider.
1914
+ if (contextProviderID) {
1915
+ for (const member of members) {
1916
+ const parsed = parseModel(member)
1917
+ if (parsed.providerID !== contextProviderID) continue
1918
+ const resolved = yield* getModel(parsed.providerID, parsed.modelID).pipe(Effect.exit)
1919
+ if (resolved._tag === "Success") return resolved.value
1920
+ }
1921
+ }
1922
+
1923
+ // Fall back to the group default.
1924
+ const parsedDefault = parseModel(def)
1925
+ return yield* getModel(parsedDefault.providerID, parsedDefault.modelID)
1926
+ })
1927
+
1928
+ const getSmallModel = Effect.fn("Provider.getSmallModel")(function* (providerID: ProviderID) {
1929
+ const cfg = yield* config.get()
1930
+
1931
+ // Explicit small_model literal wins (back-compat).
1932
+ if (cfg.small_model) {
1933
+ const parsed = parseModel(cfg.small_model)
1934
+ return yield* getModel(parsed.providerID, parsed.modelID)
1935
+ }
1936
+
1937
+ // Otherwise route through the `lite` tier: configured lite group
1938
+ // (provider-aware) → else the built-in tier fallback to defaultModel().
1939
+ return yield* resolveModelRef("lite", providerID)
1940
+ })
1941
+
1942
+ const defaultModel = Effect.fn("Provider.defaultModel")(function* () {
1943
+ const cfg = yield* config.get()
1944
+ if (cfg.model) return parseModel(cfg.model)
1945
+
1946
+ const s = yield* InstanceState.get(state)
1947
+ const recent = yield* fs.readJson(path.join(Global.Path.state, "model.json")).pipe(
1948
+ Effect.map((x): { providerID: ProviderID; modelID: ModelID }[] => {
1949
+ if (!isRecord(x) || !Array.isArray(x.recent)) return []
1950
+ return x.recent.flatMap((item) => {
1951
+ if (!isRecord(item)) return []
1952
+ if (typeof item.providerID !== "string") return []
1953
+ if (typeof item.modelID !== "string") return []
1954
+ return [{ providerID: ProviderID.make(item.providerID), modelID: ModelID.make(item.modelID) }]
1955
+ })
1956
+ }),
1957
+ Effect.catch(() => Effect.succeed([] as { providerID: ProviderID; modelID: ModelID }[])),
1958
+ )
1959
+ for (const entry of recent) {
1960
+ const provider = s.providers[entry.providerID]
1961
+ if (!provider) continue
1962
+ if (!provider.models[entry.modelID]) continue
1963
+ return { providerID: entry.providerID, modelID: entry.modelID }
1964
+ }
1965
+
1966
+ const provider = Object.values(s.providers).find((p) => !cfg.provider || Object.keys(cfg.provider).includes(p.id))
1967
+ if (!provider) throw new Error("no providers found")
1968
+ const [model] = sort(Object.values(provider.models))
1969
+ if (!model) throw new Error("no models found")
1970
+ return {
1971
+ providerID: provider.id,
1972
+ modelID: model.id,
1973
+ }
1974
+ })
1975
+
1976
+ return Service.of({ list, getProvider, getModel, getLanguage, closest, getSmallModel, defaultModel, resolveModelRef })
1977
+ }),
1978
+ )
1979
+
1980
+ export const defaultLayer = Layer.suspend(() =>
1981
+ layer.pipe(
1982
+ Layer.provide(AppFileSystem.defaultLayer),
1983
+ Layer.provide(Env.defaultLayer),
1984
+ Layer.provide(Config.defaultLayer),
1985
+ Layer.provide(Auth.defaultLayer),
1986
+ Layer.provide(Plugin.defaultLayer),
1987
+ ),
1988
+ )
1989
+
1990
+ const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
1991
+ export function sort<T extends { id: string }>(models: T[]) {
1992
+ return sortBy(
1993
+ models,
1994
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
1995
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
1996
+ [(model) => model.id, "desc"],
1997
+ )
1998
+ }
1999
+
2000
+ export function parseModel(model: string) {
2001
+ const [providerID, ...rest] = model.split("/")
2002
+ return {
2003
+ providerID: ProviderID.make(providerID),
2004
+ modelID: ModelID.make(rest.join("/")),
2005
+ }
2006
+ }
2007
+
2008
+ export const ModelNotFoundError = NamedError.create(
2009
+ "ProviderModelNotFoundError",
2010
+ z.object({
2011
+ providerID: ProviderID.zod,
2012
+ modelID: ModelID.zod,
2013
+ suggestions: z.array(z.string()).optional(),
2014
+ }),
2015
+ )
2016
+
2017
+ export const ModelGroupNotFoundError = NamedError.create(
2018
+ "ProviderModelGroupNotFoundError",
2019
+ z.object({
2020
+ group: z.string(),
2021
+ suggestions: z.array(z.string()).optional(),
2022
+ }),
2023
+ )
2024
+
2025
+ export const InitError = NamedError.create(
2026
+ "ProviderInitError",
2027
+ z.object({
2028
+ providerID: ProviderID.zod,
2029
+ }),
2030
+ )