bincode-cli 1.0.1

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 (300) hide show
  1. package/AGENTS.md +27 -0
  2. package/README.md +15 -0
  3. package/bin/bincode +98 -0
  4. package/bunfig.toml +4 -0
  5. package/package.json +124 -0
  6. package/parsers-config.ts +239 -0
  7. package/script/build.ts +167 -0
  8. package/script/postinstall.mjs +206 -0
  9. package/script/publish.ts +99 -0
  10. package/script/schema.ts +47 -0
  11. package/src/acp/README.md +164 -0
  12. package/src/acp/agent.ts +1051 -0
  13. package/src/acp/session.ts +101 -0
  14. package/src/acp/types.ts +22 -0
  15. package/src/agent/agent.ts +398 -0
  16. package/src/agent/generate.txt +75 -0
  17. package/src/agent/prompt/compaction.txt +12 -0
  18. package/src/agent/prompt/explore.txt +18 -0
  19. package/src/agent/prompt/summary.txt +10 -0
  20. package/src/agent/prompt/title.txt +36 -0
  21. package/src/auth/bineric-login.ts +506 -0
  22. package/src/auth/index.ts +70 -0
  23. package/src/bun/index.ts +114 -0
  24. package/src/bus/bus-event.ts +43 -0
  25. package/src/bus/global.ts +10 -0
  26. package/src/bus/index.ts +105 -0
  27. package/src/cli/auth-check.ts +61 -0
  28. package/src/cli/bootstrap.ts +21 -0
  29. package/src/cli/cmd/acp.ts +88 -0
  30. package/src/cli/cmd/agent.ts +256 -0
  31. package/src/cli/cmd/auth.ts +436 -0
  32. package/src/cli/cmd/cmd.ts +7 -0
  33. package/src/cli/cmd/debug/config.ts +15 -0
  34. package/src/cli/cmd/debug/file.ts +91 -0
  35. package/src/cli/cmd/debug/index.ts +43 -0
  36. package/src/cli/cmd/debug/lsp.ts +48 -0
  37. package/src/cli/cmd/debug/ripgrep.ts +83 -0
  38. package/src/cli/cmd/debug/scrap.ts +15 -0
  39. package/src/cli/cmd/debug/skill.ts +15 -0
  40. package/src/cli/cmd/debug/snapshot.ts +48 -0
  41. package/src/cli/cmd/export.ts +88 -0
  42. package/src/cli/cmd/generate.ts +38 -0
  43. package/src/cli/cmd/github.ts +1399 -0
  44. package/src/cli/cmd/import.ts +98 -0
  45. package/src/cli/cmd/login.ts +112 -0
  46. package/src/cli/cmd/logout.ts +38 -0
  47. package/src/cli/cmd/mcp.ts +654 -0
  48. package/src/cli/cmd/models.ts +77 -0
  49. package/src/cli/cmd/pr.ts +112 -0
  50. package/src/cli/cmd/run.ts +368 -0
  51. package/src/cli/cmd/serve.ts +31 -0
  52. package/src/cli/cmd/session.ts +106 -0
  53. package/src/cli/cmd/stats.ts +298 -0
  54. package/src/cli/cmd/tui/app.tsx +669 -0
  55. package/src/cli/cmd/tui/attach.ts +30 -0
  56. package/src/cli/cmd/tui/component/border.tsx +21 -0
  57. package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
  58. package/src/cli/cmd/tui/component/dialog-command.tsx +123 -0
  59. package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
  60. package/src/cli/cmd/tui/component/dialog-model.tsx +223 -0
  61. package/src/cli/cmd/tui/component/dialog-provider.tsx +224 -0
  62. package/src/cli/cmd/tui/component/dialog-session-list.tsx +102 -0
  63. package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
  64. package/src/cli/cmd/tui/component/dialog-status.tsx +162 -0
  65. package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
  66. package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
  67. package/src/cli/cmd/tui/component/logo.tsx +32 -0
  68. package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +560 -0
  69. package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
  70. package/src/cli/cmd/tui/component/prompt/index.tsx +1052 -0
  71. package/src/cli/cmd/tui/context/args.tsx +14 -0
  72. package/src/cli/cmd/tui/context/directory.ts +13 -0
  73. package/src/cli/cmd/tui/context/exit.tsx +23 -0
  74. package/src/cli/cmd/tui/context/helper.tsx +25 -0
  75. package/src/cli/cmd/tui/context/keybind.tsx +101 -0
  76. package/src/cli/cmd/tui/context/kv.tsx +49 -0
  77. package/src/cli/cmd/tui/context/local.tsx +339 -0
  78. package/src/cli/cmd/tui/context/prompt.tsx +18 -0
  79. package/src/cli/cmd/tui/context/route.tsx +46 -0
  80. package/src/cli/cmd/tui/context/sdk.tsx +74 -0
  81. package/src/cli/cmd/tui/context/sync.tsx +372 -0
  82. package/src/cli/cmd/tui/context/theme/aura.json +69 -0
  83. package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
  84. package/src/cli/cmd/tui/context/theme/bincode.json +245 -0
  85. package/src/cli/cmd/tui/context/theme/catppuccin-frappe.json +233 -0
  86. package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
  87. package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
  88. package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
  89. package/src/cli/cmd/tui/context/theme/cursor.json +249 -0
  90. package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
  91. package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
  92. package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
  93. package/src/cli/cmd/tui/context/theme/github.json +233 -0
  94. package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
  95. package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
  96. package/src/cli/cmd/tui/context/theme/lucent-orng.json +227 -0
  97. package/src/cli/cmd/tui/context/theme/material.json +235 -0
  98. package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
  99. package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
  100. package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
  101. package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
  102. package/src/cli/cmd/tui/context/theme/nord.json +223 -0
  103. package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
  104. package/src/cli/cmd/tui/context/theme/orng.json +245 -0
  105. package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
  106. package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
  107. package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
  108. package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
  109. package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
  110. package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
  111. package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
  112. package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
  113. package/src/cli/cmd/tui/context/theme.tsx +1109 -0
  114. package/src/cli/cmd/tui/event.ts +40 -0
  115. package/src/cli/cmd/tui/routes/home.tsx +105 -0
  116. package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
  117. package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
  118. package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
  119. package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
  120. package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
  121. package/src/cli/cmd/tui/routes/session/header.tsx +141 -0
  122. package/src/cli/cmd/tui/routes/session/index.tsx +1888 -0
  123. package/src/cli/cmd/tui/routes/session/sidebar.tsx +321 -0
  124. package/src/cli/cmd/tui/spawn.ts +60 -0
  125. package/src/cli/cmd/tui/thread.ts +120 -0
  126. package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
  127. package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
  128. package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
  129. package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
  130. package/src/cli/cmd/tui/ui/dialog-select.tsx +330 -0
  131. package/src/cli/cmd/tui/ui/dialog.tsx +170 -0
  132. package/src/cli/cmd/tui/ui/spinner.ts +368 -0
  133. package/src/cli/cmd/tui/ui/toast.tsx +100 -0
  134. package/src/cli/cmd/tui/util/clipboard.ts +127 -0
  135. package/src/cli/cmd/tui/util/editor.ts +32 -0
  136. package/src/cli/cmd/tui/util/terminal.ts +114 -0
  137. package/src/cli/cmd/tui/worker.ts +63 -0
  138. package/src/cli/cmd/uninstall.ts +344 -0
  139. package/src/cli/cmd/upgrade.ts +67 -0
  140. package/src/cli/cmd/web.ts +84 -0
  141. package/src/cli/error.ts +55 -0
  142. package/src/cli/ui.ts +84 -0
  143. package/src/cli/upgrade.ts +25 -0
  144. package/src/command/index.ts +80 -0
  145. package/src/command/template/initialize.txt +10 -0
  146. package/src/command/template/review.txt +97 -0
  147. package/src/config/config.ts +995 -0
  148. package/src/config/markdown.ts +41 -0
  149. package/src/env/index.ts +26 -0
  150. package/src/file/ignore.ts +83 -0
  151. package/src/file/index.ts +328 -0
  152. package/src/file/ripgrep.ts +393 -0
  153. package/src/file/time.ts +64 -0
  154. package/src/file/watcher.ts +103 -0
  155. package/src/flag/flag.ts +46 -0
  156. package/src/format/formatter.ts +315 -0
  157. package/src/format/index.ts +137 -0
  158. package/src/global/index.ts +52 -0
  159. package/src/id/id.ts +73 -0
  160. package/src/ide/index.ts +76 -0
  161. package/src/index.ts +217 -0
  162. package/src/installation/index.ts +196 -0
  163. package/src/lsp/client.ts +229 -0
  164. package/src/lsp/index.ts +485 -0
  165. package/src/lsp/language.ts +116 -0
  166. package/src/lsp/server.ts +1895 -0
  167. package/src/mcp/auth.ts +135 -0
  168. package/src/mcp/index.ts +654 -0
  169. package/src/mcp/oauth-callback.ts +200 -0
  170. package/src/mcp/oauth-provider.ts +154 -0
  171. package/src/patch/index.ts +622 -0
  172. package/src/permission/index.ts +199 -0
  173. package/src/plugin/index.ts +101 -0
  174. package/src/project/bootstrap.ts +31 -0
  175. package/src/project/instance.ts +78 -0
  176. package/src/project/project.ts +221 -0
  177. package/src/project/state.ts +65 -0
  178. package/src/project/vcs.ts +76 -0
  179. package/src/provider/auth.ts +143 -0
  180. package/src/provider/models-macro.ts +11 -0
  181. package/src/provider/models.ts +106 -0
  182. package/src/provider/provider.ts +1071 -0
  183. package/src/provider/sdk/openai-compatible/src/README.md +5 -0
  184. package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
  185. package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +101 -0
  186. package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
  187. package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +22 -0
  188. package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
  189. package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
  190. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
  191. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
  192. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
  193. package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
  194. package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
  195. package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
  196. package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
  197. package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
  198. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
  199. package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
  200. package/src/provider/transform.ts +455 -0
  201. package/src/pty/index.ts +231 -0
  202. package/src/server/error.ts +36 -0
  203. package/src/server/project.ts +79 -0
  204. package/src/server/server.ts +2642 -0
  205. package/src/server/tui.ts +71 -0
  206. package/src/session/compaction.ts +223 -0
  207. package/src/session/index.ts +458 -0
  208. package/src/session/llm.ts +201 -0
  209. package/src/session/message-v2.ts +659 -0
  210. package/src/session/message.ts +189 -0
  211. package/src/session/processor.ts +409 -0
  212. package/src/session/prompt/anthropic-20250930.txt +166 -0
  213. package/src/session/prompt/anthropic.txt +104 -0
  214. package/src/session/prompt/anthropic_spoof.txt +1 -0
  215. package/src/session/prompt/beast.txt +147 -0
  216. package/src/session/prompt/build-switch.txt +5 -0
  217. package/src/session/prompt/codex.txt +318 -0
  218. package/src/session/prompt/copilot-gpt-5.txt +143 -0
  219. package/src/session/prompt/gemini.txt +155 -0
  220. package/src/session/prompt/max-steps.txt +16 -0
  221. package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
  222. package/src/session/prompt/plan.txt +26 -0
  223. package/src/session/prompt/polaris.txt +106 -0
  224. package/src/session/prompt/qwen.txt +109 -0
  225. package/src/session/prompt.ts +1446 -0
  226. package/src/session/retry.ts +86 -0
  227. package/src/session/revert.ts +108 -0
  228. package/src/session/status.ts +76 -0
  229. package/src/session/summary.ts +194 -0
  230. package/src/session/system.ts +120 -0
  231. package/src/session/todo.ts +37 -0
  232. package/src/share/share-next.ts +194 -0
  233. package/src/share/share.ts +87 -0
  234. package/src/shell/shell.ts +67 -0
  235. package/src/skill/index.ts +1 -0
  236. package/src/skill/skill.ts +83 -0
  237. package/src/snapshot/index.ts +197 -0
  238. package/src/storage/storage.ts +226 -0
  239. package/src/tool/bash.ts +306 -0
  240. package/src/tool/bash.txt +158 -0
  241. package/src/tool/batch.ts +175 -0
  242. package/src/tool/batch.txt +24 -0
  243. package/src/tool/codesearch.ts +138 -0
  244. package/src/tool/codesearch.txt +12 -0
  245. package/src/tool/edit.ts +675 -0
  246. package/src/tool/edit.txt +10 -0
  247. package/src/tool/glob.ts +65 -0
  248. package/src/tool/glob.txt +6 -0
  249. package/src/tool/grep.ts +121 -0
  250. package/src/tool/grep.txt +8 -0
  251. package/src/tool/invalid.ts +17 -0
  252. package/src/tool/ls.ts +110 -0
  253. package/src/tool/ls.txt +1 -0
  254. package/src/tool/lsp-diagnostics.ts +26 -0
  255. package/src/tool/lsp-diagnostics.txt +1 -0
  256. package/src/tool/lsp-hover.ts +31 -0
  257. package/src/tool/lsp-hover.txt +1 -0
  258. package/src/tool/lsp.ts +87 -0
  259. package/src/tool/lsp.txt +19 -0
  260. package/src/tool/multiedit.ts +46 -0
  261. package/src/tool/multiedit.txt +41 -0
  262. package/src/tool/patch.ts +233 -0
  263. package/src/tool/patch.txt +1 -0
  264. package/src/tool/read.ts +219 -0
  265. package/src/tool/read.txt +12 -0
  266. package/src/tool/registry.ts +162 -0
  267. package/src/tool/skill.ts +100 -0
  268. package/src/tool/task.ts +136 -0
  269. package/src/tool/task.txt +60 -0
  270. package/src/tool/todo.ts +39 -0
  271. package/src/tool/todoread.txt +14 -0
  272. package/src/tool/todowrite.txt +167 -0
  273. package/src/tool/tool.ts +71 -0
  274. package/src/tool/webfetch.ts +187 -0
  275. package/src/tool/webfetch.txt +13 -0
  276. package/src/tool/websearch.ts +150 -0
  277. package/src/tool/websearch.txt +11 -0
  278. package/src/tool/write.ts +110 -0
  279. package/src/tool/write.txt +8 -0
  280. package/src/util/archive.ts +16 -0
  281. package/src/util/color.ts +19 -0
  282. package/src/util/context.ts +25 -0
  283. package/src/util/defer.ts +12 -0
  284. package/src/util/eventloop.ts +20 -0
  285. package/src/util/filesystem.ts +83 -0
  286. package/src/util/fn.ts +11 -0
  287. package/src/util/iife.ts +3 -0
  288. package/src/util/keybind.ts +102 -0
  289. package/src/util/lazy.ts +11 -0
  290. package/src/util/locale.ts +81 -0
  291. package/src/util/lock.ts +98 -0
  292. package/src/util/log.ts +180 -0
  293. package/src/util/queue.ts +32 -0
  294. package/src/util/rpc.ts +42 -0
  295. package/src/util/scrap.ts +10 -0
  296. package/src/util/signal.ts +12 -0
  297. package/src/util/timeout.ts +14 -0
  298. package/src/util/token.ts +7 -0
  299. package/src/util/wildcard.ts +54 -0
  300. package/tsconfig.json +16 -0
