opencode-codebuddy-quota 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +81 -2
- package/config.default.json +38 -0
- package/dist/gui-experimental.cjs +1 -0
- package/package.json +46 -4
- package/rpc.ts +92 -0
- package/server.ts +136 -0
- package/src/gui/battery.tsx +81 -0
- package/src/gui/dialog-helpers.ts +30 -0
- package/src/gui/dialog.css +83 -0
- package/src/gui/dialog.tsx +262 -0
- package/src/gui/pace.ts +76 -0
- package/src/gui/quota.ts +198 -0
- package/src/gui/store.ts +181 -0
- package/src/gui.tsx +111 -0
- package/src/server/catalog.ts +264 -0
- package/src/server/config-writer.ts +621 -0
- package/src/server/config.ts +195 -0
- package/src/server/headers.ts +72 -0
- package/src/server/logger.ts +26 -0
- package/src/server/login-gate.ts +21 -0
- package/src/server/login.ts +206 -0
- package/src/server/model-info.ts +109 -0
- package/src/server/models-dev.ts +77 -0
- package/src/server/package-spec.ts +42 -0
- package/src/server/package-version.ts +51 -0
- package/src/server/pricing.ts +169 -0
- package/src/server/proxy.ts +236 -0
- package/src/server/quota-source.ts +129 -0
- package/src/server/rpc-handlers.ts +87 -0
- package/src/server/signal.ts +36 -0
- package/src/server/site-select.ts +24 -0
- package/src/server/site-state.ts +58 -0
- package/src/server/token-store.ts +263 -0
- package/src/server/upstream.ts +150 -0
- package/src/server/wire.ts +67 -0
- package/src/shared.ts +20 -0
package/src/gui/store.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import type { Site } from "../shared"
|
|
2
|
+
import { normalizeQuota, type Quota } from "./quota"
|
|
3
|
+
|
|
4
|
+
/** The shape `ctx.client.rpc(CodebuddyQuota)` satisfies; kept loose so tests can fake it. */
|
|
5
|
+
export interface QuotaClient {
|
|
6
|
+
read(input: { site?: Site }): Promise<unknown>
|
|
7
|
+
login?(input: { site: Site }): Promise<unknown>
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface QuotaStore {
|
|
11
|
+
read(): Quota
|
|
12
|
+
subscribe(listener: (q: Quota) => void): () => void
|
|
13
|
+
refresh(options?: { force?: boolean; maxAgeMs?: number; site?: Site }): Promise<void>
|
|
14
|
+
login(site: Site): Promise<boolean>
|
|
15
|
+
start(): () => void
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Background safety net only; the capsule refreshes on hover and the dialog on open. */
|
|
19
|
+
const REFRESH_MS = 30 * 60_000
|
|
20
|
+
/** Hover refreshes only when the reading is older than this, so mouse traffic cannot spam. */
|
|
21
|
+
export const HOVER_MIN_AGE_MS = 60_000
|
|
22
|
+
const STALE_AFTER_RESUME_MS = 2 * 60_000
|
|
23
|
+
|
|
24
|
+
const idle = (status: "error", error: string | null): Quota => ({
|
|
25
|
+
status,
|
|
26
|
+
site: "cn",
|
|
27
|
+
sites: [
|
|
28
|
+
{ site: "cn", available: false, accounts: [], activeId: null },
|
|
29
|
+
{ site: "intl", available: false, accounts: [], activeId: null },
|
|
30
|
+
],
|
|
31
|
+
remaining: null,
|
|
32
|
+
used: null,
|
|
33
|
+
total: null,
|
|
34
|
+
usedPct: null,
|
|
35
|
+
timePct: null,
|
|
36
|
+
diff: null,
|
|
37
|
+
cycleStart: null,
|
|
38
|
+
cycleEnd: null,
|
|
39
|
+
resetAt: null,
|
|
40
|
+
fetchedAt: null,
|
|
41
|
+
ageSeconds: null,
|
|
42
|
+
error,
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* One read of the quota over the plugin RPC.
|
|
47
|
+
*
|
|
48
|
+
* Both a rejection (`RPC is unavailable`, the server restarting) and an explicit
|
|
49
|
+
* `ok: false` mean "no answer", but they keep the previous numbers differently:
|
|
50
|
+
* a rejection keeps them and marks them stale, because the quota itself is
|
|
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.
|
|
53
|
+
*/
|
|
54
|
+
export async function readQuota(opts: {
|
|
55
|
+
client: QuotaClient
|
|
56
|
+
fallback?: Quota | null
|
|
57
|
+
now?: number
|
|
58
|
+
site?: Site
|
|
59
|
+
}): Promise<Quota> {
|
|
60
|
+
const now = opts.now ?? Date.now()
|
|
61
|
+
let body: unknown
|
|
62
|
+
try {
|
|
63
|
+
body = await opts.client.read(opts.site ? { site: opts.site } : {})
|
|
64
|
+
} catch (error) {
|
|
65
|
+
const message = String((error as Error)?.message ?? error)
|
|
66
|
+
return opts.fallback
|
|
67
|
+
? { ...opts.fallback, status: "stale", error: message }
|
|
68
|
+
: idle("error", message)
|
|
69
|
+
}
|
|
70
|
+
// An explicit "unavailable" must never be dressed up as a stale number, so
|
|
71
|
+
// the fallback is deliberately not offered here.
|
|
72
|
+
return normalizeQuota(body, { now })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createQuotaStore(client: () => QuotaClient): QuotaStore {
|
|
76
|
+
let current: Quota = normalizeQuota(null, { now: Date.now() })
|
|
77
|
+
let lastAttempt = 0
|
|
78
|
+
let inflight: Promise<void> | null = null
|
|
79
|
+
let pendingSite: Site | null = null
|
|
80
|
+
let started = false
|
|
81
|
+
const listeners = new Set<(q: Quota) => void>()
|
|
82
|
+
|
|
83
|
+
const emit = (next: Quota) => {
|
|
84
|
+
current = next
|
|
85
|
+
for (const listener of listeners) listener(next)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* `force` skips every GUI-side age check (the dialog's refresh button); the
|
|
90
|
+
* server's own 30-second cache still applies behind it.
|
|
91
|
+
* `maxAgeMs` refreshes only when the last attempt is older than that, which is
|
|
92
|
+
* how hover keeps working without spamming on every pointer move.
|
|
93
|
+
*/
|
|
94
|
+
const refresh = async (options: { force?: boolean; maxAgeMs?: number; site?: Site } = {}) => {
|
|
95
|
+
// One request at a time: without this, a forced refresh racing a hover refresh
|
|
96
|
+
// can land out of order and let the older reading win.
|
|
97
|
+
if (inflight) {
|
|
98
|
+
// Compare against the IN-FLIGHT site, not current.site (which is the last
|
|
99
|
+
// emitted one and is frozen while a read runs). Last explicit request wins.
|
|
100
|
+
if (options.site) pendingSite = options.site
|
|
101
|
+
return inflight
|
|
102
|
+
}
|
|
103
|
+
const now = Date.now()
|
|
104
|
+
const maxAge = options.force ? 0 : (options.maxAgeMs ?? REFRESH_MS)
|
|
105
|
+
if (now - lastAttempt < maxAge) return
|
|
106
|
+
lastAttempt = now
|
|
107
|
+
|
|
108
|
+
inflight = (async () => {
|
|
109
|
+
try {
|
|
110
|
+
// Only a reading that actually carried data is worth falling back to.
|
|
111
|
+
const usable = current.remaining !== null ? current : null
|
|
112
|
+
let next: Quota
|
|
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 })
|
|
130
|
+
}
|
|
131
|
+
})()
|
|
132
|
+
|
|
133
|
+
return inflight
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const start = () => {
|
|
137
|
+
if (started) return () => {}
|
|
138
|
+
started = true
|
|
139
|
+
const hasDocument = typeof globalThis.document !== "undefined"
|
|
140
|
+
const tick = () => {
|
|
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)
|
|
150
|
+
if (hasDocument) globalThis.document.addEventListener("visibilitychange", onVisible)
|
|
151
|
+
// The one place the capsule gets its first number without any interaction.
|
|
152
|
+
void refresh({ force: true })
|
|
153
|
+
return () => {
|
|
154
|
+
clearInterval(timer)
|
|
155
|
+
if (hasDocument) globalThis.document.removeEventListener("visibilitychange", onVisible)
|
|
156
|
+
started = false
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
read: () => current,
|
|
162
|
+
subscribe(listener) {
|
|
163
|
+
listeners.add(listener)
|
|
164
|
+
return () => listeners.delete(listener)
|
|
165
|
+
},
|
|
166
|
+
refresh,
|
|
167
|
+
async login(site) {
|
|
168
|
+
try {
|
|
169
|
+
const loginFn = client().login
|
|
170
|
+
if (!loginFn) return false
|
|
171
|
+
const result = (await loginFn({ site })) as { ok?: boolean } | null
|
|
172
|
+
const ok = result?.ok === true
|
|
173
|
+
if (ok) await refresh({ force: true, site })
|
|
174
|
+
return ok
|
|
175
|
+
} catch {
|
|
176
|
+
return false
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
start,
|
|
180
|
+
}
|
|
181
|
+
}
|
package/src/gui.tsx
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Plugin, Slot, Style } from "@opencode/plugin/gui"
|
|
2
|
+
import { createSignal, onCleanup } from "solid-js"
|
|
3
|
+
import { CodebuddyQuota } from "../rpc"
|
|
4
|
+
import { Battery } from "./gui/battery"
|
|
5
|
+
import { QuotaDialog } from "./gui/dialog"
|
|
6
|
+
import { formatPct, paceColor } from "./gui/pace"
|
|
7
|
+
import { remainingPercent, remainingShare, type Quota } from "./gui/quota"
|
|
8
|
+
import { createQuotaStore, HOVER_MIN_AGE_MS } from "./gui/store"
|
|
9
|
+
import dialogCss from "./gui/dialog.css?inline"
|
|
10
|
+
|
|
11
|
+
export default Plugin.define({
|
|
12
|
+
setup(ctx) {
|
|
13
|
+
// Scoped dialog styles. currentColor/color-mix follow the active OpenCode
|
|
14
|
+
// theme, so the dialog stays in step with light/dark and custom themes.
|
|
15
|
+
ctx.add(Style, dialogCss)
|
|
16
|
+
|
|
17
|
+
// The client is read per request, not captured here: it changes when the
|
|
18
|
+
// OpenCode server restarts, and a captured one would keep failing.
|
|
19
|
+
const store = createQuotaStore(() => ctx.client.rpc(CodebuddyQuota))
|
|
20
|
+
const [quota, setQuota] = createSignal<Quota>(store.read())
|
|
21
|
+
onCleanup(store.subscribe(setQuota))
|
|
22
|
+
onCleanup(store.start())
|
|
23
|
+
|
|
24
|
+
const openDetails = () => {
|
|
25
|
+
// Refreshing here as well as on the dialog's mount would fire two requests
|
|
26
|
+
// for one click, so the dialog owns that refresh.
|
|
27
|
+
ctx.dialogs.open((dialog) => {
|
|
28
|
+
// The subscription lives in its own component so its owner is the dialog's
|
|
29
|
+
// render, not whatever scope `dialogs.open` happens to run in.
|
|
30
|
+
const Live = () => {
|
|
31
|
+
const [live, setLive] = createSignal<Quota>(store.read())
|
|
32
|
+
onCleanup(store.subscribe(setLive))
|
|
33
|
+
return (
|
|
34
|
+
<QuotaDialog
|
|
35
|
+
quota={live()}
|
|
36
|
+
ui={ctx.ui}
|
|
37
|
+
onRefresh={(site) => store.refresh({ force: true, site })}
|
|
38
|
+
onLogin={(site) => store.login(site)}
|
|
39
|
+
close={dialog.close}
|
|
40
|
+
/>
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
return <Live />
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Hover is the main way this refreshes: the background timer is only a safety
|
|
48
|
+
// net, so pointing at the capsule pulls a reading that is older than a minute.
|
|
49
|
+
const onHover = () => {
|
|
50
|
+
void store.refresh({ maxAgeMs: HOVER_MIN_AGE_MS, site: store.read().site })
|
|
51
|
+
}
|
|
52
|
+
const SITE_LABEL = { cn: "国内站", intl: "国际站" } as const
|
|
53
|
+
// Any site needing login shows an amber dot outside the capsule. Read the
|
|
54
|
+
// quota signal, not store.read(): the latter is a plain variable that Solid
|
|
55
|
+
// never tracks, so the dot froze on the first "needs login" verdict.
|
|
56
|
+
const needsLogin = () => quota().sites.some((s) => !s.available)
|
|
57
|
+
|
|
58
|
+
// The capsule lives on the session header row — the only surface the
|
|
59
|
+
// side-tabs layout leaves a plugin. See the design notes for why.
|
|
60
|
+
//
|
|
61
|
+
// Every value is read inside the JSX, not in the render body: a signal read
|
|
62
|
+
// outside a tracked expression is evaluated once and then frozen, which is
|
|
63
|
+
// why the capsule used to stay on "--" while the dialog showed live numbers.
|
|
64
|
+
ctx.add(Slot, {
|
|
65
|
+
at: "session.header",
|
|
66
|
+
order: 50,
|
|
67
|
+
render: () => (
|
|
68
|
+
<button
|
|
69
|
+
type="button"
|
|
70
|
+
title={
|
|
71
|
+
remainingShare(quota()) === null
|
|
72
|
+
? `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:暂不可用(点击查看/登录)`
|
|
73
|
+
: `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:剩余 ${formatPct(remainingShare(quota()))}`
|
|
74
|
+
}
|
|
75
|
+
onMouseEnter={onHover}
|
|
76
|
+
onFocus={onHover}
|
|
77
|
+
onClick={openDetails}
|
|
78
|
+
style={{
|
|
79
|
+
position: "relative",
|
|
80
|
+
background: "transparent",
|
|
81
|
+
border: "none",
|
|
82
|
+
padding: "2px 6px 2px 0",
|
|
83
|
+
"margin-left": "auto",
|
|
84
|
+
cursor: "pointer",
|
|
85
|
+
"line-height": "0",
|
|
86
|
+
}}
|
|
87
|
+
>
|
|
88
|
+
<Battery
|
|
89
|
+
value={remainingPercent(quota())}
|
|
90
|
+
color={paceColor(quota())}
|
|
91
|
+
dim={quota().status === "stale"}
|
|
92
|
+
/>
|
|
93
|
+
{needsLogin() && (
|
|
94
|
+
<span
|
|
95
|
+
style={{
|
|
96
|
+
position: "absolute",
|
|
97
|
+
top: "0",
|
|
98
|
+
right: "0",
|
|
99
|
+
width: "9px",
|
|
100
|
+
height: "9px",
|
|
101
|
+
"border-radius": "50%",
|
|
102
|
+
background: "#ffb84d",
|
|
103
|
+
border: "1.5px solid transparent",
|
|
104
|
+
}}
|
|
105
|
+
/>
|
|
106
|
+
)}
|
|
107
|
+
</button>
|
|
108
|
+
),
|
|
109
|
+
})
|
|
110
|
+
},
|
|
111
|
+
})
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CodeBuddy model catalog, read from `/v3/config`.
|
|
3
|
+
*
|
|
4
|
+
* The endpoint returns both a full model table and a per-agent allowlist. Only
|
|
5
|
+
* the `cli` allowlist matters here: it carries exactly the models the current
|
|
6
|
+
* API key may spend credits on, so a model that exists in the table but is
|
|
7
|
+
* absent from the allowlist must not be offered.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Site } from "../shared"
|
|
11
|
+
import { apiHeaders } from "./headers"
|
|
12
|
+
import type { SiteAuth } from "./login"
|
|
13
|
+
import { anySignal, timeoutSignal } from "./signal"
|
|
14
|
+
|
|
15
|
+
export const CONFIG_URL = "https://copilot.tencent.com/v3/config"
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The client identity the endpoint keys on. `CLI/` must appear in the
|
|
19
|
+
* User-Agent or the server answers HTTP 200 with a well-formed body that
|
|
20
|
+
* simply omits `data.models` — an empty catalog that looks like success.
|
|
21
|
+
* `CodeBuddy/<version>` must also parse, or the request is rejected outright.
|
|
22
|
+
*/
|
|
23
|
+
export const CLIENT_NAME = "deepseekharness"
|
|
24
|
+
export const CLI_UA_MARKER = "CLI/unknown"
|
|
25
|
+
export const CODEBUDDY_CLI_VERSION = "2.137.1"
|
|
26
|
+
export const REQUEST_USER_AGENT = `${CLIENT_NAME} ${CLI_UA_MARKER} CodeBuddy/${CODEBUDDY_CLI_VERSION}`
|
|
27
|
+
export const PRODUCT_HEADER = "SaaS"
|
|
28
|
+
|
|
29
|
+
const DEFAULT_TIMEOUT_MS = 15_000
|
|
30
|
+
|
|
31
|
+
export interface CatalogModel {
|
|
32
|
+
id: string
|
|
33
|
+
name: string
|
|
34
|
+
/** Credit multiplier from `"x0.29 credits"` as `0.29`; null when the server did not declare one. */
|
|
35
|
+
credits: number | null
|
|
36
|
+
imageInput: boolean
|
|
37
|
+
/** Reasoning effort ids, ordered from least to most. Empty when the model does not reason. */
|
|
38
|
+
efforts: readonly string[]
|
|
39
|
+
defaultEffort: string | null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface FetchCatalogDeps {
|
|
43
|
+
site: Site
|
|
44
|
+
auth: SiteAuth
|
|
45
|
+
signal?: AbortSignal
|
|
46
|
+
fetchImpl?: typeof fetch
|
|
47
|
+
timeoutMs?: number
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Effort ids the catalog uses, least to most. Unknown ids sort after all of these. */
|
|
51
|
+
const EFFORT_RANK: Readonly<Record<string, number>> = {
|
|
52
|
+
off: 0,
|
|
53
|
+
minimal: 1,
|
|
54
|
+
low: 2,
|
|
55
|
+
medium: 3,
|
|
56
|
+
high: 4,
|
|
57
|
+
xhigh: 5,
|
|
58
|
+
max: 6,
|
|
59
|
+
}
|
|
60
|
+
const UNKNOWN_EFFORT_RANK = Number.MAX_SAFE_INTEGER
|
|
61
|
+
|
|
62
|
+
/** The server does not guarantee ascending order, and downstream code relies on it. */
|
|
63
|
+
function sortEfforts(levels: readonly string[]): string[] {
|
|
64
|
+
return levels
|
|
65
|
+
.map((level, index) => ({ level, index }))
|
|
66
|
+
.sort(
|
|
67
|
+
(a, b) =>
|
|
68
|
+
(EFFORT_RANK[a.level] ?? UNKNOWN_EFFORT_RANK) - (EFFORT_RANK[b.level] ?? UNKNOWN_EFFORT_RANK) ||
|
|
69
|
+
a.index - b.index,
|
|
70
|
+
)
|
|
71
|
+
.map((entry) => entry.level)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `"x0.29 credits"` → `0.29`. A missing or unparseable value stays null. */
|
|
75
|
+
export function shortCredits(raw: unknown): number | null {
|
|
76
|
+
if (typeof raw !== "string") return null
|
|
77
|
+
const match = /x(\d+(?:\.\d+)?)/i.exec(raw)
|
|
78
|
+
if (!match) return null
|
|
79
|
+
const value = Number(match[1])
|
|
80
|
+
return Number.isFinite(value) ? value : null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** True when any of the values is a positive integer, i.e. the model declares some capacity. */
|
|
84
|
+
function declaresCapacity(...values: readonly unknown[]): boolean {
|
|
85
|
+
return values.some((value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function text(...values: readonly unknown[]): string | null {
|
|
89
|
+
for (const value of values) {
|
|
90
|
+
if (typeof value === "string" && value.length > 0) return value
|
|
91
|
+
}
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Two shapes the server uses for reasoning:
|
|
97
|
+
* `{ supportedEfforts: [...], canDisableThinking, defaultEffort }` for a model
|
|
98
|
+
* with selectable levels, and `{ effort: "high" }` for one locked to a single
|
|
99
|
+
* level. `canDisableThinking: false` means no `off` level.
|
|
100
|
+
*/
|
|
101
|
+
function readEfforts(reasoning: Record<string, unknown> | null): { efforts: string[]; defaultEffort: string | null } {
|
|
102
|
+
if (!reasoning) return { efforts: [], defaultEffort: null }
|
|
103
|
+
|
|
104
|
+
const supported = Array.isArray(reasoning.supportedEfforts)
|
|
105
|
+
? (reasoning.supportedEfforts as unknown[]).filter((l): l is string => typeof l === "string" && l.length > 0)
|
|
106
|
+
: []
|
|
107
|
+
|
|
108
|
+
if (supported.length > 0) {
|
|
109
|
+
const efforts = sortEfforts(supported)
|
|
110
|
+
// Some servers list `off` among the supported efforts and also flag it via
|
|
111
|
+
// `canDisableThinking`; the guard keeps it from shipping as two variants.
|
|
112
|
+
if (reasoning.canDisableThinking !== false && !efforts.includes("off")) efforts.unshift("off")
|
|
113
|
+
return { efforts, defaultEffort: text(reasoning.defaultEffort) }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const fixed = text(reasoning.effort)
|
|
117
|
+
if (fixed) return { efforts: [fixed], defaultEffort: fixed }
|
|
118
|
+
return { efforts: [], defaultEffort: null }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Pure parser for the `/v3/config` body. Returns `[]` rather than throwing when
|
|
123
|
+
* the body carries no models — deciding that emptiness is a failure is
|
|
124
|
+
* `fetchCatalog`'s job, not this function's.
|
|
125
|
+
*/
|
|
126
|
+
/** ids a tier blocks for the current account (paywall tiers WorkBuddy hides). */
|
|
127
|
+
function paywallIds(data: Record<string, unknown>): Set<string> {
|
|
128
|
+
const out = new Set<string>()
|
|
129
|
+
if (!Array.isArray(data.modelTiers)) return out
|
|
130
|
+
for (const tier of data.modelTiers as Array<Record<string, unknown>>) {
|
|
131
|
+
if (tier?.accessMode !== "paywall" || !Array.isArray(tier.modelIds)) continue
|
|
132
|
+
for (const id of tier.modelIds) if (typeof id === "string") out.add(id)
|
|
133
|
+
}
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** ids carrying an active-looking promotion (WorkBuddy keeps the free/featured twin). */
|
|
138
|
+
function promotedIds(data: Record<string, unknown>): Set<string> {
|
|
139
|
+
const out = new Set<string>()
|
|
140
|
+
if (!Array.isArray(data.modelPromotions)) return out
|
|
141
|
+
for (const promo of data.modelPromotions as Array<Record<string, unknown>>) {
|
|
142
|
+
if (!Array.isArray(promo?.modelIds)) continue
|
|
143
|
+
for (const id of promo.modelIds) if (typeof id === "string") out.add(id)
|
|
144
|
+
}
|
|
145
|
+
return out
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function parseModelConfig(body: unknown): readonly CatalogModel[] {
|
|
149
|
+
const data = (body as { data?: unknown })?.data as Record<string, unknown> | undefined
|
|
150
|
+
if (!data) return []
|
|
151
|
+
|
|
152
|
+
// Pro-only filtering applies where the gateway sends tier metadata (intl).
|
|
153
|
+
// Credit labels and free-vs-paid de-dup apply to every site: CN also ships a
|
|
154
|
+
// promoted free twin ("Hy4 flash") alongside its paid id.
|
|
155
|
+
const hasTiers = Array.isArray(data.modelTiers)
|
|
156
|
+
const hasPromotions = Array.isArray(data.modelPromotions)
|
|
157
|
+
const blocked = hasTiers ? paywallIds(data) : new Set<string>()
|
|
158
|
+
const promoted = promotedIds(data)
|
|
159
|
+
|
|
160
|
+
const agents = Array.isArray(data.agents)
|
|
161
|
+
? (data.agents as Array<Record<string, unknown>>)
|
|
162
|
+
: Array.isArray((data.agent as { agents?: unknown })?.agents)
|
|
163
|
+
? ((data.agent as { agents: Array<Record<string, unknown>> }).agents)
|
|
164
|
+
: []
|
|
165
|
+
|
|
166
|
+
const cli = agents.find((agent) => agent?.name === "cli")
|
|
167
|
+
const allowed = Array.isArray(cli?.models) ? (cli.models as unknown[]) : []
|
|
168
|
+
if (allowed.length === 0) return []
|
|
169
|
+
|
|
170
|
+
const byId = new Map<string, Record<string, unknown>>()
|
|
171
|
+
if (Array.isArray(data.models)) {
|
|
172
|
+
for (const model of data.models as Array<Record<string, unknown>>) {
|
|
173
|
+
const id = text(model?.id)
|
|
174
|
+
if (id) byId.set(id, model)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const parsed: CatalogModel[] = []
|
|
179
|
+
for (const raw of allowed) {
|
|
180
|
+
if (typeof raw !== "string" || blocked.has(raw)) continue
|
|
181
|
+
const model = byId.get(raw)
|
|
182
|
+
if (!model) continue
|
|
183
|
+
|
|
184
|
+
// A model that declares no capacity at all is not a usable model; the
|
|
185
|
+
// figures themselves are not imported (see model-info's fixed limit).
|
|
186
|
+
if (!declaresCapacity(model.maxInputTokens, model.maxAllowedSize, model.maxOutputTokens)) continue
|
|
187
|
+
|
|
188
|
+
const reasoning =
|
|
189
|
+
model.supportsReasoning === true && model.reasoning !== null && typeof model.reasoning === "object"
|
|
190
|
+
? (model.reasoning as Record<string, unknown>)
|
|
191
|
+
: null
|
|
192
|
+
const { efforts, defaultEffort } = readEfforts(reasoning)
|
|
193
|
+
|
|
194
|
+
parsed.push({
|
|
195
|
+
id: raw,
|
|
196
|
+
name: text(model.name) ?? raw, // base name; credit suffix added after de-dup
|
|
197
|
+
credits: shortCredits(model.credits),
|
|
198
|
+
imageInput: model.supportsImages === true,
|
|
199
|
+
efforts,
|
|
200
|
+
defaultEffort,
|
|
201
|
+
})
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let result = parsed
|
|
205
|
+
if (hasPromotions) {
|
|
206
|
+
// Same display name (e.g. two "Hy4 flash" ids): WorkBuddy keeps the one with
|
|
207
|
+
// an active promotion (the free trial) and drops the paid twin. Compare base
|
|
208
|
+
// names; the credit suffix is appended after de-dup.
|
|
209
|
+
const byName = new Map<string, CatalogModel>()
|
|
210
|
+
for (const model of parsed) {
|
|
211
|
+
const existing = byName.get(model.name)
|
|
212
|
+
if (!existing) { byName.set(model.name, model); continue }
|
|
213
|
+
const takeNew = promoted.has(model.id) && !promoted.has(existing.id)
|
|
214
|
+
if (takeNew) byName.set(model.name, model)
|
|
215
|
+
}
|
|
216
|
+
result = [...byName.values()]
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// WorkBuddy shows the credit multiplier in the picker; match its labels on
|
|
220
|
+
// every site (CN and intl) so the provider mirrors what the client displays.
|
|
221
|
+
return result.map((m) =>
|
|
222
|
+
m.credits !== null ? { ...m, name: `${m.name}(x${m.credits.toFixed(2)})` } : m,
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Fetch and parse the catalog for one API key. Throws on anything that would
|
|
228
|
+
* make the returned list untrustworthy — including the silently-empty response,
|
|
229
|
+
* whose error message names the `CLI/` marker so the cause is not a mystery.
|
|
230
|
+
*/
|
|
231
|
+
export async function fetchCatalog(deps: FetchCatalogDeps): Promise<readonly CatalogModel[]> {
|
|
232
|
+
const fetchImpl = deps.fetchImpl ?? fetch
|
|
233
|
+
const timeout = timeoutSignal(deps.timeoutMs ?? DEFAULT_TIMEOUT_MS)
|
|
234
|
+
const signal = deps.signal ? anySignal([deps.signal, timeout]) : timeout
|
|
235
|
+
const url = `${deps.auth.endpoint}/v3/config`
|
|
236
|
+
|
|
237
|
+
const headers = apiHeaders(deps.auth, { accept: "application/json" })
|
|
238
|
+
// The international gateway serves WorkBuddy's catalogue (with tier/promo
|
|
239
|
+
// metadata) only when the caller identifies as the WorkBuddy IDE. Without
|
|
240
|
+
// these headers it returns the narrower CLI catalogue with no Pro-only info.
|
|
241
|
+
if (deps.site === "intl") {
|
|
242
|
+
headers["x-ide-type"] = "WorkBuddy"
|
|
243
|
+
headers["x-product"] = "WorkBuddy"
|
|
244
|
+
headers["user-agent"] = "WorkBuddy/5.11.4"
|
|
245
|
+
}
|
|
246
|
+
const response = await fetchImpl(url, {
|
|
247
|
+
method: "GET",
|
|
248
|
+
headers,
|
|
249
|
+
signal,
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
if (!response.ok) throw new Error(`catalog HTTP ${response.status}`)
|
|
253
|
+
|
|
254
|
+
const body = (await response.json()) as { code?: number; msg?: string }
|
|
255
|
+
if (body?.code !== 0) throw new Error(`catalog code ${body?.code}: ${body?.msg ?? "unknown"}`)
|
|
256
|
+
|
|
257
|
+
const models = parseModelConfig(body)
|
|
258
|
+
if (models.length === 0) {
|
|
259
|
+
throw new Error(
|
|
260
|
+
"catalog returned no CLI models — the request must carry a `CLI/` marker in its User-Agent",
|
|
261
|
+
)
|
|
262
|
+
}
|
|
263
|
+
return models
|
|
264
|
+
}
|