opencode-codebuddy-quota 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,195 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { join } from "node:path"
4
+ import { DEFAULT_PACKAGE_VERSION, isVersion } from "./package-spec"
5
+
6
+ /** Where a CodeBuddy model lives in the models.dev catalog. */
7
+ export interface ModelMapping {
8
+ /** models.dev provider id, e.g. `deepseek`, `zhipuai`, `tencent-tokenhub`. */
9
+ provider: string
10
+ /** The id the provider files the model under, which is not always CodeBuddy's. */
11
+ model: string
12
+ }
13
+
14
+ /** Keys the user may override; everything else in the file is ignored. */
15
+ export interface QuotaConfig {
16
+ /** CodeBuddy model id → its models.dev entry. A model absent here is never offered. */
17
+ models: Record<string, ModelMapping>
18
+ /** Hard block, applied on top of `models`: listed ids are dropped even when mapped. */
19
+ excluded_models: string[]
20
+ /**
21
+ * The `@ai-sdk/openai-compatible` version to write when the npm lookup fails
22
+ * or is unavailable. Ships as "the version this plugin was tested against", so
23
+ * an offline start still produces a working config rather than a bare spec
24
+ * OpenCode would resolve unpredictably.
25
+ */
26
+ package_version: string
27
+ }
28
+
29
+ /**
30
+ * Mirrors `config.default.json`. The JSON file is documentation plus the
31
+ * schema anchor; the constant is what runs, so nothing has to read a file at
32
+ * plugin load time. A test asserts the two never drift apart.
33
+ */
34
+ export const DEFAULT_CONFIG: QuotaConfig = {
35
+ models: {
36
+ "deepseek-v4-pro": { provider: "deepseek", model: "deepseek-v4-pro" },
37
+ // CodeBuddy's revision of v4.1-flash is the vendor's plain v4-flash.
38
+ "deepseek-v4.1-flash": { provider: "deepseek", model: "deepseek-v4-flash" },
39
+ "glm-5.3-flash": { provider: "zhipuai", model: "glm-5.3-flash" },
40
+ "glm-5.3-flashx": { provider: "zhipuai", model: "glm-5.3-flashx" },
41
+ "minimax-m3.1-flash": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
42
+ "step-5-preview": { provider: "stepfun", model: "step-5-preview" },
43
+ "mimo-v2.6-pro": { provider: "xiaomi", model: "mimo-v2.6-pro" },
44
+ hy4std: { provider: "tencent-tokenhub", model: "hy4" },
45
+ // `Hy4 flash` ships twice: a free id and a paid one. models.dev has no
46
+ // flash entry, so both map to Hy4; the free one is zero-priced by credits.
47
+ "hy4flash-free": { provider: "tencent-tokenhub", model: "hy4" },
48
+ hy4flash: { provider: "tencent-tokenhub", model: "hy4" },
49
+ hy4free: { provider: "tencent-tokenhub", model: "hy4" },
50
+ hy3: { provider: "tencent-tokenhub", model: "hy3" },
51
+ "hy3-x": { provider: "tencent-tokenhub", model: "hy3" },
52
+ // Same model as minimax-m3.1-flash; CodeBuddy just bills it under its own id.
53
+ "space-bunny": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
54
+ // International-site cli-whitelist (ids from /v3/config agents[cli]).
55
+ // Four virtual routing aliases (default/fast/balanced/primary-model) have no
56
+ // models.dev entity and are intentionally left unmapped so they are skipped.
57
+ "hy4-preview": { provider: "tencent-tokenhub", model: "hy4-preview" },
58
+ // SG variant shares the same underlying model; models.dev has no separate id.
59
+ "deepseek-v4.1-flash-sg": { provider: "deepseek", model: "deepseek-v4-flash" },
60
+ // models.dev v3 carries all GPT ids under openai; use the official vendor.
61
+ "gpt-6-astra": { provider: "openai", model: "gpt-6-astra" },
62
+ "gpt-6.1-sol": { provider: "openai", model: "gpt-6.1-sol" },
63
+ "gpt-6-sol": { provider: "openai", model: "gpt-6-sol" },
64
+ "gpt-6-luna": { provider: "openai", model: "gpt-6-luna" },
65
+ "gpt-5.6-sol": { provider: "openai", model: "gpt-5.6-sol" },
66
+ "gpt-5.6-terra": { provider: "openai", model: "gpt-5.6-terra" },
67
+ "gpt-5.5": { provider: "openai", model: "gpt-5.5" },
68
+ "gpt-5.4": { provider: "openai", model: "gpt-5.4" },
69
+ "gpt-5.6-luna": { provider: "openai", model: "gpt-5.6-luna" },
70
+ // Official vendor mappings: reseller entries carry distorted prices.
71
+ "grok-4.7": { provider: "xai", model: "grok-4.7" },
72
+ "gemini-3.8-flash": { provider: "google", model: "gemini-3.8-flash" },
73
+ "glm-5.3": { provider: "zhipuai", model: "glm-5.3" },
74
+ "glm-5.2": { provider: "zhipuai", model: "glm-5.2" },
75
+ // moonshotai is the official vendor; wafer.ai resells kimi at skewed prices.
76
+ "kimi-k3.1-pro": { provider: "moonshotai", model: "kimi-k3.1-pro" },
77
+ "kimi-k3": { provider: "moonshotai", model: "kimi-k3" },
78
+ "kimi-k3.1-pro-highspeed": { provider: "moonshotai", model: "kimi-k3.1-pro-highspeed" },
79
+ },
80
+ // auto/max-model are virtual routing tiers with no models.dev entity; exclude
81
+ // them explicitly rather than relying on the no-mapping skip.
82
+ excluded_models: ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
83
+ package_version: DEFAULT_PACKAGE_VERSION,
84
+ }
85
+
86
+ export const CONFIG_FILE_NAME = "codebuddy-quota.json"
87
+
88
+ /** `$XDG_CONFIG_HOME/opencode`, or `~/.config/opencode` when it is unset. */
89
+ export function configDir(
90
+ env: Record<string, string | undefined> = process.env,
91
+ home: string = homedir(),
92
+ ): string {
93
+ const xdg = env.XDG_CONFIG_HOME
94
+ if (xdg) return join(xdg, "opencode")
95
+ return join(home, ".config", "opencode")
96
+ }
97
+
98
+ /** `~/.config/opencode/codebuddy-quota.json`, beside the user's `opencode.json(c)`. */
99
+ export function configPath(home: string = homedir()): string {
100
+ return join(configDir(undefined, home), CONFIG_FILE_NAME)
101
+ }
102
+
103
+ /**
104
+ * The names OpenCode accepts for a config file, in the order it prefers them.
105
+ * Both parse; JSONC is the one with comments.
106
+ */
107
+ export const OPENCODE_CONFIG_NAMES = ["opencode.jsonc", "opencode.json"] as const
108
+
109
+ /**
110
+ * The OpenCode config this plugin should edit.
111
+ *
112
+ * OpenCode reads `opencode.jsonc` or `opencode.json`, whichever exists — a user
113
+ * who picked `.json` must not be left with a plugin that silently imports
114
+ * nothing. The first name that exists wins; with neither present the returned
115
+ * path ends in `.jsonc`, matching what OpenCode writes for a fresh config.
116
+ */
117
+ export function opencodeConfigPath(
118
+ dir: string = configDir(),
119
+ exists: (path: string) => boolean = existsSync,
120
+ ): string {
121
+ for (const name of OPENCODE_CONFIG_NAMES) {
122
+ const candidate = join(dir, name)
123
+ if (exists(candidate)) return candidate
124
+ }
125
+ return join(dir, OPENCODE_CONFIG_NAMES[0])
126
+ }
127
+
128
+ function isRecord(value: unknown): value is Record<string, unknown> {
129
+ return typeof value === "object" && value !== null && !Array.isArray(value)
130
+ }
131
+
132
+ /**
133
+ * `{ codebuddyId: { provider, model } }`. A single malformed entry drops the
134
+ * whole field rather than half-applying it — a partially understood model list
135
+ * is worse than the shipped one.
136
+ */
137
+ function modelMap(value: unknown): Record<string, ModelMapping> | undefined {
138
+ if (!isRecord(value)) return undefined
139
+ const out: Record<string, ModelMapping> = {}
140
+ for (const [id, entry] of Object.entries(value)) {
141
+ if (id.length === 0 || !isRecord(entry)) return undefined
142
+ const { provider, model } = entry as Record<string, unknown>
143
+ if (typeof provider !== "string" || provider.length === 0) return undefined
144
+ if (typeof model !== "string" || model.length === 0) return undefined
145
+ out[id] = { provider, model }
146
+ }
147
+ return out
148
+ }
149
+
150
+ function stringList(value: unknown): string[] | undefined {
151
+ if (!Array.isArray(value)) return undefined
152
+ const out: string[] = []
153
+ for (const v of value) {
154
+ if (typeof v !== "string" || v.length === 0) return undefined
155
+ out.push(v)
156
+ }
157
+ return out
158
+ }
159
+
160
+ export interface LoadConfigDeps {
161
+ configPath?: string
162
+ readFile?: (path: string) => string
163
+ }
164
+
165
+ /**
166
+ * The user file is layered over the defaults: `models` merges one level deep so
167
+ * a user who adds a model does not have to repeat the twelve shipped ones, while
168
+ * `excluded_models` replaces wholesale. A field that fails validation silently
169
+ * keeps its default so one typo cannot take the rest down. This function never
170
+ * throws — a broken config must not stop the quota panel.
171
+ */
172
+ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
173
+ const path = deps.configPath ?? configPath()
174
+ const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
175
+
176
+ let parsed: unknown
177
+ try {
178
+ parsed = JSON.parse(read(path))
179
+ } catch {
180
+ return DEFAULT_CONFIG
181
+ }
182
+ if (!isRecord(parsed)) return DEFAULT_CONFIG
183
+
184
+ const models = modelMap(parsed.models)
185
+ const excluded = stringList(parsed.excluded_models)
186
+ // Only a real version may reach the config writer: anything else would be
187
+ // written verbatim into the provider's `package` spec.
188
+ const packageVersion = isVersion(parsed.package_version) ? parsed.package_version : undefined
189
+
190
+ return {
191
+ models: models ? { ...DEFAULT_CONFIG.models, ...models } : DEFAULT_CONFIG.models,
192
+ excluded_models: excluded ?? DEFAULT_CONFIG.excluded_models,
193
+ package_version: packageVersion ?? DEFAULT_CONFIG.package_version,
194
+ }
195
+ }
@@ -0,0 +1,72 @@
1
+ import { randomBytes } from "node:crypto"
2
+ import type { SiteAuth } from "./login"
3
+
4
+ export const CLI_VERSION = "2.185.0"
5
+ export const USER_AGENT = `CLI/${CLI_VERSION} CodeBuddy/${CLI_VERSION}`
6
+
7
+ const hostOf = (endpoint: string): string => {
8
+ try {
9
+ return new URL(endpoint).host
10
+ } catch {
11
+ return endpoint
12
+ }
13
+ }
14
+
15
+ const newRequestId = (): string => randomBytes(16).toString("hex")
16
+
17
+ /**
18
+ * Headers for config/chat/usage calls. `x-domain` is the endpoint host the
19
+ * request actually hits — never the realm/login domain, which triggers 12403.
20
+ */
21
+ export function apiHeaders(
22
+ auth: SiteAuth,
23
+ opts: { requestId?: string; accept?: string } = {},
24
+ ): Record<string, string> {
25
+ const headers: Record<string, string> = {
26
+ authorization: `Bearer ${auth.accessToken}`,
27
+ "user-agent": USER_AGENT,
28
+ "x-domain": hostOf(auth.endpoint),
29
+ "x-product": "SaaS",
30
+ "x-request-id": opts.requestId ?? newRequestId(),
31
+ "x-user-id": auth.uid,
32
+ }
33
+ if (auth.enterpriseId) headers["x-enterprise-id"] = auth.enterpriseId
34
+ if (opts.accept) headers.Accept = opts.accept
35
+ return headers
36
+ }
37
+
38
+ /**
39
+ * The international gateway verifies the full official-CLI header set on every
40
+ * chat request. CodeBuddy CN is not gated; only intl needs these. The
41
+ * X-Conversation-* family is mandatory — any subset is rejected with 11128.
42
+ */
43
+ export function channelHeaders(): Record<string, string> {
44
+ const messageId = randomBytes(16).toString("hex")
45
+ return {
46
+ "x-app": "cli",
47
+ "x-ide-type": "CLI",
48
+ "x-ide-name": "CLI",
49
+ "x-ide-version": CLI_VERSION,
50
+ "x-private-data": "false",
51
+ "x-agent-intent": "craft",
52
+ "x-agent-purpose": "conversation",
53
+ "x-conversation-id": randomBytes(16).toString("hex"),
54
+ // The official client mirrors the request id from the message id.
55
+ "x-request-id": messageId,
56
+ "x-conversation-request-id": messageId,
57
+ "x-conversation-message-id": messageId,
58
+ }
59
+ }
60
+
61
+ /** Headers for the proprietary token-refresh endpoint; no bearer token. */
62
+ export function refreshHeaders(auth: SiteAuth): Record<string, string> {
63
+ const headers: Record<string, string> = {
64
+ "X-Refresh-Token": auth.refreshToken,
65
+ "X-Auth-Refresh-Source": "plugin",
66
+ "Content-Type": "application/json",
67
+ Accept: "application/json",
68
+ "user-agent": USER_AGENT,
69
+ }
70
+ if (auth.enterpriseId) headers["x-enterprise-id"] = auth.enterpriseId
71
+ return headers
72
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * A warning sink that reports each distinct message once per process.
3
+ *
4
+ * Import runs at plugin load and can emit the same "provider X has no entry for
5
+ * Y" for several models at once; deduping keeps the console readable. Logging
6
+ * must also never be the thing that breaks a caller: a throwing writer is
7
+ * swallowed.
8
+ */
9
+ export function createDedupedLogger(
10
+ write: (line: string) => void,
11
+ prefix?: string,
12
+ ): (message: string) => void {
13
+ const seen = new Set<string>()
14
+
15
+ return (message: string) => {
16
+ // Dedupe on the raw message, not the formatted line, so changing the
17
+ // prefix later does not re-emit everything.
18
+ if (seen.has(message)) return
19
+ seen.add(message)
20
+ try {
21
+ write(prefix ? `${prefix} ${message}` : message)
22
+ } catch {
23
+ /* a broken writer must not become a broken transform */
24
+ }
25
+ }
26
+ }
@@ -0,0 +1,21 @@
1
+ import type { Site } from "../shared"
2
+
3
+ /** Per-site single-flight for the browser login flow. */
4
+ export interface LoginGate {
5
+ run(site: Site, task: () => Promise<{ ok: boolean; error: string | null }>): Promise<{ ok: boolean; error: string | null }>
6
+ }
7
+
8
+ export function createLoginGate(): LoginGate {
9
+ const inFlight: Partial<Record<Site, Promise<{ ok: boolean; error: string | null }>>> = {}
10
+ return {
11
+ run(site, task) {
12
+ const existing = inFlight[site]
13
+ if (existing) return existing
14
+ const p = task().finally(() => {
15
+ delete inFlight[site]
16
+ })
17
+ inFlight[site] = p
18
+ return p
19
+ },
20
+ }
21
+ }
@@ -0,0 +1,206 @@
1
+ import { spawn } from "node:child_process"
2
+ import type { Site } from "../shared"
3
+
4
+ /** Token pair returned by the login/refresh REST endpoints. */
5
+ export interface TokenPair {
6
+ accessToken: string
7
+ refreshToken: string
8
+ expiresIn: number
9
+ refreshExpiresIn: number
10
+ }
11
+
12
+ /** A credential for one site, cached by the plugin. Never sent to the GUI. */
13
+ export interface SiteAuth {
14
+ id: string
15
+ accessToken: string
16
+ refreshToken: string
17
+ expiresAt: number
18
+ refreshExpiresAt: number
19
+ uid: string
20
+ enterpriseId: string | null
21
+ realmDomain: string
22
+ endpoint: string
23
+ usageHost: string
24
+ }
25
+
26
+ /** Built-in site routing. `realmDomain` from the token only tags ownership. */
27
+ export const SITE_ENDPOINTS: Record<Site, { endpoint: string; usageHost: string }> = {
28
+ cn: { endpoint: "https://copilot.tencent.com", usageHost: "https://www.codebuddy.cn" },
29
+ intl: { endpoint: "https://www.codebuddy.ai", usageHost: "https://www.codebuddy.ai" },
30
+ }
31
+
32
+ const NO_CREDENTIALS_HEADERS: Record<string, string> = {
33
+ "X-No-Authorization": "true",
34
+ "X-No-User-Id": "true",
35
+ "X-No-Enterprise-Id": "true",
36
+ "X-No-Department-Info": "true",
37
+ "X-No-Tenant-Id": "true",
38
+ "Content-Type": "application/json",
39
+ Accept: "application/json",
40
+ "User-Agent": "CLI/2.185.0 CodeBuddy/2.185.0",
41
+ }
42
+
43
+ /** Decode a JWT payload without checking the signature; only trust our own server. */
44
+ export function decodeJwtPayload(jwt: string): Record<string, unknown> {
45
+ const parts = jwt.split(".")
46
+ if (parts.length < 2) return {}
47
+ try {
48
+ const json = Buffer.from(parts[1], "base64url").toString("utf8")
49
+ const parsed = JSON.parse(json)
50
+ return typeof parsed === "object" && parsed !== null
51
+ ? (parsed as Record<string, unknown>)
52
+ : {}
53
+ } catch {
54
+ return {}
55
+ }
56
+ }
57
+
58
+ const hostOf = (url: string): string => {
59
+ try {
60
+ return new URL(url).host
61
+ } catch {
62
+ return url
63
+ }
64
+ }
65
+
66
+ const asString = (v: unknown): string | null =>
67
+ typeof v === "string" && v.length > 0 ? v : null
68
+
69
+ /** Build a SiteAuth from a freshly obtained token pair. */
70
+ export function authFromToken(
71
+ site: Site,
72
+ token: TokenPair,
73
+ now: () => number = Date.now,
74
+ ): SiteAuth {
75
+ const payload = decodeJwtPayload(token.accessToken)
76
+ const uid = asString(payload.sub) ?? ""
77
+ const enterpriseId = asString(payload.enterprise_id)
78
+ const realmDomain = hostOf(asString(payload.iss) ?? "")
79
+ const route = SITE_ENDPOINTS[site]
80
+ const t = now()
81
+ return {
82
+ id: `${site}:${uid}`,
83
+ accessToken: token.accessToken,
84
+ refreshToken: token.refreshToken,
85
+ expiresAt: t + token.expiresIn * 1000,
86
+ refreshExpiresAt: t + token.refreshExpiresIn * 1000,
87
+ uid,
88
+ enterpriseId,
89
+ realmDomain,
90
+ endpoint: route.endpoint,
91
+ usageHost: route.usageHost,
92
+ }
93
+ }
94
+
95
+ export interface AuthState {
96
+ state: string
97
+ authUrl: string
98
+ }
99
+
100
+ interface GetAuthStateDeps {
101
+ fetchImpl?: typeof fetch
102
+ retries?: number
103
+ }
104
+
105
+ /** Step 1 of login: ask the server for a state + browser auth URL, no credentials. */
106
+ export async function getAuthState(
107
+ site: Site,
108
+ deps: GetAuthStateDeps = {},
109
+ ): Promise<AuthState> {
110
+ const doFetch = deps.fetchImpl ?? fetch
111
+ const url = `${SITE_ENDPOINTS[site].endpoint}/v2/plugin/auth/state?platform=CLI`
112
+ const retries = deps.retries ?? 2
113
+ let lastErr: unknown
114
+ for (let attempt = 0; attempt <= retries; attempt++) {
115
+ let res: Response
116
+ try {
117
+ res = await doFetch(url, { method: "POST", headers: NO_CREDENTIALS_HEADERS, body: "{}" })
118
+ } catch (err) {
119
+ lastErr = err
120
+ continue // network failure — retry
121
+ }
122
+ // A 4xx is a real answer, not a transient failure. It must bypass the retry
123
+ // loop entirely (a throw inside the try below would be swallowed by catch).
124
+ if (!res.ok && res.status < 500) {
125
+ throw new Error(`auth/state HTTP ${res.status}`)
126
+ }
127
+ try {
128
+ const json = (await res.json()) as {
129
+ code?: number
130
+ data?: { state?: string; authUrl?: string }
131
+ }
132
+ const state = json.data?.state
133
+ const authUrl = json.data?.authUrl
134
+ if (!state || !authUrl) throw new Error("auth/state missing state or authUrl")
135
+ return { state, authUrl }
136
+ } catch (err) {
137
+ lastErr = err
138
+ }
139
+ }
140
+ throw lastErr instanceof Error ? lastErr : new Error("getAuthState failed")
141
+ }
142
+
143
+ /** Open a URL in the system default browser; opener is injectable for tests. */
144
+ export function openBrowser(
145
+ url: string,
146
+ deps: { opener?: (url: string) => void } = {},
147
+ ): void {
148
+ const opener =
149
+ deps.opener ??
150
+ ((u: string) => {
151
+ // `cmd /c start` misparses URLs containing `&` (the authUrl always has
152
+ // `?platform=CLI&state=...`). Use a shell-free opener on Windows.
153
+ const cmd = process.platform === "win32" ? "rundll32" : process.platform === "darwin" ? "open" : "xdg-open"
154
+ const args = process.platform === "win32"
155
+ ? ["url.dll,FileProtocolHandler", u]
156
+ : [u]
157
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" })
158
+ child.unref()
159
+ })
160
+ opener(url)
161
+ }
162
+
163
+ const PENDING_CODE = 11217
164
+
165
+ interface PollTokenDeps {
166
+ fetchImpl?: typeof fetch
167
+ now?: () => number
168
+ sleep?: (ms: number) => Promise<void>
169
+ timeoutMs?: number
170
+ intervalMs?: number
171
+ }
172
+
173
+ /** Step 3 of login: poll auth/token until the browser login completes. */
174
+ export async function pollToken(
175
+ site: Site,
176
+ state: string,
177
+ deps: PollTokenDeps = {},
178
+ ): Promise<SiteAuth> {
179
+ const doFetch = deps.fetchImpl ?? fetch
180
+ const now = deps.now ?? Date.now
181
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
182
+ const timeoutMs = deps.timeoutMs ?? 5 * 60_000
183
+ const intervalMs = deps.intervalMs ?? 1000
184
+ const url = `${SITE_ENDPOINTS[site].endpoint}/v2/plugin/auth/token?state=${encodeURIComponent(state)}`
185
+ const deadline = now() + timeoutMs
186
+
187
+ for (;;) {
188
+ const res = await doFetch(url, { method: "GET", headers: NO_CREDENTIALS_HEADERS })
189
+ const json = (await res.json()) as {
190
+ code?: number
191
+ msg?: string
192
+ data?: TokenPair
193
+ }
194
+ if (json.data?.accessToken) {
195
+ return authFromToken(site, json.data, now)
196
+ }
197
+ // Only the documented pending code means "keep waiting". The message is
198
+ // advisory only — relying on its text could mask a real auth error.
199
+ const pending = json.code === PENDING_CODE
200
+ if (!pending) {
201
+ throw new Error(`pollToken failed: code=${json.code ?? "?"} msg=${json.msg ?? "?"}`)
202
+ }
203
+ if (now() >= deadline) throw new Error("pollToken timed out waiting for login")
204
+ await sleep(intervalMs)
205
+ }
206
+ }
@@ -0,0 +1,109 @@
1
+ import type { CatalogModel } from "./catalog"
2
+ import type { QuotaConfig } from "./config"
3
+ import { resolveCost, vendorEfforts, type ModelCost, type ModelsDevCatalog } from "./pricing"
4
+
5
+ /**
6
+ * Turns the CodeBuddy catalog into the shape a provider needs: models filtered
7
+ * down to the ones the user mapped, priced, and renamed where two of them would
8
+ * otherwise be indistinguishable in a model picker.
9
+ */
10
+
11
+ export interface ImportedModel {
12
+ id: string
13
+ name: string
14
+ cost: ModelCost[]
15
+ limit: { context: number; output: number }
16
+ imageInput: boolean
17
+ efforts: readonly string[]
18
+ defaultEffort: string | null
19
+ }
20
+
21
+ export interface BuildModelsDeps {
22
+ catalog: readonly CatalogModel[]
23
+ config: QuotaConfig
24
+ modelsDev: ModelsDevCatalog | null
25
+ log: (message: string) => void
26
+ }
27
+
28
+ /**
29
+ * One size for every model, regardless of what either the server or models.dev
30
+ * declares. CodeBuddy bills the same credits per token whatever the model's
31
+ * nominal window, so per-model limits only made the picker lie about capacity.
32
+ */
33
+ const LIMIT = { context: 500_000, output: 64_000 } as const
34
+
35
+ /**
36
+ * The catalog declares `Hy4 flash` twice (free and paid) and `Hy4` once. Only
37
+ * where names collide *after* exclusions are applied does the credit factor get
38
+ * appended, so a model that happens to be unique keeps its clean name.
39
+ *
40
+ * A colliding model whose factor the server never declared keeps its bare name
41
+ * rather than rendering "Hy4 flash(undefined)".
42
+ */
43
+ function dedupeNames(models: readonly ImportedModel[], credits: ReadonlyMap<string, number | null>): ImportedModel[] {
44
+ const counts = new Map<string, number>()
45
+ for (const model of models) counts.set(model.name, (counts.get(model.name) ?? 0) + 1)
46
+
47
+ return models.map((model) => {
48
+ if ((counts.get(model.name) ?? 0) < 2) return model
49
+ // catalog.ts may already have appended a credit label; never stack a second.
50
+ // Tolerate case/space variants. Known limit: an upstream name that genuinely
51
+ // ends in "(xN)" would be skipped here too — acceptable while catalog.ts is
52
+ // the only producer of such labels and marks them this way.
53
+ if (/\(\s*[xX]\s*[\d.]+\)\s*$/.test(model.name)) return model
54
+
55
+ const factor = credits.get(model.id)
56
+ if (factor === null || factor === undefined) return model
57
+ return { ...model, name: `${model.name}(x${factor.toFixed(2)})` }
58
+ })
59
+ }
60
+
61
+ export function buildModels(deps: BuildModelsDeps): readonly ImportedModel[] {
62
+ const { config, modelsDev, log } = deps
63
+ const excluded = new Set(config.excluded_models)
64
+
65
+ // A model the user has not mapped is not offered at all: without a models.dev
66
+ // entry there is no price and no vendor reasoning table, and guessing either
67
+ // would put a model in the picker that cannot be described correctly.
68
+ const kept: CatalogModel[] = []
69
+ for (const model of deps.catalog) {
70
+ if (excluded.has(model.id)) continue
71
+ if (!config.models[model.id]) {
72
+ log(`${model.id} has no models entry in codebuddy-quota.json; not offered`)
73
+ continue
74
+ }
75
+ kept.push(model)
76
+ }
77
+
78
+ const built = kept.map<ImportedModel>((model) => {
79
+ const mapping = config.models[model.id]
80
+ // Vendor levels win over whatever the gateway advertises. A model models.dev
81
+ // knows nothing about keeps the server's levels rather than losing the
82
+ // ability to reason at all.
83
+ const vendor = vendorEfforts(mapping, modelsDev)
84
+ const efforts = vendor ? vendor.efforts : model.efforts
85
+ const defaultEffort = vendor
86
+ ? // The vendor's own pick wins; without one, the gateway's if it exists in
87
+ // the vendor table, else the heaviest level so a selection is valid.
88
+ vendor.defaultEffort ??
89
+ (vendor.efforts.includes(model.defaultEffort ?? "")
90
+ ? model.defaultEffort
91
+ : vendor.efforts[vendor.efforts.length - 1])
92
+ : model.defaultEffort
93
+
94
+ return {
95
+ id: model.id,
96
+ name: model.name,
97
+ cost: resolveCost(model, mapping, modelsDev, log),
98
+ limit: { context: LIMIT.context, output: LIMIT.output },
99
+ imageInput: model.imageInput,
100
+ efforts,
101
+ defaultEffort,
102
+ }
103
+ })
104
+
105
+ const credits = new Map(kept.map((model) => [model.id, model.credits]))
106
+ // Sorted by id so the picker is stable no matter what order the server sends.
107
+ const sorted = [...built].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
108
+ return dedupeNames(sorted, credits)
109
+ }