opencode-codebuddy-quota 0.1.3 → 0.1.4
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.
- package/README.md +7 -4
- package/config.default.json +28 -26
- package/package.json +1 -1
- package/server.ts +13 -1
- package/src/server/config.ts +141 -12
- package/src/server/model-info.ts +17 -11
- package/src/server/models-dev.ts +1 -1
- package/src/server/openai-error.ts +62 -0
- package/src/server/pricing.ts +3 -3
- package/src/server/proxy.ts +25 -1
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ OpenCode 插件:在状态栏显示 CodeBuddy 额度胶囊,并把 CodeBuddy
|
|
|
37
37
|
|
|
38
38
|
## 配置
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
高级映射配置默认生成在 `~/.config/opencode/codebuddy-quota.json`,与 `opencode.json(c)` 同目录,便于直接编辑;文件不存在时插件会写入一份默认值。已有文件默认不会被覆盖,只有显式开启 `overwrite_config`,且文件里的 `plugin_version` 落后于插件版本(取插件 `package.json` 的 `version`)时才会整体刷新(刷新前保留 `.bak`):
|
|
41
41
|
|
|
42
42
|
```jsonc
|
|
43
43
|
{
|
|
@@ -45,12 +45,15 @@ OpenCode 插件:在状态栏显示 CodeBuddy 额度胶囊,并把 CodeBuddy
|
|
|
45
45
|
"<codebuddy-id>": { "provider": "<models.dev-provider>", "model": "<model-id>" }
|
|
46
46
|
},
|
|
47
47
|
"excluded_models": ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
|
|
48
|
-
"package_version": "2.0.90"
|
|
48
|
+
"package_version": "2.0.90",
|
|
49
|
+
"overwrite_config": false
|
|
49
50
|
}
|
|
50
51
|
```
|
|
51
52
|
|
|
52
|
-
- `models`:CodeBuddy 模型 id → models.dev
|
|
53
|
-
- `excluded_models`:硬排除的模型 id
|
|
53
|
+
- `models`:CodeBuddy 模型 id → models.dev 坐标;未映射的模型仍会进入选择器,但名字末尾带 `*`,且不带可信价格与厂商档位(上游标为免费的仍是零价)。
|
|
54
|
+
- `excluded_models`:硬排除的模型 id(含虚拟路由档位与别名)。
|
|
55
|
+
- `overwrite_config`:默认 `false`;设为 `true` 后,文件里的 `plugin_version` 落后于插件版本时,插件会整体覆盖该文件。覆盖前会把旧文件备份为 `.bak`(单份,每次覆盖都会被最新一次覆盖),版本比较只按 `x.y.z` 数字段,忽略预发布与构建元数据(如 `-rc.1`、`+build`)。
|
|
56
|
+
- `plugin_version`:由插件写入的标记,记录该文件是按哪个插件版本生成的,用户无需编辑。
|
|
54
57
|
- `package_version`:写入 provider 的 `@ai-sdk/openai-compatible` 版本。
|
|
55
58
|
|
|
56
59
|
默认配置见 `config.default.json`。
|
package/config.default.json
CHANGED
|
@@ -2,40 +2,42 @@
|
|
|
2
2
|
"models": {
|
|
3
3
|
"deepseek-v4-pro": { "provider": "deepseek", "model": "deepseek-v4-pro" },
|
|
4
4
|
"deepseek-v4.1-flash": { "provider": "deepseek", "model": "deepseek-v4-flash" },
|
|
5
|
+
"deepseek-v4.1-flash-sg": { "provider": "deepseek", "model": "deepseek-v4-flash" },
|
|
6
|
+
"gemini-3.8-flash": { "provider": "google", "model": "gemini-3.8-flash" },
|
|
7
|
+
"glm-5.2": { "provider": "zhipuai", "model": "glm-5.2" },
|
|
8
|
+
"glm-5.3": { "provider": "zhipuai", "model": "glm-5.3" },
|
|
5
9
|
"glm-5.3-flash": { "provider": "zhipuai", "model": "glm-5.3-flash" },
|
|
6
10
|
"glm-5.3-flashx": { "provider": "zhipuai", "model": "glm-5.3-flashx" },
|
|
7
|
-
"
|
|
8
|
-
"step-5-preview": { "provider": "stepfun", "model": "step-5-preview" },
|
|
9
|
-
"mimo-v2.6-pro": { "provider": "xiaomi", "model": "mimo-v2.6-pro" },
|
|
10
|
-
"hy4std": { "provider": "tencent-tokenhub", "model": "hy4" },
|
|
11
|
-
"hy4flash-free": { "provider": "tencent-tokenhub", "model": "hy4" },
|
|
12
|
-
"hy4flash": { "provider": "tencent-tokenhub", "model": "hy4" },
|
|
13
|
-
"hy4free": { "provider": "tencent-tokenhub", "model": "hy4" },
|
|
14
|
-
"hy3": { "provider": "tencent-tokenhub", "model": "hy3" },
|
|
15
|
-
"hy3-x": { "provider": "tencent-tokenhub", "model": "hy3" },
|
|
16
|
-
"space-bunny": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
|
|
17
|
-
"hy4-preview": { "provider": "tencent-tokenhub", "model": "hy4-preview" },
|
|
18
|
-
"deepseek-v4.1-flash-sg": { "provider": "deepseek", "model": "deepseek-v4-flash" },
|
|
19
|
-
"gpt-6-astra": { "provider": "openai", "model": "gpt-6-astra" },
|
|
20
|
-
"gpt-6.1-sol": { "provider": "openai", "model": "gpt-6.1-sol" },
|
|
21
|
-
"gpt-6-sol": { "provider": "openai", "model": "gpt-6-sol" },
|
|
22
|
-
"gpt-6-luna": { "provider": "openai", "model": "gpt-6-luna" },
|
|
23
|
-
"gpt-5.6-sol": { "provider": "openai", "model": "gpt-5.6-sol" },
|
|
24
|
-
"gpt-5.6-terra": { "provider": "openai", "model": "gpt-5.6-terra" },
|
|
25
|
-
"gpt-5.5": { "provider": "openai", "model": "gpt-5.5" },
|
|
11
|
+
"glm-5.4": { "provider": "tencent-token-plan", "model": "glm-5.4" },
|
|
26
12
|
"gpt-5.4": { "provider": "openai", "model": "gpt-5.4" },
|
|
13
|
+
"gpt-5.5": { "provider": "openai", "model": "gpt-5.5" },
|
|
27
14
|
"gpt-5.6-luna": { "provider": "openai", "model": "gpt-5.6-luna" },
|
|
15
|
+
"gpt-5.6-sol": { "provider": "openai", "model": "gpt-5.6-sol" },
|
|
16
|
+
"gpt-5.6-terra": { "provider": "openai", "model": "gpt-5.6-terra" },
|
|
17
|
+
"gpt-6-astra": { "provider": "openai", "model": "gpt-6-astra" },
|
|
18
|
+
"gpt-6-luna": { "provider": "openai", "model": "gpt-6-luna" },
|
|
19
|
+
"gpt-6-sol": { "provider": "openai", "model": "gpt-6-sol" },
|
|
20
|
+
"gpt-6.1-sol": { "provider": "openai", "model": "gpt-6.1-sol" },
|
|
28
21
|
"grok-4.7": { "provider": "xai", "model": "grok-4.7" },
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
22
|
+
"hy3": { "provider": "tencent-tokenhub", "model": "hy3" },
|
|
23
|
+
"hy3-x": { "provider": "tencent-tokenhub", "model": "hy3" },
|
|
24
|
+
"hy4-preview": { "provider": "tencent-tokenhub", "model": "hy4-preview" },
|
|
25
|
+
"hy4flash": { "provider": "tencent-tokenhub", "model": "hy4-flash" },
|
|
26
|
+
"hy4flash-free": { "provider": "tencent-tokenhub", "model": "hy4-flash" },
|
|
27
|
+
"hy4free": { "provider": "tencent-tokenhub", "model": "hy4" },
|
|
28
|
+
"hy4std": { "provider": "tencent-tokenhub", "model": "hy4" },
|
|
34
29
|
"kimi-k3": { "provider": "moonshotai", "model": "kimi-k3" },
|
|
35
|
-
"kimi-k3.1-pro
|
|
30
|
+
"kimi-k3.1-pro": { "provider": "moonshotai", "model": "kimi-k3.1-pro" },
|
|
31
|
+
"kimi-k3.1-pro-highspeed": { "provider": "moonshotai", "model": "kimi-k3.1-pro-highspeed" },
|
|
32
|
+
"mimo-v2.6-pro": { "provider": "xiaomi", "model": "mimo-v2.6-pro" },
|
|
33
|
+
"minimax-m3.1-flash": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
|
|
34
|
+
"space-bunny": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
|
|
35
|
+
"step-5": { "provider": "stepfun", "model": "step-5" },
|
|
36
|
+
"step-5-preview": { "provider": "stepfun", "model": "step-5-preview" }
|
|
36
37
|
},
|
|
37
38
|
"excluded_models": ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
|
|
38
39
|
"package_version": "2.0.90",
|
|
39
40
|
"embedding_model": "bge-m3",
|
|
40
|
-
"local_embedding_model": ""
|
|
41
|
+
"local_embedding_model": "",
|
|
42
|
+
"overwrite_config": false
|
|
41
43
|
}
|
package/package.json
CHANGED
package/server.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { Plugin } from "@opencode/plugin"
|
|
|
3
3
|
import { CodebuddyQuota } from "./rpc"
|
|
4
4
|
import { PROXY_PORT, type Site } from "./src/shared"
|
|
5
5
|
import { fetchCatalog } from "./src/server/catalog"
|
|
6
|
-
import { loadConfig, opencodeConfigPath, type QuotaConfig } from "./src/server/config"
|
|
6
|
+
import { ensureConfigFile, loadConfig, opencodeConfigPath, type QuotaConfig } from "./src/server/config"
|
|
7
7
|
import { writeProvider } from "./src/server/config-writer"
|
|
8
8
|
import { clearLocalEmbedderMemo, createLocalEmbedder, type LocalEmbedding } from "./src/server/embedding-local"
|
|
9
9
|
import { resolveEmbeddingMode } from "./src/server/embedding-mode"
|
|
@@ -109,6 +109,18 @@ export default Plugin.define({
|
|
|
109
109
|
async setup(ctx) {
|
|
110
110
|
const log = createDedupedLogger((line) => console.warn(line), "[codebuddy-quota]")
|
|
111
111
|
|
|
112
|
+
// Make the editable config discoverable before anything reads it. The file
|
|
113
|
+
// sits in OpenCode's own config directory; an existing one is left alone.
|
|
114
|
+
try {
|
|
115
|
+
const configFile = ensureConfigFile()
|
|
116
|
+
if (configFile.created) log(`created ${configFile.path}; edit it to add or override model mappings`)
|
|
117
|
+
else if (configFile.upgraded) {
|
|
118
|
+
log(`rewrote ${configFile.path} to the shipped defaults; the previous copy is ${configFile.path}.bak`)
|
|
119
|
+
}
|
|
120
|
+
} catch (error) {
|
|
121
|
+
log(`could not create the model config: ${String((error as Error)?.message ?? error)}`)
|
|
122
|
+
}
|
|
123
|
+
|
|
112
124
|
// Restore both sites' credentials from the plugin-owned cache; no CLI auth
|
|
113
125
|
// file is read, and no token ever reaches the GUI.
|
|
114
126
|
const store = createTokenStore()
|
package/src/server/config.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from "node:fs"
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
|
2
2
|
import { homedir } from "node:os"
|
|
3
|
-
import { join } from "node:path"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
4
|
import { DEFAULT_PACKAGE_VERSION, isVersion } from "./package-spec"
|
|
5
5
|
|
|
6
6
|
/** Where a CodeBuddy model lives in the models.dev catalog. */
|
|
@@ -13,7 +13,11 @@ export interface ModelMapping {
|
|
|
13
13
|
|
|
14
14
|
/** Keys the user may override; everything else in the file is ignored. */
|
|
15
15
|
export interface QuotaConfig {
|
|
16
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* CodeBuddy model id → its models.dev entry. A model absent here is still
|
|
18
|
+
* offered, with `*` appended to its display name, but carries no trusted
|
|
19
|
+
* price (unless upstream marks it free) and no vendor reasoning levels.
|
|
20
|
+
*/
|
|
17
21
|
models: Record<string, ModelMapping>
|
|
18
22
|
/** Hard block, applied on top of `models`: listed ids are dropped even when mapped. */
|
|
19
23
|
excluded_models: string[]
|
|
@@ -28,6 +32,13 @@ export interface QuotaConfig {
|
|
|
28
32
|
embedding_model: string
|
|
29
33
|
/** Local (transformers.js) embedding model id; `""` means no local model. */
|
|
30
34
|
local_embedding_model: string
|
|
35
|
+
/**
|
|
36
|
+
* Opt-in to receiving new shipped defaults. When true and the file's
|
|
37
|
+
* `plugin_version` is behind this plugin's version, the whole file is
|
|
38
|
+
* rewritten from the defaults (the previous copy is kept as `.bak`). Off by
|
|
39
|
+
* default: user edits win over later plugin updates.
|
|
40
|
+
*/
|
|
41
|
+
overwrite_config: boolean
|
|
31
42
|
}
|
|
32
43
|
|
|
33
44
|
/**
|
|
@@ -44,24 +55,27 @@ export const DEFAULT_CONFIG: QuotaConfig = {
|
|
|
44
55
|
"glm-5.3-flashx": { provider: "zhipuai", model: "glm-5.3-flashx" },
|
|
45
56
|
"minimax-m3.1-flash": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
|
|
46
57
|
"step-5-preview": { provider: "stepfun", model: "step-5-preview" },
|
|
58
|
+
// CodeBuddy replaced its preview with the final Step-5 id on the cli allowlist.
|
|
59
|
+
"step-5": { provider: "stepfun", model: "step-5" },
|
|
47
60
|
"mimo-v2.6-pro": { provider: "xiaomi", model: "mimo-v2.6-pro" },
|
|
48
61
|
hy4std: { provider: "tencent-tokenhub", model: "hy4" },
|
|
49
|
-
// `Hy4 flash` ships twice: a free id and a paid one. models.dev
|
|
50
|
-
// flash
|
|
51
|
-
"hy4flash-free": { provider: "tencent-tokenhub", model: "hy4" },
|
|
52
|
-
hy4flash: { provider: "tencent-tokenhub", model: "hy4" },
|
|
62
|
+
// `Hy4 flash` ships twice: a free id and a paid one. Both map to models.dev's
|
|
63
|
+
// hy4-flash; the free one is zero-priced by credits.
|
|
64
|
+
"hy4flash-free": { provider: "tencent-tokenhub", model: "hy4-flash" },
|
|
65
|
+
hy4flash: { provider: "tencent-tokenhub", model: "hy4-flash" },
|
|
53
66
|
hy4free: { provider: "tencent-tokenhub", model: "hy4" },
|
|
54
67
|
hy3: { provider: "tencent-tokenhub", model: "hy3" },
|
|
55
68
|
"hy3-x": { provider: "tencent-tokenhub", model: "hy3" },
|
|
56
69
|
// Same model as minimax-m3.1-flash; CodeBuddy just bills it under its own id.
|
|
57
70
|
"space-bunny": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
|
|
58
71
|
// International-site cli-whitelist (ids from /v3/config agents[cli]).
|
|
59
|
-
//
|
|
60
|
-
// models.dev entity
|
|
72
|
+
// The four virtual routing aliases (default/fast/balanced/primary-model)
|
|
73
|
+
// have no models.dev entity. Not mapped: they are shown with a `*` unless
|
|
74
|
+
// excluded by the user. The current catalog uses auto/max-model instead.
|
|
61
75
|
"hy4-preview": { provider: "tencent-tokenhub", model: "hy4-preview" },
|
|
62
76
|
// SG variant shares the same underlying model; models.dev has no separate id.
|
|
63
77
|
"deepseek-v4.1-flash-sg": { provider: "deepseek", model: "deepseek-v4-flash" },
|
|
64
|
-
// models.dev
|
|
78
|
+
// models.dev carries all GPT ids under openai; use the official vendor.
|
|
65
79
|
"gpt-6-astra": { provider: "openai", model: "gpt-6-astra" },
|
|
66
80
|
"gpt-6.1-sol": { provider: "openai", model: "gpt-6.1-sol" },
|
|
67
81
|
"gpt-6-sol": { provider: "openai", model: "gpt-6-sol" },
|
|
@@ -85,15 +99,29 @@ export const DEFAULT_CONFIG: QuotaConfig = {
|
|
|
85
99
|
"kimi-k3.1-pro-highspeed": { provider: "moonshotai", model: "kimi-k3.1-pro-highspeed" },
|
|
86
100
|
},
|
|
87
101
|
// auto/max-model are virtual routing tiers with no models.dev entity; exclude
|
|
88
|
-
// them explicitly rather than relying on the
|
|
102
|
+
// them explicitly rather than relying on the unmapped path, which now offers
|
|
103
|
+
// every model with a `*` marker.
|
|
89
104
|
excluded_models: ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
|
|
90
105
|
package_version: DEFAULT_PACKAGE_VERSION,
|
|
91
106
|
embedding_model: "bge-m3",
|
|
92
107
|
local_embedding_model: "",
|
|
108
|
+
overwrite_config: false,
|
|
93
109
|
}
|
|
94
110
|
|
|
95
111
|
export const CONFIG_FILE_NAME = "codebuddy-quota.json"
|
|
96
112
|
|
|
113
|
+
/**
|
|
114
|
+
* This plugin's own version from its package.json. Config files record it as
|
|
115
|
+
* `plugin_version` so an upgrade that changes defaults can refresh opted-in
|
|
116
|
+
* files without a separate version counter to maintain by hand.
|
|
117
|
+
*/
|
|
118
|
+
export function pluginVersion(): string {
|
|
119
|
+
const pkg = JSON.parse(readFileSync(join(import.meta.dir, "..", "..", "package.json"), "utf8")) as {
|
|
120
|
+
version?: unknown
|
|
121
|
+
}
|
|
122
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0"
|
|
123
|
+
}
|
|
124
|
+
|
|
97
125
|
/** `$XDG_CONFIG_HOME/opencode`, or `~/.config/opencode` when it is unset. */
|
|
98
126
|
export function configDir(
|
|
99
127
|
env: Record<string, string | undefined> = process.env,
|
|
@@ -104,11 +132,110 @@ export function configDir(
|
|
|
104
132
|
return join(home, ".config", "opencode")
|
|
105
133
|
}
|
|
106
134
|
|
|
107
|
-
/**
|
|
135
|
+
/** `$XDG_CONFIG_HOME/opencode/codebuddy-quota.json`, or `~/.config/opencode/...` by default, beside the user's `opencode.json(c)`. */
|
|
108
136
|
export function configPath(home: string = homedir()): string {
|
|
109
137
|
return join(configDir(undefined, home), CONFIG_FILE_NAME)
|
|
110
138
|
}
|
|
111
139
|
|
|
140
|
+
export interface EnsureConfigDeps {
|
|
141
|
+
configPath?: string
|
|
142
|
+
exists?: (path: string) => boolean
|
|
143
|
+
readFile?: (path: string) => string
|
|
144
|
+
mkdir?: (dir: string) => void
|
|
145
|
+
writeFile?: (path: string, content: string) => void
|
|
146
|
+
/** Called with the old text before an opt-in rewrite. Defaults to a single `.bak` copy, overwritten on each upgrade. */
|
|
147
|
+
backup?: (path: string, content: string) => void
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface EnsureConfigResult {
|
|
151
|
+
path: string
|
|
152
|
+
/** The file did not exist and was created from the defaults. */
|
|
153
|
+
created: boolean
|
|
154
|
+
/** An opted-in file was behind and got rewritten from the defaults. */
|
|
155
|
+
upgraded: boolean
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Writes an editable copy of the defaults next to `opencode.json(c)` when the
|
|
160
|
+
* user has none. The file must be discoverable: the plugin directory would hide
|
|
161
|
+
* it behind a package install.
|
|
162
|
+
*
|
|
163
|
+
* An existing file is the user's, not ours. It is only rewritten when the user
|
|
164
|
+
* opted in with `overwrite_config: true` AND its `plugin_version` is behind this
|
|
165
|
+
* release; the previous copy is saved as `.bak`. Comparing the plugin's own
|
|
166
|
+
* version means defaults are refreshed whenever the plugin is upgraded.
|
|
167
|
+
*
|
|
168
|
+
* A failed mkdir/write or an unreadable file throws; the plugin's setup wraps
|
|
169
|
+
* this call and falls back to the built-in defaults so startup never breaks.
|
|
170
|
+
*/
|
|
171
|
+
export function ensureConfigFile(deps: EnsureConfigDeps = {}): EnsureConfigResult {
|
|
172
|
+
const path = deps.configPath ?? configPath()
|
|
173
|
+
const exists = deps.exists ?? existsSync
|
|
174
|
+
const currentVersion = pluginVersion()
|
|
175
|
+
const write = deps.writeFile ?? ((p: string, content: string) => writeFileSync(p, content, "utf8"))
|
|
176
|
+
// The opt-in flag is the one key a rewrite must carry over: dropping it would
|
|
177
|
+
// silently unsubscribe the file from future upgrades.
|
|
178
|
+
const render = (overwrite: boolean) =>
|
|
179
|
+
`${JSON.stringify({ ...DEFAULT_CONFIG, overwrite_config: overwrite, plugin_version: currentVersion }, null, 2)}\n`
|
|
180
|
+
|
|
181
|
+
if (exists(path)) {
|
|
182
|
+
const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
|
|
183
|
+
let content: string
|
|
184
|
+
try {
|
|
185
|
+
content = read(path)
|
|
186
|
+
} catch {
|
|
187
|
+
return { path, created: false, upgraded: false }
|
|
188
|
+
}
|
|
189
|
+
let parsed: unknown
|
|
190
|
+
try {
|
|
191
|
+
parsed = JSON.parse(content)
|
|
192
|
+
} catch {
|
|
193
|
+
return { path, created: false, upgraded: false }
|
|
194
|
+
}
|
|
195
|
+
if (!isRecord(parsed) || parsed.overwrite_config !== true) {
|
|
196
|
+
return { path, created: false, upgraded: false }
|
|
197
|
+
}
|
|
198
|
+
// A missing or malformed pin counts as behind: the user asked to follow the
|
|
199
|
+
// shipped defaults, so there is nothing to preserve.
|
|
200
|
+
if (!isOlderVersion(parsed.plugin_version, currentVersion)) {
|
|
201
|
+
return { path, created: false, upgraded: false }
|
|
202
|
+
}
|
|
203
|
+
const backup = deps.backup ?? ((p: string, old: string) => writeFileSync(`${p}.bak`, old, "utf8"))
|
|
204
|
+
try {
|
|
205
|
+
backup(path, content)
|
|
206
|
+
} catch {
|
|
207
|
+
// The rewrite is what was asked for; a failed backup must not block it.
|
|
208
|
+
}
|
|
209
|
+
write(path, render(true))
|
|
210
|
+
return { path, created: false, upgraded: true }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const mkdir = deps.mkdir ?? ((dir: string) => mkdirSync(dir, { recursive: true }))
|
|
214
|
+
mkdir(dirname(path))
|
|
215
|
+
write(path, render(false))
|
|
216
|
+
return { path, created: true, upgraded: false }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* True when `candidate` is a semver older than `current`. Only the numeric
|
|
221
|
+
* major/minor/patch segments are compared; pre-release and build metadata
|
|
222
|
+
* (`0.1.4-rc.1`, `+build`) are ignored, so an rc and its final are equal.
|
|
223
|
+
* A malformed candidate counts as behind.
|
|
224
|
+
*/
|
|
225
|
+
function isOlderVersion(candidate: unknown, current: string): boolean {
|
|
226
|
+
if (typeof candidate !== "string" || !isVersion(candidate)) return true
|
|
227
|
+
const segments = (v: string) => v.split(/[-+]/, 1)[0].split(".").map(Number)
|
|
228
|
+
const left = segments(candidate)
|
|
229
|
+
const right = segments(current)
|
|
230
|
+
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
231
|
+
const a = left[i] ?? 0
|
|
232
|
+
const b = right[i] ?? 0
|
|
233
|
+
if (a < b) return true
|
|
234
|
+
if (a > b) return false
|
|
235
|
+
}
|
|
236
|
+
return false
|
|
237
|
+
}
|
|
238
|
+
|
|
112
239
|
/**
|
|
113
240
|
* The names OpenCode accepts for a config file, in the order it prefers them.
|
|
114
241
|
* Both parse; JSONC is the one with comments.
|
|
@@ -203,6 +330,7 @@ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
|
|
|
203
330
|
// Only a real version may reach the config writer: anything else would be
|
|
204
331
|
// written verbatim into the provider's `package` spec.
|
|
205
332
|
const packageVersion = isVersion(parsed.package_version) ? parsed.package_version : undefined
|
|
333
|
+
const overwrite = typeof parsed.overwrite_config === "boolean" ? parsed.overwrite_config : undefined
|
|
206
334
|
|
|
207
335
|
return {
|
|
208
336
|
models: models ? { ...DEFAULT_CONFIG.models, ...models } : DEFAULT_CONFIG.models,
|
|
@@ -211,5 +339,6 @@ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
|
|
|
211
339
|
embedding_model: optionalString(parsed.embedding_model) ?? DEFAULT_CONFIG.embedding_model,
|
|
212
340
|
local_embedding_model:
|
|
213
341
|
optionalString(parsed.local_embedding_model) ?? DEFAULT_CONFIG.local_embedding_model,
|
|
342
|
+
overwrite_config: overwrite ?? DEFAULT_CONFIG.overwrite_config,
|
|
214
343
|
}
|
|
215
344
|
}
|
package/src/server/model-info.ts
CHANGED
|
@@ -3,9 +3,9 @@ import type { QuotaConfig } from "./config"
|
|
|
3
3
|
import { resolveCost, vendorEfforts, type ModelCost, type ModelsDevCatalog } from "./pricing"
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* Turns the CodeBuddy catalog into the shape a provider needs: models
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* Turns the CodeBuddy catalog into the shape a provider needs: models minus the
|
|
7
|
+
* user's exclusions, priced and renamed, with unmapped models kept but starred
|
|
8
|
+
* so the picker shows which entries have no trusted price yet.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
export interface ImportedModel {
|
|
@@ -62,21 +62,23 @@ export function buildModels(deps: BuildModelsDeps): readonly ImportedModel[] {
|
|
|
62
62
|
const { config, modelsDev, log } = deps
|
|
63
63
|
const excluded = new Set(config.excluded_models)
|
|
64
64
|
|
|
65
|
-
// A model the user has not mapped is
|
|
66
|
-
//
|
|
67
|
-
//
|
|
65
|
+
// A model the user has not mapped is still offered: a new CodeBuddy model is
|
|
66
|
+
// usable before anyone writes a models.dev mapping for it. It stays unpriced
|
|
67
|
+
// unless upstream marks it free, and gets a `*` after naming so the gap is
|
|
68
|
+
// visible in the picker.
|
|
68
69
|
const kept: CatalogModel[] = []
|
|
69
70
|
for (const model of deps.catalog) {
|
|
70
71
|
if (excluded.has(model.id)) continue
|
|
71
|
-
if (!config.models
|
|
72
|
-
log(`${model.id} has no models entry in codebuddy-quota.json;
|
|
73
|
-
continue
|
|
72
|
+
if (!Object.hasOwn(config.models, model.id)) {
|
|
73
|
+
log(`${model.id} has no models entry in codebuddy-quota.json; offering it with a * suffix`)
|
|
74
74
|
}
|
|
75
75
|
kept.push(model)
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
const built = kept.map<ImportedModel>((model) => {
|
|
79
|
-
|
|
79
|
+
// `in`/truthiness would treat Object.prototype keys ("constructor") as
|
|
80
|
+
// mappings for a model id that happens to collide with them.
|
|
81
|
+
const mapping = Object.hasOwn(config.models, model.id) ? config.models[model.id] : undefined
|
|
80
82
|
// Vendor levels win over whatever the gateway advertises. A model models.dev
|
|
81
83
|
// knows nothing about keeps the server's levels rather than losing the
|
|
82
84
|
// ability to reason at all.
|
|
@@ -105,5 +107,9 @@ export function buildModels(deps: BuildModelsDeps): readonly ImportedModel[] {
|
|
|
105
107
|
const credits = new Map(kept.map((model) => [model.id, model.credits]))
|
|
106
108
|
// Sorted by id so the picker is stable no matter what order the server sends.
|
|
107
109
|
const sorted = [...built].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
108
|
-
|
|
110
|
+
// Star after de-duplication so the marker stays the final character even when
|
|
111
|
+
// a name collision added a credit suffix.
|
|
112
|
+
return dedupeNames(sorted, credits).map((model) =>
|
|
113
|
+
Object.hasOwn(config.models, model.id) ? model : { ...model, name: `${model.name}*` },
|
|
114
|
+
)
|
|
109
115
|
}
|
package/src/server/models-dev.ts
CHANGED
|
@@ -12,7 +12,7 @@ import type { ModelsDevCatalog } from "./pricing"
|
|
|
12
12
|
* degrade to "no prices" rather than break the plugin.
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
const KV_KEY = "models-dev:
|
|
15
|
+
const KV_KEY = "models-dev:v4:catalog"
|
|
16
16
|
const DB_FILE = "opencode.db"
|
|
17
17
|
/** Long enough to ride out another process's write lock, short enough not to stall a transform. */
|
|
18
18
|
const BUSY_TIMEOUT_MS = 2_000
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const JSON_MEDIA_TYPE = /^application\/(?:[a-z0-9.+-]+\+)?json$/i
|
|
2
|
+
|
|
3
|
+
/** Exact media-type comparison: `application/jsonp` must not pass for JSON. */
|
|
4
|
+
export function isJsonContentType(value: string | null): boolean {
|
|
5
|
+
if (!value) return false
|
|
6
|
+
const mediaType = value.split(";", 1)[0].trim()
|
|
7
|
+
return JSON_MEDIA_TYPE.test(mediaType)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* OpenCode (through the AI SDK) only surfaces `error.message` from an OpenAI-shaped
|
|
12
|
+
* error body; anything else degrades to the HTTP status phrase ("Too Many Requests").
|
|
13
|
+
* Map the status the same way the SDK classifies it so clients keep their retry policy.
|
|
14
|
+
*/
|
|
15
|
+
function errorTypeForStatus(status: number): string {
|
|
16
|
+
if (status === 401 || status === 403) return "authentication_error"
|
|
17
|
+
if (status === 402) return "insufficient_quota"
|
|
18
|
+
if (status === 429) return "rate_limit_exceeded"
|
|
19
|
+
if (status >= 500) return "api_error"
|
|
20
|
+
return "invalid_request_error"
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
24
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Rewrite CodeBuddy's `{ code, msg }` envelope into the OpenAI error shape so the
|
|
29
|
+
* upstream reason reaches the client instead of being replaced by the status text.
|
|
30
|
+
*
|
|
31
|
+
* Returns `null` when the body must be passed through verbatim: non-JSON content,
|
|
32
|
+
* unparseable text, an already OpenAI-shaped error, or a missing/blank `msg`.
|
|
33
|
+
* The status never decides *whether* to rewrite; it only picks `error.type`.
|
|
34
|
+
* Callers must keep it as-is.
|
|
35
|
+
*/
|
|
36
|
+
export function normalizeUpstreamError(status: number, contentType: string | null, body: string): string | null {
|
|
37
|
+
if (!isJsonContentType(contentType)) return null
|
|
38
|
+
|
|
39
|
+
let parsed: unknown
|
|
40
|
+
try {
|
|
41
|
+
parsed = JSON.parse(body)
|
|
42
|
+
} catch {
|
|
43
|
+
return null
|
|
44
|
+
}
|
|
45
|
+
if (!isRecord(parsed)) return null
|
|
46
|
+
|
|
47
|
+
const existing = parsed.error
|
|
48
|
+
if (isRecord(existing) && typeof existing.message === "string") return null
|
|
49
|
+
|
|
50
|
+
const rawMessage = parsed.msg
|
|
51
|
+
if (typeof rawMessage !== "string") return null
|
|
52
|
+
if (rawMessage.trim() === "") return null
|
|
53
|
+
|
|
54
|
+
// Keep the upstream code and request id: they are what upstream support asks for,
|
|
55
|
+
// and the SDK ignores unknown keys so they cost nothing on the client side.
|
|
56
|
+
// OpenAI defines `code` as a string, so a numeric upstream code is stringified.
|
|
57
|
+
const error: Record<string, unknown> = { message: rawMessage, type: errorTypeForStatus(status) }
|
|
58
|
+
if (typeof parsed.code === "number" || typeof parsed.code === "string") error.code = String(parsed.code)
|
|
59
|
+
if (typeof parsed.requestId === "string") error.request_id = parsed.requestId
|
|
60
|
+
|
|
61
|
+
return JSON.stringify({ error })
|
|
62
|
+
}
|
package/src/server/pricing.ts
CHANGED
|
@@ -10,7 +10,7 @@ import type { ModelMapping } from "./config"
|
|
|
10
10
|
* which is exactly why the mapping names the provider rather than inferring it.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
/** models.dev
|
|
13
|
+
/** models.dev sometimes declares cache.write as per-duration tiers, e.g. {"5m":3,"1h":6}. */
|
|
14
14
|
export type CacheWritePrice = number | Record<string, number>
|
|
15
15
|
|
|
16
16
|
export interface ModelsDevCost {
|
|
@@ -35,7 +35,7 @@ export interface ModelsDevEntry {
|
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
/** `{ [providerID]: { models: { [modelID]: entry } } }`, as stored under `models-dev:
|
|
38
|
+
/** `{ [providerID]: { models: { [modelID]: entry } } }`, as stored under `models-dev:v4:catalog`. */
|
|
39
39
|
export type ModelsDevCatalog = Record<string, { models?: Record<string, ModelsDevEntry> }>
|
|
40
40
|
|
|
41
41
|
export interface ModelCost {
|
|
@@ -101,7 +101,7 @@ function toCost(entry: ModelsDevEntry): ModelCost | null {
|
|
|
101
101
|
return {
|
|
102
102
|
input,
|
|
103
103
|
output,
|
|
104
|
-
// Most catalog entries omit cache.write; some
|
|
104
|
+
// Most catalog entries omit cache.write; some declare it as a
|
|
105
105
|
// per-duration tier object. Neither is a usable scalar, so fall back to zero.
|
|
106
106
|
cache: {
|
|
107
107
|
read: finitePrice(text?.input?.cache?.read),
|
package/src/server/proxy.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { createLocalEmbedder, isLocalModel, routeEmbedding, type LocalEmbedding
|
|
|
4
4
|
import { apiHeaders, channelHeaders } from "./headers"
|
|
5
5
|
import { SITE_ENDPOINTS } from "./login"
|
|
6
6
|
import type { ModelsListResponse } from "./models-endpoint"
|
|
7
|
+
import { isJsonContentType, normalizeUpstreamError } from "./openai-error"
|
|
7
8
|
import { collectSse, collectSseFromStream, toChatCompletion } from "./stream-collect"
|
|
8
9
|
import type { TokenStore } from "./token-store"
|
|
9
10
|
|
|
@@ -438,7 +439,8 @@ export async function handleRequest(
|
|
|
438
439
|
}
|
|
439
440
|
|
|
440
441
|
// Plain OpenAI clients expect a single JSON object. Upstream errors are never
|
|
441
|
-
// aggregated
|
|
442
|
+
// aggregated; a chat error that is a JSON envelope gets normalized below so
|
|
443
|
+
// clients can read the real reason instead of the HTTP status phrase.
|
|
442
444
|
const isAggregate = !wantsStream && upstream.ok && isChat
|
|
443
445
|
if (isAggregate) {
|
|
444
446
|
// Aggregate through a reader rather than `text()`: a client that walks away
|
|
@@ -473,6 +475,28 @@ export async function handleRequest(
|
|
|
473
475
|
)
|
|
474
476
|
}
|
|
475
477
|
|
|
478
|
+
// Side effect only for chat errors: the AI SDK derives `error.message` from an
|
|
479
|
+
// OpenAI-shaped body and falls back to the status phrase otherwise, which hides
|
|
480
|
+
// the upstream reason ("Too Many Requests"). Keep the status so the client's
|
|
481
|
+
// classification and backoff stay unchanged; only the body is rewritten.
|
|
482
|
+
if (isChat && !upstream.ok && isJsonContentType(upstream.headers.get("content-type"))) {
|
|
483
|
+
const text = await upstream.text()
|
|
484
|
+
if (deps.signal?.aborted) return
|
|
485
|
+
const normalized = normalizeUpstreamError(upstream.status, upstream.headers.get("content-type"), text)
|
|
486
|
+
// Copy first so retry-after and other hints survive, then override the type:
|
|
487
|
+
// headers must be set before status(), which is where Node emits the head.
|
|
488
|
+
copyHeaders(upstream.headers, res)
|
|
489
|
+
if (normalized !== null) {
|
|
490
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8")
|
|
491
|
+
res.status(upstream.status)
|
|
492
|
+
res.end(normalized)
|
|
493
|
+
return
|
|
494
|
+
}
|
|
495
|
+
res.status(upstream.status)
|
|
496
|
+
res.end(text)
|
|
497
|
+
return
|
|
498
|
+
}
|
|
499
|
+
|
|
476
500
|
copyHeaders(upstream.headers, res)
|
|
477
501
|
res.status(upstream.status)
|
|
478
502
|
|