pantheon-opencode 1.6.1 → 1.6.2-beta.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/AGENTS.global.md +11 -11
- package/AGENTS.md +2 -2
- package/CHANGELOG.md +29 -0
- package/README.md +100 -19
- package/README.pt-BR.md +27 -11
- package/bin/pantheon-init.mjs +106 -19
- package/package.json +3 -2
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/build-agents-md.mjs +1 -1
- package/scripts/doctor.mjs +213 -45
- package/scripts/install/agents-md.mjs +2 -1
- package/scripts/install/config-migration.mjs +344 -393
- package/scripts/install/config-paths.mjs +15 -0
- package/scripts/install/mcp-permissions.mjs +164 -0
- package/scripts/install/opencode-version.mjs +31 -13
- package/scripts/install/opencode-wildcard.mjs +106 -0
- package/scripts/install/opencode.mjs +240 -69
- package/scripts/install/plan-artifact.mjs +12 -1
- package/scripts/install/plugin.mjs +17 -1
- package/scripts/install/v2-capabilities.mjs +5 -6
- package/scripts/package-evidence.mjs +1 -0
- package/scripts/sandbox-env.sh +174 -0
- package/scripts/setup-v2-config.mjs +1703 -0
- package/scripts/setup.mjs +415 -0
- package/scripts/sync-tui.mjs +9 -1
- package/scripts/test-opencode-v2-sandbox.sh +438 -151
- package/scripts/update-skills-lock.mjs +30 -0
- package/skills-lock.json +10 -10
- package/src/agents/aphrodite.md +5 -2
- package/src/agents/apollo.md +5 -0
- package/src/agents/athena.md +6 -1
- package/src/agents/demeter.md +5 -1
- package/src/agents/gaia.md +4 -0
- package/src/agents/hephaestus.md +6 -1
- package/src/agents/hermes.md +6 -3
- package/src/agents/iris.md +5 -1
- package/src/agents/mnemosyne.md +20 -50
- package/src/agents/nyx.md +5 -1
- package/src/agents/prometheus.md +4 -0
- package/src/agents/talos.md +4 -0
- package/src/agents/themis.md +4 -0
- package/src/agents/zeus.md +9 -3
- package/src/instructions/agent-return-format.instructions.md +1 -1
- package/src/instructions/memory-protocol.instructions.md +3 -3
- package/src/instructions/test-economy.instructions.md +6 -6
- package/src/mcp/pantheon_vision.py +37 -36
- package/src/pantheon/cost-command.ts +30 -133
- package/src/pantheon/model-pricing.ts +1 -536
- package/src/pantheon/v2-vision.ts +34 -29
- package/src/pantheon/vision.ts +43 -10
- package/src/plugin-v2.ts +30 -53
- package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.js +1142 -0
- package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
- package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
- package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
- package/src/plugins/tui/dist/quota-cli.js +184 -0
- package/src/plugins/tui/dist/quota-cli.js.map +1 -0
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +684 -0
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
- package/src/plugins/tui/dist/server-v2.d.ts +14 -0
- package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
- package/src/plugins/tui/dist/server-v2.js +796 -0
- package/src/plugins/tui/dist/server-v2.js.map +1 -0
- package/src/plugins/tui/dist/tui-v2.d.ts +375 -53
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +5876 -530
- package/src/plugins/tui/dist/tui-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
- package/src/plugins/tui/dist/usage-history-worker.js +25 -0
- package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
- package/src/plugins/tui/index-v2.ts +3 -6
- package/src/plugins/tui/package-lock.json +17 -2
- package/src/plugins/tui/package.json +6 -3
- package/src/plugins/tui/src/context-gauge.ts +59 -0
- package/src/plugins/tui/src/cost-data.ts +607 -0
- package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
- package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
- package/src/plugins/tui/src/index-v2.tsx +231 -240
- package/src/plugins/tui/src/model-pricing.ts +536 -0
- package/src/plugins/tui/src/model-usage-limits.ts +4 -0
- package/src/plugins/tui/src/quota-adapters.ts +1598 -0
- package/src/plugins/tui/src/quota-cli.ts +237 -0
- package/src/plugins/tui/src/quota-rpc.ts +373 -0
- package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
- package/src/plugins/tui/src/quota-v2.tsx +1238 -0
- package/src/plugins/tui/src/server-v2.ts +985 -0
- package/src/plugins/tui/src/sidebar-width.ts +129 -0
- package/src/plugins/tui/src/usage-history-contract.ts +217 -0
- package/src/plugins/tui/src/usage-history-validation.ts +104 -0
- package/src/plugins/tui/src/usage-history-view.tsx +236 -0
- package/src/plugins/tui/src/usage-history-worker.ts +25 -0
- package/src/plugins/tui/src/usage-view-model.ts +272 -0
- package/src/plugins/tui/tsconfig.typecheck.json +6 -1
- package/src/plugins/tui/tsdown.config.ts +44 -5
- package/src/routing.yml +72 -13
- package/src/skills/README.md +4 -0
- package/src/skills/agent-coordination/SKILL.md +0 -3
- package/src/skills/artifact-management/SKILL.md +0 -3
- package/src/skills/auto-continue/SKILL.md +0 -3
- package/src/skills/code-review-checklist/SKILL.md +0 -3
- package/src/skills/context-compression/SKILL.md +0 -3
- package/src/skills/memory-bank/SKILL.md +6 -28
- package/src/skills/session-goal/SKILL.md +0 -3
- package/src/skills/simplify/SKILL.md +5 -4
- package/src/skills/tdd-with-agents/SKILL.md +0 -3
- package/src/skills/visual-review-pipeline/SKILL.md +0 -1
- package/src/pantheon/memory-context.ts +0 -1017
|
@@ -1,536 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* Model pricing — money for `pantheon_cost`.
|
|
3
|
-
*
|
|
4
|
-
* Prices come from the public catalog the OpenCode ecosystem already uses,
|
|
5
|
-
* `https://models.dev/api.json` (USD per 1M tokens). The rule that shapes this
|
|
6
|
-
* module is that a tool call must NEVER block on the network:
|
|
7
|
-
*
|
|
8
|
-
* - every call reads a normalized on-disk cache synchronously;
|
|
9
|
-
* - an explicit `refreshPricing` is the only AWAITED fetch (bounded timeout);
|
|
10
|
-
* - a missing or stale cache is refreshed in the BACKGROUND, with a short
|
|
11
|
-
* timeout, so the next call benefits without this one waiting;
|
|
12
|
-
* - every network/parse failure degrades to "pricing unavailable" and the
|
|
13
|
-
* token report keeps working.
|
|
14
|
-
*
|
|
15
|
-
* An unknown model is never priced at zero. `0` is a real catalog price (a free
|
|
16
|
-
* model), and conflating it with "no price" would report free usage for every
|
|
17
|
-
* model the catalog has never heard of — which is precisely the number a tier
|
|
18
|
-
* decision would be made on.
|
|
19
|
-
*
|
|
20
|
-
* Cache location follows the repository's existing config-dir convention
|
|
21
|
-
* (`PANTHEON_HOME` → `$XDG_CONFIG_HOME/opencode` → `~/.config/opencode`), so no
|
|
22
|
-
* new root is invented: `<configDir>/cache/models-dev.json`.
|
|
23
|
-
*
|
|
24
|
-
* @module model-pricing
|
|
25
|
-
*/
|
|
26
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
27
|
-
import { homedir } from 'node:os'
|
|
28
|
-
import { dirname, join } from 'node:path'
|
|
29
|
-
|
|
30
|
-
/** The catalog URL every OpenCode-adjacent tool prices against. */
|
|
31
|
-
const MODELS_DEV_URL = 'https://models.dev/api.json'
|
|
32
|
-
|
|
33
|
-
/** Cache payload version; a mismatch is treated as "no cache". */
|
|
34
|
-
const PRICING_CACHE_VERSION = 1
|
|
35
|
-
|
|
36
|
-
/** Cached prices are considered fresh for one day. */
|
|
37
|
-
const PRICING_TTL_MS = 24 * 60 * 60 * 1000
|
|
38
|
-
|
|
39
|
-
/** Upper bound for any catalog fetch, so no request can outlive a tool call. */
|
|
40
|
-
const PRICING_TIMEOUT_MS = 3000
|
|
41
|
-
|
|
42
|
-
/** One model's list price, in USD per 1M tokens. */
|
|
43
|
-
export interface ModelPrice {
|
|
44
|
-
inputPerMTok: number
|
|
45
|
-
outputPerMTok: number
|
|
46
|
-
/**
|
|
47
|
-
* Absent when the catalog publishes no cache-read price. Kept distinct from
|
|
48
|
-
* `0` so cache tokens can never be priced as free by accident.
|
|
49
|
-
*/
|
|
50
|
-
cacheReadPerMTok?: number
|
|
51
|
-
cacheWritePerMTok?: number
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Token counts a cost is computed from. */
|
|
55
|
-
export interface TokenAmounts {
|
|
56
|
-
input: number
|
|
57
|
-
output: number
|
|
58
|
-
cacheRead: number
|
|
59
|
-
cacheWrite: number
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** Why a row could not be priced. */
|
|
63
|
-
export type UnpricedReason =
|
|
64
|
-
| 'no-pricing'
|
|
65
|
-
| 'unknown-model'
|
|
66
|
-
| 'ambiguous-model'
|
|
67
|
-
| 'missing-cache-price'
|
|
68
|
-
|
|
69
|
-
/** Resolved prices, ready for lookup. */
|
|
70
|
-
export interface PricingSnapshot {
|
|
71
|
-
/** `${providerId}/${modelId}`, lowercased. */
|
|
72
|
-
index: ReadonlyMap<string, ModelPrice>
|
|
73
|
-
/** Model id → every provider's price for it, for provider-less lookups. */
|
|
74
|
-
modelIndex: ReadonlyMap<string, readonly ModelPrice[]>
|
|
75
|
-
/** True when the cache is older than the TTL. */
|
|
76
|
-
stale: boolean
|
|
77
|
-
/** True when a background refresh is in flight. */
|
|
78
|
-
refreshing: boolean
|
|
79
|
-
/** Epoch ms of the cached catalog. */
|
|
80
|
-
fetchedAt?: number
|
|
81
|
-
/** Set when pricing cannot be used at all, or when a refresh failed. */
|
|
82
|
-
unavailableReason?: string
|
|
83
|
-
/**
|
|
84
|
-
* Set when a refresh was REFUSED rather than attempted (offline mode).
|
|
85
|
-
* Distinguished from a failed fetch so the report can say "no request was
|
|
86
|
-
* made" instead of implying the network was tried.
|
|
87
|
-
*/
|
|
88
|
-
refused?: boolean
|
|
89
|
-
/** True when offline mode was in effect for this snapshot. */
|
|
90
|
-
offline?: boolean
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** Minimal fetch boundary, so tests never touch the network. */
|
|
94
|
-
export type FetchLike = (
|
|
95
|
-
url: string,
|
|
96
|
-
init: { signal?: AbortSignal; headers?: Record<string, string> },
|
|
97
|
-
) => Promise<{ ok: boolean; status: number; json(): Promise<unknown> }>
|
|
98
|
-
|
|
99
|
-
/** Injectable knobs (tests, air-gapped hosts, unusual installs). */
|
|
100
|
-
export interface PricingOptions {
|
|
101
|
-
/** Cache file. Default: `<configDir>/cache/models-dev.json`. */
|
|
102
|
-
cachePath?: string
|
|
103
|
-
/** Fetch boundary. Default: global `fetch`. */
|
|
104
|
-
fetchImpl?: FetchLike
|
|
105
|
-
/** Clock. Default: `Date.now`. */
|
|
106
|
-
now?: () => number
|
|
107
|
-
/** Freshness window. Default: {@link PRICING_TTL_MS}. */
|
|
108
|
-
ttlMs?: number
|
|
109
|
-
/** Environment used for cache-path resolution. Default: `process.env`. */
|
|
110
|
-
env?: NodeJS.ProcessEnv
|
|
111
|
-
/** Disable every network attempt (tests / air-gapped hosts). */
|
|
112
|
-
offline?: boolean
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
interface CachedCatalog {
|
|
116
|
-
version: number
|
|
117
|
-
fetchedAt: number
|
|
118
|
-
providers: Record<string, Record<string, ModelPrice>>
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
type ProviderPrices = Record<string, Record<string, ModelPrice>>
|
|
122
|
-
|
|
123
|
-
/** Resolve the OpenCode config dir, mirroring `_pantheon_paths.py`. */
|
|
124
|
-
function resolvePricingCacheDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
125
|
-
const explicit = env.PANTHEON_HOME?.trim()
|
|
126
|
-
if (explicit !== undefined && explicit !== '') return explicit
|
|
127
|
-
const xdg = env.XDG_CONFIG_HOME?.trim()
|
|
128
|
-
const base = xdg !== undefined && xdg !== '' ? xdg : join(homedir(), '.config')
|
|
129
|
-
return join(base, 'opencode')
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/** Cache file for the normalized catalog. */
|
|
133
|
-
function resolvePricingCachePath(env: NodeJS.ProcessEnv = process.env): string {
|
|
134
|
-
return join(resolvePricingCacheDir(env), 'cache', 'models-dev.json')
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
138
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function finiteNumber(value: unknown): number | undefined {
|
|
142
|
-
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** Reject nonsense prices rather than reporting a $2B session. */
|
|
146
|
-
const MAX_SANE_PER_MTOK = 100_000
|
|
147
|
-
|
|
148
|
-
function nonNegativePrice(value: unknown): number | undefined {
|
|
149
|
-
const parsed = finiteNumber(value)
|
|
150
|
-
if (parsed === undefined || parsed < 0 || parsed > MAX_SANE_PER_MTOK) return undefined
|
|
151
|
-
return parsed
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/** Validate one already-normalized price from the cache file. */
|
|
155
|
-
function buildPrice(
|
|
156
|
-
input: number | undefined,
|
|
157
|
-
output: number | undefined,
|
|
158
|
-
cacheRead: number | undefined,
|
|
159
|
-
cacheWrite: number | undefined,
|
|
160
|
-
): ModelPrice | undefined {
|
|
161
|
-
if (input === undefined || output === undefined) return undefined
|
|
162
|
-
return {
|
|
163
|
-
inputPerMTok: input,
|
|
164
|
-
outputPerMTok: output,
|
|
165
|
-
...(cacheRead === undefined ? {} : { cacheReadPerMTok: cacheRead }),
|
|
166
|
-
...(cacheWrite === undefined ? {} : { cacheWritePerMTok: cacheWrite }),
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
function parseNormalizedPrice(value: unknown): ModelPrice | undefined {
|
|
171
|
-
if (!isRecord(value)) return undefined
|
|
172
|
-
return buildPrice(
|
|
173
|
-
nonNegativePrice(value.inputPerMTok),
|
|
174
|
-
nonNegativePrice(value.outputPerMTok),
|
|
175
|
-
nonNegativePrice(value.cacheReadPerMTok),
|
|
176
|
-
nonNegativePrice(value.cacheWritePerMTok),
|
|
177
|
-
)
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Validate the normalized `provider → model → price` shape.
|
|
182
|
-
*
|
|
183
|
-
* The cache stores the RESULT of {@link parseCatalogPayload}, not the raw
|
|
184
|
-
* models.dev payload, so it must not be re-parsed as one: a normalized entry has
|
|
185
|
-
* no `models` key, and treating it as a payload would silently read a valid
|
|
186
|
-
* cache as empty.
|
|
187
|
-
*/
|
|
188
|
-
function parseNormalizedProviders(value: unknown): ProviderPrices | undefined {
|
|
189
|
-
if (!isRecord(value)) return undefined
|
|
190
|
-
const providers: ProviderPrices = {}
|
|
191
|
-
for (const [providerId, models] of Object.entries(value)) {
|
|
192
|
-
if (!isRecord(models)) continue
|
|
193
|
-
const priced: Record<string, ModelPrice> = {}
|
|
194
|
-
for (const [modelId, price] of Object.entries(models)) {
|
|
195
|
-
const parsed = parseNormalizedPrice(price)
|
|
196
|
-
if (parsed !== undefined) priced[modelId.toLowerCase()] = parsed
|
|
197
|
-
}
|
|
198
|
-
if (Object.keys(priced).length > 0) providers[providerId.toLowerCase()] = priced
|
|
199
|
-
}
|
|
200
|
-
return Object.keys(providers).length === 0 ? undefined : providers
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
/** Parse one catalog model entry. Missing input/output cost ⇒ unpriced. */
|
|
204
|
-
function parseModelPrice(model: unknown): ModelPrice | undefined {
|
|
205
|
-
if (!isRecord(model)) return undefined
|
|
206
|
-
const cost = model.cost
|
|
207
|
-
if (!isRecord(cost)) return undefined
|
|
208
|
-
return buildPrice(
|
|
209
|
-
nonNegativePrice(cost.input),
|
|
210
|
-
nonNegativePrice(cost.output),
|
|
211
|
-
nonNegativePrice(cost.cache_read),
|
|
212
|
-
nonNegativePrice(cost.cache_write),
|
|
213
|
-
)
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Normalize a models.dev payload into `provider → model → price`.
|
|
218
|
-
*
|
|
219
|
-
* Provider and model ids are lowercased because the ledger stores whatever the
|
|
220
|
-
* host wrote (`opencode-go`) and the catalog keys are not case-normalized.
|
|
221
|
-
*/
|
|
222
|
-
export function parseCatalogPayload(payload: unknown): ProviderPrices | undefined {
|
|
223
|
-
if (!isRecord(payload)) return undefined
|
|
224
|
-
const providers: ProviderPrices = {}
|
|
225
|
-
for (const [providerId, provider] of Object.entries(payload)) {
|
|
226
|
-
if (!isRecord(provider)) continue
|
|
227
|
-
const models = provider.models
|
|
228
|
-
if (!isRecord(models)) continue
|
|
229
|
-
const priced: Record<string, ModelPrice> = {}
|
|
230
|
-
for (const [modelId, model] of Object.entries(models)) {
|
|
231
|
-
const price = parseModelPrice(model)
|
|
232
|
-
if (price !== undefined) priced[modelId.toLowerCase()] = price
|
|
233
|
-
}
|
|
234
|
-
if (Object.keys(priced).length > 0) providers[providerId.toLowerCase()] = priced
|
|
235
|
-
}
|
|
236
|
-
return Object.keys(providers).length === 0 ? undefined : providers
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
function priceKey(price: ModelPrice): string {
|
|
240
|
-
return [
|
|
241
|
-
price.inputPerMTok,
|
|
242
|
-
price.outputPerMTok,
|
|
243
|
-
price.cacheReadPerMTok ?? '-',
|
|
244
|
-
price.cacheWritePerMTok ?? '-',
|
|
245
|
-
].join('/')
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
function indexCatalog(providers: ProviderPrices): {
|
|
249
|
-
index: Map<string, ModelPrice>
|
|
250
|
-
modelIndex: Map<string, readonly ModelPrice[]>
|
|
251
|
-
} {
|
|
252
|
-
const index = new Map<string, ModelPrice>()
|
|
253
|
-
const modelIndex = new Map<string, ModelPrice[]>()
|
|
254
|
-
const seen = new Map<string, Set<string>>()
|
|
255
|
-
for (const [providerId, models] of Object.entries(providers)) {
|
|
256
|
-
for (const [modelId, price] of Object.entries(models)) {
|
|
257
|
-
index.set(`${providerId}/${modelId}`, price)
|
|
258
|
-
const bucket = modelIndex.get(modelId) ?? []
|
|
259
|
-
const keys = seen.get(modelId) ?? new Set<string>()
|
|
260
|
-
const key = priceKey(price)
|
|
261
|
-
if (!keys.has(key)) {
|
|
262
|
-
keys.add(key)
|
|
263
|
-
bucket.push(price)
|
|
264
|
-
seen.set(modelId, keys)
|
|
265
|
-
modelIndex.set(modelId, bucket)
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
return { index, modelIndex }
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
function snapshotFromCatalog(
|
|
273
|
-
catalog: CachedCatalog,
|
|
274
|
-
now: number,
|
|
275
|
-
ttlMs: number,
|
|
276
|
-
refreshing: boolean,
|
|
277
|
-
): PricingSnapshot {
|
|
278
|
-
const { index, modelIndex } = indexCatalog(catalog.providers)
|
|
279
|
-
return {
|
|
280
|
-
index,
|
|
281
|
-
modelIndex,
|
|
282
|
-
fetchedAt: catalog.fetchedAt,
|
|
283
|
-
stale: Math.max(0, now - catalog.fetchedAt) > ttlMs,
|
|
284
|
-
refreshing,
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
function unavailableSnapshot(reason: string): PricingSnapshot {
|
|
289
|
-
return {
|
|
290
|
-
index: new Map(),
|
|
291
|
-
modelIndex: new Map(),
|
|
292
|
-
stale: false,
|
|
293
|
-
refreshing: false,
|
|
294
|
-
unavailableReason: reason,
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
function parseCachedCatalog(raw: unknown): CachedCatalog | undefined {
|
|
299
|
-
if (!isRecord(raw)) return undefined
|
|
300
|
-
if (raw.version !== PRICING_CACHE_VERSION) return undefined
|
|
301
|
-
const fetchedAt = finiteNumber(raw.fetchedAt)
|
|
302
|
-
if (fetchedAt === undefined) return undefined
|
|
303
|
-
const providers = parseNormalizedProviders(raw.providers)
|
|
304
|
-
if (providers === undefined) return undefined
|
|
305
|
-
return { version: PRICING_CACHE_VERSION, fetchedAt, providers }
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
/** Read the normalized cache. Any problem reads as "no cache", never as zero. */
|
|
309
|
-
function readPricingCache(cachePath: string): CachedCatalog | undefined {
|
|
310
|
-
try {
|
|
311
|
-
if (!existsSync(cachePath)) return undefined
|
|
312
|
-
return parseCachedCatalog(JSON.parse(readFileSync(cachePath, 'utf8')))
|
|
313
|
-
} catch {
|
|
314
|
-
return undefined
|
|
315
|
-
}
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/** Write atomically; a cache that cannot be written must not break a report. */
|
|
319
|
-
function writePricingCache(cachePath: string, catalog: CachedCatalog): boolean {
|
|
320
|
-
const temp = `${cachePath}.tmp-${process.pid}`
|
|
321
|
-
try {
|
|
322
|
-
mkdirSync(dirname(cachePath), { recursive: true })
|
|
323
|
-
writeFileSync(temp, `${JSON.stringify(catalog)}\n`, 'utf8')
|
|
324
|
-
renameSync(temp, cachePath)
|
|
325
|
-
return true
|
|
326
|
-
} catch {
|
|
327
|
-
return false
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
const inFlight = new Map<string, Promise<PricingSnapshot>>()
|
|
332
|
-
|
|
333
|
-
/**
|
|
334
|
-
* Offline is a HOST-wide guarantee, not a hint.
|
|
335
|
-
*
|
|
336
|
-
* Both switches are honoured on every path that could open a socket, so the
|
|
337
|
-
* env var cannot be defeated by a caller that passes `refreshPricing` (or by a
|
|
338
|
-
* future code path that forgets to check). The reason names both switches,
|
|
339
|
-
* because a user reading the report needs to know which one to change.
|
|
340
|
-
*/
|
|
341
|
-
const OFFLINE_REFUSAL =
|
|
342
|
-
'refreshPricing cannot run: PANTHEON_COST_OFFLINE=1 (or the offline option) forbids every network request'
|
|
343
|
-
|
|
344
|
-
function isPricingOffline(options?: PricingOptions): boolean {
|
|
345
|
-
const env = options?.env ?? process.env
|
|
346
|
-
return options?.offline === true || env.PANTHEON_COST_OFFLINE === '1'
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/**
|
|
350
|
-
* Fetch the catalog once per cache path at a time, bounded by a timeout.
|
|
351
|
-
*
|
|
352
|
-
* Failures are values, not throws: the caller reports "pricing unavailable" and
|
|
353
|
-
* keeps the token ledger it already read.
|
|
354
|
-
*/
|
|
355
|
-
function refreshPricingCatalog(options?: PricingOptions): Promise<PricingSnapshot> {
|
|
356
|
-
// The gate sits on the fetch itself, so no caller — background, forced, or a
|
|
357
|
-
// future one — can open a socket while offline.
|
|
358
|
-
if (isPricingOffline(options)) {
|
|
359
|
-
return Promise.resolve({
|
|
360
|
-
...unavailableSnapshot(OFFLINE_REFUSAL),
|
|
361
|
-
refused: true,
|
|
362
|
-
offline: true,
|
|
363
|
-
})
|
|
364
|
-
}
|
|
365
|
-
const env = options?.env ?? process.env
|
|
366
|
-
const cachePath = options?.cachePath ?? resolvePricingCachePath(env)
|
|
367
|
-
const existing = inFlight.get(cachePath)
|
|
368
|
-
if (existing !== undefined) return existing
|
|
369
|
-
|
|
370
|
-
const now = (options?.now ?? Date.now)()
|
|
371
|
-
const ttlMs = options?.ttlMs ?? PRICING_TTL_MS
|
|
372
|
-
const doFetch: FetchLike =
|
|
373
|
-
options?.fetchImpl ??
|
|
374
|
-
((url, init) =>
|
|
375
|
-
fetch(url, {
|
|
376
|
-
...(init.signal === undefined ? {} : { signal: init.signal }),
|
|
377
|
-
...(init.headers === undefined ? {} : { headers: init.headers }),
|
|
378
|
-
}))
|
|
379
|
-
|
|
380
|
-
const task = (async (): Promise<PricingSnapshot> => {
|
|
381
|
-
try {
|
|
382
|
-
const response = await doFetch(MODELS_DEV_URL, {
|
|
383
|
-
signal: AbortSignal.timeout(PRICING_TIMEOUT_MS),
|
|
384
|
-
headers: { accept: 'application/json' },
|
|
385
|
-
})
|
|
386
|
-
if (!response.ok) {
|
|
387
|
-
return unavailableSnapshot(`models.dev returned HTTP ${response.status}`)
|
|
388
|
-
}
|
|
389
|
-
const providers = parseCatalogPayload(await response.json())
|
|
390
|
-
if (providers === undefined) {
|
|
391
|
-
return unavailableSnapshot('models.dev payload carried no usable prices')
|
|
392
|
-
}
|
|
393
|
-
const catalog: CachedCatalog = { version: PRICING_CACHE_VERSION, fetchedAt: now, providers }
|
|
394
|
-
const cached = writePricingCache(cachePath, catalog)
|
|
395
|
-
const snapshot = snapshotFromCatalog(catalog, now, ttlMs, false)
|
|
396
|
-
return cached ? snapshot : { ...snapshot, unavailableReason: 'price cache is not writable' }
|
|
397
|
-
} catch (error) {
|
|
398
|
-
const detail = error instanceof Error ? error.message : String(error)
|
|
399
|
-
return unavailableSnapshot(`models.dev fetch failed: ${detail}`)
|
|
400
|
-
} finally {
|
|
401
|
-
inFlight.delete(cachePath)
|
|
402
|
-
}
|
|
403
|
-
})()
|
|
404
|
-
|
|
405
|
-
inFlight.set(cachePath, task)
|
|
406
|
-
return task
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/**
|
|
410
|
-
* Load prices without blocking on the network.
|
|
411
|
-
*
|
|
412
|
-
* A stale cache is served immediately and refreshed in the background; with no
|
|
413
|
-
* cache there is nothing to serve, so the snapshot is explicitly unavailable
|
|
414
|
-
* and `pending` carries the opportunistic refresh for callers that want it.
|
|
415
|
-
*/
|
|
416
|
-
export function loadPricing(options?: PricingOptions): {
|
|
417
|
-
snapshot: PricingSnapshot
|
|
418
|
-
pending?: Promise<void>
|
|
419
|
-
} {
|
|
420
|
-
const env = options?.env ?? process.env
|
|
421
|
-
const cachePath = options?.cachePath ?? resolvePricingCachePath(env)
|
|
422
|
-
const now = (options?.now ?? Date.now)()
|
|
423
|
-
const ttlMs = options?.ttlMs ?? PRICING_TTL_MS
|
|
424
|
-
const catalog = readPricingCache(cachePath)
|
|
425
|
-
const offline = isPricingOffline(options)
|
|
426
|
-
|
|
427
|
-
if (catalog === undefined) {
|
|
428
|
-
if (offline) {
|
|
429
|
-
return {
|
|
430
|
-
snapshot: {
|
|
431
|
-
...unavailableSnapshot(
|
|
432
|
-
'no price cache, and pricing is offline (PANTHEON_COST_OFFLINE=1 or the offline option)',
|
|
433
|
-
),
|
|
434
|
-
offline: true,
|
|
435
|
-
},
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
const pending = refreshPricingCatalog(options)
|
|
439
|
-
return {
|
|
440
|
-
snapshot: unavailableSnapshot(
|
|
441
|
-
'no cached models.dev catalog yet; fetching one in the background',
|
|
442
|
-
),
|
|
443
|
-
pending: pending.then(() => undefined),
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
const snapshot = snapshotFromCatalog(catalog, now, ttlMs, false)
|
|
448
|
-
if (!snapshot.stale || offline) {
|
|
449
|
-
return { snapshot: offline ? { ...snapshot, offline: true } : snapshot }
|
|
450
|
-
}
|
|
451
|
-
// Stale prices are better than none: serve them and refresh behind the call.
|
|
452
|
-
const pending = refreshPricingCatalog(options)
|
|
453
|
-
return {
|
|
454
|
-
snapshot: { ...snapshot, refreshing: true },
|
|
455
|
-
pending: pending.then(() => undefined),
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
/**
|
|
460
|
-
* Await a refresh — only for an explicit `refreshPricing: true`.
|
|
461
|
-
*
|
|
462
|
-
* On failure the previously cached prices are still returned (marked stale), so
|
|
463
|
-
* a failed refresh does not erase the only prices the host has.
|
|
464
|
-
*/
|
|
465
|
-
export async function forceRefreshPricing(options?: PricingOptions): Promise<PricingSnapshot> {
|
|
466
|
-
const refreshed = await refreshPricingCatalog(options)
|
|
467
|
-
if (refreshed.unavailableReason === undefined) return refreshed
|
|
468
|
-
const env = options?.env ?? process.env
|
|
469
|
-
const cachePath = options?.cachePath ?? resolvePricingCachePath(env)
|
|
470
|
-
const catalog = readPricingCache(cachePath)
|
|
471
|
-
if (catalog === undefined) return refreshed
|
|
472
|
-
const now = (options?.now ?? Date.now)()
|
|
473
|
-
const cached = snapshotFromCatalog(catalog, now, options?.ttlMs ?? PRICING_TTL_MS, false)
|
|
474
|
-
return {
|
|
475
|
-
...cached,
|
|
476
|
-
unavailableReason: refreshed.unavailableReason,
|
|
477
|
-
...(refreshed.refused === true ? { refused: true } : {}),
|
|
478
|
-
...(refreshed.offline === true ? { offline: true } : {}),
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
/** Result of a price lookup. */
|
|
483
|
-
export type PriceLookup = { ok: true; price: ModelPrice } | { ok: false; reason: UnpricedReason }
|
|
484
|
-
|
|
485
|
-
/**
|
|
486
|
-
* Resolve a price for one ledger model.
|
|
487
|
-
*
|
|
488
|
-
* Exact `provider/model` wins. A model that exists under exactly one provider
|
|
489
|
-
* price is accepted when the ledger's provider id is unknown to the catalog
|
|
490
|
-
* (real hosts name their own gateways, e.g. `opencode-go` serving a model the
|
|
491
|
-
* catalog lists under `opencode`). Two DIFFERENT prices for the same model id
|
|
492
|
-
* are ambiguous and stay unpriced rather than guessing a provider.
|
|
493
|
-
*/
|
|
494
|
-
export function lookupModelPrice(
|
|
495
|
-
snapshot: PricingSnapshot,
|
|
496
|
-
providerId: string | undefined,
|
|
497
|
-
modelId: string | undefined,
|
|
498
|
-
): PriceLookup {
|
|
499
|
-
if (snapshot.index.size === 0) return { ok: false, reason: 'no-pricing' }
|
|
500
|
-
const model = (modelId ?? '').trim().toLowerCase()
|
|
501
|
-
if (model === '') return { ok: false, reason: 'unknown-model' }
|
|
502
|
-
const provider = (providerId ?? '').trim().toLowerCase()
|
|
503
|
-
if (provider !== '') {
|
|
504
|
-
const exact = snapshot.index.get(`${provider}/${model}`)
|
|
505
|
-
if (exact !== undefined) return { ok: true, price: exact }
|
|
506
|
-
}
|
|
507
|
-
const candidates = snapshot.modelIndex.get(model) ?? []
|
|
508
|
-
const only = candidates.length === 1 ? candidates[0] : undefined
|
|
509
|
-
if (only !== undefined) return { ok: true, price: only }
|
|
510
|
-
if (candidates.length === 0) return { ok: false, reason: 'unknown-model' }
|
|
511
|
-
return { ok: false, reason: 'ambiguous-model' }
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
/** Result of the cost math. */
|
|
515
|
-
export type CostResult = { ok: true; usd: number } | { ok: false; reason: 'missing-cache-price' }
|
|
516
|
-
|
|
517
|
-
/**
|
|
518
|
-
* Cost of one model's token counts.
|
|
519
|
-
*
|
|
520
|
-
* Cache tokens are billed at their own rate; when the catalog has no cache rate
|
|
521
|
-
* the row is unpriced instead of being charged at the input rate or at zero.
|
|
522
|
-
*/
|
|
523
|
-
export function computeModelCost(price: ModelPrice, tokens: TokenAmounts): CostResult {
|
|
524
|
-
let usd = (tokens.input * price.inputPerMTok + tokens.output * price.outputPerMTok) / 1_000_000
|
|
525
|
-
if (tokens.cacheRead > 0) {
|
|
526
|
-
const rate = price.cacheReadPerMTok
|
|
527
|
-
if (rate === undefined) return { ok: false, reason: 'missing-cache-price' }
|
|
528
|
-
usd += (tokens.cacheRead * rate) / 1_000_000
|
|
529
|
-
}
|
|
530
|
-
if (tokens.cacheWrite > 0) {
|
|
531
|
-
const rate = price.cacheWritePerMTok
|
|
532
|
-
if (rate === undefined) return { ok: false, reason: 'missing-cache-price' }
|
|
533
|
-
usd += (tokens.cacheWrite * rate) / 1_000_000
|
|
534
|
-
}
|
|
535
|
-
return { ok: true, usd }
|
|
536
|
-
}
|
|
1
|
+
export * from '../plugins/tui/src/model-pricing.ts'
|
|
@@ -10,6 +10,7 @@ import { homedir } from 'node:os'
|
|
|
10
10
|
import { join, resolve } from 'node:path'
|
|
11
11
|
import { fileURLToPath } from 'node:url'
|
|
12
12
|
import { resolveActivePreset } from './presets.mjs'
|
|
13
|
+
import { isValidSessionId } from './session-guard.ts'
|
|
13
14
|
import {
|
|
14
15
|
describeImagesNative,
|
|
15
16
|
NATIVE_MAX_TOKENS,
|
|
@@ -93,10 +94,10 @@ function imageReference(uri: string, mime: string, name: string): string {
|
|
|
93
94
|
* tool's `prompt`. NOTE: the description cache keys on the full prompt, so the
|
|
94
95
|
* same image asked with a new question gets a fresh describe — same image +
|
|
95
96
|
* same question within the TTL reuses the stored description.
|
|
96
|
-
* `sessionID` (the V2 `prompt` hook event's live session id, when
|
|
97
|
-
* relayed as an MCP `session_id` instruction: the
|
|
98
|
-
* process the host hands no session id to, and the Zen
|
|
99
|
-
* sessionless call with HTTP 400 `MissingSessionID` (mirrors
|
|
97
|
+
* `sessionID` (the V2 `prompt` hook event's live session id, when valid under
|
|
98
|
+
* the host session guard) is relayed as an MCP `session_id` instruction: the
|
|
99
|
+
* MCP runs in a separate process the host hands no session id to, and the Zen
|
|
100
|
+
* gateway rejects a sessionless call with HTTP 400 `MissingSessionID` (mirrors
|
|
100
101
|
* `generateInjectionPrompt` on the V1 path).
|
|
101
102
|
* The question and the session id are never logged.
|
|
102
103
|
*/
|
|
@@ -144,10 +145,9 @@ export function buildV2VisionPromptContext(
|
|
|
144
145
|
}
|
|
145
146
|
// MCP session relay (see the doc comment above): JSON.stringify quotes the
|
|
146
147
|
// id so it cannot spoof the surrounding instruction layout; never logged.
|
|
147
|
-
|
|
148
|
-
if (session) {
|
|
148
|
+
if (isValidSessionId(sessionID)) {
|
|
149
149
|
lines.push(
|
|
150
|
-
`Prefira a ferramenta nativa \`vision_describe\` (ela já repassa a sessão automaticamente). Se usar o MCP pantheon-vision (\`vision_describe\`/\`vision_ocr\`/\`vision_analyze\`), repasse session_id=${JSON.stringify(
|
|
150
|
+
`Prefira a ferramenta nativa \`vision_describe\` (ela já repassa a sessão automaticamente). Se usar o MCP pantheon-vision (\`vision_describe\`/\`vision_ocr\`/\`vision_analyze\`), repasse session_id=${JSON.stringify(sessionID)} no parâmetro \`session_id\` — sem ele o gateway Zen rejeita a chamada com MissingSessionID.`,
|
|
151
151
|
)
|
|
152
152
|
}
|
|
153
153
|
return lines.join('\n')
|
|
@@ -241,14 +241,11 @@ function exactModelMatch(models: V2VisionModel[], requested: string): V2VisionMo
|
|
|
241
241
|
}
|
|
242
242
|
|
|
243
243
|
/**
|
|
244
|
-
* Select a native transport model. An
|
|
245
|
-
*
|
|
246
|
-
*
|
|
247
|
-
*
|
|
248
|
-
*
|
|
249
|
-
* (`-free` suffix / cost ≤ 0) applies ONLY to AUTOMATIC selection — discovery
|
|
250
|
-
* then the Go default — because the direct gateway rejects free-tier models
|
|
251
|
-
* with HTTP 403, so they cannot serve the native describe path unasked.
|
|
244
|
+
* Select a native transport model. An explicit pin must be eligible for the
|
|
245
|
+
* native Zen image path or selection fails; it is never silently substituted.
|
|
246
|
+
* Free-tier exclusion (`-free` suffix / cost ≤ 0) applies only to automatic
|
|
247
|
+
* discovery, preserving the user's choice when a free model is explicitly
|
|
248
|
+
* pinned (the gateway can then return its actionable 403).
|
|
252
249
|
*/
|
|
253
250
|
export function selectV2VisionModel(
|
|
254
251
|
available: unknown,
|
|
@@ -263,8 +260,7 @@ export function selectV2VisionModel(
|
|
|
263
260
|
)
|
|
264
261
|
const pinned = preferred?.trim()
|
|
265
262
|
if (pinned) {
|
|
266
|
-
|
|
267
|
-
if (configured) return configured
|
|
263
|
+
return exactModelMatch(capable, pinned)
|
|
268
264
|
}
|
|
269
265
|
const candidates = capable.filter((model) => !isFreeVisionModel(model))
|
|
270
266
|
const defaultModel = exactModelMatch(candidates, DEFAULT_MODEL)
|
|
@@ -314,21 +310,19 @@ async function configuredVisionModel(directory: string): Promise<string | undefi
|
|
|
314
310
|
return undefined
|
|
315
311
|
}
|
|
316
312
|
|
|
317
|
-
async function preferredVisionModel(directory: string): Promise<string> {
|
|
313
|
+
async function preferredVisionModel(directory: string): Promise<string | undefined> {
|
|
318
314
|
const envModel = process.env.PANTHEON_VISION_MODEL?.trim()
|
|
319
315
|
if (envModel) return envModel
|
|
320
316
|
const configModel = await configuredVisionModel(directory)
|
|
321
317
|
if (configModel) return configModel
|
|
322
318
|
try {
|
|
323
|
-
return (
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
})?.vision?.model ?? DEFAULT_MODEL
|
|
329
|
-
)
|
|
319
|
+
return resolveActivePreset({
|
|
320
|
+
env: process.env,
|
|
321
|
+
candidates: activePresetCandidates(directory),
|
|
322
|
+
logger: { warn: () => undefined },
|
|
323
|
+
})?.vision?.model
|
|
330
324
|
} catch {
|
|
331
|
-
return
|
|
325
|
+
return undefined
|
|
332
326
|
}
|
|
333
327
|
}
|
|
334
328
|
|
|
@@ -551,17 +545,28 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini
|
|
|
551
545
|
},
|
|
552
546
|
output: {},
|
|
553
547
|
execute: async (input, rawContext) => {
|
|
554
|
-
let stage = '
|
|
548
|
+
let stage = 'validate OpenCode session'
|
|
555
549
|
try {
|
|
556
|
-
const pathValue = typeof input.path === 'string' ? input.path : ''
|
|
557
550
|
const call = (asRecord(rawContext) ?? {}) as V2VisionToolContext
|
|
551
|
+
if (!isValidSessionId(call.sessionID)) {
|
|
552
|
+
throw new Error(
|
|
553
|
+
'a valid OpenCode session id is required; retry this tool from an active OpenCode session',
|
|
554
|
+
)
|
|
555
|
+
}
|
|
556
|
+
const pathValue = typeof input.path === 'string' ? input.path : ''
|
|
558
557
|
const directory = call.directory || process.cwd()
|
|
558
|
+
stage = 'load image'
|
|
559
559
|
const image = await imageAttachment(pathValue, directory, call.signal)
|
|
560
560
|
stage = 'read model catalog'
|
|
561
561
|
const preferred = await preferredVisionModel(directory)
|
|
562
562
|
const catalog = await runtime.model.list()
|
|
563
563
|
const model = selectV2VisionModel(catalog, preferred)
|
|
564
564
|
if (!model) {
|
|
565
|
+
if (preferred?.trim()) {
|
|
566
|
+
throw new Error(
|
|
567
|
+
`explicitly configured Vision model "${preferred}" is unavailable or ineligible for the native OpenCode Zen image path; update or remove the explicit model pin (PANTHEON_VISION_MODEL, visionModel config, or active preset), or choose an enabled image-capable OpenCode Zen model`,
|
|
568
|
+
)
|
|
569
|
+
}
|
|
565
570
|
throw new Error(
|
|
566
571
|
'no available OpenCode Zen multimodal model accepts image input; connect OpenCode Zen and enable an image-capable model',
|
|
567
572
|
)
|
|
@@ -586,7 +591,7 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini
|
|
|
586
591
|
// header ONLY for Zen targets, never to a non-Zen provider.
|
|
587
592
|
const requestTarget: NativeVisionTarget = {
|
|
588
593
|
...target,
|
|
589
|
-
|
|
594
|
+
sessionID: call.sessionID,
|
|
590
595
|
}
|
|
591
596
|
let failure: NativeVisionFailure | undefined
|
|
592
597
|
const output = await describeImagesNative(
|