opencode-codebuddy-quota 0.1.0 → 0.1.3

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.
@@ -1,195 +1,215 @@
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
- }
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
+ /** Cloud embedding model id; set to `""` to disable cloud embeddings. */
28
+ embedding_model: string
29
+ /** Local (transformers.js) embedding model id; `""` means no local model. */
30
+ local_embedding_model: string
31
+ }
32
+
33
+ /**
34
+ * Mirrors `config.default.json`. The JSON file is documentation plus the
35
+ * schema anchor; the constant is what runs, so nothing has to read a file at
36
+ * plugin load time. A test asserts the two never drift apart.
37
+ */
38
+ export const DEFAULT_CONFIG: QuotaConfig = {
39
+ models: {
40
+ "deepseek-v4-pro": { provider: "deepseek", model: "deepseek-v4-pro" },
41
+ // CodeBuddy's revision of v4.1-flash is the vendor's plain v4-flash.
42
+ "deepseek-v4.1-flash": { provider: "deepseek", model: "deepseek-v4-flash" },
43
+ "glm-5.3-flash": { provider: "zhipuai", model: "glm-5.3-flash" },
44
+ "glm-5.3-flashx": { provider: "zhipuai", model: "glm-5.3-flashx" },
45
+ "minimax-m3.1-flash": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
46
+ "step-5-preview": { provider: "stepfun", model: "step-5-preview" },
47
+ "mimo-v2.6-pro": { provider: "xiaomi", model: "mimo-v2.6-pro" },
48
+ hy4std: { provider: "tencent-tokenhub", model: "hy4" },
49
+ // `Hy4 flash` ships twice: a free id and a paid one. models.dev has no
50
+ // flash entry, so both map to Hy4; the free one is zero-priced by credits.
51
+ "hy4flash-free": { provider: "tencent-tokenhub", model: "hy4" },
52
+ hy4flash: { provider: "tencent-tokenhub", model: "hy4" },
53
+ hy4free: { provider: "tencent-tokenhub", model: "hy4" },
54
+ hy3: { provider: "tencent-tokenhub", model: "hy3" },
55
+ "hy3-x": { provider: "tencent-tokenhub", model: "hy3" },
56
+ // Same model as minimax-m3.1-flash; CodeBuddy just bills it under its own id.
57
+ "space-bunny": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
58
+ // International-site cli-whitelist (ids from /v3/config agents[cli]).
59
+ // Four virtual routing aliases (default/fast/balanced/primary-model) have no
60
+ // models.dev entity and are intentionally left unmapped so they are skipped.
61
+ "hy4-preview": { provider: "tencent-tokenhub", model: "hy4-preview" },
62
+ // SG variant shares the same underlying model; models.dev has no separate id.
63
+ "deepseek-v4.1-flash-sg": { provider: "deepseek", model: "deepseek-v4-flash" },
64
+ // models.dev v3 carries all GPT ids under openai; use the official vendor.
65
+ "gpt-6-astra": { provider: "openai", model: "gpt-6-astra" },
66
+ "gpt-6.1-sol": { provider: "openai", model: "gpt-6.1-sol" },
67
+ "gpt-6-sol": { provider: "openai", model: "gpt-6-sol" },
68
+ "gpt-6-luna": { provider: "openai", model: "gpt-6-luna" },
69
+ "gpt-5.6-sol": { provider: "openai", model: "gpt-5.6-sol" },
70
+ "gpt-5.6-terra": { provider: "openai", model: "gpt-5.6-terra" },
71
+ "gpt-5.5": { provider: "openai", model: "gpt-5.5" },
72
+ "gpt-5.4": { provider: "openai", model: "gpt-5.4" },
73
+ "gpt-5.6-luna": { provider: "openai", model: "gpt-5.6-luna" },
74
+ // Official vendor mappings: reseller entries carry distorted prices.
75
+ "grok-4.7": { provider: "xai", model: "grok-4.7" },
76
+ "gemini-3.8-flash": { provider: "google", model: "gemini-3.8-flash" },
77
+ "glm-5.3": { provider: "zhipuai", model: "glm-5.3" },
78
+ // models.dev's `zhipuai` provider has no glm-5.4 entry; only coding-plan
79
+ // resellers do. tencent-token-plan is the one carrying real per-token prices.
80
+ "glm-5.4": { provider: "tencent-token-plan", model: "glm-5.4" },
81
+ "glm-5.2": { provider: "zhipuai", model: "glm-5.2" },
82
+ // moonshotai is the official vendor; wafer.ai resells kimi at skewed prices.
83
+ "kimi-k3.1-pro": { provider: "moonshotai", model: "kimi-k3.1-pro" },
84
+ "kimi-k3": { provider: "moonshotai", model: "kimi-k3" },
85
+ "kimi-k3.1-pro-highspeed": { provider: "moonshotai", model: "kimi-k3.1-pro-highspeed" },
86
+ },
87
+ // auto/max-model are virtual routing tiers with no models.dev entity; exclude
88
+ // them explicitly rather than relying on the no-mapping skip.
89
+ excluded_models: ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
90
+ package_version: DEFAULT_PACKAGE_VERSION,
91
+ embedding_model: "bge-m3",
92
+ local_embedding_model: "",
93
+ }
94
+
95
+ export const CONFIG_FILE_NAME = "codebuddy-quota.json"
96
+
97
+ /** `$XDG_CONFIG_HOME/opencode`, or `~/.config/opencode` when it is unset. */
98
+ export function configDir(
99
+ env: Record<string, string | undefined> = process.env,
100
+ home: string = homedir(),
101
+ ): string {
102
+ const xdg = env.XDG_CONFIG_HOME
103
+ if (xdg) return join(xdg, "opencode")
104
+ return join(home, ".config", "opencode")
105
+ }
106
+
107
+ /** `~/.config/opencode/codebuddy-quota.json`, beside the user's `opencode.json(c)`. */
108
+ export function configPath(home: string = homedir()): string {
109
+ return join(configDir(undefined, home), CONFIG_FILE_NAME)
110
+ }
111
+
112
+ /**
113
+ * The names OpenCode accepts for a config file, in the order it prefers them.
114
+ * Both parse; JSONC is the one with comments.
115
+ */
116
+ export const OPENCODE_CONFIG_NAMES = ["opencode.jsonc", "opencode.json"] as const
117
+
118
+ /**
119
+ * The OpenCode config this plugin should edit.
120
+ *
121
+ * OpenCode reads `opencode.jsonc` or `opencode.json`, whichever exists — a user
122
+ * who picked `.json` must not be left with a plugin that silently imports
123
+ * nothing. The first name that exists wins; with neither present the returned
124
+ * path ends in `.jsonc`, matching what OpenCode writes for a fresh config.
125
+ */
126
+ export function opencodeConfigPath(
127
+ dir: string = configDir(),
128
+ exists: (path: string) => boolean = existsSync,
129
+ ): string {
130
+ for (const name of OPENCODE_CONFIG_NAMES) {
131
+ const candidate = join(dir, name)
132
+ if (exists(candidate)) return candidate
133
+ }
134
+ return join(dir, OPENCODE_CONFIG_NAMES[0])
135
+ }
136
+
137
+ function isRecord(value: unknown): value is Record<string, unknown> {
138
+ return typeof value === "object" && value !== null && !Array.isArray(value)
139
+ }
140
+
141
+ /**
142
+ * `{ codebuddyId: { provider, model } }`. A single malformed entry drops the
143
+ * whole field rather than half-applying it — a partially understood model list
144
+ * is worse than the shipped one.
145
+ */
146
+ function modelMap(value: unknown): Record<string, ModelMapping> | undefined {
147
+ if (!isRecord(value)) return undefined
148
+ const out: Record<string, ModelMapping> = {}
149
+ for (const [id, entry] of Object.entries(value)) {
150
+ if (id.length === 0 || !isRecord(entry)) return undefined
151
+ const { provider, model } = entry as Record<string, unknown>
152
+ if (typeof provider !== "string" || provider.length === 0) return undefined
153
+ if (typeof model !== "string" || model.length === 0) return undefined
154
+ out[id] = { provider, model }
155
+ }
156
+ return out
157
+ }
158
+
159
+ function stringList(value: unknown): string[] | undefined {
160
+ if (!Array.isArray(value)) return undefined
161
+ const out: string[] = []
162
+ for (const v of value) {
163
+ if (typeof v !== "string" || v.length === 0) return undefined
164
+ out.push(v)
165
+ }
166
+ return out
167
+ }
168
+
169
+ /**
170
+ * Unlike `stringList`, an empty string is a meaningful value here: it is how a
171
+ * user disables one embedding backend. Only the wrong type falls back.
172
+ */
173
+ function optionalString(value: unknown): string | undefined {
174
+ return typeof value === "string" ? value : undefined
175
+ }
176
+
177
+ export interface LoadConfigDeps {
178
+ configPath?: string
179
+ readFile?: (path: string) => string
180
+ }
181
+
182
+ /**
183
+ * The user file is layered over the defaults: `models` merges one level deep so
184
+ * a user who adds a model does not have to repeat the twelve shipped ones, while
185
+ * `excluded_models` replaces wholesale. A field that fails validation silently
186
+ * keeps its default so one typo cannot take the rest down. This function never
187
+ * throws — a broken config must not stop the quota panel.
188
+ */
189
+ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
190
+ const path = deps.configPath ?? configPath()
191
+ const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
192
+
193
+ let parsed: unknown
194
+ try {
195
+ parsed = JSON.parse(read(path))
196
+ } catch {
197
+ return DEFAULT_CONFIG
198
+ }
199
+ if (!isRecord(parsed)) return DEFAULT_CONFIG
200
+
201
+ const models = modelMap(parsed.models)
202
+ const excluded = stringList(parsed.excluded_models)
203
+ // Only a real version may reach the config writer: anything else would be
204
+ // written verbatim into the provider's `package` spec.
205
+ const packageVersion = isVersion(parsed.package_version) ? parsed.package_version : undefined
206
+
207
+ return {
208
+ models: models ? { ...DEFAULT_CONFIG.models, ...models } : DEFAULT_CONFIG.models,
209
+ excluded_models: excluded ?? DEFAULT_CONFIG.excluded_models,
210
+ package_version: packageVersion ?? DEFAULT_CONFIG.package_version,
211
+ embedding_model: optionalString(parsed.embedding_model) ?? DEFAULT_CONFIG.embedding_model,
212
+ local_embedding_model:
213
+ optionalString(parsed.local_embedding_model) ?? DEFAULT_CONFIG.local_embedding_model,
214
+ }
215
+ }
@@ -0,0 +1,166 @@
1
+ import { join } from "node:path"
2
+ import { configDir } from "./config"
3
+
4
+ /** An in-process embedder that mirrors the cloud `bge-m3` contract. */
5
+ export interface LocalEmbedding {
6
+ embed(inputs: string[]): Promise<number[][]>
7
+ readonly dimension: number
8
+ }
9
+
10
+ /** OpenAI's `/embeddings` wire shape. */
11
+ export interface EmbeddingResponse {
12
+ object: "list"
13
+ data: { object: "embedding"; index: number; embedding: number[] }[]
14
+ model: string
15
+ usage: { prompt_tokens: number; total_tokens: number }
16
+ }
17
+
18
+ /** The cloud model is 1024-dim; a local result must not change the caller's index shape. */
19
+ const DIMENSION = 1024
20
+
21
+ /**
22
+ * Guard the wire shape against a mis-shaped ONNX output. A vector of the wrong
23
+ * width would be accepted by clients with no error and silently corrupt their
24
+ * index, so it is converted into a failure here, at the one place every local
25
+ * result passes through.
26
+ */
27
+ function assertVectors(vectors: number[][], expected: number, count: number): number[][] {
28
+ if (vectors.length !== count) {
29
+ throw new Error(`local embedder returned ${vectors.length} vectors for ${count} inputs`)
30
+ }
31
+ for (const vector of vectors) {
32
+ if (!Array.isArray(vector) || vector.length !== expected) {
33
+ throw new Error(`local embedder returned a vector of width ${vector?.length} (expected ${expected})`)
34
+ }
35
+ }
36
+ return vectors
37
+ }
38
+
39
+ /**
40
+ * The full HuggingFace id is the only local selector. The bare `bge-m3` must keep
41
+ * going upstream so existing cloud callers are unaffected.
42
+ */
43
+ const LOCAL_PREFIX = "Xenova/"
44
+
45
+ /**
46
+ * Single source of truth for the local-vs-upstream split; `proxy.ts` uses this
47
+ * too, so the two call sites cannot drift apart.
48
+ */
49
+ export function isLocalModel(model: string): boolean {
50
+ return model.startsWith(LOCAL_PREFIX)
51
+ }
52
+
53
+ /** Keep the cache inside the plugin's own config tree so it never fights OpenCode or opencode-mem. */
54
+ export const MODEL_CACHE_DIR = join(configDir(), "codebuddy-quota-models")
55
+
56
+ export async function routeEmbedding(
57
+ model: string,
58
+ input: string | string[],
59
+ deps: { local: LocalEmbedding },
60
+ ): Promise<EmbeddingResponse | null> {
61
+ if (!isLocalModel(model)) return null
62
+ const inputs = Array.isArray(input) ? input : [input]
63
+ const vectors = assertVectors(await deps.local.embed(inputs), DIMENSION, inputs.length)
64
+ return {
65
+ object: "list",
66
+ data: vectors.map((embedding, index) => ({ object: "embedding" as const, index, embedding })),
67
+ model,
68
+ // Tokenisation would need the model's own tokenizer; a per-input count is
69
+ // enough to keep the field populated without pulling one in.
70
+ usage: { prompt_tokens: inputs.length, total_tokens: inputs.length },
71
+ }
72
+ }
73
+
74
+ /** The slice of transformers.js this module uses. */
75
+ type FeatureExtractor = (
76
+ inputs: string[],
77
+ options: { pooling: "cls"; normalize: boolean },
78
+ ) => Promise<{ tolist(): number[][] }>
79
+
80
+ /** The shipped default; a configured local model id overrides it. */
81
+ const DEFAULT_LOCAL_MODEL = "Xenova/bge-m3"
82
+
83
+ /**
84
+ * A build is expensive (~600 MB download + ONNX load), so failures must not be
85
+ * sticky. The builder receives the target id so tests can assert which model a
86
+ * factory was asked to load without downloading it.
87
+ */
88
+ export type LocalEmbedderBuilder = (modelId: string) => Promise<LocalEmbedding>
89
+
90
+ /**
91
+ * The successful pipeline is memoised at module scope on purpose: production
92
+ * constructs a new embedder per request (`deps.local ?? createLocalEmbedder()`),
93
+ * so a per-instance memo would reload the ONNX sessions on every local call.
94
+ */
95
+ let pending: Promise<LocalEmbedding> | null = null
96
+
97
+ /**
98
+ * Forget the memoised build. Production calls this after repairing a corrupt
99
+ * cache: the files that were deleted must be downloaded again, and the memo
100
+ * would otherwise hand every later request the old, broken pipeline. Only the
101
+ * repair path calls it; one pipeline per process is still the normal contract.
102
+ */
103
+ export function clearLocalEmbedderMemo(): void {
104
+ pending = null
105
+ }
106
+
107
+ /** Test alias: each case must start from a cold process. */
108
+ export function resetLocalEmbedderForTests(): void {
109
+ clearLocalEmbedderMemo()
110
+ }
111
+
112
+ /**
113
+ * Builds the pipeline on first use. `@huggingface/transformers` is imported
114
+ * dynamically on purpose: a static import would make every plugin cold start
115
+ * pay for ONNX runtime even though almost no request uses local embeddings.
116
+ * The promise is memoised process-wide so concurrent first requests share one
117
+ * pipeline. A failed build clears the memo before rethrowing, otherwise a single
118
+ * transient download error would pin every later request to 502 until the
119
+ * process restarts.
120
+ *
121
+ * Both call styles are supported: `createLocalEmbedder(modelId, builder)` and
122
+ * the legacy `createLocalEmbedder(builder)`, so existing callers keep the
123
+ * shipped default id. `builder` exists so tests can exercise the retry without
124
+ * downloading the model.
125
+ */
126
+ export function createLocalEmbedder(modelId?: string, builder?: LocalEmbedderBuilder): LocalEmbedding
127
+ export function createLocalEmbedder(builder: LocalEmbedderBuilder, modelId?: string): LocalEmbedding
128
+ export function createLocalEmbedder(
129
+ first?: string | LocalEmbedderBuilder,
130
+ second?: string | LocalEmbedderBuilder,
131
+ ): LocalEmbedding {
132
+ const modelId = typeof first === "string" ? first : typeof second === "string" ? second : DEFAULT_LOCAL_MODEL
133
+ const builder = typeof first === "function" ? first : typeof second === "function" ? second : undefined
134
+ const build = async (): Promise<LocalEmbedding> => {
135
+ const { pipeline, env } = await import("@huggingface/transformers")
136
+ // Must be set before the pipeline is created, otherwise the model lands in
137
+ // the shared default cache.
138
+ env.cacheDir = MODEL_CACHE_DIR
139
+ // The configured id drives both the download and the cache directory that
140
+ // prewarm verifies (model-cache.ts uses `join(cacheDir, model)`).
141
+ const extractor = (await pipeline("feature-extraction", modelId, { dtype: "q8" })) as FeatureExtractor
142
+ return {
143
+ dimension: DIMENSION,
144
+ embed: async (inputs) => {
145
+ const output = await extractor(inputs, { pooling: "cls", normalize: true })
146
+ // Validate the raw ONNX rows, not just the wire response: `tolist()` can
147
+ // hand back a ragged array that would otherwise only fail much later.
148
+ return assertVectors(output.tolist(), DIMENSION, inputs.length)
149
+ },
150
+ }
151
+ }
152
+ const ensure = (): Promise<LocalEmbedding> => {
153
+ if (!pending) {
154
+ pending = (builder ? builder(modelId) : build()).catch((error: unknown) => {
155
+ // Rejections are not nullish, so `??=` would reuse them forever.
156
+ pending = null
157
+ throw error
158
+ })
159
+ }
160
+ return pending
161
+ }
162
+ return {
163
+ dimension: DIMENSION,
164
+ embed: async (inputs) => (await ensure()).embed(inputs),
165
+ }
166
+ }
@@ -0,0 +1,14 @@
1
+ import type { QuotaConfig } from "./config"
2
+
3
+ /**
4
+ * Choose the embedding backend from configuration alone. Pure: no I/O and no
5
+ * request-body sniffing, so proxy routing and startup warmup agree on one rule.
6
+ * Local mode requires an explicit opt-in: the cloud model must be disabled
7
+ * *and* a local model must be named.
8
+ */
9
+ export function resolveEmbeddingMode(
10
+ config: Pick<QuotaConfig, "embedding_model" | "local_embedding_model">,
11
+ ): "cloud" | "local" {
12
+ if (config.local_embedding_model !== "" && config.embedding_model === "") return "local"
13
+ return "cloud"
14
+ }