pantheon-opencode 1.6.0-beta.9 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.global.md +118 -0
- package/AGENTS.md +18 -168
- package/CHANGELOG.md +126 -376
- package/README.md +83 -610
- package/README.pt-BR.md +120 -345
- package/bin/pantheon-init.mjs +366 -132
- package/commands/pantheon-deepwork.md +14 -3
- package/commands/pantheon-vision.md +61 -12
- package/package.json +19 -11
- package/plugin.json +1 -1
- package/pyproject.toml +6 -2
- package/scripts/_pantheon_paths.py +24 -0
- package/scripts/build-agents-md.mjs +368 -69
- package/scripts/changelog-merge.mjs +161 -0
- package/scripts/check-plugin-v2-coverage.mjs +11 -8
- package/scripts/docs-check-changelog.mjs +204 -0
- package/scripts/docs-link-check.mjs +314 -0
- package/scripts/docs-media.mjs +157 -0
- package/scripts/doctor.mjs +828 -40
- package/scripts/install/agents-md.mjs +2 -2
- package/scripts/install/backup.mjs +648 -0
- package/scripts/install/cli-ui.mjs +303 -72
- package/scripts/install/component-selection.mjs +61 -0
- package/scripts/install/config-migration.mjs +583 -27
- package/scripts/install/exit-codes.mjs +26 -0
- package/scripts/install/file-inventory.mjs +555 -0
- package/scripts/install/health-check.mjs +31 -25
- package/scripts/install/interactive.mjs +78 -383
- package/scripts/install/migrate.mjs +49 -25
- package/scripts/install/model-picker.mjs +218 -250
- package/scripts/install/opencode-version.mjs +83 -21
- package/scripts/install/opencode.mjs +1413 -154
- package/scripts/install/plan-artifact.mjs +517 -0
- package/scripts/install/plan.mjs +475 -0
- package/scripts/install/plugin.mjs +214 -27
- package/scripts/install/prompt-result.mjs +2 -0
- package/scripts/install/shared.mjs +256 -99
- package/scripts/install/state.mjs +63 -8
- package/scripts/install/strings.mjs +60 -4
- package/scripts/install/venv.mjs +90 -47
- package/scripts/install/verify.mjs +128 -0
- package/scripts/install/vision-prompt.mjs +173 -0
- package/scripts/install-mcp.mjs +2 -2
- package/scripts/manifest-inventory.mjs +49 -3
- package/scripts/mcp_persistence.py +1535 -1050
- package/scripts/memory_mcp.py +12 -843
- package/scripts/node-engine-policy.mjs +85 -0
- package/scripts/package-evidence.mjs +10 -2
- package/scripts/postinstall.mjs +26 -26
- package/scripts/probe-pantheon-cost.mjs +118 -19
- package/scripts/prune.mjs +9 -3
- package/scripts/reconcile.mjs +325 -0
- package/scripts/release-gates.mjs +682 -0
- package/scripts/restore.mjs +222 -0
- package/scripts/run-node-tests.mjs +24 -8
- package/scripts/sync-artifacts.mjs +19 -7
- package/scripts/sync-tui.mjs +5 -1
- package/scripts/test-opencode-v2-sandbox.sh +36 -123
- package/scripts/uninstall.mjs +369 -34
- package/scripts/update.mjs +164 -0
- package/scripts/validate-node-engine-policy.mjs +13 -0
- package/scripts/version-check.mjs +34 -1
- package/scripts/versioning.mjs +23 -3
- package/scripts/vision-status.mjs +682 -0
- package/skills-lock.json +8 -8
- package/src/agents/aphrodite.md +13 -10
- package/src/agents/apollo.md +4 -5
- package/src/agents/athena.md +74 -46
- package/src/agents/demeter.md +10 -7
- package/src/agents/gaia.md +0 -1
- package/src/agents/hephaestus.md +4 -3
- package/src/agents/hermes.md +10 -9
- package/src/agents/iris.md +6 -1
- package/src/agents/mnemosyne.md +10 -4
- package/src/agents/nyx.md +4 -4
- package/src/agents/prometheus.md +12 -11
- package/src/agents/talos.md +6 -0
- package/src/agents/zeus.md +84 -56
- package/src/instructions/agent-return-format.instructions.md +12 -41
- package/src/instructions/memory-protocol.instructions.md +5 -11
- package/src/instructions/test-economy.instructions.md +12 -0
- package/src/instructions/yagni.instructions.md +6 -15
- package/src/instructions/zeus-anti-stall.instructions.md +6 -6
- package/src/instructions/zeus-communication-rules.instructions.md +6 -6
- package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
- package/src/instructions/zeus-memory-operations.instructions.md +13 -7
- package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
- package/src/mcp/_pantheon_paths.py +24 -0
- package/src/mcp/mcp_codemap_module.py +86 -18
- package/src/mcp/mcp_persistence.py +1535 -1050
- package/src/mcp/memory_mcp.py +444 -94
- package/src/mcp/pantheon_vision.py +285 -41
- package/src/mcp/requirements-mcp.txt +5 -0
- package/src/pantheon/context-pruner.ts +541 -0
- package/src/pantheon/cost-command.ts +814 -60
- package/src/pantheon/goal-loop.ts +11 -8
- package/src/pantheon/memory-context.ts +1017 -0
- package/src/pantheon/model-agents.ts +19 -0
- package/src/pantheon/model-command.ts +218 -56
- package/src/pantheon/model-pricing.ts +536 -0
- package/src/pantheon/presets.mjs +2 -0
- package/src/pantheon/task-result-guard.ts +50 -14
- package/src/pantheon/v2-bounded-read.ts +640 -0
- package/src/pantheon/v2-delegation-enforce.ts +133 -6
- package/src/pantheon/v2-execute-after.ts +135 -24
- package/src/pantheon/v2-model-overrides.ts +275 -0
- package/src/pantheon/v2-tools.ts +89 -35
- package/src/pantheon/v2-unsupported.mjs +2 -3
- package/src/pantheon/v2-vision.ts +622 -0
- package/src/pantheon/vision-local.ts +531 -0
- package/src/pantheon/vision.ts +1160 -115
- package/src/plugin-v2.ts +654 -162
- package/src/plugin.ts +15 -11
- package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +3742 -85
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +6 -6
- package/src/plugins/tui/package.json +5 -4
- package/src/plugins/tui/src/index-v2.tsx +4314 -50
- package/src/plugins/tui/tsconfig.typecheck.json +5 -0
- package/src/routing.yml +50 -5
- package/src/skills/agent-coordination/SKILL.md +7 -2
- package/src/skills/artifact-management/SKILL.md +5 -1
- package/src/skills/auto-continue/SKILL.md +14 -6
- package/src/skills/codemap/SKILL.md +1 -1
- package/src/skills/memory-bank/SKILL.md +21 -13
- package/src/skills/session-goal/SKILL.md +12 -22
- package/src/skills/spec-driven-development/SKILL.md +3 -1
- package/src/skills/worktrees/SKILL.md +30 -11
- package/scripts/probe-context-rehydrate.mjs +0 -263
|
@@ -0,0 +1,536 @@
|
|
|
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
|
+
}
|
package/src/pantheon/presets.mjs
CHANGED
|
@@ -61,6 +61,8 @@ export const CAPABILITY_TABLE = [
|
|
|
61
61
|
// entry above matches 'mimo/v2.5' (full-string) but NOT 'mimo-v2.5'
|
|
62
62
|
// (segment 'mimo-v2.5' has no slash, so 'mimo/' prefix cannot match).
|
|
63
63
|
{ prefix: 'mimo-v2.5', maxEffort: 'low', stripEffort: false, vision: true },
|
|
64
|
+
// Current free OpenCode Zen vision model (renamed to the v2.6 Flash family).
|
|
65
|
+
{ prefix: 'mimo-v2.6-flash', maxEffort: 'low', stripEffort: false, vision: true },
|
|
64
66
|
// mimo-v2.5-pro is text-only per models.dev api.json (2026-08-27).
|
|
65
67
|
{ prefix: 'mimo-v2.5-pro', maxEffort: 'low', stripEffort: false, vision: false },
|
|
66
68
|
// Go subscription specific — bare segment prefixes so opencode-go/<model> IDs match
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Task Result Guard — detects empty task
|
|
3
|
-
*
|
|
2
|
+
* Task Result Guard — detects empty `task`/`subagent` tool results and converts
|
|
3
|
+
* them to explicit errors. Accepted labels do not prove live-host event mapping.
|
|
4
4
|
*
|
|
5
5
|
* Bug context (reproduced 2026-09-10): task() native creates a child session
|
|
6
6
|
* that inherits the parent transcript. When the payload exceeds the provider's
|
|
@@ -11,9 +11,9 @@
|
|
|
11
11
|
* task as `completed` with empty content. The parent LLM receives an empty
|
|
12
12
|
* result and proceeds as if the task succeeded.
|
|
13
13
|
*
|
|
14
|
-
* The guard intercepts
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* The guard intercepts empty results for either `task` or `subagent` tool
|
|
15
|
+
* labels in `tool.execute.after` and replaces them with an explicit error.
|
|
16
|
+
* This adapter compatibility does not establish which label a live host emits.
|
|
17
17
|
*
|
|
18
18
|
* Pure TypeScript — zero runtime dependencies. Meant to be wired into the
|
|
19
19
|
* `combinedAfter` hook chain in plugin.ts alongside the sandbox and read
|
|
@@ -57,32 +57,68 @@ export interface TaskResultGuardOptions {
|
|
|
57
57
|
// ─── Constants ─────────────────────────────────────────────────────────
|
|
58
58
|
|
|
59
59
|
/**
|
|
60
|
-
* The error message injected when a
|
|
60
|
+
* The error message injected when a child-dispatch result is empty.
|
|
61
61
|
* Keeps the historical "no assistant or tool output" contract text.
|
|
62
62
|
*/
|
|
63
63
|
export const EMPTY_TASK_ERROR =
|
|
64
64
|
'ERROR: task() returned empty output — child session produced no assistant or tool output. ' +
|
|
65
65
|
'This typically means the provider rejected the request (admission control / rate limit) ' +
|
|
66
66
|
'or the child session crashed before producing any response. ' +
|
|
67
|
-
'Consider splitting the work into a smaller task
|
|
67
|
+
'Consider splitting the work into a smaller task. No retry is automatic; investigate before retrying manually.'
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The placeholder text the HOST substitutes into a child-dispatch tool result
|
|
71
|
+
* when the child produced no assistant text.
|
|
72
|
+
*
|
|
73
|
+
* Field-measured on an OpenCode V2 host: the host binary contains the literal
|
|
74
|
+
* `Subagent completed without a text response.` and injects it into the tool
|
|
75
|
+
* result, so the parent sees a success-looking string instead of silence.
|
|
76
|
+
*
|
|
77
|
+
* This MUST be re-confirmed against each host build — if a host changes the
|
|
78
|
+
* wording, this branch silently stops firing again.
|
|
79
|
+
*/
|
|
80
|
+
export const HOST_EMPTY_RESULT_TEXT = 'Subagent completed without a text response.'
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Whether a tool label is a child dispatch the guard must inspect.
|
|
84
|
+
*
|
|
85
|
+
* The accepted labels are `task` and `subagent`. Exported so the V2 adapter's
|
|
86
|
+
* pre-guard early return uses the SAME set: a label the guard handles must
|
|
87
|
+
* never be dropped before the guard sees it.
|
|
88
|
+
*
|
|
89
|
+
* @param tool - the tool label reported by the host
|
|
90
|
+
* @returns `true` for `task` and `subagent`
|
|
91
|
+
*/
|
|
92
|
+
export function isChildDispatchTool(tool: string): boolean {
|
|
93
|
+
return tool === 'task' || tool === 'subagent'
|
|
94
|
+
}
|
|
68
95
|
|
|
69
96
|
// ─── Implementation ────────────────────────────────────────────────────
|
|
70
97
|
|
|
71
98
|
/**
|
|
72
99
|
* Whether a result carries any text content (whitespace-only counts as empty).
|
|
100
|
+
*
|
|
101
|
+
* The host placeholder ({@link HOST_EMPTY_RESULT_TEXT}) also counts as empty:
|
|
102
|
+
* it means "no child text", not "the child answered".
|
|
103
|
+
*
|
|
104
|
+
* The host placeholder is matched EXACTLY (after trimming). Substring or
|
|
105
|
+
* prefix matching would rewrite legitimate agent messages that merely quote
|
|
106
|
+
* the phrase, which is worse than the defect being fixed.
|
|
73
107
|
*/
|
|
74
108
|
function isEmptyOutput(output: unknown): boolean {
|
|
75
109
|
if (output == null) return true
|
|
76
110
|
if (typeof output !== 'string') return true
|
|
77
|
-
|
|
111
|
+
const trimmed = output.trim()
|
|
112
|
+
if (trimmed === '') return true
|
|
113
|
+
return trimmed === HOST_EMPTY_RESULT_TEXT
|
|
78
114
|
}
|
|
79
115
|
|
|
80
116
|
/**
|
|
81
117
|
* Create a task result guard handler for the `tool.execute.after` hook.
|
|
82
118
|
*
|
|
83
|
-
* When the tool is `task` and
|
|
84
|
-
* the output with an explicit error message.
|
|
85
|
-
* untouched.
|
|
119
|
+
* When the tool label is `task` or `subagent` and its output is
|
|
120
|
+
* empty/whitespace-only, replaces the output with an explicit error message.
|
|
121
|
+
* All other tools pass through untouched; no child is retried automatically.
|
|
86
122
|
*
|
|
87
123
|
* @returns A `ToolExecuteAfterHandler`-compatible async function.
|
|
88
124
|
*/
|
|
@@ -90,14 +126,14 @@ export function createTaskResultGuard(options?: TaskResultGuardOptions): TaskRes
|
|
|
90
126
|
const warn = options?.logger?.warn ?? ((message: string) => log.warn(message))
|
|
91
127
|
|
|
92
128
|
return async (input: TaskGuardInput, output: TaskGuardOutput): Promise<void> => {
|
|
93
|
-
//
|
|
94
|
-
if (input.tool
|
|
129
|
+
// Accept both labels without claiming which one a live host emits.
|
|
130
|
+
if (!isChildDispatchTool(input.tool)) return
|
|
95
131
|
|
|
96
132
|
// Only flag truly empty results — non-empty content is the happy path.
|
|
97
133
|
if (!isEmptyOutput(output.output)) return
|
|
98
134
|
|
|
99
135
|
warn(
|
|
100
|
-
`[task-result-guard] Empty
|
|
136
|
+
`[task-result-guard] Empty ${input.tool} result detected on session ${input.sessionID} ` +
|
|
101
137
|
`(callID=${input.callID}). Replacing with explicit error.`,
|
|
102
138
|
)
|
|
103
139
|
|