@@ -0,0 +1,1071 @@
1
+ import z from "zod"
2
+ import fuzzysort from "fuzzysort"
3
+ import { Config } from "../config/config"
4
+ import { mapValues, mergeDeep, sortBy } from "remeda"
5
+ import { NoSuchModelError, type Provider as SDK } from "ai"
6
+ import { Log } from "../util/log"
7
+ import { BunProc } from "../bun"
8
+ import { Plugin } from "../plugin"
9
+ import { ModelsDev } from "./models"
10
+ import { NamedError } from "@bincode-ai/util/error"
11
+ import { Auth } from "../auth"
12
+ import { Env } from "../env"
13
+ import { Instance } from "../project/instance"
14
+ import { Flag } from "../flag/flag"
15
+ import { iife } from "@/util/iife"
16
+
17
+ // Direct imports for bundled providers
18
+ import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock"
19
+ import { createAnthropic } from "@ai-sdk/anthropic"
20
+ import { createAzure } from "@ai-sdk/azure"
21
+ import { createGoogleGenerativeAI } from "@ai-sdk/google"
22
+ import { createVertex } from "@ai-sdk/google-vertex"
23
+ import { createVertexAnthropic } from "@ai-sdk/google-vertex/anthropic"
24
+ import { createOpenAI } from "@ai-sdk/openai"
25
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
26
+ import { createOpenRouter, type LanguageModelV2 } from "@openrouter/ai-sdk-provider"
27
+ import { createOpenaiCompatible as createGitHubCopilotOpenAICompatible } from "./sdk/openai-compatible/src"
28
+ import { createXai } from "@ai-sdk/xai"
29
+ import { createMistral } from "@ai-sdk/mistral"
30
+ import { createGroq } from "@ai-sdk/groq"
31
+ import { createDeepInfra } from "@ai-sdk/deepinfra"
32
+ import { createCerebras } from "@ai-sdk/cerebras"
33
+ import { createCohere } from "@ai-sdk/cohere"
34
+ import { createGateway } from "@ai-sdk/gateway"
35
+ import { createTogetherAI } from "@ai-sdk/togetherai"
36
+ import { createPerplexity } from "@ai-sdk/perplexity"
37
+
38
+ export namespace Provider {
39
+ const log = Log.create({ service: "provider" })
40
+
41
+ const BUNDLED_PROVIDERS: Record<string, (options: any) => SDK> = {
42
+ "@ai-sdk/amazon-bedrock": createAmazonBedrock,
43
+ "@ai-sdk/anthropic": createAnthropic,
44
+ "@ai-sdk/azure": createAzure,
45
+ "@ai-sdk/google": createGoogleGenerativeAI,
46
+ "@ai-sdk/google-vertex": createVertex,
47
+ "@ai-sdk/google-vertex/anthropic": createVertexAnthropic,
48
+ "@ai-sdk/openai": createOpenAI,
49
+ "@ai-sdk/openai-compatible": createOpenAICompatible,
50
+ "@openrouter/ai-sdk-provider": createOpenRouter,
51
+ "@ai-sdk/xai": createXai,
52
+ "@ai-sdk/mistral": createMistral,
53
+ "@ai-sdk/groq": createGroq,
54
+ "@ai-sdk/deepinfra": createDeepInfra,
55
+ "@ai-sdk/cerebras": createCerebras,
56
+ "@ai-sdk/cohere": createCohere,
57
+ "@ai-sdk/gateway": createGateway,
58
+ "@ai-sdk/togetherai": createTogetherAI,
59
+ "@ai-sdk/perplexity": createPerplexity,
60
+ // @ts-ignore (TODO: kill this code so we dont have to maintain it)
61
+ "@ai-sdk/github-copilot": createGitHubCopilotOpenAICompatible,
62
+ }
63
+
64
+ type CustomModelLoader = (sdk: any, modelID: string, options?: Record<string, any>) => Promise<any>
65
+ type CustomLoader = (provider: Info) => Promise<{
66
+ autoload: boolean
67
+ getModel?: CustomModelLoader
68
+ options?: Record<string, any>
69
+ }>
70
+
71
+ const CUSTOM_LOADERS: Record<string, CustomLoader> = {
72
+ async anthropic() {
73
+ return {
74
+ autoload: false,
75
+ options: {
76
+ headers: {
77
+ "anthropic-beta":
78
+ "claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
79
+ },
80
+ },
81
+ }
82
+ },
83
+ async bincode(input) {
84
+ const hasKey = await (async () => {
85
+ const env = Env.all()
86
+ if (input.env.some((item) => env[item])) return true
87
+ if (await Auth.get(input.id)) return true
88
+ const config = await Config.get()
89
+ if (config.provider?.["bincode"]?.options?.apiKey) return true
90
+ return false
91
+ })()
92
+
93
+ if (!hasKey) {
94
+ for (const [key, value] of Object.entries(input.models)) {
95
+ if (value.cost.input === 0) continue
96
+ delete input.models[key]
97
+ }
98
+ }
99
+
100
+ return {
101
+ autoload: Object.keys(input.models).length > 0,
102
+ options: hasKey ? {} : { apiKey: "public" },
103
+ }
104
+ },
105
+ openai: async () => {
106
+ return {
107
+ autoload: false,
108
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
109
+ return sdk.responses(modelID)
110
+ },
111
+ options: {},
112
+ }
113
+ },
114
+ "github-copilot": async () => {
115
+ return {
116
+ autoload: false,
117
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
118
+ if (modelID.includes("codex")) {
119
+ return sdk.responses(modelID)
120
+ }
121
+ return sdk.chat(modelID)
122
+ },
123
+ options: {},
124
+ }
125
+ },
126
+ "github-copilot-enterprise": async () => {
127
+ return {
128
+ autoload: false,
129
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
130
+ if (modelID.includes("codex")) {
131
+ return sdk.responses(modelID)
132
+ }
133
+ return sdk.chat(modelID)
134
+ },
135
+ options: {},
136
+ }
137
+ },
138
+ azure: async () => {
139
+ return {
140
+ autoload: false,
141
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
142
+ if (options?.["useCompletionUrls"]) {
143
+ return sdk.chat(modelID)
144
+ } else {
145
+ return sdk.responses(modelID)
146
+ }
147
+ },
148
+ options: {},
149
+ }
150
+ },
151
+ "azure-cognitive-services": async () => {
152
+ const resourceName = Env.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME")
153
+ return {
154
+ autoload: false,
155
+ async getModel(sdk: any, modelID: string, options?: Record<string, any>) {
156
+ if (options?.["useCompletionUrls"]) {
157
+ return sdk.chat(modelID)
158
+ } else {
159
+ return sdk.responses(modelID)
160
+ }
161
+ },
162
+ options: {
163
+ baseURL: resourceName ? `https://${resourceName}.cognitiveservices.azure.com/openai` : undefined,
164
+ },
165
+ }
166
+ },
167
+ "amazon-bedrock": async () => {
168
+ const [awsProfile, awsAccessKeyId, awsBearerToken, awsRegion] = await Promise.all([
169
+ Env.get("AWS_PROFILE"),
170
+ Env.get("AWS_ACCESS_KEY_ID"),
171
+ Env.get("AWS_BEARER_TOKEN_BEDROCK"),
172
+ Env.get("AWS_REGION"),
173
+ ])
174
+ if (!awsProfile && !awsAccessKeyId && !awsBearerToken) return { autoload: false }
175
+
176
+ const region = awsRegion ?? "us-east-1"
177
+
178
+ const { fromNodeProviderChain } = await import(await BunProc.install("@aws-sdk/credential-providers"))
179
+ return {
180
+ autoload: true,
181
+ options: {
182
+ region,
183
+ credentialProvider: fromNodeProviderChain(),
184
+ },
185
+ async getModel(sdk: any, modelID: string, _options?: Record<string, any>) {
186
+ // Skip region prefixing if model already has global prefix
187
+ if (modelID.startsWith("global.")) {
188
+ return sdk.languageModel(modelID)
189
+ }
190
+
191
+ let regionPrefix = region.split("-")[0]
192
+
193
+ switch (regionPrefix) {
194
+ case "us": {
195
+ const modelRequiresPrefix = [
196
+ "nova-micro",
197
+ "nova-lite",
198
+ "nova-pro",
199
+ "nova-premier",
200
+ "claude",
201
+ "deepseek",
202
+ ].some((m) => modelID.includes(m))
203
+ const isGovCloud = region.startsWith("us-gov")
204
+ if (modelRequiresPrefix && !isGovCloud) {
205
+ modelID = `${regionPrefix}.${modelID}`
206
+ }
207
+ break
208
+ }
209
+ case "eu": {
210
+ const regionRequiresPrefix = [
211
+ "eu-west-1",
212
+ "eu-west-2",
213
+ "eu-west-3",
214
+ "eu-north-1",
215
+ "eu-central-1",
216
+ "eu-south-1",
217
+ "eu-south-2",
218
+ ].some((r) => region.includes(r))
219
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "llama3", "pixtral"].some((m) =>
220
+ modelID.includes(m),
221
+ )
222
+ if (regionRequiresPrefix && modelRequiresPrefix) {
223
+ modelID = `${regionPrefix}.${modelID}`
224
+ }
225
+ break
226
+ }
227
+ case "ap": {
228
+ const isAustraliaRegion = ["ap-southeast-2", "ap-southeast-4"].includes(region)
229
+ if (
230
+ isAustraliaRegion &&
231
+ ["anthropic.claude-sonnet-4-5", "anthropic.claude-haiku"].some((m) => modelID.includes(m))
232
+ ) {
233
+ regionPrefix = "au"
234
+ modelID = `${regionPrefix}.${modelID}`
235
+ } else {
236
+ const modelRequiresPrefix = ["claude", "nova-lite", "nova-micro", "nova-pro"].some((m) =>
237
+ modelID.includes(m),
238
+ )
239
+ if (modelRequiresPrefix) {
240
+ regionPrefix = "apac"
241
+ modelID = `${regionPrefix}.${modelID}`
242
+ }
243
+ }
244
+ break
245
+ }
246
+ }
247
+
248
+ return sdk.languageModel(modelID)
249
+ },
250
+ }
251
+ },
252
+ openrouter: async () => {
253
+ return {
254
+ autoload: false,
255
+ options: {
256
+ headers: {
257
+ "HTTP-Referer": "https://platform.bineric.com/",
258
+ "X-Title": "bincode",
259
+ },
260
+ },
261
+ }
262
+ },
263
+ "Bineric": async (input) => {
264
+ const config = await Config.get()
265
+ const backendConfig = config.provider?.["Bineric"]
266
+ // Priority: env var > config (required, no default)
267
+ // Handle empty strings from env var substitution in config
268
+ const envUrl = Env.get("BINERIC_API_URL")
269
+ const configUrl = backendConfig?.options?.baseURL
270
+ const baseURL = (envUrl && envUrl.trim()) || (configUrl && configUrl.trim())
271
+
272
+ if (!baseURL) {
273
+ throw new Error("BINERIC_API_URL environment variable or baseURL in bincode.json must be set for Bineric provider")
274
+ }
275
+ const token = backendConfig?.options?.token
276
+
277
+ // Only return config if provider exists in database (from config)
278
+ if (!input) return { autoload: false }
279
+
280
+ // Use token instead of apiKey - token contains API key and email
281
+ // Backend will extract email from token and use that user's API key
282
+ return {
283
+ autoload: false,
284
+ options: {
285
+ baseURL,
286
+ // Use token in Authorization header instead of apiKey
287
+ token: token,
288
+ // Don't set apiKey - use token instead
289
+ apiKey: token ? undefined : (backendConfig?.options?.apiKey ?? "not-needed"),
290
+ },
291
+ }
292
+ },
293
+ vercel: async () => {
294
+ return {
295
+ autoload: false,
296
+ options: {
297
+ headers: {
298
+ "http-referer": "https://platform.bineric.com/",
299
+ "x-title": "bincode",
300
+ },
301
+ },
302
+ }
303
+ },
304
+ "google-vertex": async () => {
305
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
306
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "us-east5"
307
+ const autoload = Boolean(project)
308
+ if (!autoload) return { autoload: false }
309
+ return {
310
+ autoload: true,
311
+ options: {
312
+ project,
313
+ location,
314
+ },
315
+ async getModel(sdk: any, modelID: string) {
316
+ const id = String(modelID).trim()
317
+ return sdk.languageModel(id)
318
+ },
319
+ }
320
+ },
321
+ "google-vertex-anthropic": async () => {
322
+ const project = Env.get("GOOGLE_CLOUD_PROJECT") ?? Env.get("GCP_PROJECT") ?? Env.get("GCLOUD_PROJECT")
323
+ const location = Env.get("GOOGLE_CLOUD_LOCATION") ?? Env.get("VERTEX_LOCATION") ?? "global"
324
+ const autoload = Boolean(project)
325
+ if (!autoload) return { autoload: false }
326
+ return {
327
+ autoload: true,
328
+ options: {
329
+ project,
330
+ location,
331
+ },
332
+ async getModel(sdk: any, modelID) {
333
+ const id = String(modelID).trim()
334
+ return sdk.languageModel(id)
335
+ },
336
+ }
337
+ },
338
+ "sap-ai-core": async () => {
339
+ const auth = await Auth.get("sap-ai-core")
340
+ const envServiceKey = iife(() => {
341
+ const envAICoreServiceKey = Env.get("AICORE_SERVICE_KEY")
342
+ if (envAICoreServiceKey) return envAICoreServiceKey
343
+ if (auth?.type === "api") {
344
+ Env.set("AICORE_SERVICE_KEY", auth.key)
345
+ return auth.key
346
+ }
347
+ return undefined
348
+ })
349
+ const deploymentId = Env.get("AICORE_DEPLOYMENT_ID")
350
+ const resourceGroup = Env.get("AICORE_RESOURCE_GROUP")
351
+
352
+ return {
353
+ autoload: !!envServiceKey,
354
+ options: envServiceKey ? { deploymentId, resourceGroup } : {},
355
+ async getModel(sdk: any, modelID: string) {
356
+ return sdk(modelID)
357
+ },
358
+ }
359
+ },
360
+ zenmux: async () => {
361
+ return {
362
+ autoload: false,
363
+ options: {
364
+ headers: {
365
+ "HTTP-Referer": "https://platform.bineric.com",
366
+ "X-Title": "bincode",
367
+ },
368
+ },
369
+ }
370
+ },
371
+ cerebras: async () => {
372
+ return {
373
+ autoload: false,
374
+ options: {
375
+ headers: {
376
+ "X-Cerebras-3rd-Party-Integration": "bincode",
377
+ },
378
+ },
379
+ }
380
+ },
381
+ }
382
+
383
+ export const Model = z
384
+ .object({
385
+ id: z.string(),
386
+ providerID: z.string(),
387
+ api: z.object({
388
+ id: z.string(),
389
+ url: z.string(),
390
+ npm: z.string(),
391
+ }),
392
+ name: z.string(),
393
+ family: z.string().optional(),
394
+ capabilities: z.object({
395
+ temperature: z.boolean(),
396
+ reasoning: z.boolean(),
397
+ attachment: z.boolean(),
398
+ toolcall: z.boolean(),
399
+ input: z.object({
400
+ text: z.boolean(),
401
+ audio: z.boolean(),
402
+ image: z.boolean(),
403
+ video: z.boolean(),
404
+ pdf: z.boolean(),
405
+ }),
406
+ output: z.object({
407
+ text: z.boolean(),
408
+ audio: z.boolean(),
409
+ image: z.boolean(),
410
+ video: z.boolean(),
411
+ pdf: z.boolean(),
412
+ }),
413
+ interleaved: z.union([
414
+ z.boolean(),
415
+ z.object({
416
+ field: z.enum(["reasoning_content", "reasoning_details"]),
417
+ }),
418
+ ]),
419
+ }),
420
+ cost: z.object({
421
+ input: z.number(),
422
+ output: z.number(),
423
+ cache: z.object({
424
+ read: z.number(),
425
+ write: z.number(),
426
+ }),
427
+ experimentalOver200K: z
428
+ .object({
429
+ input: z.number(),
430
+ output: z.number(),
431
+ cache: z.object({
432
+ read: z.number(),
433
+ write: z.number(),
434
+ }),
435
+ })
436
+ .optional(),
437
+ }),
438
+ limit: z.object({
439
+ context: z.number(),
440
+ output: z.number(),
441
+ }),
442
+ status: z.enum(["alpha", "beta", "deprecated", "active"]),
443
+ options: z.record(z.string(), z.any()),
444
+ headers: z.record(z.string(), z.string()),
445
+ release_date: z.string(),
446
+ })
447
+ .meta({
448
+ ref: "Model",
449
+ })
450
+ export type Model = z.infer<typeof Model>
451
+
452
+ export const Info = z
453
+ .object({
454
+ id: z.string(),
455
+ name: z.string(),
456
+ source: z.enum(["env", "config", "custom", "api"]),
457
+ env: z.string().array(),
458
+ key: z.string().optional(),
459
+ options: z.record(z.string(), z.any()),
460
+ models: z.record(z.string(), Model),
461
+ })
462
+ .meta({
463
+ ref: "Provider",
464
+ })
465
+ export type Info = z.infer<typeof Info>
466
+
467
+ function fromModelsDevModel(provider: ModelsDev.Provider, model: ModelsDev.Model): Model {
468
+ return {
469
+ id: model.id,
470
+ providerID: provider.id,
471
+ name: model.name,
472
+ family: model.family,
473
+ api: {
474
+ id: model.id,
475
+ url: provider.api!,
476
+ npm: model.provider?.npm ?? provider.npm ?? provider.id,
477
+ },
478
+ status: model.status ?? "active",
479
+ headers: model.headers ?? {},
480
+ options: model.options ?? {},
481
+ cost: {
482
+ input: model.cost?.input ?? 0,
483
+ output: model.cost?.output ?? 0,
484
+ cache: {
485
+ read: model.cost?.cache_read ?? 0,
486
+ write: model.cost?.cache_write ?? 0,
487
+ },
488
+ experimentalOver200K: model.cost?.context_over_200k
489
+ ? {
490
+ cache: {
491
+ read: model.cost.context_over_200k.cache_read ?? 0,
492
+ write: model.cost.context_over_200k.cache_write ?? 0,
493
+ },
494
+ input: model.cost.context_over_200k.input,
495
+ output: model.cost.context_over_200k.output,
496
+ }
497
+ : undefined,
498
+ },
499
+ limit: {
500
+ context: model.limit.context,
501
+ output: model.limit.output,
502
+ },
503
+ capabilities: {
504
+ temperature: model.temperature,
505
+ reasoning: model.reasoning,
506
+ attachment: model.attachment,
507
+ toolcall: model.tool_call,
508
+ input: {
509
+ text: model.modalities?.input?.includes("text") ?? false,
510
+ audio: model.modalities?.input?.includes("audio") ?? false,
511
+ image: model.modalities?.input?.includes("image") ?? false,
512
+ video: model.modalities?.input?.includes("video") ?? false,
513
+ pdf: model.modalities?.input?.includes("pdf") ?? false,
514
+ },
515
+ output: {
516
+ text: model.modalities?.output?.includes("text") ?? false,
517
+ audio: model.modalities?.output?.includes("audio") ?? false,
518
+ image: model.modalities?.output?.includes("image") ?? false,
519
+ video: model.modalities?.output?.includes("video") ?? false,
520
+ pdf: model.modalities?.output?.includes("pdf") ?? false,
521
+ },
522
+ interleaved: model.interleaved ?? false,
523
+ },
524
+ release_date: model.release_date,
525
+ }
526
+ }
527
+
528
+ export function fromModelsDevProvider(provider: ModelsDev.Provider): Info {
529
+ return {
530
+ id: provider.id,
531
+ source: "custom",
532
+ name: provider.name,
533
+ env: provider.env ?? [],
534
+ options: {},
535
+ models: mapValues(provider.models, (model) => fromModelsDevModel(provider, model)),
536
+ }
537
+ }
538
+
539
+ const state = Instance.state(async () => {
540
+ using _ = log.time("state")
541
+ const config = await Config.get()
542
+ const modelsDev = await ModelsDev.get()
543
+ const database = mapValues(modelsDev, fromModelsDevProvider)
544
+
545
+ const disabled = new Set(config.disabled_providers ?? [])
546
+ const enabled = config.enabled_providers ? new Set(config.enabled_providers) : null
547
+
548
+ function isProviderAllowed(providerID: string): boolean {
549
+ if (enabled && !enabled.has(providerID)) return false
550
+ if (disabled.has(providerID)) return false
551
+ return true
552
+ }
553
+
554
+ const providers: { [providerID: string]: Info } = {}
555
+ const languages = new Map<string, LanguageModelV2>()
556
+ const modelLoaders: {
557
+ [providerID: string]: CustomModelLoader
558
+ } = {}
559
+ const sdk = new Map<number, SDK>()
560
+
561
+ log.info("init")
562
+
563
+ const configProviders = Object.entries(config.provider ?? {})
564
+
565
+ // Add GitHub Copilot Enterprise provider that inherits from GitHub Copilot
566
+ if (database["github-copilot"]) {
567
+ const githubCopilot = database["github-copilot"]
568
+ database["github-copilot-enterprise"] = {
569
+ ...githubCopilot,
570
+ id: "github-copilot-enterprise",
571
+ name: "GitHub Copilot Enterprise",
572
+ models: mapValues(githubCopilot.models, (model) => ({
573
+ ...model,
574
+ providerID: "github-copilot-enterprise",
575
+ })),
576
+ }
577
+ }
578
+
579
+ function mergeProvider(providerID: string, provider: Partial<Info>) {
580
+ const existing = providers[providerID]
581
+ if (existing) {
582
+ // @ts-expect-error
583
+ providers[providerID] = mergeDeep(existing, provider)
584
+ return
585
+ }
586
+ const match = database[providerID]
587
+ if (!match) return
588
+ // @ts-expect-error
589
+ providers[providerID] = mergeDeep(match, provider)
590
+ }
591
+
592
+ // extend database from config
593
+ for (const [providerID, provider] of configProviders) {
594
+ const existing = database[providerID]
595
+ const parsed: Info = {
596
+ id: providerID,
597
+ name: provider.name ?? existing?.name ?? providerID,
598
+ env: provider.env ?? existing?.env ?? [],
599
+ options: mergeDeep(existing?.options ?? {}, provider.options ?? {}),
600
+ source: "config",
601
+ models: existing?.models ?? {},
602
+ }
603
+
604
+ for (const [modelID, model] of Object.entries(provider.models ?? {})) {
605
+ const existingModel = parsed.models[model.id ?? modelID]
606
+ const name = iife(() => {
607
+ if (model.name) return model.name
608
+ if (model.id && model.id !== modelID) return modelID
609
+ return existingModel?.name ?? modelID
610
+ })
611
+ const parsedModel: Model = {
612
+ id: modelID,
613
+ api: {
614
+ id: model.id ?? existingModel?.api.id ?? modelID,
615
+ npm:
616
+ model.provider?.npm ?? provider.npm ?? existingModel?.api.npm ?? modelsDev[providerID]?.npm ?? providerID,
617
+ url: provider?.api ?? existingModel?.api.url ?? modelsDev[providerID]?.api,
618
+ },
619
+ status: model.status ?? existingModel?.status ?? "active",
620
+ name,
621
+ providerID,
622
+ capabilities: {
623
+ temperature: model.temperature ?? existingModel?.capabilities.temperature ?? false,
624
+ reasoning: model.reasoning ?? existingModel?.capabilities.reasoning ?? false,
625
+ attachment: model.attachment ?? existingModel?.capabilities.attachment ?? false,
626
+ toolcall: model.tool_call ?? existingModel?.capabilities.toolcall ?? true,
627
+ input: {
628
+ text: model.modalities?.input?.includes("text") ?? existingModel?.capabilities.input.text ?? true,
629
+ audio: model.modalities?.input?.includes("audio") ?? existingModel?.capabilities.input.audio ?? false,
630
+ image: model.modalities?.input?.includes("image") ?? existingModel?.capabilities.input.image ?? false,
631
+ video: model.modalities?.input?.includes("video") ?? existingModel?.capabilities.input.video ?? false,
632
+ pdf: model.modalities?.input?.includes("pdf") ?? existingModel?.capabilities.input.pdf ?? false,
633
+ },
634
+ output: {
635
+ text: model.modalities?.output?.includes("text") ?? existingModel?.capabilities.output.text ?? true,
636
+ audio: model.modalities?.output?.includes("audio") ?? existingModel?.capabilities.output.audio ?? false,
637
+ image: model.modalities?.output?.includes("image") ?? existingModel?.capabilities.output.image ?? false,
638
+ video: model.modalities?.output?.includes("video") ?? existingModel?.capabilities.output.video ?? false,
639
+ pdf: model.modalities?.output?.includes("pdf") ?? existingModel?.capabilities.output.pdf ?? false,
640
+ },
641
+ interleaved: model.interleaved ?? false,
642
+ },
643
+ cost: {
644
+ input: model?.cost?.input ?? existingModel?.cost?.input ?? 0,
645
+ output: model?.cost?.output ?? existingModel?.cost?.output ?? 0,
646
+ cache: {
647
+ read: model?.cost?.cache_read ?? existingModel?.cost?.cache.read ?? 0,
648
+ write: model?.cost?.cache_write ?? existingModel?.cost?.cache.write ?? 0,
649
+ },
650
+ },
651
+ options: mergeDeep(existingModel?.options ?? {}, model.options ?? {}),
652
+ limit: {
653
+ context: model.limit?.context ?? existingModel?.limit?.context ?? 0,
654
+ output: model.limit?.output ?? existingModel?.limit?.output ?? 0,
655
+ },
656
+ headers: mergeDeep(existingModel?.headers ?? {}, model.headers ?? {}),
657
+ family: model.family ?? existingModel?.family ?? "",
658
+ release_date: model.release_date ?? existingModel?.release_date ?? "",
659
+ }
660
+ parsed.models[modelID] = parsedModel
661
+ }
662
+ database[providerID] = parsed
663
+ // Add config providers to providers object so custom loaders can find them
664
+ if (isProviderAllowed(providerID)) {
665
+ mergeProvider(providerID, parsed)
666
+ }
667
+ }
668
+
669
+ // load env
670
+ const env = Env.all()
671
+ for (const [providerID, provider] of Object.entries(database)) {
672
+ if (disabled.has(providerID)) continue
673
+ const apiKey = provider.env.map((item) => env[item]).find(Boolean)
674
+ if (!apiKey) continue
675
+ mergeProvider(providerID, {
676
+ source: "env",
677
+ key: provider.env.length === 1 ? apiKey : undefined,
678
+ })
679
+ }
680
+
681
+ // load apikeys
682
+ for (const [providerID, provider] of Object.entries(await Auth.all())) {
683
+ if (disabled.has(providerID)) continue
684
+ if (provider.type === "api") {
685
+ mergeProvider(providerID, {
686
+ source: "api",
687
+ key: provider.key,
688
+ })
689
+ }
690
+ }
691
+
692
+ for (const plugin of await Plugin.list()) {
693
+ if (!plugin.auth) continue
694
+ const providerID = plugin.auth.provider
695
+ if (disabled.has(providerID)) continue
696
+
697
+ // For github-copilot plugin, check if auth exists for either github-copilot or github-copilot-enterprise
698
+ let hasAuth = false
699
+ const auth = await Auth.get(providerID)
700
+ if (auth) hasAuth = true
701
+
702
+ // Special handling for github-copilot: also check for enterprise auth
703
+ if (providerID === "github-copilot" && !hasAuth) {
704
+ const enterpriseAuth = await Auth.get("github-copilot-enterprise")
705
+ if (enterpriseAuth) hasAuth = true
706
+ }
707
+
708
+ if (!hasAuth) continue
709
+ if (!plugin.auth.loader) continue
710
+
711
+ // Load for the main provider if auth exists
712
+ if (auth) {
713
+ const options = await plugin.auth.loader(() => Auth.get(providerID) as any, database[plugin.auth.provider])
714
+ mergeProvider(plugin.auth.provider, {
715
+ source: "custom",
716
+ options: options,
717
+ })
718
+ }
719
+
720
+ // If this is github-copilot plugin, also register for github-copilot-enterprise if auth exists
721
+ if (providerID === "github-copilot") {
722
+ const enterpriseProviderID = "github-copilot-enterprise"
723
+ if (!disabled.has(enterpriseProviderID)) {
724
+ const enterpriseAuth = await Auth.get(enterpriseProviderID)
725
+ if (enterpriseAuth) {
726
+ const enterpriseOptions = await plugin.auth.loader(
727
+ () => Auth.get(enterpriseProviderID) as any,
728
+ database[enterpriseProviderID],
729
+ )
730
+ mergeProvider(enterpriseProviderID, {
731
+ source: "custom",
732
+ options: enterpriseOptions,
733
+ })
734
+ }
735
+ }
736
+ }
737
+ }
738
+
739
+ for (const [providerID, fn] of Object.entries(CUSTOM_LOADERS)) {
740
+ if (disabled.has(providerID)) continue
741
+ const providerInfo = database[providerID]
742
+ if (!providerInfo) continue
743
+ const result = await fn(providerInfo)
744
+ if (result && (result.autoload || providers[providerID] || providerInfo.source === "config")) {
745
+ if (result.getModel) modelLoaders[providerID] = result.getModel
746
+ mergeProvider(providerID, {
747
+ source: "custom",
748
+ options: result.options,
749
+ })
750
+ }
751
+ }
752
+
753
+ // load config
754
+ for (const [providerID, provider] of configProviders) {
755
+ const partial: Partial<Info> = { source: "config" }
756
+ if (provider.env) partial.env = provider.env
757
+ if (provider.name) partial.name = provider.name
758
+ if (provider.options) partial.options = provider.options
759
+ mergeProvider(providerID, partial)
760
+ }
761
+
762
+ for (const [providerID, provider] of Object.entries(providers)) {
763
+ if (!isProviderAllowed(providerID)) {
764
+ delete providers[providerID]
765
+ continue
766
+ }
767
+
768
+ if (providerID === "github-copilot" || providerID === "github-copilot-enterprise") {
769
+ provider.models = mapValues(provider.models, (model) => ({
770
+ ...model,
771
+ api: {
772
+ ...model.api,
773
+ npm: "@ai-sdk/github-copilot",
774
+ },
775
+ }))
776
+ }
777
+
778
+ const configProvider = config.provider?.[providerID]
779
+
780
+ for (const [modelID, model] of Object.entries(provider.models)) {
781
+ model.api.id = model.api.id ?? model.id ?? modelID
782
+ if (modelID === "gpt-5-chat-latest" || (providerID === "openrouter" && modelID === "openai/gpt-5-chat"))
783
+ delete provider.models[modelID]
784
+ if (model.status === "alpha" && !Flag.BINCODE_ENABLE_EXPERIMENTAL_MODELS) delete provider.models[modelID]
785
+ if (
786
+ (configProvider?.blacklist && configProvider.blacklist.includes(modelID)) ||
787
+ (configProvider?.whitelist && !configProvider.whitelist.includes(modelID))
788
+ )
789
+ delete provider.models[modelID]
790
+ }
791
+
792
+ if (Object.keys(provider.models).length === 0) {
793
+ delete providers[providerID]
794
+ continue
795
+ }
796
+
797
+ log.info("found", { providerID })
798
+ }
799
+
800
+ return {
801
+ models: languages,
802
+ providers,
803
+ sdk,
804
+ modelLoaders,
805
+ }
806
+ })
807
+
808
+ export async function list() {
809
+ return state().then((state) => state.providers)
810
+ }
811
+
812
+ async function getSDK(model: Model) {
813
+ try {
814
+ using _ = log.time("getSDK", {
815
+ providerID: model.providerID,
816
+ })
817
+ const s = await state()
818
+ const provider = s.providers[model.providerID]
819
+ const options = { ...provider.options }
820
+
821
+ if (model.api.npm.includes("@ai-sdk/openai-compatible") && options["includeUsage"] !== false) {
822
+ options["includeUsage"] = true
823
+ }
824
+
825
+ if (!options["baseURL"]) options["baseURL"] = model.api.url
826
+
827
+ // For Bineric provider, use token instead of apiKey
828
+ if (model.providerID === "Bineric" && options["token"]) {
829
+ // Token will be used in Authorization header
830
+ // Don't set apiKey, use token instead
831
+ options["apiKey"] = options["token"]
832
+ } else if (options["apiKey"] === undefined && provider.key) {
833
+ options["apiKey"] = provider.key
834
+ }
835
+
836
+ if (model.headers)
837
+ options["headers"] = {
838
+ ...options["headers"],
839
+ ...model.headers,
840
+ }
841
+
842
+ const key = Bun.hash.xxHash32(JSON.stringify({ npm: model.api.npm, options }))
843
+ const existing = s.sdk.get(key)
844
+ if (existing) return existing
845
+
846
+ const customFetch = options["fetch"]
847
+
848
+ options["fetch"] = async (input: any, init?: BunFetchRequestInit) => {
849
+ // Preserve custom fetch if it exists, wrap it with timeout logic
850
+ const fetchFn = customFetch ?? fetch
851
+ const opts = init ?? {}
852
+
853
+ if (options["timeout"] !== undefined && options["timeout"] !== null) {
854
+ const signals: AbortSignal[] = []
855
+ if (opts.signal) signals.push(opts.signal)
856
+ if (options["timeout"] !== false) signals.push(AbortSignal.timeout(options["timeout"]))
857
+
858
+ const combined = signals.length > 1 ? AbortSignal.any(signals) : signals[0]
859
+
860
+ opts.signal = combined
861
+ }
862
+
863
+ return fetchFn(input, {
864
+ ...opts,
865
+ // @ts-ignore see here: https://github.com/oven-sh/bun/issues/16682
866
+ timeout: false,
867
+ })
868
+ }
869
+
870
+ // Special case: google-vertex-anthropic uses a subpath import
871
+ const bundledKey =
872
+ model.providerID === "google-vertex-anthropic" ? "@ai-sdk/google-vertex/anthropic" : model.api.npm
873
+ const bundledFn = BUNDLED_PROVIDERS[bundledKey]
874
+ if (bundledFn) {
875
+ log.info("using bundled provider", { providerID: model.providerID, pkg: bundledKey })
876
+ const loaded = bundledFn({
877
+ name: model.providerID,
878
+ ...options,
879
+ })
880
+ s.sdk.set(key, loaded)
881
+ return loaded as SDK
882
+ }
883
+
884
+ let installedPath: string
885
+ if (!model.api.npm.startsWith("file://")) {
886
+ installedPath = await BunProc.install(model.api.npm, "latest")
887
+ } else {
888
+ log.info("loading local provider", { pkg: model.api.npm })
889
+ installedPath = model.api.npm
890
+ }
891
+
892
+ const mod = await import(installedPath)
893
+
894
+ const fn = mod[Object.keys(mod).find((key) => key.startsWith("create"))!]
895
+ const loaded = fn({
896
+ name: model.providerID,
897
+ ...options,
898
+ })
899
+ s.sdk.set(key, loaded)
900
+ return loaded as SDK
901
+ } catch (e) {
902
+ throw new InitError({ providerID: model.providerID }, { cause: e })
903
+ }
904
+ }
905
+
906
+ export async function getProvider(providerID: string) {
907
+ return state().then((s) => s.providers[providerID])
908
+ }
909
+
910
+ export async function getModel(providerID: string, modelID: string) {
911
+ const s = await state()
912
+ const provider = s.providers[providerID]
913
+ if (!provider) {
914
+ const availableProviders = Object.keys(s.providers)
915
+ const matches = fuzzysort.go(providerID, availableProviders, { limit: 3, threshold: -10000 })
916
+ const suggestions = matches.map((m) => m.target)
917
+ throw new ModelNotFoundError({ providerID, modelID, suggestions })
918
+ }
919
+
920
+ const info = provider.models[modelID]
921
+ if (!info) {
922
+ const availableModels = Object.keys(provider.models)
923
+ const matches = fuzzysort.go(modelID, availableModels, { limit: 3, threshold: -10000 })
924
+ const suggestions = matches.map((m) => m.target)
925
+ throw new ModelNotFoundError({ providerID, modelID, suggestions })
926
+ }
927
+ return info
928
+ }
929
+
930
+ export async function getLanguage(model: Model): Promise<LanguageModelV2> {
931
+ const s = await state()
932
+ const key = `${model.providerID}/${model.id}`
933
+ if (s.models.has(key)) return s.models.get(key)!
934
+
935
+ const provider = s.providers[model.providerID]
936
+ const sdk = await getSDK(model)
937
+
938
+ try {
939
+ const language = s.modelLoaders[model.providerID]
940
+ ? await s.modelLoaders[model.providerID](sdk, model.api.id, provider.options)
941
+ : sdk.languageModel(model.api.id)
942
+ s.models.set(key, language)
943
+ return language
944
+ } catch (e) {
945
+ if (e instanceof NoSuchModelError)
946
+ throw new ModelNotFoundError(
947
+ {
948
+ modelID: model.id,
949
+ providerID: model.providerID,
950
+ },
951
+ { cause: e },
952
+ )
953
+ throw e
954
+ }
955
+ }
956
+
957
+ export async function closest(providerID: string, query: string[]) {
958
+ const s = await state()
959
+ const provider = s.providers[providerID]
960
+ if (!provider) return undefined
961
+ for (const item of query) {
962
+ for (const modelID of Object.keys(provider.models)) {
963
+ if (modelID.includes(item))
964
+ return {
965
+ providerID,
966
+ modelID,
967
+ }
968
+ }
969
+ }
970
+ }
971
+
972
+ export async function getSmallModel(providerID: string) {
973
+ const cfg = await Config.get()
974
+
975
+ if (cfg.small_model) {
976
+ const parsed = parseModel(cfg.small_model)
977
+ return getModel(parsed.providerID, parsed.modelID)
978
+ }
979
+
980
+ const provider = await state().then((state) => state.providers[providerID])
981
+ if (provider) {
982
+ let priority = [
983
+ "claude-haiku-4-5",
984
+ "claude-haiku-4.5",
985
+ "3-5-haiku",
986
+ "3.5-haiku",
987
+ "gemini-2.5-flash",
988
+ "gpt-5-nano",
989
+ ]
990
+ // claude-haiku-4.5 is considered a premium model in github copilot, we shouldn't use premium requests for title gen
991
+ if (providerID === "github-copilot") {
992
+ priority = priority.filter((m) => m !== "claude-haiku-4.5")
993
+ }
994
+ // For Bineric/bincode providers, use gpt-4 for small model tasks (title generation)
995
+ if (providerID.startsWith("bincode") || providerID === "Bineric") {
996
+ priority = ["gpt-4"]
997
+ // Only look for gpt-4, don't fall back to other models
998
+ for (const item of priority) {
999
+ for (const model of Object.keys(provider.models)) {
1000
+ if (model.includes(item)) return getModel(providerID, model)
1001
+ }
1002
+ }
1003
+ // If gpt-4 not found, return undefined to use the main model instead
1004
+ return undefined
1005
+ }
1006
+ for (const item of priority) {
1007
+ for (const model of Object.keys(provider.models)) {
1008
+ if (model.includes(item)) return getModel(providerID, model)
1009
+ }
1010
+ }
1011
+ }
1012
+
1013
+ // Check if Bineric provider is available before using it
1014
+ const bincodeProvider = await state().then((state) => state.providers["Bineric"])
1015
+ if (bincodeProvider && bincodeProvider.models["gpt-4"]) {
1016
+ return getModel("Bineric", "gpt-4")
1017
+ }
1018
+
1019
+ return undefined
1020
+ }
1021
+
1022
+ const priority = ["gpt-5", "claude-sonnet-4", "big-pickle", "gemini-3-pro"]
1023
+ export function sort(models: Model[]) {
1024
+ return sortBy(
1025
+ models,
1026
+ [(model) => priority.findIndex((filter) => model.id.includes(filter)), "desc"],
1027
+ [(model) => (model.id.includes("latest") ? 0 : 1), "asc"],
1028
+ [(model) => model.id, "desc"],
1029
+ )
1030
+ }
1031
+
1032
+ export async function defaultModel() {
1033
+ const cfg = await Config.get()
1034
+ if (cfg.model) return parseModel(cfg.model)
1035
+
1036
+ const provider = await list()
1037
+ .then((val) => Object.values(val))
1038
+ .then((x) => x.find((p) => !cfg.provider || Object.keys(cfg.provider).includes(p.id)))
1039
+ if (!provider) throw new Error("no providers found")
1040
+ const [model] = sort(Object.values(provider.models))
1041
+ if (!model) throw new Error("no models found")
1042
+ return {
1043
+ providerID: provider.id,
1044
+ modelID: model.id,
1045
+ }
1046
+ }
1047
+
1048
+ export function parseModel(model: string) {
1049
+ const [providerID, ...rest] = model.split("/")
1050
+ return {
1051
+ providerID: providerID,
1052
+ modelID: rest.join("/"),
1053
+ }
1054
+ }
1055
+
1056
+ export const ModelNotFoundError = NamedError.create(
1057
+ "ProviderModelNotFoundError",
1058
+ z.object({
1059
+ providerID: z.string(),
1060
+ modelID: z.string(),
1061
+ suggestions: z.array(z.string()).optional(),
1062
+ }),
1063
+ )
1064
+
1065
+ export const InitError = NamedError.create(
1066
+ "ProviderInitError",
1067
+ z.object({
1068
+ providerID: z.string(),
1069
+ }),
1070
+ )
1071
+ }