opencode-codebuddy-quota 0.1.0 → 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.
- package/config.default.json +41 -38
- package/package.json +2 -1
- package/rpc.ts +92 -92
- package/server.ts +132 -17
- package/src/gui/battery.tsx +81 -81
- package/src/gui/pace.ts +76 -76
- package/src/gui/quota.ts +198 -198
- package/src/gui/store.ts +181 -181
- package/src/gui.tsx +111 -111
- package/src/server/catalog.ts +264 -264
- package/src/server/config-writer.ts +621 -621
- package/src/server/config.ts +215 -195
- package/src/server/embedding-local.ts +166 -0
- package/src/server/embedding-mode.ts +14 -0
- package/src/server/gateway-owner.ts +243 -0
- package/src/server/gateway-setup.ts +51 -0
- package/src/server/logger.ts +26 -26
- package/src/server/model-cache.ts +136 -0
- package/src/server/model-info.ts +109 -109
- package/src/server/model-prewarm.ts +123 -0
- package/src/server/models-dev.ts +77 -77
- package/src/server/models-endpoint.ts +74 -0
- package/src/server/package-spec.ts +42 -42
- package/src/server/package-version.ts +51 -51
- package/src/server/pricing.ts +169 -169
- package/src/server/proxy.ts +335 -7
- package/src/server/stream-collect.ts +166 -0
- package/src/server/wire.ts +67 -67
package/src/server/model-info.ts
CHANGED
|
@@ -1,109 +1,109 @@
|
|
|
1
|
-
import type { CatalogModel } from "./catalog"
|
|
2
|
-
import type { QuotaConfig } from "./config"
|
|
3
|
-
import { resolveCost, vendorEfforts, type ModelCost, type ModelsDevCatalog } from "./pricing"
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Turns the CodeBuddy catalog into the shape a provider needs: models filtered
|
|
7
|
-
* down to the ones the user mapped, priced, and renamed where two of them would
|
|
8
|
-
* otherwise be indistinguishable in a model picker.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
export interface ImportedModel {
|
|
12
|
-
id: string
|
|
13
|
-
name: string
|
|
14
|
-
cost: ModelCost[]
|
|
15
|
-
limit: { context: number; output: number }
|
|
16
|
-
imageInput: boolean
|
|
17
|
-
efforts: readonly string[]
|
|
18
|
-
defaultEffort: string | null
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface BuildModelsDeps {
|
|
22
|
-
catalog: readonly CatalogModel[]
|
|
23
|
-
config: QuotaConfig
|
|
24
|
-
modelsDev: ModelsDevCatalog | null
|
|
25
|
-
log: (message: string) => void
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* One size for every model, regardless of what either the server or models.dev
|
|
30
|
-
* declares. CodeBuddy bills the same credits per token whatever the model's
|
|
31
|
-
* nominal window, so per-model limits only made the picker lie about capacity.
|
|
32
|
-
*/
|
|
33
|
-
const LIMIT = { context: 500_000, output: 64_000 } as const
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* The catalog declares `Hy4 flash` twice (free and paid) and `Hy4` once. Only
|
|
37
|
-
* where names collide *after* exclusions are applied does the credit factor get
|
|
38
|
-
* appended, so a model that happens to be unique keeps its clean name.
|
|
39
|
-
*
|
|
40
|
-
* A colliding model whose factor the server never declared keeps its bare name
|
|
41
|
-
* rather than rendering "Hy4 flash(undefined)".
|
|
42
|
-
*/
|
|
43
|
-
function dedupeNames(models: readonly ImportedModel[], credits: ReadonlyMap<string, number | null>): ImportedModel[] {
|
|
44
|
-
const counts = new Map<string, number>()
|
|
45
|
-
for (const model of models) counts.set(model.name, (counts.get(model.name) ?? 0) + 1)
|
|
46
|
-
|
|
47
|
-
return models.map((model) => {
|
|
48
|
-
if ((counts.get(model.name) ?? 0) < 2) return model
|
|
49
|
-
// catalog.ts may already have appended a credit label; never stack a second.
|
|
50
|
-
// Tolerate case/space variants. Known limit: an upstream name that genuinely
|
|
51
|
-
// ends in "(xN)" would be skipped here too — acceptable while catalog.ts is
|
|
52
|
-
// the only producer of such labels and marks them this way.
|
|
53
|
-
if (/\(\s*[xX]\s*[\d.]+\)\s*$/.test(model.name)) return model
|
|
54
|
-
|
|
55
|
-
const factor = credits.get(model.id)
|
|
56
|
-
if (factor === null || factor === undefined) return model
|
|
57
|
-
return { ...model, name: `${model.name}(x${factor.toFixed(2)})` }
|
|
58
|
-
})
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function buildModels(deps: BuildModelsDeps): readonly ImportedModel[] {
|
|
62
|
-
const { config, modelsDev, log } = deps
|
|
63
|
-
const excluded = new Set(config.excluded_models)
|
|
64
|
-
|
|
65
|
-
// A model the user has not mapped is not offered at all: without a models.dev
|
|
66
|
-
// entry there is no price and no vendor reasoning table, and guessing either
|
|
67
|
-
// would put a model in the picker that cannot be described correctly.
|
|
68
|
-
const kept: CatalogModel[] = []
|
|
69
|
-
for (const model of deps.catalog) {
|
|
70
|
-
if (excluded.has(model.id)) continue
|
|
71
|
-
if (!config.models[model.id]) {
|
|
72
|
-
log(`${model.id} has no models entry in codebuddy-quota.json; not offered`)
|
|
73
|
-
continue
|
|
74
|
-
}
|
|
75
|
-
kept.push(model)
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
const built = kept.map<ImportedModel>((model) => {
|
|
79
|
-
const mapping = config.models[model.id]
|
|
80
|
-
// Vendor levels win over whatever the gateway advertises. A model models.dev
|
|
81
|
-
// knows nothing about keeps the server's levels rather than losing the
|
|
82
|
-
// ability to reason at all.
|
|
83
|
-
const vendor = vendorEfforts(mapping, modelsDev)
|
|
84
|
-
const efforts = vendor ? vendor.efforts : model.efforts
|
|
85
|
-
const defaultEffort = vendor
|
|
86
|
-
? // The vendor's own pick wins; without one, the gateway's if it exists in
|
|
87
|
-
// the vendor table, else the heaviest level so a selection is valid.
|
|
88
|
-
vendor.defaultEffort ??
|
|
89
|
-
(vendor.efforts.includes(model.defaultEffort ?? "")
|
|
90
|
-
? model.defaultEffort
|
|
91
|
-
: vendor.efforts[vendor.efforts.length - 1])
|
|
92
|
-
: model.defaultEffort
|
|
93
|
-
|
|
94
|
-
return {
|
|
95
|
-
id: model.id,
|
|
96
|
-
name: model.name,
|
|
97
|
-
cost: resolveCost(model, mapping, modelsDev, log),
|
|
98
|
-
limit: { context: LIMIT.context, output: LIMIT.output },
|
|
99
|
-
imageInput: model.imageInput,
|
|
100
|
-
efforts,
|
|
101
|
-
defaultEffort,
|
|
102
|
-
}
|
|
103
|
-
})
|
|
104
|
-
|
|
105
|
-
const credits = new Map(kept.map((model) => [model.id, model.credits]))
|
|
106
|
-
// Sorted by id so the picker is stable no matter what order the server sends.
|
|
107
|
-
const sorted = [...built].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
108
|
-
return dedupeNames(sorted, credits)
|
|
109
|
-
}
|
|
1
|
+
import type { CatalogModel } from "./catalog"
|
|
2
|
+
import type { QuotaConfig } from "./config"
|
|
3
|
+
import { resolveCost, vendorEfforts, type ModelCost, type ModelsDevCatalog } from "./pricing"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Turns the CodeBuddy catalog into the shape a provider needs: models filtered
|
|
7
|
+
* down to the ones the user mapped, priced, and renamed where two of them would
|
|
8
|
+
* otherwise be indistinguishable in a model picker.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface ImportedModel {
|
|
12
|
+
id: string
|
|
13
|
+
name: string
|
|
14
|
+
cost: ModelCost[]
|
|
15
|
+
limit: { context: number; output: number }
|
|
16
|
+
imageInput: boolean
|
|
17
|
+
efforts: readonly string[]
|
|
18
|
+
defaultEffort: string | null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface BuildModelsDeps {
|
|
22
|
+
catalog: readonly CatalogModel[]
|
|
23
|
+
config: QuotaConfig
|
|
24
|
+
modelsDev: ModelsDevCatalog | null
|
|
25
|
+
log: (message: string) => void
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* One size for every model, regardless of what either the server or models.dev
|
|
30
|
+
* declares. CodeBuddy bills the same credits per token whatever the model's
|
|
31
|
+
* nominal window, so per-model limits only made the picker lie about capacity.
|
|
32
|
+
*/
|
|
33
|
+
const LIMIT = { context: 500_000, output: 64_000 } as const
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The catalog declares `Hy4 flash` twice (free and paid) and `Hy4` once. Only
|
|
37
|
+
* where names collide *after* exclusions are applied does the credit factor get
|
|
38
|
+
* appended, so a model that happens to be unique keeps its clean name.
|
|
39
|
+
*
|
|
40
|
+
* A colliding model whose factor the server never declared keeps its bare name
|
|
41
|
+
* rather than rendering "Hy4 flash(undefined)".
|
|
42
|
+
*/
|
|
43
|
+
function dedupeNames(models: readonly ImportedModel[], credits: ReadonlyMap<string, number | null>): ImportedModel[] {
|
|
44
|
+
const counts = new Map<string, number>()
|
|
45
|
+
for (const model of models) counts.set(model.name, (counts.get(model.name) ?? 0) + 1)
|
|
46
|
+
|
|
47
|
+
return models.map((model) => {
|
|
48
|
+
if ((counts.get(model.name) ?? 0) < 2) return model
|
|
49
|
+
// catalog.ts may already have appended a credit label; never stack a second.
|
|
50
|
+
// Tolerate case/space variants. Known limit: an upstream name that genuinely
|
|
51
|
+
// ends in "(xN)" would be skipped here too — acceptable while catalog.ts is
|
|
52
|
+
// the only producer of such labels and marks them this way.
|
|
53
|
+
if (/\(\s*[xX]\s*[\d.]+\)\s*$/.test(model.name)) return model
|
|
54
|
+
|
|
55
|
+
const factor = credits.get(model.id)
|
|
56
|
+
if (factor === null || factor === undefined) return model
|
|
57
|
+
return { ...model, name: `${model.name}(x${factor.toFixed(2)})` }
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function buildModels(deps: BuildModelsDeps): readonly ImportedModel[] {
|
|
62
|
+
const { config, modelsDev, log } = deps
|
|
63
|
+
const excluded = new Set(config.excluded_models)
|
|
64
|
+
|
|
65
|
+
// A model the user has not mapped is not offered at all: without a models.dev
|
|
66
|
+
// entry there is no price and no vendor reasoning table, and guessing either
|
|
67
|
+
// would put a model in the picker that cannot be described correctly.
|
|
68
|
+
const kept: CatalogModel[] = []
|
|
69
|
+
for (const model of deps.catalog) {
|
|
70
|
+
if (excluded.has(model.id)) continue
|
|
71
|
+
if (!config.models[model.id]) {
|
|
72
|
+
log(`${model.id} has no models entry in codebuddy-quota.json; not offered`)
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
kept.push(model)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const built = kept.map<ImportedModel>((model) => {
|
|
79
|
+
const mapping = config.models[model.id]
|
|
80
|
+
// Vendor levels win over whatever the gateway advertises. A model models.dev
|
|
81
|
+
// knows nothing about keeps the server's levels rather than losing the
|
|
82
|
+
// ability to reason at all.
|
|
83
|
+
const vendor = vendorEfforts(mapping, modelsDev)
|
|
84
|
+
const efforts = vendor ? vendor.efforts : model.efforts
|
|
85
|
+
const defaultEffort = vendor
|
|
86
|
+
? // The vendor's own pick wins; without one, the gateway's if it exists in
|
|
87
|
+
// the vendor table, else the heaviest level so a selection is valid.
|
|
88
|
+
vendor.defaultEffort ??
|
|
89
|
+
(vendor.efforts.includes(model.defaultEffort ?? "")
|
|
90
|
+
? model.defaultEffort
|
|
91
|
+
: vendor.efforts[vendor.efforts.length - 1])
|
|
92
|
+
: model.defaultEffort
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
id: model.id,
|
|
96
|
+
name: model.name,
|
|
97
|
+
cost: resolveCost(model, mapping, modelsDev, log),
|
|
98
|
+
limit: { context: LIMIT.context, output: LIMIT.output },
|
|
99
|
+
imageInput: model.imageInput,
|
|
100
|
+
efforts,
|
|
101
|
+
defaultEffort,
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
const credits = new Map(kept.map((model) => [model.id, model.credits]))
|
|
106
|
+
// Sorted by id so the picker is stable no matter what order the server sends.
|
|
107
|
+
const sorted = [...built].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
|
108
|
+
return dedupeNames(sorted, credits)
|
|
109
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync, unlinkSync } from "node:fs"
|
|
2
|
+
import { join, sep } from "node:path"
|
|
3
|
+
import { MODEL_CACHE_DIR, type LocalEmbedding } from "./embedding-local"
|
|
4
|
+
import {
|
|
5
|
+
fetchOfficialHashes,
|
|
6
|
+
FLAGS_VERSION,
|
|
7
|
+
readReadyFlag,
|
|
8
|
+
sha256Of,
|
|
9
|
+
verifyCache,
|
|
10
|
+
writeReadyFlag,
|
|
11
|
+
type ReadyFlag,
|
|
12
|
+
} from "./model-cache"
|
|
13
|
+
|
|
14
|
+
export interface PrewarmDeps {
|
|
15
|
+
model: string
|
|
16
|
+
/** Must trigger the real (memoised) build and resolve to the ready embedder. */
|
|
17
|
+
build: () => Promise<LocalEmbedding>
|
|
18
|
+
/**
|
|
19
|
+
* Invoked after bad files are deleted, before the rebuild. Lets the builder
|
|
20
|
+
* drop any memoised pipeline that would otherwise skip the re-download.
|
|
21
|
+
*/
|
|
22
|
+
onCacheRepair?: () => void
|
|
23
|
+
fetchImpl?: typeof fetch
|
|
24
|
+
cacheDir?: string
|
|
25
|
+
listFiles?: (dir: string) => string[]
|
|
26
|
+
hashFile?: (path: string) => string
|
|
27
|
+
log?: (s: string) => void
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Remove only the files the Hub disagrees with. A missing path is not a failure. */
|
|
31
|
+
function deleteBadFiles(paths: string[], log: (s: string) => void): void {
|
|
32
|
+
for (const path of paths) {
|
|
33
|
+
try {
|
|
34
|
+
unlinkSync(path)
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
37
|
+
log(`[local-embedding-prewarm] could not delete ${path}: ${String(error)}`)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A flag is a performance hint; failing to persist it must not fail prewarm. */
|
|
44
|
+
function saveFlag(flag: ReadyFlag, cacheDir: string, log: (s: string) => void): void {
|
|
45
|
+
try {
|
|
46
|
+
writeReadyFlag(flag, { cacheDir })
|
|
47
|
+
} catch (error) {
|
|
48
|
+
log(`[local-embedding-prewarm] could not write ready flag: ${String(error)}`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Warm the local model cache before serving requests: verify against the Hub,
|
|
54
|
+
* download via `build`, and only then persist a ready flag. A corrupt cache is
|
|
55
|
+
* repaired once (bad files deleted, then rebuilt); if it still does not verify,
|
|
56
|
+
* the already-built embedder is returned so requests still work but the flag is
|
|
57
|
+
* left absent so the next process retries. Failures are logged and rethrown for
|
|
58
|
+
* the caller to swallow — prewarm never blocks startup.
|
|
59
|
+
*/
|
|
60
|
+
export async function warmLocalModel(deps: PrewarmDeps): Promise<LocalEmbedding> {
|
|
61
|
+
const cacheDir = deps.cacheDir ?? MODEL_CACHE_DIR
|
|
62
|
+
const log = deps.log ?? console.warn
|
|
63
|
+
// `readdirSync` with `recursive` yields paths relative to `dir`. Two seams
|
|
64
|
+
// are needed to match the Hub's nested `rfilename` keys exactly: drop directory
|
|
65
|
+
// entries (which `verifyCache` would mistake for stray files) and use forward
|
|
66
|
+
// slashes on Windows, where `readdirSync` emits `\` but the Hub emits `/`.
|
|
67
|
+
const listFiles =
|
|
68
|
+
deps.listFiles ??
|
|
69
|
+
((dir: string) =>
|
|
70
|
+
readdirSync(dir, { recursive: true, withFileTypes: false, encoding: "utf8" })
|
|
71
|
+
.filter((rel) => {
|
|
72
|
+
try {
|
|
73
|
+
return statSync(join(dir, rel)).isFile()
|
|
74
|
+
} catch {
|
|
75
|
+
return false
|
|
76
|
+
}
|
|
77
|
+
})
|
|
78
|
+
.map((rel) => (sep === "/" ? rel : rel.split(sep).join("/"))))
|
|
79
|
+
const hashFile = deps.hashFile ?? ((path: string) => sha256Of(readFileSync(path)))
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
// A previously verified flag for this same model means transformers.js
|
|
83
|
+
// reads straight from its FS cache: no Hub lookup, no re-hashing, just
|
|
84
|
+
// trigger the local build. A flag naming another model is stale — the
|
|
85
|
+
// configured model changed — so fall through and verify the new one.
|
|
86
|
+
const readyFlag = readReadyFlag({ cacheDir })
|
|
87
|
+
if (readyFlag && readyFlag.model === deps.model) {
|
|
88
|
+
return await deps.build()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const official = await fetchOfficialHashes(deps.model, { fetchImpl: deps.fetchImpl })
|
|
92
|
+
let embedder = await deps.build()
|
|
93
|
+
|
|
94
|
+
const flag: ReadyFlag = {
|
|
95
|
+
version: FLAGS_VERSION,
|
|
96
|
+
model: deps.model,
|
|
97
|
+
revision: official.revision,
|
|
98
|
+
hashes: official.hashes,
|
|
99
|
+
}
|
|
100
|
+
const verify = () =>
|
|
101
|
+
verifyCache({ cacheDir, model: deps.model, official: official.hashes, listFiles, hashFile })
|
|
102
|
+
|
|
103
|
+
let result = verify()
|
|
104
|
+
if (!result.ok) {
|
|
105
|
+
deleteBadFiles(result.badFiles, log)
|
|
106
|
+
// A memoised embedder points at the files just deleted; without this the
|
|
107
|
+
// rebuild would reuse it and re-verification could never recover.
|
|
108
|
+
deps.onCacheRepair?.()
|
|
109
|
+
embedder = await deps.build()
|
|
110
|
+
result = verify()
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (result.ok) {
|
|
114
|
+
saveFlag(flag, cacheDir, log)
|
|
115
|
+
} else {
|
|
116
|
+
log(`[local-embedding-prewarm] verification failed after retry for ${deps.model}; ready flag not written`)
|
|
117
|
+
}
|
|
118
|
+
return embedder
|
|
119
|
+
} catch (error) {
|
|
120
|
+
log(`[local-embedding-prewarm] prewarm failed for ${deps.model}: ${String(error)}`)
|
|
121
|
+
throw error
|
|
122
|
+
}
|
|
123
|
+
}
|
package/src/server/models-dev.ts
CHANGED
|
@@ -1,77 +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
|
-
}
|
|
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
|
+
}
|
|
@@ -1,42 +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
|
-
}
|
|
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
|
+
}
|