opencode-codebuddy-quota 0.1.2 → 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 +8 -4
- package/config.default.json +28 -26
- package/package.json +1 -1
- package/server.ts +14 -3
- package/src/server/config-writer.ts +2 -1
- package/src/server/config.ts +141 -12
- package/src/server/gateway-owner.ts +76 -13
- package/src/server/gateway-setup.ts +33 -10
- 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 +78 -11
- package/src/shared.ts +3 -0
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`。
|
|
@@ -76,6 +79,7 @@ bun run build:gui # 构建桌面端 GUI(dist/gui-experimental.cjs)
|
|
|
76
79
|
- 每站本期至多一个账号;数据结构预留了多账号,但本期不提供切换 UI。
|
|
77
80
|
- 本地代理是 "confused deputy":本机任意进程都能借它用 JWT 调上游,接受此风险。
|
|
78
81
|
- 模型倍率名称来自上游 `credits` 字段;上游未声明时倍率标签会省略。
|
|
82
|
+
- 7688 网关在同进程的多个 workspace 间共享,且沿用**首个绑定实例**的凭证与配置(store / models / embeddingMode)。因此插件重载后在 GUI 里重新登录或改嵌入配置,代理仍用首实例的旧值;若上游返回 401/403,日志会提示「重启 OpenCode 或重新登录」以刷新凭证。这是单监听实例设计的已知取舍。
|
|
79
83
|
|
|
80
84
|
## License
|
|
81
85
|
|
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
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { existsSync, writeFileSync } from "node:fs"
|
|
2
2
|
import { Plugin } from "@opencode/plugin"
|
|
3
3
|
import { CodebuddyQuota } from "./rpc"
|
|
4
|
-
import type
|
|
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"
|
|
@@ -24,7 +24,6 @@ import { anySignal, timeoutSignal } from "./src/server/signal"
|
|
|
24
24
|
import { createTokenStore } from "./src/server/token-store"
|
|
25
25
|
import { fetchUpstream } from "./src/server/upstream"
|
|
26
26
|
|
|
27
|
-
const PROXY_PORT = 7688
|
|
28
27
|
const UPSTREAM_TIMEOUT_MS = 15_000
|
|
29
28
|
|
|
30
29
|
/** Offline inputs the /v2/models list is built from; injected so the seam is testable. */
|
|
@@ -110,6 +109,18 @@ export default Plugin.define({
|
|
|
110
109
|
async setup(ctx) {
|
|
111
110
|
const log = createDedupedLogger((line) => console.warn(line), "[codebuddy-quota]")
|
|
112
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
|
+
|
|
113
124
|
// Restore both sites' credentials from the plugin-owned cache; no CLI auth
|
|
114
125
|
// file is read, and no token ever reaches the GUI.
|
|
115
126
|
const store = createTokenStore()
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readFileSync, writeFileSync } from "node:fs"
|
|
2
|
+
import { PROXY_PORT } from "../shared"
|
|
2
3
|
import type { ImportedModel } from "./model-info"
|
|
3
4
|
import { withVersion } from "./package-version"
|
|
4
5
|
import { isVersion, packageSpec, PROVIDER_IDS } from "./package-spec"
|
|
@@ -543,7 +544,7 @@ export function writeProvider(deps: WriteProviderDeps): WriteModelsResult {
|
|
|
543
544
|
return { status: "skipped", reason: "invalid package version" }
|
|
544
545
|
}
|
|
545
546
|
|
|
546
|
-
const port = deps.proxyPort ??
|
|
547
|
+
const port = deps.proxyPort ?? PROXY_PORT
|
|
547
548
|
const site = deps.providerId === "codebuddy-intl" ? "intl" : "cn"
|
|
548
549
|
const baseURL = `http://127.0.0.1:${port}/${site}/v2`
|
|
549
550
|
|
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
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HEALTH_BODY, type ProxyServer } from "./proxy"
|
|
1
|
+
import { HEALTH_BODY, processNonce, type ProxyServer } from "./proxy"
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Process-wide owner of the single bound gateway. The state lives on globalThis
|
|
@@ -14,9 +14,12 @@ export interface GatewayOwnerState {
|
|
|
14
14
|
probeTimer: ReturnType<typeof setInterval> | null
|
|
15
15
|
/** In-flight cold bind; concurrent ensures await it instead of racing a second listen. */
|
|
16
16
|
starting: Promise<ProxyServer | null> | null
|
|
17
|
+
/** In-flight close of the previous server; a new cold bind waits for it. */
|
|
18
|
+
closing: Promise<void> | null
|
|
17
19
|
}
|
|
18
20
|
|
|
19
|
-
|
|
21
|
+
/** Exposed for tests so they read the real key instead of a hardcoded copy. */
|
|
22
|
+
export const OWNER_KEY = Symbol.for("codebuddy-quota.gateway.owner")
|
|
20
23
|
const DEFAULT_GRACE_MS = 8000
|
|
21
24
|
const DEFAULT_PROBE_MS = 5000
|
|
22
25
|
const PROBE_TIMEOUT_MS = 2000
|
|
@@ -44,6 +47,7 @@ function owner(): GatewayOwnerState {
|
|
|
44
47
|
generation: 0,
|
|
45
48
|
probeTimer: null,
|
|
46
49
|
starting: null,
|
|
50
|
+
closing: null,
|
|
47
51
|
}
|
|
48
52
|
;(globalThis as unknown as GlobalWithOwner)[OWNER_KEY] = created
|
|
49
53
|
return created
|
|
@@ -54,7 +58,6 @@ export interface EnsureGatewayDeps {
|
|
|
54
58
|
createServer: () => ProxyServer
|
|
55
59
|
start: (s: ProxyServer, port: number) => Promise<void>
|
|
56
60
|
log: (s: string) => void
|
|
57
|
-
graceMs?: number
|
|
58
61
|
/** Injected health probe; defaults to an HTTP GET of `/health`. */
|
|
59
62
|
probe?: () => Promise<boolean>
|
|
60
63
|
/** Probe interval in milliseconds (default 5000). */
|
|
@@ -84,17 +87,40 @@ function isEaddrinuse(error: unknown): boolean {
|
|
|
84
87
|
return /EADDRINUSE|address already in use/i.test(text)
|
|
85
88
|
}
|
|
86
89
|
|
|
87
|
-
/**
|
|
90
|
+
/**
|
|
91
|
+
* Default probe: a bare `GET /health`. The body carries a process nonce so the
|
|
92
|
+
* probe distinguishes its own gateway (nonce matches) from another OpenCode
|
|
93
|
+
* instance serving the same port (nonce differs) — a foreign gateway is not
|
|
94
|
+
* "recovered"; we log an actionable hint and keep probing without taking over.
|
|
95
|
+
*/
|
|
88
96
|
function makeDefaultProbe(deps: EnsureGatewayDeps): () => Promise<boolean> {
|
|
89
97
|
const fetchImpl = deps.fetchImpl ?? fetch
|
|
98
|
+
let foreignReported = false
|
|
90
99
|
return async () => {
|
|
91
100
|
try {
|
|
92
101
|
const response = await fetchImpl(`http://127.0.0.1:${deps.port}/health`, {
|
|
93
102
|
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
|
|
94
103
|
})
|
|
95
104
|
if (response.status !== 200) return false
|
|
96
|
-
const body = (await response.json()) as {
|
|
97
|
-
|
|
105
|
+
const body = (await response.json()) as {
|
|
106
|
+
status?: string
|
|
107
|
+
service?: string
|
|
108
|
+
nonce?: string
|
|
109
|
+
} | null
|
|
110
|
+
if (body?.status !== HEALTH_FIELDS.status || body?.service !== HEALTH_FIELDS.service) {
|
|
111
|
+
return false
|
|
112
|
+
}
|
|
113
|
+
if (body.nonce !== processNonce()) {
|
|
114
|
+
if (!foreignReported) {
|
|
115
|
+
foreignReported = true
|
|
116
|
+
safeLog(
|
|
117
|
+
deps.log,
|
|
118
|
+
`another OpenCode instance is serving port ${deps.port}; close the duplicate instance (no takeover)`,
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
return false
|
|
122
|
+
}
|
|
123
|
+
return true
|
|
98
124
|
} catch {
|
|
99
125
|
return false
|
|
100
126
|
}
|
|
@@ -102,9 +128,10 @@ function makeDefaultProbe(deps: EnsureGatewayDeps): () => Promise<boolean> {
|
|
|
102
128
|
}
|
|
103
129
|
|
|
104
130
|
/**
|
|
105
|
-
*
|
|
106
|
-
* socket. In-process reloads reuse the shared server and never reach here.
|
|
107
|
-
*
|
|
131
|
+
* Diagnostic backstop for a port held by another process or a Windows orphan
|
|
132
|
+
* socket. In-process reloads reuse the shared server and never reach here. The
|
|
133
|
+
* loop only observes /health (own vs foreign via nonce); it never rebinds. The
|
|
134
|
+
* loop is owned by `state`, so a reset / rebind / newer probe can cancel it.
|
|
108
135
|
*/
|
|
109
136
|
function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void {
|
|
110
137
|
if (state.probeTimer !== null) {
|
|
@@ -125,9 +152,15 @@ function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void
|
|
|
125
152
|
if (!healthy) return
|
|
126
153
|
clearInterval(timer)
|
|
127
154
|
if (state.probeTimer === timer) state.probeTimer = null
|
|
128
|
-
|
|
155
|
+
// A healthy /health responder stops the diagnostic probe; this process
|
|
156
|
+
// never (re)bound the port itself. The default probe already emitted an
|
|
157
|
+
// own-vs-foreign nonce hint, so keep this line neutral — never claim a
|
|
158
|
+
// takeover/recovery that did not happen.
|
|
159
|
+
safeLog(deps.log, "gateway /health responder present; diagnostic probe stopped (no rebind by this process)")
|
|
129
160
|
})()
|
|
130
161
|
}, deps.probeMs ?? DEFAULT_PROBE_MS)
|
|
162
|
+
// Do not keep the process alive solely for the backstop probe.
|
|
163
|
+
timer.unref?.()
|
|
131
164
|
state.probeTimer = timer
|
|
132
165
|
}
|
|
133
166
|
|
|
@@ -138,7 +171,9 @@ function startProbeLoop(state: GatewayOwnerState, deps: EnsureGatewayDeps): void
|
|
|
138
171
|
*
|
|
139
172
|
* Create/start failures roll the ref count back. A non-EADDRINUSE failure is
|
|
140
173
|
* rethrown unchanged; EADDRINUSE does not claim ownership (returns null) and
|
|
141
|
-
* instead starts a probe
|
|
174
|
+
* instead starts a diagnostic probe that watches for a healthy /health responder
|
|
175
|
+
* (distinguishing own vs foreign by nonce). The probe never rebinds — recovery
|
|
176
|
+
* still requires a later ensure (e.g. a plugin reload).
|
|
142
177
|
*/
|
|
143
178
|
export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServer | null> {
|
|
144
179
|
const state = owner()
|
|
@@ -148,6 +183,10 @@ export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServe
|
|
|
148
183
|
state.closeTimer = null
|
|
149
184
|
}
|
|
150
185
|
if (state.server !== null) return state.server
|
|
186
|
+
// If a previous holder's server is still closing, wait for it to release the
|
|
187
|
+
// port before attempting a cold bind. Otherwise the bind races the close,
|
|
188
|
+
// hits EADDRINUSE, and leaves no owner once the old server finishes closing.
|
|
189
|
+
if (state.closing !== null) await state.closing
|
|
151
190
|
// A concurrent cold start must not race a second bind on the same port.
|
|
152
191
|
// Everyone arriving while `starting` is pending awaits the same promise, so
|
|
153
192
|
// start is invoked once and every caller observes the same outcome. The
|
|
@@ -158,6 +197,13 @@ export async function ensureGateway(deps: EnsureGatewayDeps): Promise<ProxyServe
|
|
|
158
197
|
try {
|
|
159
198
|
const server = deps.createServer()
|
|
160
199
|
await deps.start(server, deps.port)
|
|
200
|
+
// A successful bind (cold or after a prior EADDRINUSE) means we now own
|
|
201
|
+
// the port. Any leftover probe from an earlier EADDRINUSE is stale —
|
|
202
|
+
// clear it so it cannot emit a false "foreign gateway" log or leak.
|
|
203
|
+
if (state.probeTimer !== null) {
|
|
204
|
+
clearInterval(state.probeTimer)
|
|
205
|
+
state.probeTimer = null
|
|
206
|
+
}
|
|
161
207
|
state.server = server
|
|
162
208
|
return server
|
|
163
209
|
} catch (error) {
|
|
@@ -201,7 +247,17 @@ export function releaseGateway(deps: ReleaseGatewayDeps): void {
|
|
|
201
247
|
// invalidate an already-scheduled close timer and leak the port via a different
|
|
202
248
|
// path. Only a real holder drop advances the generation.
|
|
203
249
|
const hadHolder = state.refs > 0
|
|
204
|
-
if (!hadHolder)
|
|
250
|
+
if (!hadHolder) {
|
|
251
|
+
// A null-proxy setup (EADDRINUSE) holds no ref but may have left a probe
|
|
252
|
+
// loop running. When the last instance disposes with no owned server, tear
|
|
253
|
+
// the probe down so it cannot outlive the plugin. Do not touch generation
|
|
254
|
+
// or any close timer — this release never represented a real holder.
|
|
255
|
+
if (state.refs === 0 && state.server === null && state.probeTimer !== null) {
|
|
256
|
+
clearInterval(state.probeTimer)
|
|
257
|
+
state.probeTimer = null
|
|
258
|
+
}
|
|
259
|
+
return
|
|
260
|
+
}
|
|
205
261
|
state.generation++
|
|
206
262
|
state.refs = Math.max(0, state.refs - 1)
|
|
207
263
|
if (state.refs !== 0) return
|
|
@@ -213,7 +269,10 @@ export function releaseGateway(deps: ReleaseGatewayDeps): void {
|
|
|
213
269
|
if (state.refs !== 0 || state.generation !== generation || state.server === null) return
|
|
214
270
|
const server = state.server
|
|
215
271
|
state.server = null
|
|
216
|
-
|
|
272
|
+
// Track the in-flight close so a new cold bind waits for the port to be
|
|
273
|
+
// released instead of racing it (which would EADDRINUSE and strand the
|
|
274
|
+
// owner). Swallow close failures into a log — setup must stay non-fatal.
|
|
275
|
+
const closing = server.close().catch((error: unknown) => {
|
|
217
276
|
const reason = String((error as Error)?.message ?? error)
|
|
218
277
|
try {
|
|
219
278
|
deps.log(`gateway close error: ${reason}`)
|
|
@@ -221,6 +280,10 @@ export function releaseGateway(deps: ReleaseGatewayDeps): void {
|
|
|
221
280
|
// A throwing injected logger must not turn into an unhandled rejection.
|
|
222
281
|
}
|
|
223
282
|
})
|
|
283
|
+
state.closing = closing
|
|
284
|
+
void closing.finally(() => {
|
|
285
|
+
if (state.closing === closing) state.closing = null
|
|
286
|
+
})
|
|
224
287
|
}, deps.graceMs ?? DEFAULT_GRACE_MS)
|
|
225
288
|
}
|
|
226
289
|
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { ensureGateway, releaseGateway } from "./gateway-owner"
|
|
2
2
|
import type { ProxyServer } from "./proxy"
|
|
3
|
-
|
|
4
|
-
const PROXY_PORT = 7688
|
|
3
|
+
import { PROXY_PORT } from "../shared"
|
|
5
4
|
|
|
6
5
|
/**
|
|
7
6
|
* Pure startup wiring: acquire the shared gateway, register the RPC handlers,
|
|
@@ -28,24 +27,48 @@ export interface GatewaySetup {
|
|
|
28
27
|
* dispose must never close it directly.
|
|
29
28
|
*/
|
|
30
29
|
export async function setupGateway(deps: SetupGatewayDeps): Promise<GatewaySetup> {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
30
|
+
let proxy: ProxyServer | null = null
|
|
31
|
+
let holdsRef = false
|
|
32
|
+
try {
|
|
33
|
+
proxy = await deps.ensureGateway({
|
|
34
|
+
port: PROXY_PORT,
|
|
35
|
+
createServer: deps.createServer,
|
|
36
|
+
start: (server, port) => server.start(port),
|
|
37
|
+
log: deps.log,
|
|
38
|
+
})
|
|
39
|
+
// A non-null proxy is a real acquired ref. EADDRINUSE returns null *after*
|
|
40
|
+
// ensureGateway already rolled its own ref back, so null means "not held".
|
|
41
|
+
holdsRef = proxy !== null
|
|
42
|
+
} catch (error) {
|
|
43
|
+
// A bind failure other than EADDRINUSE must stay non-fatal, as it was before
|
|
44
|
+
// the shared-owner refactor: log it and let the rest of setup (RPC/providers)
|
|
45
|
+
// proceed. ensureGateway already rolled back its own ref — no release.
|
|
46
|
+
const reason = String((error as Error)?.message ?? error)
|
|
47
|
+
try {
|
|
48
|
+
deps.log(`gateway bind failed; proxy unavailable (non-fatal): ${reason}`)
|
|
49
|
+
} catch {
|
|
50
|
+
// a throwing logger must never turn a non-fatal bind failure fatal
|
|
51
|
+
}
|
|
52
|
+
}
|
|
37
53
|
|
|
38
54
|
try {
|
|
39
55
|
await deps.register()
|
|
40
56
|
} catch (error) {
|
|
41
|
-
await deps.releaseGateway({ log: deps.log })
|
|
57
|
+
if (holdsRef) await deps.releaseGateway({ log: deps.log })
|
|
42
58
|
throw error
|
|
43
59
|
}
|
|
44
60
|
|
|
61
|
+
// Only an instance that actually acquired a ref may release it. Releasing
|
|
62
|
+
// from a null-proxy instance would decrement a *different* live holder and,
|
|
63
|
+
// after grace, close a server this instance never owned. The released guard
|
|
64
|
+
// makes dispose idempotent so a repeated call cannot double-release.
|
|
65
|
+
let released = false
|
|
45
66
|
return {
|
|
46
67
|
proxy,
|
|
47
68
|
dispose: async () => {
|
|
48
|
-
|
|
69
|
+
if (released) return
|
|
70
|
+
released = true
|
|
71
|
+
if (holdsRef) await deps.releaseGateway({ log: deps.log })
|
|
49
72
|
},
|
|
50
73
|
}
|
|
51
74
|
}
|
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,16 +4,36 @@ 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
|
|
|
10
11
|
/**
|
|
11
|
-
*
|
|
12
|
+
* Base fields of `GET /health`. Cross-task contract: a probe parses
|
|
12
13
|
* `status === "ok" && service === "codebuddy-quota"`, so both the keys and the
|
|
13
|
-
* spelling are part of the API.
|
|
14
|
+
* spelling are part of the API. The live body adds a process nonce (below) so a
|
|
15
|
+
* probe can tell its own gateway from another OpenCode instance on the port.
|
|
14
16
|
*/
|
|
15
17
|
export const HEALTH_BODY = '{"status":"ok","service":"codebuddy-quota"}'
|
|
16
18
|
|
|
19
|
+
const NONCE_KEY = Symbol.for("codebuddy-quota.gateway.nonce")
|
|
20
|
+
|
|
21
|
+
/** Process-wide nonce, stable across plugin module reloads via globalThis. */
|
|
22
|
+
export function processNonce(): string {
|
|
23
|
+
const g = globalThis as unknown as Record<PropertyKey, string | undefined>
|
|
24
|
+
if (!g[NONCE_KEY]) g[NONCE_KEY] = crypto.randomUUID()
|
|
25
|
+
return g[NONCE_KEY] as string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Live health body: base fields plus the process nonce. */
|
|
29
|
+
export function healthBody(): string {
|
|
30
|
+
return JSON.stringify({
|
|
31
|
+
status: "ok",
|
|
32
|
+
service: "codebuddy-quota",
|
|
33
|
+
nonce: processNonce(),
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
17
37
|
export function routeSite(url: string): Site | null {
|
|
18
38
|
if (url.startsWith("/cn/v2/")) return "cn"
|
|
19
39
|
if (url.startsWith("/intl/v2/")) return "intl"
|
|
@@ -258,7 +278,7 @@ export async function handleRequest(
|
|
|
258
278
|
if ((req.method === "GET" || req.method === undefined) && req.url === "/health") {
|
|
259
279
|
res.setHeader("Content-Type", "application/json")
|
|
260
280
|
res.status(200)
|
|
261
|
-
res.end(
|
|
281
|
+
res.end(healthBody())
|
|
262
282
|
return
|
|
263
283
|
}
|
|
264
284
|
|
|
@@ -419,7 +439,8 @@ export async function handleRequest(
|
|
|
419
439
|
}
|
|
420
440
|
|
|
421
441
|
// Plain OpenAI clients expect a single JSON object. Upstream errors are never
|
|
422
|
-
// 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.
|
|
423
444
|
const isAggregate = !wantsStream && upstream.ok && isChat
|
|
424
445
|
if (isAggregate) {
|
|
425
446
|
// Aggregate through a reader rather than `text()`: a client that walks away
|
|
@@ -443,6 +464,39 @@ export async function handleRequest(
|
|
|
443
464
|
return
|
|
444
465
|
}
|
|
445
466
|
|
|
467
|
+
// An upstream 401/403 on a request we authenticated is actionable: the shared
|
|
468
|
+
// gateway uses the first plugin instance's credential store (by design), so a
|
|
469
|
+
// re-login in a later instance can leave this store holding a stale token.
|
|
470
|
+
// Keep the response untouched; only emit a hint that maps the symptom to the
|
|
471
|
+
// known trade-off so it is diagnosable instead of a silent failure.
|
|
472
|
+
if ((upstream.status === 401 || upstream.status === 403) && !isAggregate) {
|
|
473
|
+
deps.log?.(
|
|
474
|
+
`upstream ${upstream.status}: the shared gateway may hold a stale credential from the first plugin instance; restart OpenCode or re-login to refresh it`,
|
|
475
|
+
)
|
|
476
|
+
}
|
|
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
|
+
|
|
446
500
|
copyHeaders(upstream.headers, res)
|
|
447
501
|
res.status(upstream.status)
|
|
448
502
|
|
|
@@ -466,16 +520,23 @@ export interface ProxyServer {
|
|
|
466
520
|
}
|
|
467
521
|
|
|
468
522
|
/**
|
|
469
|
-
* Bind options for the listener.
|
|
470
|
-
*
|
|
471
|
-
* injected object overrides these defaults field by field.
|
|
523
|
+
* Bind options for the listener. An injected object overrides the defaults
|
|
524
|
+
* field by field. Only options Node/Bun actually recognize belong here.
|
|
472
525
|
*/
|
|
473
526
|
export interface ListenOptions {
|
|
474
|
-
reuseAddr?: boolean
|
|
475
527
|
exclusive?: boolean
|
|
476
528
|
}
|
|
477
529
|
|
|
478
|
-
|
|
530
|
+
/**
|
|
531
|
+
* Bind options for the fixed local port. `exclusive:false` is an explicit
|
|
532
|
+
* `server.listen` option (disables SO_EXCLUSIVEADDRUSE on Windows). A genuinely
|
|
533
|
+
* occupied/orphaned port is NOT recovered here — that is the EADDRINUSE probe's
|
|
534
|
+
* job in gateway-owner.ts. There is no `reuseAddr` server.listen option (it is
|
|
535
|
+
* silently ignored), so none is carried; `reusePort` must never be set because
|
|
536
|
+
* under Bun it lets two processes share the port and split requests across
|
|
537
|
+
* per-process token stores, causing intermittent 401s. A guard test pins this.
|
|
538
|
+
*/
|
|
539
|
+
export const DEFAULT_LISTEN_OPTIONS: Required<ListenOptions> = { exclusive: false }
|
|
479
540
|
|
|
480
541
|
export function createProxy(deps: {
|
|
481
542
|
store: TokenStore
|
|
@@ -552,9 +613,15 @@ export function createProxy(deps: {
|
|
|
552
613
|
return {
|
|
553
614
|
start: (port) =>
|
|
554
615
|
new Promise<void>((resolve, reject) => {
|
|
555
|
-
|
|
616
|
+
const onError = (error: Error) => reject(error)
|
|
617
|
+
server.once("error", onError)
|
|
556
618
|
const options = { ...DEFAULT_LISTEN_OPTIONS, ...deps.listenOptions }
|
|
557
|
-
server.listen({ port, host: "127.0.0.1", ...options }, () =>
|
|
619
|
+
server.listen({ port, host: "127.0.0.1", ...options }, () => {
|
|
620
|
+
// The temporary bind-error listener must not linger after a successful
|
|
621
|
+
// listen; otherwise it accumulates on repeated start attempts.
|
|
622
|
+
server.removeListener("error", onError)
|
|
623
|
+
resolve()
|
|
624
|
+
})
|
|
558
625
|
}),
|
|
559
626
|
close: () =>
|
|
560
627
|
new Promise<void>((resolve, reject) => {
|
package/src/shared.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/** The two CodeBuddy sites. Pure type shared by server and GUI bundles. */
|
|
2
2
|
export type Site = "cn" | "intl"
|
|
3
3
|
|
|
4
|
+
/** Fixed local proxy port. Provider baseURLs in opencode.jsonc are pinned to it. */
|
|
5
|
+
export const PROXY_PORT = 7688
|
|
6
|
+
|
|
4
7
|
/** A brief account identity sent to the GUI. Never carries a token. */
|
|
5
8
|
export interface AccountBrief {
|
|
6
9
|
id: string
|