opencode-codebuddy-quota 0.0.0-stage → 0.1.2

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
@@ -0,0 +1,77 @@
1
+ import { DatabaseSync } from "node:sqlite"
2
+ import { homedir } from "node:os"
3
+ import { join } from "node:path"
4
+ import type { ModelsDevCatalog } from "./pricing"
5
+
6
+ /**
7
+ * Reads the models.dev catalog out of the database OpenCode keeps for itself.
8
+ *
9
+ * The catalog is stored as a `kv` row whose `value` is JSON wrapping a `body`
10
+ * string that is itself JSON — two parses, not one. Everything here is
11
+ * best-effort: a missing database, a schema change, or a locked file must
12
+ * degrade to "no prices" rather than break the plugin.
13
+ */
14
+
15
+ const KV_KEY = "models-dev:v3:catalog"
16
+ const DB_FILE = "opencode.db"
17
+ /** Long enough to ride out another process's write lock, short enough not to stall a transform. */
18
+ const BUSY_TIMEOUT_MS = 2_000
19
+
20
+ /**
21
+ * OpenCode's data directory. Mirrors its own precedence so a relocated install
22
+ * is picked up without configuration.
23
+ */
24
+ export function storageDir(
25
+ env: Record<string, string | undefined> = process.env,
26
+ home: string = homedir(),
27
+ ): string {
28
+ const explicit = env.OPENCODE_STORAGE_DIR
29
+ if (explicit) return explicit
30
+ const xdg = env.XDG_DATA_HOME
31
+ if (xdg) return join(xdg, "opencode")
32
+ return join(home, ".local", "share", "opencode")
33
+ }
34
+
35
+ /** `{ updatedAt, digest, body: "<json>" }` → the catalog. Null if either layer is unparseable. */
36
+ export function parseCatalogValue(value: string): ModelsDevCatalog | null {
37
+ try {
38
+ const outer = JSON.parse(value) as { body?: unknown }
39
+ if (typeof outer?.body !== "string") return null
40
+ const catalog = JSON.parse(outer.body) as unknown
41
+ if (typeof catalog !== "object" || catalog === null) return null
42
+ return catalog as ModelsDevCatalog
43
+ } catch {
44
+ return null
45
+ }
46
+ }
47
+
48
+ export interface ReadCatalogDeps {
49
+ dbPath?: string
50
+ /** Seam for tests: given the database path and kv key, return the raw `kv.value` or null. */
51
+ readValue?: (dbPath: string, key: string) => string | null
52
+ }
53
+
54
+ function readValueFromDatabase(dbPath: string, key: string): string | null {
55
+ // Read-only: the plugin must never write to OpenCode's database.
56
+ const db = new DatabaseSync(dbPath, { readOnly: true })
57
+ try {
58
+ db.exec(`pragma busy_timeout = ${BUSY_TIMEOUT_MS}`)
59
+ const row = db.prepare("select value from kv where key = ?").get(key) as { value?: unknown } | undefined
60
+ return typeof row?.value === "string" ? row.value : null
61
+ } finally {
62
+ db.close()
63
+ }
64
+ }
65
+
66
+ /** The whole models.dev catalog, or null when it cannot be read. Never throws. */
67
+ export function readModelsDevCatalog(deps: ReadCatalogDeps = {}): ModelsDevCatalog | null {
68
+ const dbPath = deps.dbPath ?? join(storageDir(), DB_FILE)
69
+ const read = deps.readValue ?? readValueFromDatabase
70
+ try {
71
+ const value = read(dbPath, KV_KEY)
72
+ if (value === null) return null
73
+ return parseCatalogValue(value)
74
+ } catch {
75
+ return null
76
+ }
77
+ }
@@ -0,0 +1,74 @@
1
+ import type { Site } from "../shared"
2
+
3
+ /** OpenAI's `/models` wire shape. */
4
+ export interface ModelsListEntry {
5
+ id: string
6
+ object: "model"
7
+ created: number
8
+ owned_by: string
9
+ }
10
+
11
+ export interface ModelsListResponse {
12
+ object: "list"
13
+ data: ModelsListEntry[]
14
+ }
15
+
16
+ const OWNED_BY: Readonly<Record<Site, string>> = {
17
+ cn: "codebuddy-cn",
18
+ intl: "codebuddy-intl",
19
+ }
20
+
21
+ export function toModelsList(models: readonly { id: string }[], ownedBy: string): ModelsListResponse {
22
+ return {
23
+ object: "list",
24
+ data: models.map((model) => ({
25
+ id: model.id,
26
+ object: "model",
27
+ // The catalog has no creation timestamps; inventing one would make the
28
+ // endpoint lie to clients that rely on this field, so use the epoch.
29
+ created: 0,
30
+ owned_by: ownedBy,
31
+ })),
32
+ }
33
+ }
34
+
35
+ const TTL_MS = 300_000
36
+
37
+ /**
38
+ * Caches the already-shaped response per site. Refreshing `/v3/config` on every
39
+ * list call would be wasteful and rate-limit the account; five minutes matches
40
+ * how often the provider config is rewritten.
41
+ *
42
+ * The pending promise is what gets stored, replaced once it settles (the same
43
+ * shape `token-store.ts`'s `ensureFresh` uses): N concurrent cold requests share
44
+ * one `/v3/config` fetch, which a rate-limited upstream would otherwise answer
45
+ * with errors. A rejection is never cached, so the next call retries.
46
+ */
47
+ export function createModelsCache(
48
+ fetchModels: (site: Site) => Promise<readonly { id: string }[]>,
49
+ now: () => number = Date.now,
50
+ ): { get(site: Site): Promise<ModelsListResponse> } {
51
+ const entries = new Map<Site, { at: number; value: ModelsListResponse }>()
52
+ const inFlight = new Map<Site, Promise<ModelsListResponse>>()
53
+ return {
54
+ get(site: Site): Promise<ModelsListResponse> {
55
+ const cached = entries.get(site)
56
+ if (cached && now() - cached.at < TTL_MS) return Promise.resolve(cached.value)
57
+ const pending = inFlight.get(site)
58
+ if (pending) return pending
59
+ // Shape once and cache the finished body, not the raw ids, so a cache hit
60
+ // does no mapping work at all.
61
+ const task = fetchModels(site)
62
+ .then((models) => {
63
+ const value = toModelsList(models, OWNED_BY[site])
64
+ entries.set(site, { at: now(), value })
65
+ return value
66
+ })
67
+ .finally(() => {
68
+ inFlight.delete(site)
69
+ })
70
+ inFlight.set(site, task)
71
+ return task
72
+ },
73
+ }
74
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The `@ai-sdk/openai-compatible` spec inside the user's `codebuddy` provider,
3
+ * and validation for the versions that feed it.
4
+ *
5
+ * The provider block itself is the user's: it carries their endpoint, their key
6
+ * reference and anything else they wrote. The plugin only owns the `package`
7
+ * spec, whose version it keeps current.
8
+ */
9
+
10
+ /** New v2 provider ids. The legacy `codebuddy` id is intentionally absent. */
11
+ export const PROVIDER_IDS = ["codebuddy-cn", "codebuddy-intl"] as const
12
+ export type ProviderId = (typeof PROVIDER_IDS)[number]
13
+
14
+ export const PACKAGE_PREFIX = "aisdk:"
15
+ export const PACKAGE_NAME = "@ai-sdk/openai-compatible"
16
+
17
+ /**
18
+ * The version this build was tested against, used when npm cannot be reached.
19
+ * `config.ts` seeds `package_version` with it, and `config.test.ts` keeps that,
20
+ * `config.default.json` and this constant equal.
21
+ */
22
+ export const DEFAULT_PACKAGE_VERSION = "2.0.90"
23
+
24
+ /** A published version and nothing else: `2.0.90`, `2.1.0-rc.1`, `2.1.0+build`. */
25
+ const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
26
+
27
+ export function isVersion(value: unknown): value is string {
28
+ return typeof value === "string" && VERSION_PATTERN.test(value)
29
+ }
30
+
31
+ /**
32
+ * `aisdk:@ai-sdk/openai-compatible@2.0.90`. OpenCode strips the `aisdk:` prefix
33
+ * and resolves the rest as an npm specifier, caching it under `<name>@<version>`
34
+ * — which is why the version has to be spelled out and kept current.
35
+ *
36
+ * Throws on a non-version: this is the last point before the value becomes a
37
+ * spec, and a stray file or empty string must never get this far.
38
+ */
39
+ export function packageSpec(version: string): string {
40
+ if (!isVersion(version)) throw new Error(`not a version: ${JSON.stringify(version)}`)
41
+ return `${PACKAGE_PREFIX}${PACKAGE_NAME}@${version}`
42
+ }
@@ -0,0 +1,51 @@
1
+ import { PACKAGE_NAME, PACKAGE_PREFIX, isVersion, packageSpec } from "./package-spec"
2
+ import { timeoutSignal } from "./signal"
3
+
4
+ /**
5
+ * Looks up the newest `@ai-sdk/openai-compatible` build published under the
6
+ * `ai-v6` dist-tag.
7
+ *
8
+ * OpenCode resolves a bare `@ai-sdk/*` spec through that tag, but it caches the
9
+ * result under `<name>@<version>` and never re-resolves. Writing an explicit
10
+ * version into the config is therefore the only way an upgrade takes effect,
11
+ * which is why this exists rather than letting OpenCode follow the tag.
12
+ */
13
+
14
+ /** The dist-tag OpenCode's own `aisdk:` resolution points at. */
15
+ export const DIST_TAG = "ai-v6"
16
+ export const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}`
17
+
18
+ const DEFAULT_TIMEOUT_MS = 10_000
19
+
20
+ export interface LatestVersionDeps {
21
+ fetchImpl?: typeof fetch
22
+ timeoutMs?: number
23
+ }
24
+
25
+ /** The version the tag points at, or null when the registry cannot be read. Never throws. */
26
+ export async function latestTaggedVersion(deps: LatestVersionDeps = {}): Promise<string | null> {
27
+ const fetchImpl = deps.fetchImpl ?? fetch
28
+ try {
29
+ const response = await fetchImpl(REGISTRY_URL, {
30
+ // The abbreviated doc is enough: it carries dist-tags and is far smaller.
31
+ headers: { accept: "application/vnd.npm.install-v1+json" },
32
+ signal: timeoutSignal(deps.timeoutMs ?? DEFAULT_TIMEOUT_MS),
33
+ })
34
+ if (!response.ok) return null
35
+ const body = (await response.json()) as { "dist-tags"?: Record<string, unknown> }
36
+ const version = body?.["dist-tags"]?.[DIST_TAG]
37
+ return isVersion(version) ? version : null
38
+ } catch {
39
+ return null
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Rewrites the version inside an `aisdk:` provider package spec, or returns
45
+ * null when the spec names some other package. A bare spec gains the version.
46
+ */
47
+ export function withVersion(spec: string, version: string): string | null {
48
+ const prefix = `${PACKAGE_PREFIX}${PACKAGE_NAME}`
49
+ if (spec !== prefix && !spec.startsWith(`${prefix}@`)) return null
50
+ return packageSpec(version)
51
+ }
@@ -0,0 +1,169 @@
1
+ import type { ModelMapping } from "./config"
2
+
3
+ /**
4
+ * Pricing and reasoning levels for a CodeBuddy model, taken from the models.dev
5
+ * catalog that OpenCode keeps locally.
6
+ *
7
+ * Every lookup goes through the user's `models` map: a model is only offered
8
+ * because someone wrote down where it lives, so there is nothing to guess. The
9
+ * same model carries different prices and levels depending on who resells it,
10
+ * which is exactly why the mapping names the provider rather than inferring it.
11
+ */
12
+
13
+ /** models.dev v3 sometimes declares cache.write as per-duration tiers, e.g. {"5m":3,"1h":6}. */
14
+ export type CacheWritePrice = number | Record<string, number>
15
+
16
+ export interface ModelsDevCost {
17
+ text?: {
18
+ input?: { price?: number; cache?: { read?: number; write?: CacheWritePrice } }
19
+ output?: { price?: number }
20
+ }
21
+ }
22
+
23
+ export interface ModelsDevEntry {
24
+ name?: string
25
+ cost?: ModelsDevCost
26
+ capabilities?: {
27
+ reasoning?: {
28
+ supported?: boolean
29
+ toggle?: boolean
30
+ /** Selectable reasoning levels, least to most. */
31
+ effort?: readonly string[]
32
+ /** The level the vendor picks when the caller names none. */
33
+ default?: { type?: string; value?: string } | string
34
+ }
35
+ }
36
+ }
37
+
38
+ /** `{ [providerID]: { models: { [modelID]: entry } } }`, as stored under `models-dev:v3:catalog`. */
39
+ export type ModelsDevCatalog = Record<string, { models?: Record<string, ModelsDevEntry> }>
40
+
41
+ export interface ModelCost {
42
+ input: number
43
+ output: number
44
+ cache: { read: number; write: number }
45
+ }
46
+
47
+ /** What a lookup needs: the models.dev coordinates plus the credit multiplier. */
48
+ export interface PricedModel {
49
+ id: string
50
+ /** Credit multiplier. `0` means the model is free; `null` means the server did not say. */
51
+ credits: number | null
52
+ }
53
+
54
+ const ZERO_COST: ModelCost = { input: 0, output: 0, cache: { read: 0, write: 0 } }
55
+
56
+ /** The models.dev entry a CodeBuddy model maps to, or undefined when unmapped or absent. */
57
+ export function mappingEntry(
58
+ catalog: ModelsDevCatalog | null,
59
+ mapping: ModelMapping | undefined,
60
+ ): ModelsDevEntry | undefined {
61
+ if (!catalog || !mapping) return undefined
62
+ return catalog[mapping.provider]?.models?.[mapping.model]
63
+ }
64
+
65
+ /**
66
+ * Exact id first, then a case-insensitive pass — the server writes
67
+ * `minimax-m3.1-flash` while models.dev writes `MiniMax-M3.1-Flash`.
68
+ *
69
+ * Nothing fuzzier than that: the catalog is full of `-free` siblings
70
+ * (`step-5-preview-free`, `hy3-free`, …) that price at zero, so a prefix or
71
+ * substring match would quietly report those instead of the paid model.
72
+ */
73
+ export function findEntry(
74
+ catalog: ModelsDevCatalog,
75
+ provider: string,
76
+ modelID: string,
77
+ ): ModelsDevEntry | undefined {
78
+ const models = catalog[provider]?.models
79
+ if (!models) return undefined
80
+
81
+ const exact = models[modelID]
82
+ if (exact) return exact
83
+
84
+ const lowered = modelID.toLowerCase()
85
+ for (const [id, entry] of Object.entries(models)) {
86
+ if (id.toLowerCase() === lowered) return entry
87
+ }
88
+ return undefined
89
+ }
90
+
91
+ /** Only a finite number is a usable price; tier objects and strings fall back to zero. */
92
+ function finitePrice(value: unknown): number {
93
+ return typeof value === "number" && Number.isFinite(value) ? value : 0
94
+ }
95
+
96
+ function toCost(entry: ModelsDevEntry): ModelCost | null {
97
+ const text = entry.cost?.text
98
+ const input = text?.input?.price
99
+ const output = text?.output?.price
100
+ if (typeof input !== "number" || typeof output !== "number") return null
101
+ return {
102
+ input,
103
+ output,
104
+ // Most catalog entries omit cache.write; some v3 entries declare it as a
105
+ // per-duration tier object. Neither is a usable scalar, so fall back to zero.
106
+ cache: {
107
+ read: finitePrice(text?.input?.cache?.read),
108
+ write: finitePrice(text?.input?.cache?.write),
109
+ },
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Resolve a model's price, returning `[]` when no price can be trusted — an
115
+ * unpriced model is better than a wrong one.
116
+ */
117
+ export function resolveCost(
118
+ model: PricedModel,
119
+ mapping: ModelMapping | undefined,
120
+ catalog: ModelsDevCatalog | null,
121
+ log: (message: string) => void,
122
+ ): ModelCost[] {
123
+ // Checked before any lookup: a free model needs no price, and looking one up
124
+ // would contradict the credit factor the server reported.
125
+ if (model.credits === 0) return [ZERO_COST]
126
+
127
+ if (!catalog) {
128
+ log(`models.dev catalog unavailable; ${model.id} stays unpriced`)
129
+ return []
130
+ }
131
+ if (!mapping) {
132
+ log(`${model.id} has no models.dev mapping; leaving it unpriced`)
133
+ return []
134
+ }
135
+
136
+ const entry = findEntry(catalog, mapping.provider, mapping.model)
137
+ if (!entry) {
138
+ log(`${mapping.provider} has no entry for ${mapping.model} (${model.id}); leaving it unpriced`)
139
+ return []
140
+ }
141
+ const cost = toCost(entry)
142
+ if (!cost) {
143
+ log(`${mapping.provider}/${mapping.model} has no text pricing; ${model.id} stays unpriced`)
144
+ return []
145
+ }
146
+ return [cost]
147
+ }
148
+
149
+ /**
150
+ * The vendor's own reasoning levels for a model, or null when models.dev has
151
+ * none for it. CodeBuddy's gateway rewrites some of these (it swaps `max` for
152
+ * `xhigh` on `deepseek-v4-pro`, for instance), but the vendor table is the
153
+ * source of record here.
154
+ */
155
+ export function vendorEfforts(
156
+ mapping: ModelMapping | undefined,
157
+ catalog: ModelsDevCatalog | null,
158
+ ): { efforts: string[]; defaultEffort: string | null } | null {
159
+ const reasoning = mappingEntry(catalog, mapping)?.capabilities?.reasoning
160
+ const efforts = reasoning?.effort
161
+ if (!efforts || efforts.length === 0) return null
162
+
163
+ const declared = typeof reasoning.default === "string" ? reasoning.default : reasoning.default?.value ?? null
164
+ return {
165
+ efforts: [...efforts],
166
+ // Only honour a vendor default that is actually one of its levels.
167
+ defaultEffort: declared && efforts.includes(declared) ? declared : null,
168
+ }
169
+ }