opencode-codebuddy-quota 0.0.0-stage → 0.1.2

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
@@ -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,136 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ /** A verified local model cache, persisted across process restarts. */
6
+ export interface ReadyFlag {
7
+ version: number
8
+ model: string
9
+ revision: string
10
+ /** filename -> official HuggingFace sha256 */
11
+ hashes: Record<string, string>
12
+ }
13
+
14
+ /** Bump this when `ReadyFlag` changes shape; old flags are then treated as absent. */
15
+ export const FLAGS_VERSION = 1
16
+
17
+ function readyFlagPath(cacheDir: string): string {
18
+ return join(cacheDir, "ready.json")
19
+ }
20
+
21
+ /**
22
+ * transformers.js FS cache stores a model's files directly under
23
+ * `path.join(env.cacheDir, pathJoin(modelId, filename))` — no `models--`
24
+ * prefix and no `blobs/` subdirectory.
25
+ */
26
+ function modelDir(cacheDir: string, model: string): string {
27
+ return join(cacheDir, model)
28
+ }
29
+
30
+ function isReadyFlag(value: unknown): value is ReadyFlag {
31
+ if (typeof value !== "object" || value === null) return false
32
+ const flag = value as Record<string, unknown>
33
+ if (flag.version !== FLAGS_VERSION) return false
34
+ if (typeof flag.model !== "string" || typeof flag.revision !== "string") return false
35
+ if (typeof flag.hashes !== "object" || flag.hashes === null || Array.isArray(flag.hashes)) return false
36
+ return Object.values(flag.hashes).every((hash) => typeof hash === "string")
37
+ }
38
+
39
+ /**
40
+ * A missing, corrupt or outdated flag is indistinguishable from "never warmed":
41
+ * the caller retries instead of trusting a half-written marker. Never throws.
42
+ */
43
+ export function readReadyFlag(deps: { cacheDir: string }): ReadyFlag | null {
44
+ try {
45
+ const raw = readFileSync(readyFlagPath(deps.cacheDir), "utf8")
46
+ const parsed: unknown = JSON.parse(raw)
47
+ return isReadyFlag(parsed) ? parsed : null
48
+ } catch {
49
+ return null
50
+ }
51
+ }
52
+
53
+ /** Commit via rename so a reader never observes a partially written flag. */
54
+ export function writeReadyFlag(flag: ReadyFlag, deps: { cacheDir: string }): void {
55
+ const path = readyFlagPath(deps.cacheDir)
56
+ const tmp = `${path}.tmp.${process.pid}`
57
+ mkdirSync(deps.cacheDir, { recursive: true })
58
+ try {
59
+ writeFileSync(tmp, JSON.stringify(flag, null, 2))
60
+ renameSync(tmp, path)
61
+ } catch (error) {
62
+ try { unlinkSync(tmp) } catch { /* nothing to clean up */ }
63
+ throw error
64
+ }
65
+ }
66
+
67
+ /** Ask the Hub for the authoritative sha256 of every LFS-backed model file. */
68
+ export async function fetchOfficialHashes(
69
+ model: string,
70
+ deps: { fetchImpl?: typeof fetch } = {},
71
+ ): Promise<{ revision: string; hashes: Record<string, string> }> {
72
+ const doFetch = deps.fetchImpl ?? fetch
73
+ const res = await doFetch(`https://huggingface.co/api/models/${model}?blobs=true`)
74
+ if (!res.ok) throw new Error(`HuggingFace hash lookup failed for ${model}: HTTP ${res.status}`)
75
+ const json = (await res.json()) as {
76
+ sha?: string
77
+ siblings?: { rfilename?: string; lfs?: { sha256?: string } }[]
78
+ }
79
+ const hashes: Record<string, string> = {}
80
+ for (const sibling of json.siblings ?? []) {
81
+ const sha256 = sibling.lfs?.sha256
82
+ if (typeof sibling.rfilename === "string" && typeof sha256 === "string" && sha256 !== "") {
83
+ hashes[sibling.rfilename] = sha256
84
+ }
85
+ }
86
+ return { revision: typeof json.sha === "string" ? json.sha : "main", hashes }
87
+ }
88
+
89
+ export interface VerifyCacheDeps {
90
+ cacheDir: string
91
+ model: string
92
+ official: Record<string, string>
93
+ listFiles: (dir: string) => string[]
94
+ hashFile: (path: string) => string
95
+ }
96
+
97
+ /**
98
+ * Only LFS-backed files (those with an official sha256 from the Hub) are verified:
99
+ * each must be present locally with the expected hash. Small non-LFS files have
100
+ * no official hash and are deliberately ignored, never treated as bad. Bad
101
+ * entries are returned as full paths so the caller can delete them and re-download.
102
+ */
103
+ export function verifyCache(deps: VerifyCacheDeps): { ok: boolean; badFiles: string[] } {
104
+ const dir = modelDir(deps.cacheDir, deps.model)
105
+ let files: string[]
106
+ try {
107
+ files = deps.listFiles(dir)
108
+ } catch {
109
+ return { ok: false, badFiles: [] }
110
+ }
111
+
112
+ const local = new Set(files)
113
+ const badFiles: string[] = []
114
+ for (const [filename, expectedHash] of Object.entries(deps.official)) {
115
+ const path = join(dir, filename)
116
+ if (!local.has(filename)) {
117
+ badFiles.push(path)
118
+ continue
119
+ }
120
+ let actualHash: string
121
+ try {
122
+ actualHash = deps.hashFile(path)
123
+ } catch {
124
+ badFiles.push(path)
125
+ continue
126
+ }
127
+ if (actualHash !== expectedHash) badFiles.push(path)
128
+ }
129
+
130
+ return { ok: badFiles.length === 0, badFiles }
131
+ }
132
+
133
+ /** Content hash used by the default `hashFile` seam in callers. */
134
+ export function sha256Of(contents: string | Buffer): string {
135
+ return createHash("sha256").update(contents).digest("hex")
136
+ }
@@ -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
+ }
@@ -0,0 +1,123 @@
1
+ import { readdirSync, readFileSync, statSync, unlinkSync } from "node:fs"
2
+ import { join, sep } from "node:path"
3
+ import { MODEL_CACHE_DIR, type LocalEmbedding } from "./embedding-local"
4
+ import {
5
+ fetchOfficialHashes,
6
+ FLAGS_VERSION,
7
+ readReadyFlag,
8
+ sha256Of,
9
+ verifyCache,
10
+ writeReadyFlag,
11
+ type ReadyFlag,
12
+ } from "./model-cache"
13
+
14
+ export interface PrewarmDeps {
15
+ model: string
16
+ /** Must trigger the real (memoised) build and resolve to the ready embedder. */
17
+ build: () => Promise<LocalEmbedding>
18
+ /**
19
+ * Invoked after bad files are deleted, before the rebuild. Lets the builder
20
+ * drop any memoised pipeline that would otherwise skip the re-download.
21
+ */
22
+ onCacheRepair?: () => void
23
+ fetchImpl?: typeof fetch
24
+ cacheDir?: string
25
+ listFiles?: (dir: string) => string[]
26
+ hashFile?: (path: string) => string
27
+ log?: (s: string) => void
28
+ }
29
+
30
+ /** Remove only the files the Hub disagrees with. A missing path is not a failure. */
31
+ function deleteBadFiles(paths: string[], log: (s: string) => void): void {
32
+ for (const path of paths) {
33
+ try {
34
+ unlinkSync(path)
35
+ } catch (error) {
36
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
37
+ log(`[local-embedding-prewarm] could not delete ${path}: ${String(error)}`)
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ /** A flag is a performance hint; failing to persist it must not fail prewarm. */
44
+ function saveFlag(flag: ReadyFlag, cacheDir: string, log: (s: string) => void): void {
45
+ try {
46
+ writeReadyFlag(flag, { cacheDir })
47
+ } catch (error) {
48
+ log(`[local-embedding-prewarm] could not write ready flag: ${String(error)}`)
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Warm the local model cache before serving requests: verify against the Hub,
54
+ * download via `build`, and only then persist a ready flag. A corrupt cache is
55
+ * repaired once (bad files deleted, then rebuilt); if it still does not verify,
56
+ * the already-built embedder is returned so requests still work but the flag is
57
+ * left absent so the next process retries. Failures are logged and rethrown for
58
+ * the caller to swallow — prewarm never blocks startup.
59
+ */
60
+ export async function warmLocalModel(deps: PrewarmDeps): Promise<LocalEmbedding> {
61
+ const cacheDir = deps.cacheDir ?? MODEL_CACHE_DIR
62
+ const log = deps.log ?? console.warn
63
+ // `readdirSync` with `recursive` yields paths relative to `dir`. Two seams
64
+ // are needed to match the Hub's nested `rfilename` keys exactly: drop directory
65
+ // entries (which `verifyCache` would mistake for stray files) and use forward
66
+ // slashes on Windows, where `readdirSync` emits `\` but the Hub emits `/`.
67
+ const listFiles =
68
+ deps.listFiles ??
69
+ ((dir: string) =>
70
+ readdirSync(dir, { recursive: true, withFileTypes: false, encoding: "utf8" })
71
+ .filter((rel) => {
72
+ try {
73
+ return statSync(join(dir, rel)).isFile()
74
+ } catch {
75
+ return false
76
+ }
77
+ })
78
+ .map((rel) => (sep === "/" ? rel : rel.split(sep).join("/"))))
79
+ const hashFile = deps.hashFile ?? ((path: string) => sha256Of(readFileSync(path)))
80
+
81
+ try {
82
+ // A previously verified flag for this same model means transformers.js
83
+ // reads straight from its FS cache: no Hub lookup, no re-hashing, just
84
+ // trigger the local build. A flag naming another model is stale — the
85
+ // configured model changed — so fall through and verify the new one.
86
+ const readyFlag = readReadyFlag({ cacheDir })
87
+ if (readyFlag && readyFlag.model === deps.model) {
88
+ return await deps.build()
89
+ }
90
+
91
+ const official = await fetchOfficialHashes(deps.model, { fetchImpl: deps.fetchImpl })
92
+ let embedder = await deps.build()
93
+
94
+ const flag: ReadyFlag = {
95
+ version: FLAGS_VERSION,
96
+ model: deps.model,
97
+ revision: official.revision,
98
+ hashes: official.hashes,
99
+ }
100
+ const verify = () =>
101
+ verifyCache({ cacheDir, model: deps.model, official: official.hashes, listFiles, hashFile })
102
+
103
+ let result = verify()
104
+ if (!result.ok) {
105
+ deleteBadFiles(result.badFiles, log)
106
+ // A memoised embedder points at the files just deleted; without this the
107
+ // rebuild would reuse it and re-verification could never recover.
108
+ deps.onCacheRepair?.()
109
+ embedder = await deps.build()
110
+ result = verify()
111
+ }
112
+
113
+ if (result.ok) {
114
+ saveFlag(flag, cacheDir, log)
115
+ } else {
116
+ log(`[local-embedding-prewarm] verification failed after retry for ${deps.model}; ready flag not written`)
117
+ }
118
+ return embedder
119
+ } catch (error) {
120
+ log(`[local-embedding-prewarm] prewarm failed for ${deps.model}: ${String(error)}`)
121
+ throw error
122
+ }
123
+ }