opencode-codebuddy-quota 0.1.3 → 0.1.5
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 +29 -26
- package/dist/gui-experimental.cjs +1 -1
- package/package.json +1 -1
- package/rpc.ts +24 -0
- package/server.ts +34 -16
- package/src/gui/dialog-helpers.ts +33 -0
- package/src/gui/dialog.css +8 -0
- package/src/gui/dialog.tsx +39 -3
- package/src/gui/quota.ts +37 -6
- package/src/gui/store.ts +146 -76
- package/src/gui.tsx +17 -0
- package/src/server/config.ts +155 -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 +91 -1
- package/src/server/rate-limit-store.ts +102 -0
- package/src/server/rpc-handlers.ts +16 -2
- package/src/server/setup-order.ts +17 -0
- package/src/server/wire.ts +6 -2
- package/src/shared.ts +9 -0
package/src/gui/store.ts
CHANGED
|
@@ -7,19 +7,31 @@ export interface QuotaClient {
|
|
|
7
7
|
login?(input: { site: Site }): Promise<unknown>
|
|
8
8
|
}
|
|
9
9
|
|
|
10
|
+
/** Injectable clock/timers so the backoff state machine can be tested deterministically. */
|
|
11
|
+
export interface Timers {
|
|
12
|
+
setInterval(fn: () => void, ms: number): unknown
|
|
13
|
+
clearInterval(id: unknown): void
|
|
14
|
+
setTimeout(fn: () => void, ms: number): unknown
|
|
15
|
+
clearTimeout(id: unknown): void
|
|
16
|
+
}
|
|
17
|
+
|
|
10
18
|
export interface QuotaStore {
|
|
11
19
|
read(): Quota
|
|
12
20
|
subscribe(listener: (q: Quota) => void): () => void
|
|
13
21
|
refresh(options?: { force?: boolean; maxAgeMs?: number; site?: Site }): Promise<void>
|
|
14
22
|
login(site: Site): Promise<boolean>
|
|
15
23
|
start(): () => void
|
|
24
|
+
setRefreshMs(ms: number): void
|
|
16
25
|
}
|
|
17
26
|
|
|
27
|
+
export type ReadOutcome = { kind: "ok"; quota: Quota } | { kind: "failed"; quota: Quota }
|
|
28
|
+
|
|
18
29
|
/** Background safety net only; the capsule refreshes on hover and the dialog on open. */
|
|
19
|
-
const
|
|
30
|
+
export const DEFAULT_REFRESH_MS = 10 * 60_000
|
|
20
31
|
/** Hover refreshes only when the reading is older than this, so mouse traffic cannot spam. */
|
|
21
32
|
export const HOVER_MIN_AGE_MS = 60_000
|
|
22
33
|
const STALE_AFTER_RESUME_MS = 2 * 60_000
|
|
34
|
+
const MAX_RETRIES = 5
|
|
23
35
|
|
|
24
36
|
const idle = (status: "error", error: string | null): Quota => ({
|
|
25
37
|
status,
|
|
@@ -40,44 +52,65 @@ const idle = (status: "error", error: string | null): Quota => ({
|
|
|
40
52
|
fetchedAt: null,
|
|
41
53
|
ageSeconds: null,
|
|
42
54
|
error,
|
|
55
|
+
rateLimits: [],
|
|
43
56
|
})
|
|
44
57
|
|
|
45
58
|
/**
|
|
46
|
-
* One read of the quota over the plugin RPC.
|
|
59
|
+
* One read of the quota over the plugin RPC. `getClient` is a function because
|
|
60
|
+
* the client changes when the server restarts and can itself throw — evaluating
|
|
61
|
+
* it inside the try keeps that failure in the outcome instead of escaping.
|
|
47
62
|
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
* probably fine; `ok: false` is the server saying it has nothing, so the old
|
|
52
|
-
* numbers are dropped rather than dressed up as merely stale.
|
|
63
|
+
* `ok:false` normally drops the fallback (quota.ts), but here the previous
|
|
64
|
+
* numbers are deliberately restored when available: during GUI retries the user
|
|
65
|
+
* should keep seeing the numbers already on screen rather than `--`.
|
|
53
66
|
*/
|
|
54
67
|
export async function readQuota(opts: {
|
|
55
|
-
|
|
68
|
+
getClient: () => QuotaClient
|
|
56
69
|
fallback?: Quota | null
|
|
57
70
|
now?: number
|
|
58
71
|
site?: Site
|
|
59
|
-
}): Promise<
|
|
72
|
+
}): Promise<ReadOutcome> {
|
|
60
73
|
const now = opts.now ?? Date.now()
|
|
61
74
|
let body: unknown
|
|
62
75
|
try {
|
|
63
|
-
body = await opts.
|
|
76
|
+
body = await opts.getClient().read(opts.site ? { site: opts.site } : {})
|
|
64
77
|
} catch (error) {
|
|
65
78
|
const message = String((error as Error)?.message ?? error)
|
|
66
|
-
|
|
67
|
-
? { ...opts.fallback, status: "stale", error: message }
|
|
68
|
-
: idle("error", message)
|
|
79
|
+
const quota = opts.fallback
|
|
80
|
+
? { ...opts.fallback, status: "stale" as const, error: message }
|
|
81
|
+
: { ...idle("error", message), site: opts.site ?? "cn" }
|
|
82
|
+
return { kind: "failed", quota }
|
|
83
|
+
}
|
|
84
|
+
const normalized = normalizeQuota(body, { now })
|
|
85
|
+
// normalizeQuota's empty() hardcodes site "cn"; on a failed read there is no
|
|
86
|
+
// payload to carry the site, so keep the site the user actually requested.
|
|
87
|
+
const withSite = (q: Quota): Quota =>
|
|
88
|
+
opts.site && q.remaining === null ? { ...q, site: opts.site } : q
|
|
89
|
+
if (normalized.status === "stale" || normalized.status === "error") {
|
|
90
|
+
// Restore the fallback only for the explicit `ok:false` case (payload said
|
|
91
|
+
// unavailable). A stale reading already carries the numbers we want.
|
|
92
|
+
const quota =
|
|
93
|
+
normalized.status === "error" && opts.fallback && opts.fallback.remaining !== null
|
|
94
|
+
? { ...opts.fallback, status: "stale" as const, error: normalized.error }
|
|
95
|
+
: withSite(normalized)
|
|
96
|
+
return { kind: "failed", quota }
|
|
69
97
|
}
|
|
70
|
-
|
|
71
|
-
// the fallback is deliberately not offered here.
|
|
72
|
-
return normalizeQuota(body, { now })
|
|
98
|
+
return { kind: "ok", quota: normalized }
|
|
73
99
|
}
|
|
74
100
|
|
|
75
|
-
export function createQuotaStore(
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
101
|
+
export function createQuotaStore(
|
|
102
|
+
client: () => QuotaClient,
|
|
103
|
+
timers: Timers = globalThis,
|
|
104
|
+
now: () => number = Date.now,
|
|
105
|
+
): QuotaStore {
|
|
106
|
+
let current: Quota = normalizeQuota(null, { now: now() })
|
|
107
|
+
let refreshMs = DEFAULT_REFRESH_MS
|
|
108
|
+
let timerId: unknown = null
|
|
80
109
|
let started = false
|
|
110
|
+
let lastSuccessAt = 0
|
|
111
|
+
let lastAttempt = 0
|
|
112
|
+
let inflight: { site?: Site; promise: Promise<ReadOutcome> } | null = null
|
|
113
|
+
const retry = { tries: 0, timer: null as unknown | null, cancelled: false }
|
|
81
114
|
const listeners = new Set<(q: Quota) => void>()
|
|
82
115
|
|
|
83
116
|
const emit = (next: Quota) => {
|
|
@@ -85,78 +118,114 @@ export function createQuotaStore(client: () => QuotaClient): QuotaStore {
|
|
|
85
118
|
for (const listener of listeners) listener(next)
|
|
86
119
|
}
|
|
87
120
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
121
|
+
function clearRetry() {
|
|
122
|
+
timers.clearTimeout(retry.timer)
|
|
123
|
+
retry.timer = null
|
|
124
|
+
retry.tries = 0
|
|
125
|
+
lastSuccessAt = now()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function onOutcome(o: ReadOutcome) {
|
|
129
|
+
if (o.kind === "ok") clearRetry()
|
|
130
|
+
else scheduleRetry()
|
|
131
|
+
// Emit unless explicitly cleaned up. Unit callers refresh() without start(),
|
|
132
|
+
// and gating emission on `started` froze their reading at the initial value.
|
|
133
|
+
if (!retry.cancelled) emit(o.quota)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function scheduleRetry() {
|
|
137
|
+
// start() is the only entry to background scheduling: an unstarted store
|
|
138
|
+
// must not leave pending timers behind (e.g. failed tests).
|
|
139
|
+
if (retry.cancelled || !started) return
|
|
140
|
+
if (retry.timer !== null) return
|
|
141
|
+
if (retry.tries >= MAX_RETRIES) {
|
|
142
|
+
retry.tries = 0
|
|
143
|
+
return
|
|
102
144
|
}
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
145
|
+
const delay = 5_000 * 2 ** retry.tries
|
|
146
|
+
retry.tries++
|
|
147
|
+
retry.timer = timers.setTimeout(() => {
|
|
148
|
+
retry.timer = null
|
|
149
|
+
// A hover may slip into runOnce() as a reuser while this window is open;
|
|
150
|
+
// that is harmless — reusers never start a new request or advance tries.
|
|
151
|
+
if (!retry.cancelled) void runOnce()
|
|
152
|
+
}, delay)
|
|
153
|
+
}
|
|
107
154
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
try {
|
|
114
|
-
// Read the client per request: it changes when the server restarts.
|
|
115
|
-
next = await readQuota({ client: client(), fallback: usable, site: options.site })
|
|
116
|
-
} catch (error) {
|
|
117
|
-
// `client()` itself can throw when the server client is unavailable,
|
|
118
|
-
// which is the same situation as a rejected RPC call.
|
|
119
|
-
const message = String((error as Error)?.message ?? error)
|
|
120
|
-
next = usable ? { ...usable, status: "stale", error: message } : idle("error", message)
|
|
121
|
-
}
|
|
122
|
-
emit(next)
|
|
123
|
-
} finally {
|
|
124
|
-
inflight = null
|
|
125
|
-
const queued = pendingSite
|
|
126
|
-
pendingSite = null
|
|
127
|
-
// Re-run only if the last request was for a different site than the one
|
|
128
|
-
// that just completed; otherwise it is already served.
|
|
129
|
-
if (queued && queued !== current.site) void refresh({ force: true, site: queued })
|
|
155
|
+
async function runOnce(site?: Site): Promise<ReadOutcome> {
|
|
156
|
+
if (inflight) {
|
|
157
|
+
if (inflight.site !== site) {
|
|
158
|
+
await inflight.promise
|
|
159
|
+
return runOnce(site)
|
|
130
160
|
}
|
|
131
|
-
|
|
161
|
+
const o = await inflight.promise
|
|
162
|
+
if (o.kind === "ok") clearRetry()
|
|
163
|
+
return o
|
|
164
|
+
}
|
|
165
|
+
// Only fall back to numbers belonging to the requested site — otherwise a
|
|
166
|
+
// failed intl read would display cn's balance and reroute later hovers to cn.
|
|
167
|
+
const fallback =
|
|
168
|
+
current.remaining !== null && (site === undefined || current.site === site) ? current : null
|
|
169
|
+
const entry: { site?: Site; promise: Promise<ReadOutcome> } = {
|
|
170
|
+
site,
|
|
171
|
+
promise: Promise.resolve() as never,
|
|
172
|
+
}
|
|
173
|
+
entry.promise = readQuota({ getClient: client, fallback, now: now(), site })
|
|
174
|
+
inflight = entry
|
|
175
|
+
try {
|
|
176
|
+
const o = await entry.promise
|
|
177
|
+
onOutcome(o)
|
|
178
|
+
return o
|
|
179
|
+
} finally {
|
|
180
|
+
inflight = null
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const refresh = async (options: { force?: boolean; maxAgeMs?: number; site?: Site } = {}) => {
|
|
185
|
+
if (options.force) {
|
|
186
|
+
// A manual refresh (dialog button) is allowed during backoff and ends it early.
|
|
187
|
+
} else if (retry.timer !== null) {
|
|
188
|
+
return
|
|
189
|
+
} else if (now() - lastSuccessAt < (options.maxAgeMs ?? refreshMs)) {
|
|
190
|
+
return
|
|
191
|
+
}
|
|
192
|
+
lastAttempt = now()
|
|
193
|
+
await runOnce(options.site)
|
|
194
|
+
}
|
|
132
195
|
|
|
133
|
-
|
|
196
|
+
const hasDocument = typeof globalThis.document !== "undefined"
|
|
197
|
+
const tick = () => {
|
|
198
|
+
if (hasDocument && globalThis.document.hidden) return
|
|
199
|
+
void refresh()
|
|
200
|
+
}
|
|
201
|
+
const onVisible = () => {
|
|
202
|
+
if (globalThis.document.hidden) return
|
|
203
|
+
if (now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
|
|
134
204
|
}
|
|
135
205
|
|
|
136
206
|
const start = () => {
|
|
137
207
|
if (started) return () => {}
|
|
138
208
|
started = true
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
// A hidden window must not poll; on return, refresh only if the data aged.
|
|
142
|
-
if (hasDocument && globalThis.document.hidden) return
|
|
143
|
-
void refresh()
|
|
144
|
-
}
|
|
145
|
-
const onVisible = () => {
|
|
146
|
-
if (globalThis.document.hidden) return
|
|
147
|
-
if (Date.now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
|
|
148
|
-
}
|
|
149
|
-
const timer = setInterval(tick, REFRESH_MS)
|
|
209
|
+
retry.cancelled = false
|
|
210
|
+
timerId = timers.setInterval(tick, refreshMs)
|
|
150
211
|
if (hasDocument) globalThis.document.addEventListener("visibilitychange", onVisible)
|
|
151
|
-
// The one place the capsule gets its first number without any interaction.
|
|
152
212
|
void refresh({ force: true })
|
|
153
213
|
return () => {
|
|
154
|
-
|
|
214
|
+
retry.cancelled = true
|
|
215
|
+
timers.clearTimeout(retry.timer)
|
|
216
|
+
timers.clearInterval(timerId)
|
|
155
217
|
if (hasDocument) globalThis.document.removeEventListener("visibilitychange", onVisible)
|
|
156
218
|
started = false
|
|
157
219
|
}
|
|
158
220
|
}
|
|
159
221
|
|
|
222
|
+
const setRefreshMs = (ms: number) => {
|
|
223
|
+
refreshMs = ms
|
|
224
|
+
if (!started) return
|
|
225
|
+
timers.clearInterval(timerId)
|
|
226
|
+
timerId = timers.setInterval(tick, refreshMs)
|
|
227
|
+
}
|
|
228
|
+
|
|
160
229
|
return {
|
|
161
230
|
read: () => current,
|
|
162
231
|
subscribe(listener) {
|
|
@@ -177,5 +246,6 @@ export function createQuotaStore(client: () => QuotaClient): QuotaStore {
|
|
|
177
246
|
}
|
|
178
247
|
},
|
|
179
248
|
start,
|
|
249
|
+
setRefreshMs,
|
|
180
250
|
}
|
|
181
251
|
}
|
package/src/gui.tsx
CHANGED
|
@@ -21,6 +21,22 @@ export default Plugin.define({
|
|
|
21
21
|
onCleanup(store.subscribe(setQuota))
|
|
22
22
|
onCleanup(store.start())
|
|
23
23
|
|
|
24
|
+
// The interval is configurable on the server; start() already armed the
|
|
25
|
+
// default 10-minute timer, so a successful config read just rebuilds it.
|
|
26
|
+
// config() is fire-and-forget: setup() must stay synchronous (no thenable
|
|
27
|
+
// return), and a failure here keeps the default rather than retrying.
|
|
28
|
+
void ctx.client.rpc(CodebuddyQuota).config({})
|
|
29
|
+
.then((r) => {
|
|
30
|
+
const { refreshMinutes } = r as { refreshMinutes?: number }
|
|
31
|
+
// Do not trust the RPC: match the server's 1..30 integer rule so a NaN
|
|
32
|
+
// or 0 can never turn setInterval into a 0ms hot loop.
|
|
33
|
+
if (typeof refreshMinutes === "number" && Number.isInteger(refreshMinutes)
|
|
34
|
+
&& refreshMinutes >= 1 && refreshMinutes <= 30) {
|
|
35
|
+
store.setRefreshMs(refreshMinutes * 60_000)
|
|
36
|
+
}
|
|
37
|
+
})
|
|
38
|
+
.catch(() => { /* startup race: keep the default 10 minutes */ })
|
|
39
|
+
|
|
24
40
|
const openDetails = () => {
|
|
25
41
|
// Refreshing here as well as on the dialog's mount would fire two requests
|
|
26
42
|
// for one click, so the dialog owns that refresh.
|
|
@@ -34,6 +50,7 @@ export default Plugin.define({
|
|
|
34
50
|
<QuotaDialog
|
|
35
51
|
quota={live()}
|
|
36
52
|
ui={ctx.ui}
|
|
53
|
+
currentModel={ctx.screen.current()?.composer.model()?.modelID}
|
|
37
54
|
onRefresh={(site) => store.refresh({ force: true, site })}
|
|
38
55
|
onLogin={(site) => store.login(site)}
|
|
39
56
|
close={dialog.close}
|
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,18 @@ 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
|
|
42
|
+
/**
|
|
43
|
+
* Minutes between background quota refreshes. Shorter keeps the capsule
|
|
44
|
+
* fresher but polls more; bounded to a sane 1..30 range.
|
|
45
|
+
*/
|
|
46
|
+
refresh_minutes: number
|
|
31
47
|
}
|
|
32
48
|
|
|
33
49
|
/**
|
|
@@ -44,24 +60,27 @@ export const DEFAULT_CONFIG: QuotaConfig = {
|
|
|
44
60
|
"glm-5.3-flashx": { provider: "zhipuai", model: "glm-5.3-flashx" },
|
|
45
61
|
"minimax-m3.1-flash": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
|
|
46
62
|
"step-5-preview": { provider: "stepfun", model: "step-5-preview" },
|
|
63
|
+
// CodeBuddy replaced its preview with the final Step-5 id on the cli allowlist.
|
|
64
|
+
"step-5": { provider: "stepfun", model: "step-5" },
|
|
47
65
|
"mimo-v2.6-pro": { provider: "xiaomi", model: "mimo-v2.6-pro" },
|
|
48
66
|
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" },
|
|
67
|
+
// `Hy4 flash` ships twice: a free id and a paid one. Both map to models.dev's
|
|
68
|
+
// hy4-flash; the free one is zero-priced by credits.
|
|
69
|
+
"hy4flash-free": { provider: "tencent-tokenhub", model: "hy4-flash" },
|
|
70
|
+
hy4flash: { provider: "tencent-tokenhub", model: "hy4-flash" },
|
|
53
71
|
hy4free: { provider: "tencent-tokenhub", model: "hy4" },
|
|
54
72
|
hy3: { provider: "tencent-tokenhub", model: "hy3" },
|
|
55
73
|
"hy3-x": { provider: "tencent-tokenhub", model: "hy3" },
|
|
56
74
|
// Same model as minimax-m3.1-flash; CodeBuddy just bills it under its own id.
|
|
57
75
|
"space-bunny": { provider: "minimax-cn", model: "MiniMax-M3.1-Flash" },
|
|
58
76
|
// International-site cli-whitelist (ids from /v3/config agents[cli]).
|
|
59
|
-
//
|
|
60
|
-
// models.dev entity
|
|
77
|
+
// The four virtual routing aliases (default/fast/balanced/primary-model)
|
|
78
|
+
// have no models.dev entity. Not mapped: they are shown with a `*` unless
|
|
79
|
+
// excluded by the user. The current catalog uses auto/max-model instead.
|
|
61
80
|
"hy4-preview": { provider: "tencent-tokenhub", model: "hy4-preview" },
|
|
62
81
|
// SG variant shares the same underlying model; models.dev has no separate id.
|
|
63
82
|
"deepseek-v4.1-flash-sg": { provider: "deepseek", model: "deepseek-v4-flash" },
|
|
64
|
-
// models.dev
|
|
83
|
+
// models.dev carries all GPT ids under openai; use the official vendor.
|
|
65
84
|
"gpt-6-astra": { provider: "openai", model: "gpt-6-astra" },
|
|
66
85
|
"gpt-6.1-sol": { provider: "openai", model: "gpt-6.1-sol" },
|
|
67
86
|
"gpt-6-sol": { provider: "openai", model: "gpt-6-sol" },
|
|
@@ -85,15 +104,30 @@ export const DEFAULT_CONFIG: QuotaConfig = {
|
|
|
85
104
|
"kimi-k3.1-pro-highspeed": { provider: "moonshotai", model: "kimi-k3.1-pro-highspeed" },
|
|
86
105
|
},
|
|
87
106
|
// auto/max-model are virtual routing tiers with no models.dev entity; exclude
|
|
88
|
-
// them explicitly rather than relying on the
|
|
107
|
+
// them explicitly rather than relying on the unmapped path, which now offers
|
|
108
|
+
// every model with a `*` marker.
|
|
89
109
|
excluded_models: ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
|
|
90
110
|
package_version: DEFAULT_PACKAGE_VERSION,
|
|
91
111
|
embedding_model: "bge-m3",
|
|
92
112
|
local_embedding_model: "",
|
|
113
|
+
overwrite_config: false,
|
|
114
|
+
refresh_minutes: 10,
|
|
93
115
|
}
|
|
94
116
|
|
|
95
117
|
export const CONFIG_FILE_NAME = "codebuddy-quota.json"
|
|
96
118
|
|
|
119
|
+
/**
|
|
120
|
+
* This plugin's own version from its package.json. Config files record it as
|
|
121
|
+
* `plugin_version` so an upgrade that changes defaults can refresh opted-in
|
|
122
|
+
* files without a separate version counter to maintain by hand.
|
|
123
|
+
*/
|
|
124
|
+
export function pluginVersion(): string {
|
|
125
|
+
const pkg = JSON.parse(readFileSync(join(import.meta.dir, "..", "..", "package.json"), "utf8")) as {
|
|
126
|
+
version?: unknown
|
|
127
|
+
}
|
|
128
|
+
return typeof pkg.version === "string" ? pkg.version : "0.0.0"
|
|
129
|
+
}
|
|
130
|
+
|
|
97
131
|
/** `$XDG_CONFIG_HOME/opencode`, or `~/.config/opencode` when it is unset. */
|
|
98
132
|
export function configDir(
|
|
99
133
|
env: Record<string, string | undefined> = process.env,
|
|
@@ -104,11 +138,110 @@ export function configDir(
|
|
|
104
138
|
return join(home, ".config", "opencode")
|
|
105
139
|
}
|
|
106
140
|
|
|
107
|
-
/**
|
|
141
|
+
/** `$XDG_CONFIG_HOME/opencode/codebuddy-quota.json`, or `~/.config/opencode/...` by default, beside the user's `opencode.json(c)`. */
|
|
108
142
|
export function configPath(home: string = homedir()): string {
|
|
109
143
|
return join(configDir(undefined, home), CONFIG_FILE_NAME)
|
|
110
144
|
}
|
|
111
145
|
|
|
146
|
+
export interface EnsureConfigDeps {
|
|
147
|
+
configPath?: string
|
|
148
|
+
exists?: (path: string) => boolean
|
|
149
|
+
readFile?: (path: string) => string
|
|
150
|
+
mkdir?: (dir: string) => void
|
|
151
|
+
writeFile?: (path: string, content: string) => void
|
|
152
|
+
/** Called with the old text before an opt-in rewrite. Defaults to a single `.bak` copy, overwritten on each upgrade. */
|
|
153
|
+
backup?: (path: string, content: string) => void
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface EnsureConfigResult {
|
|
157
|
+
path: string
|
|
158
|
+
/** The file did not exist and was created from the defaults. */
|
|
159
|
+
created: boolean
|
|
160
|
+
/** An opted-in file was behind and got rewritten from the defaults. */
|
|
161
|
+
upgraded: boolean
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Writes an editable copy of the defaults next to `opencode.json(c)` when the
|
|
166
|
+
* user has none. The file must be discoverable: the plugin directory would hide
|
|
167
|
+
* it behind a package install.
|
|
168
|
+
*
|
|
169
|
+
* An existing file is the user's, not ours. It is only rewritten when the user
|
|
170
|
+
* opted in with `overwrite_config: true` AND its `plugin_version` is behind this
|
|
171
|
+
* release; the previous copy is saved as `.bak`. Comparing the plugin's own
|
|
172
|
+
* version means defaults are refreshed whenever the plugin is upgraded.
|
|
173
|
+
*
|
|
174
|
+
* A failed mkdir/write or an unreadable file throws; the plugin's setup wraps
|
|
175
|
+
* this call and falls back to the built-in defaults so startup never breaks.
|
|
176
|
+
*/
|
|
177
|
+
export function ensureConfigFile(deps: EnsureConfigDeps = {}): EnsureConfigResult {
|
|
178
|
+
const path = deps.configPath ?? configPath()
|
|
179
|
+
const exists = deps.exists ?? existsSync
|
|
180
|
+
const currentVersion = pluginVersion()
|
|
181
|
+
const write = deps.writeFile ?? ((p: string, content: string) => writeFileSync(p, content, "utf8"))
|
|
182
|
+
// The opt-in flag is the one key a rewrite must carry over: dropping it would
|
|
183
|
+
// silently unsubscribe the file from future upgrades.
|
|
184
|
+
const render = (overwrite: boolean) =>
|
|
185
|
+
`${JSON.stringify({ ...DEFAULT_CONFIG, overwrite_config: overwrite, plugin_version: currentVersion }, null, 2)}\n`
|
|
186
|
+
|
|
187
|
+
if (exists(path)) {
|
|
188
|
+
const read = deps.readFile ?? ((p: string) => readFileSync(p, "utf8"))
|
|
189
|
+
let content: string
|
|
190
|
+
try {
|
|
191
|
+
content = read(path)
|
|
192
|
+
} catch {
|
|
193
|
+
return { path, created: false, upgraded: false }
|
|
194
|
+
}
|
|
195
|
+
let parsed: unknown
|
|
196
|
+
try {
|
|
197
|
+
parsed = JSON.parse(content)
|
|
198
|
+
} catch {
|
|
199
|
+
return { path, created: false, upgraded: false }
|
|
200
|
+
}
|
|
201
|
+
if (!isRecord(parsed) || parsed.overwrite_config !== true) {
|
|
202
|
+
return { path, created: false, upgraded: false }
|
|
203
|
+
}
|
|
204
|
+
// A missing or malformed pin counts as behind: the user asked to follow the
|
|
205
|
+
// shipped defaults, so there is nothing to preserve.
|
|
206
|
+
if (!isOlderVersion(parsed.plugin_version, currentVersion)) {
|
|
207
|
+
return { path, created: false, upgraded: false }
|
|
208
|
+
}
|
|
209
|
+
const backup = deps.backup ?? ((p: string, old: string) => writeFileSync(`${p}.bak`, old, "utf8"))
|
|
210
|
+
try {
|
|
211
|
+
backup(path, content)
|
|
212
|
+
} catch {
|
|
213
|
+
// The rewrite is what was asked for; a failed backup must not block it.
|
|
214
|
+
}
|
|
215
|
+
write(path, render(true))
|
|
216
|
+
return { path, created: false, upgraded: true }
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const mkdir = deps.mkdir ?? ((dir: string) => mkdirSync(dir, { recursive: true }))
|
|
220
|
+
mkdir(dirname(path))
|
|
221
|
+
write(path, render(false))
|
|
222
|
+
return { path, created: true, upgraded: false }
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* True when `candidate` is a semver older than `current`. Only the numeric
|
|
227
|
+
* major/minor/patch segments are compared; pre-release and build metadata
|
|
228
|
+
* (`0.1.4-rc.1`, `+build`) are ignored, so an rc and its final are equal.
|
|
229
|
+
* A malformed candidate counts as behind.
|
|
230
|
+
*/
|
|
231
|
+
function isOlderVersion(candidate: unknown, current: string): boolean {
|
|
232
|
+
if (typeof candidate !== "string" || !isVersion(candidate)) return true
|
|
233
|
+
const segments = (v: string) => v.split(/[-+]/, 1)[0].split(".").map(Number)
|
|
234
|
+
const left = segments(candidate)
|
|
235
|
+
const right = segments(current)
|
|
236
|
+
for (let i = 0; i < Math.max(left.length, right.length); i++) {
|
|
237
|
+
const a = left[i] ?? 0
|
|
238
|
+
const b = right[i] ?? 0
|
|
239
|
+
if (a < b) return true
|
|
240
|
+
if (a > b) return false
|
|
241
|
+
}
|
|
242
|
+
return false
|
|
243
|
+
}
|
|
244
|
+
|
|
112
245
|
/**
|
|
113
246
|
* The names OpenCode accepts for a config file, in the order it prefers them.
|
|
114
247
|
* Both parse; JSONC is the one with comments.
|
|
@@ -174,6 +307,13 @@ function optionalString(value: unknown): string | undefined {
|
|
|
174
307
|
return typeof value === "string" ? value : undefined
|
|
175
308
|
}
|
|
176
309
|
|
|
310
|
+
/** Only an integer in 1..30 is accepted; everything else keeps the default. */
|
|
311
|
+
function refreshMinutes(value: unknown): number | undefined {
|
|
312
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 30
|
|
313
|
+
? value
|
|
314
|
+
: undefined
|
|
315
|
+
}
|
|
316
|
+
|
|
177
317
|
export interface LoadConfigDeps {
|
|
178
318
|
configPath?: string
|
|
179
319
|
readFile?: (path: string) => string
|
|
@@ -203,6 +343,7 @@ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
|
|
|
203
343
|
// Only a real version may reach the config writer: anything else would be
|
|
204
344
|
// written verbatim into the provider's `package` spec.
|
|
205
345
|
const packageVersion = isVersion(parsed.package_version) ? parsed.package_version : undefined
|
|
346
|
+
const overwrite = typeof parsed.overwrite_config === "boolean" ? parsed.overwrite_config : undefined
|
|
206
347
|
|
|
207
348
|
return {
|
|
208
349
|
models: models ? { ...DEFAULT_CONFIG.models, ...models } : DEFAULT_CONFIG.models,
|
|
@@ -211,5 +352,7 @@ export function loadConfig(deps: LoadConfigDeps = {}): QuotaConfig {
|
|
|
211
352
|
embedding_model: optionalString(parsed.embedding_model) ?? DEFAULT_CONFIG.embedding_model,
|
|
212
353
|
local_embedding_model:
|
|
213
354
|
optionalString(parsed.local_embedding_model) ?? DEFAULT_CONFIG.local_embedding_model,
|
|
355
|
+
overwrite_config: overwrite ?? DEFAULT_CONFIG.overwrite_config,
|
|
356
|
+
refresh_minutes: refreshMinutes(parsed.refresh_minutes) ?? DEFAULT_CONFIG.refresh_minutes,
|
|
214
357
|
}
|
|
215
358
|
}
|
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
|