opencode-model-costs 0.0.0-stage → 0.5.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/CHANGELOG.md +91 -0
- package/LICENSE +21 -0
- package/README.md +86 -2
- package/package.json +39 -4
- package/src/costs.ts +540 -0
- package/src/index.ts +17 -0
- package/src/tui.tsx +898 -0
package/src/costs.ts
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Data layer for opencode-model-costs.
|
|
3
|
+
*
|
|
4
|
+
* Reads pricing and authoring facts through OpenCode's client. V2 exposes
|
|
5
|
+
* effective model data through model.list() and provider.list(). Older
|
|
6
|
+
* clients can supply the same data via config.providers().
|
|
7
|
+
*
|
|
8
|
+
* config.get() identifies the declared models and explicit price overrides.
|
|
9
|
+
* When any provider is declared, the browser lists only declared models.
|
|
10
|
+
* A successful read with no declarations lets the browser show the configured
|
|
11
|
+
* catalog. A failed config read leaves the scope unknown.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export interface CostTier {
|
|
15
|
+
/** When set, this price applies to prompts over `size` context tokens. */
|
|
16
|
+
tier?: { type: "context"; size: number }
|
|
17
|
+
/** USD per million input tokens. */
|
|
18
|
+
input?: number
|
|
19
|
+
/** USD per million output tokens. */
|
|
20
|
+
output?: number
|
|
21
|
+
cache?: { read?: number; write?: number }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ModelRow {
|
|
25
|
+
providerID: string
|
|
26
|
+
providerName: string
|
|
27
|
+
/** Provider provenance as reported by the server: "config" | "env" | "custom" | "api". */
|
|
28
|
+
providerSource?: string
|
|
29
|
+
modelID: string
|
|
30
|
+
modelName?: string
|
|
31
|
+
variantIDs: string[]
|
|
32
|
+
/** Normalized cost tiers, ascending by context threshold. Empty = no cost info at all. */
|
|
33
|
+
tiers: CostTier[]
|
|
34
|
+
/** The model is declared under `providers.*.models.*` in opencode.json(c). */
|
|
35
|
+
declaredInConfig: boolean
|
|
36
|
+
/** The `cost` field itself was authored in opencode.json(c). */
|
|
37
|
+
costFromConfig: boolean
|
|
38
|
+
contextLimit?: number
|
|
39
|
+
isDefault: boolean
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface CostData {
|
|
43
|
+
rows: ModelRow[]
|
|
44
|
+
/** True when at least one provider/model is authored in opencode.json(c). */
|
|
45
|
+
hasAuthoredConfig: boolean
|
|
46
|
+
configUnavailable?: boolean
|
|
47
|
+
providerPricesUnavailable?: boolean
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ---------------------------------------------------------------------------
|
|
51
|
+
// Server access
|
|
52
|
+
// ---------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
/** Unwraps hey-api `RequestResult` ({ data, error }) or passes plain values through. */
|
|
55
|
+
function unwrapResult(result: any): any {
|
|
56
|
+
if (result && typeof result === "object" && ("data" in result || "error" in result)) {
|
|
57
|
+
if (result.error) throw new Error(errorText(result.error))
|
|
58
|
+
return result.data
|
|
59
|
+
}
|
|
60
|
+
return result
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function errorText(error: unknown): string {
|
|
64
|
+
if (typeof error === "string") return error
|
|
65
|
+
const anyError = error as any
|
|
66
|
+
const message = anyError?.message ?? anyError?.detail ?? anyError
|
|
67
|
+
return typeof message === "string" ? message : String(error)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Generated SDK methods differ in whether they require an input object. */
|
|
71
|
+
async function callFlexible(fn: (...args: any[]) => any, location?: { directory: string }): Promise<any> {
|
|
72
|
+
try {
|
|
73
|
+
return await fn(location ? { location } : {})
|
|
74
|
+
} catch {
|
|
75
|
+
return await fn()
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function tryRead(api: any, method: string, location?: { directory: string }): Promise<any> {
|
|
80
|
+
try {
|
|
81
|
+
const read = api?.[method]
|
|
82
|
+
if (typeof read === "function") return unwrapResult(await callFlexible(read.bind(api), location))
|
|
83
|
+
} catch {
|
|
84
|
+
// A missing or failed endpoint must not prevent the remaining reads.
|
|
85
|
+
}
|
|
86
|
+
return undefined
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function tryProvidersPayload(client: any, location?: { directory: string }): Promise<{
|
|
90
|
+
providers: any[]
|
|
91
|
+
default?: Record<string, string>
|
|
92
|
+
} | undefined> {
|
|
93
|
+
const legacy = await tryRead(client?.config, "providers", location)
|
|
94
|
+
if (Array.isArray(legacy?.providers)) return legacy
|
|
95
|
+
|
|
96
|
+
const [models, providers] = await Promise.all([
|
|
97
|
+
tryRead(client?.model, "list", location),
|
|
98
|
+
tryRead(client?.provider, "list", location),
|
|
99
|
+
])
|
|
100
|
+
if (!Array.isArray(models)) return undefined
|
|
101
|
+
|
|
102
|
+
const groups = new Map<string, { id: string; name?: string; models: Record<string, unknown> }>()
|
|
103
|
+
const names = new Map<string, string>()
|
|
104
|
+
for (const provider of Array.isArray(providers) ? providers : []) {
|
|
105
|
+
if (typeof provider?.id === "string" && typeof provider.name === "string") names.set(provider.id, provider.name)
|
|
106
|
+
}
|
|
107
|
+
for (const model of models) {
|
|
108
|
+
const providerID = str(model?.providerID)
|
|
109
|
+
const modelID = str(model?.id) ?? str(model?.modelID)
|
|
110
|
+
if (!providerID || !modelID || model.enabled === false) continue
|
|
111
|
+
const group = groups.get(providerID) ?? { id: providerID, name: names.get(providerID), models: Object.create(null) }
|
|
112
|
+
group.models[modelID] = model
|
|
113
|
+
groups.set(providerID, group)
|
|
114
|
+
}
|
|
115
|
+
return { providers: [...groups.values()] }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Returns config documents, lowest → highest priority. Older servers return a single merged config object. */
|
|
119
|
+
async function tryConfigDocuments(client: any, location?: { directory: string }): Promise<any[] | undefined> {
|
|
120
|
+
const data = await tryRead(client?.config, "get", location)
|
|
121
|
+
if (Array.isArray(data)) {
|
|
122
|
+
return data.filter((entry: any) => entry?.type === "document" && entry.info && typeof entry.info === "object")
|
|
123
|
+
}
|
|
124
|
+
if (data && typeof data === "object") return [{ type: "document", info: data }]
|
|
125
|
+
return undefined
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Switches the current session to the given model via the server
|
|
130
|
+
* (`POST /api/session/{sessionID}/model`, operation id `session.switchModel`,
|
|
131
|
+
* body `{ model: { providerID, id } }`). Uses the typed client method when
|
|
132
|
+
* available and falls back to the underlying request client otherwise.
|
|
133
|
+
*/
|
|
134
|
+
export async function switchSessionModel(client: unknown, sessionID: string, row: ModelRow, variant?: string): Promise<void> {
|
|
135
|
+
const anyClient = client as any
|
|
136
|
+
const model = { providerID: row.providerID, id: row.modelID, variant }
|
|
137
|
+
|
|
138
|
+
const typed = anyClient?.session?.switchModel
|
|
139
|
+
if (typeof typed === "function") {
|
|
140
|
+
unwrapResult(await typed.call(anyClient.session, { sessionID, model }))
|
|
141
|
+
return
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const raw = anyClient?.client // hey-api request client inside OpencodeClient
|
|
145
|
+
if (raw && typeof raw.post === "function") {
|
|
146
|
+
const body = { model }
|
|
147
|
+
try {
|
|
148
|
+
unwrapResult(await raw.post({ url: `/api/session/${encodeURIComponent(sessionID)}/model`, body }))
|
|
149
|
+
return
|
|
150
|
+
} catch {
|
|
151
|
+
unwrapResult(await raw.post({ url: `/session/${encodeURIComponent(sessionID)}/model`, body }))
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
throw new Error("This OpenCode version does not expose the session model-switch API. Update OpenCode and try again.")
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
// Collection
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
export async function fetchCostData(client: unknown, location?: { directory: string }): Promise<CostData> {
|
|
164
|
+
const anyClient = client as any
|
|
165
|
+
const [payload, documents] = await Promise.all([tryProvidersPayload(anyClient, location), tryConfigDocuments(anyClient, location)])
|
|
166
|
+
if (!documents) return { rows: [], hasAuthoredConfig: false, configUnavailable: true }
|
|
167
|
+
|
|
168
|
+
const authored = collectAuthored(documents)
|
|
169
|
+
const authoredDefault = collectAuthoredDefault(documents)
|
|
170
|
+
const strict = authored.size > 0 // only models declared in opencode.json(c)
|
|
171
|
+
|
|
172
|
+
const rows: ModelRow[] = []
|
|
173
|
+
const seen = new Set<string>()
|
|
174
|
+
|
|
175
|
+
for (const provider of payload?.providers ?? []) {
|
|
176
|
+
const providerID = str(provider?.id)
|
|
177
|
+
if (!providerID) continue
|
|
178
|
+
const authoredProvider = authored.get(providerID)
|
|
179
|
+
if (strict && !authoredProvider) continue
|
|
180
|
+
|
|
181
|
+
const providerName = str(provider?.name) || authoredProvider?.name || providerID
|
|
182
|
+
const providerSource = str(provider?.source)
|
|
183
|
+
const models = provider?.models && typeof provider.models === "object" ? provider.models : {}
|
|
184
|
+
const wanted = authoredProvider ? authoredProvider.models.keys() : Object.keys(models)
|
|
185
|
+
|
|
186
|
+
for (const modelID of wanted) {
|
|
187
|
+
const authoredCost = authoredProvider?.models.get(modelID)
|
|
188
|
+
const key = `${providerID}/${modelID}`
|
|
189
|
+
if (seen.has(key)) continue
|
|
190
|
+
seen.add(key)
|
|
191
|
+
|
|
192
|
+
const model = models[modelID]
|
|
193
|
+
// The server fills omitted cache fields with zero. Preserve the authored
|
|
194
|
+
// shape when a rate was configured so an omitted field stays unavailable.
|
|
195
|
+
const cost = authoredCost ?? model?.cost
|
|
196
|
+
rows.push(
|
|
197
|
+
makeRow({
|
|
198
|
+
providerID,
|
|
199
|
+
providerName,
|
|
200
|
+
providerSource,
|
|
201
|
+
modelID,
|
|
202
|
+
modelName: str(model?.name),
|
|
203
|
+
variants: model?.variants,
|
|
204
|
+
cost,
|
|
205
|
+
declaredInConfig: strict,
|
|
206
|
+
costFromConfig: authoredCost != null,
|
|
207
|
+
contextLimit: model?.limit?.context,
|
|
208
|
+
}),
|
|
209
|
+
)
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Declared models the active-provider payload does not know about
|
|
214
|
+
// (inactive provider, disabled model, ID typo) — show the authored cost.
|
|
215
|
+
for (const [providerID, info] of authored) {
|
|
216
|
+
const providerName = info.name || providerID
|
|
217
|
+
for (const [modelID, authoredCost] of info.models) {
|
|
218
|
+
const key = `${providerID}/${modelID}`
|
|
219
|
+
if (seen.has(key)) continue
|
|
220
|
+
seen.add(key)
|
|
221
|
+
rows.push(
|
|
222
|
+
makeRow({
|
|
223
|
+
providerID,
|
|
224
|
+
providerName,
|
|
225
|
+
providerSource: "config",
|
|
226
|
+
modelID,
|
|
227
|
+
cost: authoredCost,
|
|
228
|
+
declaredInConfig: true,
|
|
229
|
+
costFromConfig: authoredCost != null,
|
|
230
|
+
}),
|
|
231
|
+
)
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const defaultSelector = authoredDefault ?? payloadDefaultSelector(payload)
|
|
236
|
+
if (defaultSelector) {
|
|
237
|
+
for (const row of rows) {
|
|
238
|
+
row.isDefault = row.providerID === defaultSelector.providerID && row.modelID === defaultSelector.modelID
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
rows.sort(compareRows)
|
|
243
|
+
return { rows, hasAuthoredConfig: strict, providerPricesUnavailable: !payload }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function variantIDs(variants: unknown): string[] {
|
|
247
|
+
const ids = Array.isArray(variants)
|
|
248
|
+
? variants.map((variant) => str(variant?.id) ?? str(variant))
|
|
249
|
+
: variants && typeof variants === "object" ? Object.keys(variants) : []
|
|
250
|
+
return [...new Set(ids.filter((id): id is string => !!id && id !== "default"))]
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function makeRow(input: {
|
|
254
|
+
providerID: string
|
|
255
|
+
providerName: string
|
|
256
|
+
providerSource?: string
|
|
257
|
+
modelID: string
|
|
258
|
+
modelName?: string
|
|
259
|
+
variants?: unknown
|
|
260
|
+
cost: unknown
|
|
261
|
+
declaredInConfig: boolean
|
|
262
|
+
costFromConfig: boolean
|
|
263
|
+
contextLimit?: number
|
|
264
|
+
}): ModelRow {
|
|
265
|
+
return {
|
|
266
|
+
providerID: input.providerID,
|
|
267
|
+
providerName: input.providerName,
|
|
268
|
+
providerSource: input.providerSource,
|
|
269
|
+
modelID: input.modelID,
|
|
270
|
+
modelName: input.modelName,
|
|
271
|
+
variantIDs: variantIDs(input.variants),
|
|
272
|
+
tiers: normalizeTiers(input.cost),
|
|
273
|
+
declaredInConfig: input.declaredInConfig,
|
|
274
|
+
costFromConfig: input.costFromConfig,
|
|
275
|
+
contextLimit: input.contextLimit,
|
|
276
|
+
isDefault: false,
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Providers/models authored in opencode.json(c), merged across documents (later wins). */
|
|
281
|
+
function collectAuthored(documents: any[]): Map<string, { name?: string; models: Map<string, any> }> {
|
|
282
|
+
const map = new Map<string, { name?: string; models: Map<string, any> }>()
|
|
283
|
+
for (const document of documents) {
|
|
284
|
+
const info = document?.info
|
|
285
|
+
if (!info || typeof info !== "object") continue
|
|
286
|
+
// Walk both the V2 `providers` key and the deprecated V1 `provider` key
|
|
287
|
+
// (same entry shape for this plugin's purposes).
|
|
288
|
+
for (const key of ["providers", "provider"] as const) {
|
|
289
|
+
const providers = (info as any)[key]
|
|
290
|
+
if (!providers || typeof providers !== "object") continue
|
|
291
|
+
for (const [providerID, rawProvider] of Object.entries(providers as Record<string, any>)) {
|
|
292
|
+
if (!rawProvider || typeof rawProvider !== "object") continue
|
|
293
|
+
const entry = map.get(providerID) ?? { name: str(rawProvider.name), models: new Map<string, any>() }
|
|
294
|
+
if (!entry.name && str(rawProvider.name)) entry.name = str(rawProvider.name)
|
|
295
|
+
const models = rawProvider.models
|
|
296
|
+
if (models && typeof models === "object") {
|
|
297
|
+
for (const [modelID, rawModel] of Object.entries(models as Record<string, any>)) {
|
|
298
|
+
if (!rawModel || typeof rawModel !== "object") continue
|
|
299
|
+
const cost = rawModel.cost
|
|
300
|
+
if (cost !== undefined || !entry.models.has(modelID)) entry.models.set(modelID, cost)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
map.set(providerID, entry)
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return map
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The `model` default from the last config document that sets one. */
|
|
311
|
+
function collectAuthoredDefault(documents: any[]): { providerID: string; modelID: string } | undefined {
|
|
312
|
+
let selector: { providerID: string; modelID: string } | undefined
|
|
313
|
+
for (const document of documents) {
|
|
314
|
+
const model = document?.info?.model
|
|
315
|
+
if (typeof model === "string") {
|
|
316
|
+
selector = parseSelector(model)
|
|
317
|
+
} else if (model && typeof model === "object" && typeof (model as any).providerID === "string") {
|
|
318
|
+
selector = { providerID: (model as any).providerID, modelID: str((model as any).model) ?? "" }
|
|
319
|
+
}
|
|
320
|
+
if (selector && !selector.modelID) selector = undefined
|
|
321
|
+
}
|
|
322
|
+
return selector
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function payloadDefaultSelector(payload: { default?: Record<string, string> } | undefined) {
|
|
326
|
+
const map = payload?.default
|
|
327
|
+
if (!map || typeof map !== "object") return undefined
|
|
328
|
+
const value =
|
|
329
|
+
(typeof map.default === "string" && map.default) ||
|
|
330
|
+
Object.values(map).find((entry) => typeof entry === "string" && entry.includes("/"))
|
|
331
|
+
return typeof value === "string" ? parseSelector(value) : undefined
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** "provider/model(#variant)" or "provider/nested/model(#variant)" → { providerID, modelID }. */
|
|
335
|
+
function parseSelector(reference: string): { providerID: string; modelID: string } | undefined {
|
|
336
|
+
const slash = reference.indexOf("/")
|
|
337
|
+
if (slash <= 0) return undefined
|
|
338
|
+
const providerID = reference.slice(0, slash)
|
|
339
|
+
const rest = reference.slice(slash + 1)
|
|
340
|
+
const hash = rest.indexOf("#")
|
|
341
|
+
const modelID = hash >= 0 ? rest.slice(0, hash) : rest
|
|
342
|
+
if (!modelID) return undefined
|
|
343
|
+
return { providerID, modelID }
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function compareRows(a: ModelRow, b: ModelRow): number {
|
|
347
|
+
const provider = a.providerName.localeCompare(b.providerName) || a.providerID.localeCompare(b.providerID)
|
|
348
|
+
if (provider !== 0) return provider
|
|
349
|
+
return a.modelID.localeCompare(b.modelID)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ---------------------------------------------------------------------------
|
|
353
|
+
// Cost normalization
|
|
354
|
+
// ---------------------------------------------------------------------------
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Accepts every known cost shape:
|
|
358
|
+
* - config `cost` object: { tier?, input, output, cache? { read?, write? } }
|
|
359
|
+
* - config `cost` tier array of the objects above
|
|
360
|
+
* - SDK `Model.cost`: { input, output, cache, tiers?, experimentalOver200K? }
|
|
361
|
+
*/
|
|
362
|
+
export function normalizeTiers(cost: unknown): CostTier[] {
|
|
363
|
+
if (Array.isArray(cost)) return cost.map(normalizeConfigTier).filter(hasRates).sort(byTierSize)
|
|
364
|
+
if (!cost || typeof cost !== "object") return []
|
|
365
|
+
const source = cost as any
|
|
366
|
+
|
|
367
|
+
if (Array.isArray(source.tiers) && source.tiers.length > 0) {
|
|
368
|
+
return source.tiers
|
|
369
|
+
.map((entry: any) => ({
|
|
370
|
+
tier: tierOf(entry?.tier),
|
|
371
|
+
input: num(entry?.input),
|
|
372
|
+
output: num(entry?.output),
|
|
373
|
+
cache: cacheOf(entry?.cache),
|
|
374
|
+
}))
|
|
375
|
+
.filter(hasRates)
|
|
376
|
+
.sort(byTierSize)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const tiers: CostTier[] = [
|
|
380
|
+
{
|
|
381
|
+
tier: tierOf(source.tier),
|
|
382
|
+
input: num(source.input),
|
|
383
|
+
output: num(source.output),
|
|
384
|
+
cache: cacheOf(source.cache) ?? flatCacheOf(source),
|
|
385
|
+
},
|
|
386
|
+
]
|
|
387
|
+
// SDK shape and deprecated V1 config shape (`context_over_200k`).
|
|
388
|
+
const over = source.experimentalOver200K ?? source.context_over_200k
|
|
389
|
+
if (over && typeof over === "object") {
|
|
390
|
+
tiers.push({
|
|
391
|
+
tier: { type: "context", size: 200000 },
|
|
392
|
+
input: num(over.input),
|
|
393
|
+
output: num(over.output),
|
|
394
|
+
cache: cacheOf(over.cache) ?? flatCacheOf(over),
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
return tiers.filter(hasRates).sort(byTierSize)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function normalizeConfigTier(entry: any): CostTier {
|
|
401
|
+
if (!entry || typeof entry !== "object") return {}
|
|
402
|
+
return {
|
|
403
|
+
tier: tierOf(entry.tier),
|
|
404
|
+
input: num(entry.input),
|
|
405
|
+
output: num(entry.output),
|
|
406
|
+
cache: cacheOf(entry.cache) ?? flatCacheOf(entry),
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function hasRates(tier: CostTier): boolean {
|
|
411
|
+
return tier.input !== undefined || tier.output !== undefined ||
|
|
412
|
+
tier.cache?.read !== undefined || tier.cache?.write !== undefined
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function byTierSize(a: CostTier, b: CostTier): number {
|
|
416
|
+
return (a.tier?.size ?? 0) - (b.tier?.size ?? 0)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function tierOf(tier: any): { type: "context"; size: number } | undefined {
|
|
420
|
+
if (tier?.type === "context" && typeof tier.size === "number" && Number.isFinite(tier.size)) {
|
|
421
|
+
return { type: "context", size: tier.size }
|
|
422
|
+
}
|
|
423
|
+
return undefined
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function cacheOf(cache: any): { read?: number; write?: number } | undefined {
|
|
427
|
+
if (!cache || typeof cache !== "object") return undefined
|
|
428
|
+
const read = cache.read == null ? undefined : num(cache.read)
|
|
429
|
+
const write = cache.write == null ? undefined : num(cache.write)
|
|
430
|
+
if (read == null && write == null) return undefined
|
|
431
|
+
return { read, write }
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** Deprecated V1 config shape: flat `cache_read` / `cache_write` next to `input` / `output`. */
|
|
435
|
+
function flatCacheOf(source: any): { read?: number; write?: number } | undefined {
|
|
436
|
+
if (!source || typeof source !== "object") return undefined
|
|
437
|
+
const read = source.cache_read
|
|
438
|
+
const write = source.cache_write
|
|
439
|
+
if (read == null && write == null) return undefined
|
|
440
|
+
return {
|
|
441
|
+
read: read == null ? undefined : num(read),
|
|
442
|
+
write: write == null ? undefined : num(write),
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function num(value: unknown): number | undefined {
|
|
447
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function str(value: unknown): string | undefined {
|
|
451
|
+
return typeof value === "string" && value.length > 0 ? value : undefined
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ---------------------------------------------------------------------------
|
|
455
|
+
// Formatting
|
|
456
|
+
// ---------------------------------------------------------------------------
|
|
457
|
+
|
|
458
|
+
/** "$15", "$3.25", "$0.3", "$1.2e-7" — compact but precise for sub-dollar rates. */
|
|
459
|
+
export function fmtMoney(value: number | undefined): string {
|
|
460
|
+
if (value === undefined || !Number.isFinite(value)) return "—"
|
|
461
|
+
if (value === 0) return "$0"
|
|
462
|
+
if (Math.abs(value) >= 1) return `$${trimZeros(value.toFixed(2))}`
|
|
463
|
+
if (Math.abs(value) >= 0.001) return `$${trimZeros(value.toFixed(4))}`
|
|
464
|
+
return `$${value.toExponential(1)}`
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function trimZeros(text: string): string {
|
|
468
|
+
return text.replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "")
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** 200000 → "200k", 1000000 → "1M", 128000 → "128k". */
|
|
472
|
+
export function fmtK(tokens: number): string {
|
|
473
|
+
if (!Number.isFinite(tokens) || tokens <= 0) return String(tokens)
|
|
474
|
+
if (tokens % 1_000_000 === 0) return `${tokens / 1_000_000}M`
|
|
475
|
+
if (tokens % 1_000 === 0) return `${tokens / 1_000}k`
|
|
476
|
+
return String(tokens)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Compact input/output price summary for the picker and footer.
|
|
481
|
+
*/
|
|
482
|
+
export function fmtRatesTop(tier: CostTier): string {
|
|
483
|
+
return `in ${fmtMoney(tier.input)} · out ${fmtMoney(tier.output)}`
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** "cache read $0.55 · cache write $5.5" — the cache portion of a details line. */
|
|
487
|
+
function fmtRatesCache(tier: CostTier): string {
|
|
488
|
+
return `cache read ${fmtMoney(tier.cache?.read)} · cache write ${fmtMoney(tier.cache?.write)}`
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** All four rates on one line — the dialog description and extra-tier lines. */
|
|
492
|
+
export function fmtRates(tier: CostTier): string {
|
|
493
|
+
return `${fmtRatesTop(tier)} · ${fmtRatesCache(tier)}`
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** Base rates for the footer, with cache rates when they fit. */
|
|
497
|
+
export function fmtBadge(row: ModelRow, width: number): string {
|
|
498
|
+
const base = row.tiers.find((tier) => !tier.tier)
|
|
499
|
+
if (!base) return ""
|
|
500
|
+
const unit = " / 1M tokens"
|
|
501
|
+
if (base.cache?.read !== undefined || base.cache?.write !== undefined) {
|
|
502
|
+
const full = fmtRates(base) + unit
|
|
503
|
+
if (full.length <= width) return full
|
|
504
|
+
}
|
|
505
|
+
const compact = fmtRatesTop(base) + unit
|
|
506
|
+
return (base.input !== undefined || base.output !== undefined) && compact.length <= width ? compact : ""
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// ---------------------------------------------------------------------------
|
|
510
|
+
// Dialog sizing
|
|
511
|
+
// ---------------------------------------------------------------------------
|
|
512
|
+
|
|
513
|
+
/** Host dialog presets and their widths (packages/tui/src/ui/dialog.tsx, `dialogWidth`). */
|
|
514
|
+
const DIALOG_PRESETS = [
|
|
515
|
+
{ size: "medium", width: 60 },
|
|
516
|
+
{ size: "large", width: 88 },
|
|
517
|
+
{ size: "xlarge", width: 116 },
|
|
518
|
+
] as const
|
|
519
|
+
|
|
520
|
+
export type DialogSize = (typeof DIALOG_PRESETS)[number]["size"]
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* The smallest host dialog preset whose list fits the widest rendered line.
|
|
524
|
+
* The host reserves the list chrome (side insets, gutter, row padding — about
|
|
525
|
+
* 12 cells) inside each preset's width, and two more cells of slack absorb
|
|
526
|
+
* minor host-side drift. Lines wider than every preset still open, on xlarge,
|
|
527
|
+
* where the host clips them.
|
|
528
|
+
*/
|
|
529
|
+
export function fitsDialogWidth(contentWidth: number, terminalWidth: number): boolean {
|
|
530
|
+
return contentWidth + 14 <= Math.min(terminalWidth - 4, DIALOG_PRESETS[2].width)
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export function fitDialogSize(lines: readonly string[]): DialogSize {
|
|
534
|
+
const widest = Math.max(0, ...lines.map((line) => line.length))
|
|
535
|
+
return DIALOG_PRESETS.find((preset) => widest <= preset.width - 14)?.size ?? "xlarge"
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function findRow(rows: ModelRow[], providerID: string, modelID: string): ModelRow | undefined {
|
|
539
|
+
return rows.find((row) => row.providerID === providerID && row.modelID === modelID)
|
|
540
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Plugin } from "@opencode/plugin"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Server part of the opencode-model-costs plugin.
|
|
5
|
+
*
|
|
6
|
+
* It intentionally does no work: all behavior lives in the TUI part
|
|
7
|
+
* (src/tui.tsx), which reads cost data from the OpenCode server through its
|
|
8
|
+
* own client. This part exists so the package is a complete plugin — the
|
|
9
|
+
* server part defines the plugin id and makes the TUI part load
|
|
10
|
+
* automatically alongside it.
|
|
11
|
+
*/
|
|
12
|
+
export default Plugin.define({
|
|
13
|
+
id: "opencode-model-costs",
|
|
14
|
+
setup() {
|
|
15
|
+
// No server-side behavior needed.
|
|
16
|
+
},
|
|
17
|
+
})
|