pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-gates.mjs +6 -82
  42. package/scripts/release-notes.mjs +30 -7
  43. package/scripts/restore.mjs +22 -10
  44. package/scripts/sync-tui.mjs +3 -3
  45. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  46. package/scripts/versioning.mjs +41 -5
  47. package/src/agents/aphrodite.md +6 -1
  48. package/src/agents/apollo.md +1 -0
  49. package/src/agents/athena.md +1 -0
  50. package/src/agents/demeter.md +1 -1
  51. package/src/agents/gaia.md +1 -0
  52. package/src/agents/hephaestus.md +1 -1
  53. package/src/agents/hermes.md +8 -10
  54. package/src/agents/iris.md +1 -1
  55. package/src/agents/mnemosyne.md +1 -0
  56. package/src/agents/nyx.md +1 -1
  57. package/src/agents/prometheus.md +1 -1
  58. package/src/agents/talos.md +6 -1
  59. package/src/agents/themis.md +1 -1
  60. package/src/agents/zeus.md +52 -62
  61. package/src/mcp/eval_store.py +11 -4
  62. package/src/mcp/mcp_resources.py +11 -9
  63. package/src/mcp/memory_mcp.py +293 -150
  64. package/src/pantheon/cost-command.ts +30 -133
  65. package/src/pantheon/jev-decision-tool.ts +359 -0
  66. package/src/pantheon/jev-decisions.ts +625 -0
  67. package/src/pantheon/local-decision-agents.ts +170 -0
  68. package/src/pantheon/local-decision-budget.ts +1046 -0
  69. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  70. package/src/pantheon/local-decision-prompt.ts +256 -0
  71. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  72. package/src/pantheon/local-decision-router.ts +225 -0
  73. package/src/pantheon/local-decision-skills.ts +281 -0
  74. package/src/pantheon/local-decision-tool.ts +160 -0
  75. package/src/pantheon/local-decision-turn.ts +101 -0
  76. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  77. package/src/pantheon/local-orchestration.ts +322 -0
  78. package/src/pantheon/model-pricing.ts +1 -536
  79. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  80. package/src/pantheon/v2-decision-budget.ts +456 -0
  81. package/src/pantheon/v2-decision-contracts.ts +300 -0
  82. package/src/pantheon/v2-decision-egress.ts +203 -0
  83. package/src/pantheon/v2-decision-events.ts +180 -0
  84. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  85. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  86. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  87. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  88. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  89. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  90. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  91. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  92. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  93. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  94. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  95. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  96. package/src/pantheon/v2-decision-points.ts +242 -0
  97. package/src/pantheon/v2-decision-policy.ts +166 -0
  98. package/src/pantheon/v2-decision-premises.ts +146 -0
  99. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  100. package/src/pantheon/v2-decision-rank.ts +91 -0
  101. package/src/pantheon/v2-decision-registry.ts +391 -0
  102. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  103. package/src/pantheon/v2-decision-shadow.ts +123 -0
  104. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  105. package/src/pantheon/v2-decision-verify.ts +51 -0
  106. package/src/pantheon/v2-hook-engine.ts +307 -0
  107. package/src/pantheon/v2-native-decisions.ts +365 -0
  108. package/src/pantheon/v2-shell-hooks.ts +66 -2
  109. package/src/pantheon/v2-tools.ts +38 -15
  110. package/src/plugin-v2.ts +419 -26
  111. package/src/plugin.ts +4 -0
  112. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  113. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  114. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  115. package/src/plugins/tui/dist/server-v2.js +19 -666
  116. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  117. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  119. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  121. package/src/plugins/tui/dist/tui.js +1 -1
  122. package/src/plugins/tui/package-lock.json +17 -2
  123. package/src/plugins/tui/package.json +4 -2
  124. package/src/plugins/tui/src/cost-data.ts +607 -0
  125. package/src/plugins/tui/src/index-v2.tsx +213 -54
  126. package/src/plugins/tui/src/model-pricing.ts +536 -0
  127. package/src/plugins/tui/src/server-v2.ts +18 -838
  128. package/src/plugins/tui/tsdown.config.ts +28 -6
  129. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  130. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  131. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  132. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  133. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  134. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  135. package/src/plugins/tui/dist/quota-cli.js +0 -184
  136. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  138. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  139. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  140. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  141. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  142. package/src/plugins/tui/src/quota-cli.ts +0 -237
  143. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  144. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  145. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -0,0 +1,758 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process'
3
+ import { existsSync } from 'node:fs'
4
+ import { pathToFileURL } from 'node:url'
5
+ // Prebuilt bundles: Node refuses to strip TypeScript types under node_modules,
6
+ // so the published CLI cannot import the TypeScript sources directly. Regenerate
7
+ // with `npm run build:decision-router`; `--check` guards against drift.
8
+ import {
9
+ openLocalDecisionBudgetLedger,
10
+ resolveLocalDecisionBudgetDbPath,
11
+ } from './decision-router-budget.mjs'
12
+ import {
13
+ evaluateCapGate,
14
+ evaluatePeriodGate,
15
+ inspectDecisionBudget,
16
+ listDecisionHoldsReadOnly,
17
+ utcPeriodOf,
18
+ } from './decision-router-v2-budget.mjs'
19
+ import {
20
+ resolveV2DecisionEgress,
21
+ V2_DECISION_EGRESS_DEFAULT,
22
+ V2_DECISION_EGRESS_TRANSPORT,
23
+ } from './decision-router-v2-egress.mjs'
24
+ import {
25
+ applyDecisionLayerPlan,
26
+ buildDecisionLayerPlan,
27
+ formatDecisionLayerPlan,
28
+ resolveInstallStatePath,
29
+ toDecisionLayerPlanJson,
30
+ } from './install/decision-layer-preview.mjs'
31
+ import {
32
+ DECISION_PROVIDER_BUDGET_MAPPING,
33
+ DECISION_ROUTER_MODELS,
34
+ diffDecisionRouterSurfaces,
35
+ readUserDecisionRouterConfig,
36
+ resolveUserDecisionRouterConfigPath,
37
+ updateUserDecisionRouterConfig,
38
+ writeUserDecisionRouterConfig,
39
+ } from './install/decision-router-config.mjs'
40
+ import { readState } from './install/state.mjs'
41
+
42
+ const BUDGET_PROVIDERS = DECISION_PROVIDER_BUDGET_MAPPING
43
+
44
+ const USAGE =
45
+ 'Usage: decision-router help|status|setup|preview|select|enable|disable|consent|caps|period|holds|setup-model|doctor'
46
+
47
+ /**
48
+ * Malformed command line (wrong flags, unknown provider, invalid value).
49
+ * Callers report it as a short message; a stack implies a bug, not bad input.
50
+ */
51
+ export class DecisionRouterUsageError extends TypeError {
52
+ name = 'DecisionRouterUsageError'
53
+ }
54
+
55
+ /** Read-only command help. Touches no file, ledger or environment path. */
56
+ export function decisionRouterHelp() {
57
+ return [
58
+ USAGE,
59
+ '',
60
+ 'Read-only (never create, migrate or write anything):',
61
+ ' help this text',
62
+ ' status [--target <dir>] configuration, egress posture and budget facts',
63
+ ' setup [options] computed artifact diff; writes only with --apply',
64
+ ' preview alias of `setup` (never writes)',
65
+ ' holds unresolved reservations, read-only',
66
+ '',
67
+ 'Explicit actions (each one changes exactly one thing):',
68
+ ' select local|auto|<provider>/<model> record a selection; enables nothing',
69
+ ' enable | disable turn selection on or off',
70
+ ' enable <provider> <model> toggle one candidate',
71
+ ' consent yes|no record egress consent',
72
+ ' caps user|provider <p>|model <p> <m> --monthly-usd N --per-decision-usd N',
73
+ ' period confirm --current none|YYYY-MM --next YYYY-MM',
74
+ '',
75
+ 'Guided (each does the whole chain in one command):',
76
+ ' setup-model <provider>/<model> --monthly-usd N --per-decision-usd N [--no-consent]',
77
+ ' select + enable + consent + caps + period in one write,',
78
+ ' then print the verification summary',
79
+ ' doctor read-only diagnosis of the native decision route with',
80
+ ' the exact command to run for each failing gate',
81
+ '',
82
+ 'setup options:',
83
+ ' --apply write the previewed artifacts (otherwise nothing is written)',
84
+ ' --json machine-readable plan',
85
+ ' --target <dir> also reconcile <dir>/.pantheon/install-state.json when present',
86
+ ' --selection <value> same values as `select`',
87
+ ' --accept-migration allow a schema migration that would enable turn selection',
88
+ '',
89
+ `Egress default: ${V2_DECISION_EGRESS_DEFAULT}. Enablement, consent, one cap- and period-eligible`,
90
+ 'candidate and the host permission gate are all required; any missing item means zero requests.',
91
+ `Provider endpoints are retained ${V2_DECISION_EGRESS_TRANSPORT.wireStatus} (UNWIRED) here; this`,
92
+ 'interface adds no transport and never claims the transport was removed.',
93
+ ].join('\n')
94
+ }
95
+
96
+ /** Run an explicit, non-secret administrative command for the user-level router config. */
97
+ export async function runDecisionRouterCommand(
98
+ args,
99
+ { env = process.env, stdout = console.log } = {},
100
+ ) {
101
+ const [command, ...rest] = args
102
+
103
+ if (command === 'help' || command === '--help' || command === '-h') {
104
+ if (rest.length > 0) throw new DecisionRouterUsageError(USAGE)
105
+ stdout(decisionRouterHelp())
106
+ return
107
+ }
108
+
109
+ if (command === 'status') {
110
+ const options = parseNamedFlags(rest, ['--target'])
111
+ const config = readUserDecisionRouterConfig({ env })
112
+ const dbPath = resolveLocalDecisionBudgetDbPath(env)
113
+ const inspection = inspectDecisionBudget(dbPath)
114
+ const wallPeriod = utcPeriodOf(Date.now())
115
+ const egress = describeEgress(config, inspection, wallPeriod)
116
+
117
+ stdout(`Config: ${resolveUserDecisionRouterConfigPath(env)}`)
118
+ stdout(
119
+ `Config file: ${existsSync(resolveUserDecisionRouterConfigPath(env)) ? 'present' : 'absent'}`,
120
+ )
121
+ stdout(`Enabled: ${config.enabled ? 'yes' : 'no'}`)
122
+ stdout(`Selection: ${formatSelection(config.selection)}`)
123
+ stdout(`Egress consent: ${config.egress_consent ? 'yes' : 'no'}`)
124
+ stdout(
125
+ `Enabled candidates: ${config.enabled_candidates.length ? config.enabled_candidates.map(formatCandidate).join(', ') : 'none'}`,
126
+ )
127
+ stdout(describeEgressLine(egress))
128
+ stdout(`Ledger: ${formatLedger(inspection, dbPath)}`)
129
+ stdout(`Budget period: ${formatPeriod(inspection)}`)
130
+ stdout(`Caps: ${formatCaps(inspection)}`)
131
+ if (options['--target'] !== undefined) {
132
+ stdout(`Install-state: ${formatInstallState(config, options['--target'])}`)
133
+ }
134
+ stdout('Mode: read-only — status and help never create, migrate or write anything.')
135
+ return
136
+ }
137
+
138
+ if (command === 'setup' || command === 'preview') {
139
+ const options = parseSetupOptions(rest, command === 'preview')
140
+ const plan = buildDecisionLayerPlan({
141
+ env,
142
+ ...(options['--target'] === undefined ? {} : { target: options['--target'] }),
143
+ ...(options['--selection'] === undefined
144
+ ? {}
145
+ : { selection: parseSelectionTarget(options['--selection']) }),
146
+ acceptMigration: options['--accept-migration'] === true,
147
+ })
148
+ if (options['--json'] === true) {
149
+ stdout(JSON.stringify(toDecisionLayerPlanJson(plan), null, 2))
150
+ } else {
151
+ stdout(
152
+ formatDecisionLayerPlan(plan, {
153
+ scope: options['--target'] ?? 'user',
154
+ applyPending: options['--apply'] === true,
155
+ }),
156
+ )
157
+ }
158
+ if (options['--apply'] === true) {
159
+ const result = applyDecisionLayerPlan(plan, { env })
160
+ stdout(
161
+ `Applied: ${result.written.length} written, ${result.skipped.length} unchanged. ` +
162
+ 'No backup copy was created.',
163
+ )
164
+ }
165
+ return
166
+ }
167
+
168
+ if (command === 'select') {
169
+ const target = rest[0]
170
+ if (rest.length !== 1 || typeof target !== 'string')
171
+ throw new DecisionRouterUsageError('Usage: decision-router select local|auto|provider/model')
172
+ const selection = parseSelectionTarget(target)
173
+ const before = readUserDecisionRouterConfig({ env })
174
+ saveConfig(env, { selection })
175
+ const after = readUserDecisionRouterConfig({ env })
176
+ const revoked = before.egress_consent && !after.egress_consent
177
+ stdout(
178
+ `Selection saved: ${formatSelection(selection)}. ${
179
+ revoked
180
+ ? 'Egress consent was revoked because the target changed; nothing was enabled.'
181
+ : 'Enablement, consent, caps and period are unchanged.'
182
+ }`,
183
+ )
184
+ return
185
+ }
186
+
187
+ if (command === 'enable' || command === 'disable') {
188
+ const [provider, model, ...extra] = rest
189
+ if (extra.length) {
190
+ throw new DecisionRouterUsageError(`Usage: decision-router ${command} [<provider> <model>]`)
191
+ }
192
+ if (provider === undefined && model === undefined) {
193
+ saveConfig(env, { enabled: command === 'enable' })
194
+ stdout(
195
+ `Turn selection ${command === 'enable' ? 'enabled' : 'disabled'}. Provider consent and candidate enablement are unchanged.`,
196
+ )
197
+ return
198
+ }
199
+ if (provider === undefined || !isKnownCandidate(provider, model)) {
200
+ throw new DecisionRouterUsageError(`Usage: decision-router ${command} <provider> <model>`)
201
+ }
202
+ const config = readUserDecisionRouterConfig({ env })
203
+ const key = candidateKey(provider, model)
204
+ const candidates = config.enabled_candidates.filter(
205
+ (candidate) => candidateKey(candidate.provider, candidate.model) !== key,
206
+ )
207
+ if (command === 'enable') candidates.push({ provider, model })
208
+ saveConfig(env, { enabled_candidates: candidates })
209
+ stdout(`${command === 'enable' ? 'Enabled' : 'Disabled'} ${provider}/${model}.`)
210
+ return
211
+ }
212
+
213
+ if (command === 'consent') {
214
+ const value = rest[0]
215
+ if (rest.length !== 1 || (value !== 'yes' && value !== 'no')) {
216
+ throw new DecisionRouterUsageError('Usage: decision-router consent yes|no')
217
+ }
218
+ saveConfig(env, { egress_consent: value === 'yes' })
219
+ stdout(`Egress consent saved: ${value}.`)
220
+ return
221
+ }
222
+
223
+ if (command === 'caps') {
224
+ const [scope, ...scopeArgs] = rest
225
+ const { monthly, perDecision, rest: targetArgs } = parseCaps(scopeArgs)
226
+ const ledger = openLedger(env)
227
+ try {
228
+ if (scope === 'user' && targetArgs.length === 0) {
229
+ ledger.configureUserCaps({ monthlyCapMicros: monthly, perDecisionCapMicros: perDecision })
230
+ } else if (scope === 'provider' && targetArgs.length === 1) {
231
+ const budgetProvider = Object.hasOwn(BUDGET_PROVIDERS, targetArgs[0])
232
+ ? BUDGET_PROVIDERS[targetArgs[0]]
233
+ : undefined
234
+ if (!budgetProvider) throw new DecisionRouterUsageError('Unsupported budget provider')
235
+ ledger.configureProviderCaps(budgetProvider, {
236
+ monthlyCapMicros: monthly,
237
+ perDecisionCapMicros: perDecision,
238
+ })
239
+ } else if (scope === 'model' && targetArgs.length === 2) {
240
+ const [provider, model] = targetArgs
241
+ if (!isKnownCandidate(provider, model))
242
+ throw new DecisionRouterUsageError('Unsupported provider/model pair')
243
+ ledger.configureModelCaps(BUDGET_PROVIDERS[provider], model, {
244
+ monthlyCapMicros: monthly,
245
+ perDecisionCapMicros: perDecision,
246
+ })
247
+ } else {
248
+ throw new DecisionRouterUsageError(
249
+ 'Usage: decision-router caps user|provider <provider>|model <provider> <model> --monthly-usd N --per-decision-usd N',
250
+ )
251
+ }
252
+ } finally {
253
+ ledger.close()
254
+ }
255
+ stdout(
256
+ `Configured ${scope} admission caps. Caps limit local admission; they are not invoice guarantees.`,
257
+ )
258
+ return
259
+ }
260
+
261
+ if (command === 'holds' && rest.length === 0) {
262
+ // Read-only: a listing must never create, migrate or reserve anything (D8).
263
+ const holds = listDecisionHoldsReadOnly(resolveLocalDecisionBudgetDbPath(env))
264
+ if (holds === null || holds.length === 0) {
265
+ stdout('No unresolved provider holds.')
266
+ return
267
+ }
268
+ for (const hold of holds) {
269
+ stdout(
270
+ `Hold ${hold.reservationId}: status=${hold.state} provider=${hold.provider} model=${hold.model} period=${hold.period} reserved_micros=${hold.reservedMicros}`,
271
+ )
272
+ }
273
+ stdout(
274
+ 'This listing is read-only: it does not reserve, reconcile, release or prune, it never ' +
275
+ 'creates or migrates the ledger, and unresolved holds are never auto-released. ' +
276
+ 'Reconcile or resolve them explicitly before pruning their period.',
277
+ )
278
+ return
279
+ }
280
+
281
+ if (command === 'period') {
282
+ const [action, ...periodArgs] = rest
283
+ if (action !== 'confirm')
284
+ throw new DecisionRouterUsageError(
285
+ 'Usage: decision-router period confirm --current none|YYYY-MM --next YYYY-MM',
286
+ )
287
+ const options = parseNamedOptions(periodArgs, ['--current', '--next'])
288
+ const expected = options['--current'] === 'none' ? null : options['--current']
289
+ const target = options['--next']
290
+ if ((expected !== null && !isMonth(expected)) || !isMonth(target)) {
291
+ throw new DecisionRouterUsageError(
292
+ 'Budget periods must use YYYY-MM; initial current period is `none`',
293
+ )
294
+ }
295
+ const ledger = openLedger(env)
296
+ try {
297
+ const result = ledger.confirmBudgetPeriod(expected, target)
298
+ if (result.status !== 'confirmed')
299
+ throw new Error(`Budget period confirmation denied: ${result.reason}`)
300
+ stdout(`Explicit period confirmed: ${result.activePeriod}. Automatic rollover is disabled.`)
301
+ } finally {
302
+ ledger.close()
303
+ }
304
+ return
305
+ }
306
+
307
+ if (command === 'setup-model') {
308
+ const [target, ...flagArgs] = rest
309
+ const selection = parseSelectionTarget(target)
310
+ if (selection.mode !== 'explicit') {
311
+ throw new DecisionRouterUsageError(
312
+ 'setup-model requires an explicit provider/model pair, not local or auto',
313
+ )
314
+ }
315
+ const noConsent = flagArgs.includes('--no-consent')
316
+ const capArgs = flagArgs.filter((arg) => arg !== '--no-consent')
317
+ // Exactly the two caps flags with values; parseCaps validates them and
318
+ // leaves `rest` empty because setup-model has no positional caps targets.
319
+ if (capArgs.length !== 4) throw new DecisionRouterUsageError(USAGE)
320
+ const caps = parseCaps(capArgs)
321
+ if (caps.rest.length > 0) throw new DecisionRouterUsageError(USAGE)
322
+ const { provider, model } = selection
323
+ const candidate = { provider, model }
324
+
325
+ // One update names selection, enablement, candidates and (unless refused)
326
+ // consent together: selecting a different target revokes consent unless
327
+ // the same update names it, so this single write is the consent act.
328
+ saveConfig(env, {
329
+ enabled: true,
330
+ selection,
331
+ enabled_candidates: [candidate],
332
+ ...(noConsent ? {} : { egress_consent: true }),
333
+ })
334
+ stdout(`Selected and enabled ${provider}/${model}.`)
335
+ stdout(
336
+ noConsent ? 'Egress consent NOT recorded (--no-consent).' : 'Egress consent recorded: yes.',
337
+ )
338
+
339
+ const ledger = openLedger(env)
340
+ try {
341
+ ledger.configureUserCaps({
342
+ monthlyCapMicros: caps.monthly,
343
+ perDecisionCapMicros: caps.perDecision,
344
+ })
345
+ ledger.configureProviderCaps(DECISION_PROVIDER_BUDGET_MAPPING[provider], {
346
+ monthlyCapMicros: caps.monthly,
347
+ perDecisionCapMicros: caps.perDecision,
348
+ })
349
+ ledger.configureModelCaps(DECISION_PROVIDER_BUDGET_MAPPING[provider], model, {
350
+ monthlyCapMicros: caps.monthly,
351
+ perDecisionCapMicros: caps.perDecision,
352
+ })
353
+ stdout(
354
+ `Caps set (user/provider/model): $${(caps.monthly / 1_000_000).toFixed(2)}/month, $${(caps.perDecision / 1_000_000).toFixed(2)}/decision.`,
355
+ )
356
+ const wallPeriod = utcPeriodOf(Date.now())
357
+ const active = ledger.getActiveBudgetPeriod()
358
+ if (active === wallPeriod) {
359
+ stdout(`Budget period already active: ${wallPeriod}.`)
360
+ } else {
361
+ const result = ledger.confirmBudgetPeriod(active, wallPeriod)
362
+ if (result.status === 'confirmed') {
363
+ stdout(`Budget period confirmed: ${result.activePeriod}. Automatic rollover is disabled.`)
364
+ } else {
365
+ stdout(
366
+ `Budget period NOT confirmed (${result.reason}); run: decision-router period confirm --current ${active ?? 'none'} --next ${wallPeriod}`,
367
+ )
368
+ }
369
+ }
370
+ } finally {
371
+ ledger.close()
372
+ }
373
+
374
+ stdout('')
375
+ stdout('Native route checklist:')
376
+ stdout(
377
+ ' 1. Host catalog: the model must exist as type "decision" (stock: opencode/jev-1.13; custom providers need type: "decision" in opencode.json). Verify: decision-router doctor',
378
+ )
379
+ stdout(' 2. Restart OpenCode so the plugin registers pantheon_jev_decide.')
380
+ stdout(' 3. Ask the Zeus agent to call pantheon_jev_decide (mode: "delegation" or "skills").')
381
+ stdout('Read-only verification: decision-router status / doctor / holds.')
382
+ return
383
+ }
384
+
385
+ if (command === 'doctor' && rest.length === 0) {
386
+ // Read-only diagnosis. The host-catalog probe runs `opencode models` with a
387
+ // timeout; a missing/unavailable binary is a warning, not a failure.
388
+ const config = readUserDecisionRouterConfig({ env })
389
+ const dbPath = resolveLocalDecisionBudgetDbPath(env)
390
+ const inspection = inspectDecisionBudget(dbPath)
391
+ const wallPeriod = utcPeriodOf(Date.now())
392
+ const egress = describeEgress(config, inspection, wallPeriod)
393
+ const rows = []
394
+ const fail = (name, detail, fix) => rows.push({ name, state: 'FAIL', detail, fix })
395
+ const warn = (name, detail, fix) => rows.push({ name, state: 'WARN', detail, fix })
396
+ const pass = (name, detail) => rows.push({ name, state: 'PASS', detail })
397
+
398
+ if (!existsSync(resolveUserDecisionRouterConfigPath(env))) {
399
+ fail(
400
+ 'config',
401
+ 'no user-level config yet',
402
+ 'decision-router setup-model <provider>/<model> --monthly-usd N --per-decision-usd N',
403
+ )
404
+ } else if (!config.enabled) {
405
+ fail('config', 'turn selection is disabled', 'decision-router enable')
406
+ } else {
407
+ pass('config', 'enabled')
408
+ }
409
+ if (config.enabled && !config.egress_consent) {
410
+ fail(
411
+ 'consent',
412
+ 'egress consent missing',
413
+ 'decision-router consent yes (or rerun setup-model without --no-consent)',
414
+ )
415
+ } else if (config.enabled) {
416
+ pass('consent', 'recorded')
417
+ }
418
+
419
+ const selection = config.selection
420
+ if (config.enabled && selection.mode === 'local') {
421
+ fail('selection', 'selection is local', 'decision-router select <provider>/<model>')
422
+ } else if (config.enabled && selection.mode === 'auto') {
423
+ if (egress.mode === 'opt-in')
424
+ pass('selection', `auto resolved ${egress.provider}/${egress.candidate.model}`)
425
+ else
426
+ fail(
427
+ 'selection',
428
+ `auto did not resolve (${egress.reason})`,
429
+ 'enable exactly one cap-valid candidate, or select explicitly',
430
+ )
431
+ } else if (config.enabled && selection.mode === 'explicit') {
432
+ const enabled = config.enabled_candidates.some(
433
+ (candidate) =>
434
+ candidate.provider === selection.provider && candidate.model === selection.model,
435
+ )
436
+ if (!enabled) {
437
+ fail(
438
+ 'selection',
439
+ `${selection.provider}/${selection.model} selected but not enabled`,
440
+ `decision-router enable ${selection.provider} ${selection.model}`,
441
+ )
442
+ } else {
443
+ pass('selection', `${selection.provider}/${selection.model}`)
444
+ }
445
+ }
446
+
447
+ if (config.enabled && egress.mode !== 'opt-in' && config.egress_consent) {
448
+ fail(
449
+ 'budget',
450
+ `no cap- and period-eligible candidate (${egress.reason})`,
451
+ 'decision-router caps user|provider|model ... and decision-router period confirm',
452
+ )
453
+ } else if (config.enabled && egress.mode === 'opt-in') {
454
+ pass('budget', `admission open for ${egress.provider}/${egress.candidate.model}`)
455
+ }
456
+ if (inspection.ledger.present && inspection.ledger.readable && inspection.ledger.holds > 0) {
457
+ warn(
458
+ 'holds',
459
+ `${inspection.ledger.holds} unresolved hold(s) hold budget until reconciled`,
460
+ 'decision-router holds',
461
+ )
462
+ }
463
+
464
+ const target =
465
+ config.enabled && selection.mode === 'explicit'
466
+ ? selection
467
+ : egress.mode === 'opt-in'
468
+ ? { provider: egress.provider, model: egress.candidate.model }
469
+ : null
470
+ if (target !== null) {
471
+ const probe = probeHostCatalog(env)
472
+ const hostProvider = target.provider === 'typesafe-jev' ? 'typesafe-ai' : 'opencode'
473
+ if (probe.ok) {
474
+ const exact = probe.models.has(`${hostProvider}/${target.model}`)
475
+ const loose = probe.models.has(target.model)
476
+ if (exact || loose) {
477
+ pass('host-catalog', `${hostProvider}/${target.model} listed by \`opencode models\``)
478
+ } else {
479
+ warn(
480
+ 'host-catalog',
481
+ `${hostProvider}/${target.model} not in the flat models list`,
482
+ 'the flat list can omit decision-typed models; if a call refuses with ROUTE_UNRESOLVED, add a custom provider entry with type: "decision" (see docs/reference/native-decisions.md) or pick a listed decision model',
483
+ )
484
+ }
485
+ } else {
486
+ warn(
487
+ 'host-catalog',
488
+ `could not probe: ${probe.reason}`,
489
+ 'run `opencode models` manually; slow plugin activation is the usual cause',
490
+ )
491
+ }
492
+ }
493
+
494
+ for (const row of rows) {
495
+ const mark = row.state === 'PASS' ? '✔' : row.state === 'WARN' ? '▲' : '✖'
496
+ stdout(`${mark} ${row.name}: ${row.detail}`)
497
+ if (row.fix) stdout(` fix → ${row.fix}`)
498
+ }
499
+ stdout('Read-only: doctor never creates, migrates or writes anything.')
500
+ return
501
+ }
502
+
503
+ throw new DecisionRouterUsageError(USAGE)
504
+ }
505
+
506
+ /** Spawn-sync timeout floor so a wedged host cannot stall the doctor. */
507
+ const HOST_PROBE_TIMEOUT_MS = 30_000
508
+
509
+ /**
510
+ * Best-effort host catalog probe for the doctor. Returns the set of
511
+ * `provider/model` (and bare model ids, for exact-id matching) the host
512
+ * reports, or the reason the probe failed. Never writes anything.
513
+ */
514
+ function probeHostCatalog(env) {
515
+ let result
516
+ try {
517
+ result = spawnSync('opencode', ['models'], {
518
+ encoding: 'utf8',
519
+ timeout: HOST_PROBE_TIMEOUT_MS,
520
+ env,
521
+ })
522
+ } catch (error) {
523
+ return { ok: false, reason: String(error?.message ?? error) }
524
+ }
525
+ if (result.error) return { ok: false, reason: String(result.error.message ?? result.error) }
526
+ if (result.status !== 0) {
527
+ const output = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim()
528
+ return { ok: false, reason: output.slice(0, 120) || `exit ${result.status}` }
529
+ }
530
+ const models = new Set()
531
+ for (const line of `${result.stdout ?? ''}`.split(/\r?\n/)) {
532
+ const id = line.trim()
533
+ if (!id) continue
534
+ models.add(id)
535
+ const slash = id.indexOf('/')
536
+ if (slash > 0) models.add(id.slice(slash + 1))
537
+ }
538
+ return { ok: true, models }
539
+ }
540
+
541
+ /** Cap- and period-eligible candidates, read-only, from the separated surfaces. */
542
+ function capEligibleCandidates(config, inspection, wallPeriod) {
543
+ if (inspection.caps === null) return []
544
+ const period = evaluatePeriodGate({
545
+ activePeriod: inspection.period.activePeriod,
546
+ wallPeriod,
547
+ })
548
+ return config.enabled_candidates.filter(({ provider, model }) => {
549
+ const accounting = DECISION_PROVIDER_BUDGET_MAPPING[provider]
550
+ if (!accounting) return false
551
+ const cap = evaluateCapGate({
552
+ user: inspection.caps.user ?? undefined,
553
+ provider: inspection.caps.providers[accounting],
554
+ model: inspection.caps.models[`${accounting}/${model}`],
555
+ })
556
+ return cap.ok && period.ok
557
+ })
558
+ }
559
+
560
+ function describeEgress(config, inspection, wallPeriod) {
561
+ return resolveV2DecisionEgress(config, capEligibleCandidates(config, inspection, wallPeriod))
562
+ }
563
+
564
+ function describeEgressLine(egress) {
565
+ if (egress.mode === 'opt-in') {
566
+ return `Egress: opt-in (${egress.reason}) — ${egress.provider}/${egress.candidate.model}`
567
+ }
568
+ return `Egress: ${egress.mode} (${egress.reason}) — zero requests`
569
+ }
570
+
571
+ function formatLedger(inspection, dbPath) {
572
+ const { ledger } = inspection
573
+ if (!ledger.present) return `${dbPath} (absent; not created by this command)`
574
+ if (!ledger.readable) return `${dbPath} (unreadable: ${ledger.reason})`
575
+ return `${dbPath} (schema v${ledger.schemaVersion}, ${ledger.holds} unresolved hold(s), ${ledger.reservations} reservation(s))`
576
+ }
577
+
578
+ function formatPeriod(inspection) {
579
+ const { ledger, period } = inspection
580
+ if (!ledger.present) return 'unconfirmed (no ledger)'
581
+ if (!ledger.readable) return `unknown (${ledger.reason})`
582
+ return period.activePeriod ?? 'unconfirmed'
583
+ }
584
+
585
+ function formatCaps(inspection) {
586
+ if (inspection.caps === null) return 'none (no ledger)'
587
+ const providers = Object.keys(inspection.caps.providers).length
588
+ const models = Object.keys(inspection.caps.models).length
589
+ return `${inspection.caps.user === null ? 'user none' : 'user set'}, ${providers} provider, ${models} model`
590
+ }
591
+
592
+ function formatInstallState(config, target) {
593
+ const statePath = resolveInstallStatePath(target)
594
+ if (!existsSync(statePath)) return `no install-state at ${statePath} (nothing to reconcile)`
595
+ const state = readState(target)
596
+ if (state === null) {
597
+ return `unreadable install-state at ${statePath} (left untouched; repair or reinstall first)`
598
+ }
599
+ const diff = diffDecisionRouterSurfaces(config, state.decision_router)
600
+ if (diff.differences.length === 0) return `consistent with ${statePath}`
601
+ const fields = diff.differences
602
+ .map(
603
+ (entry) =>
604
+ `${entry.field}: install-state ${String(entry.installState)} -> user-config ${String(entry.userConfig)}`,
605
+ )
606
+ .join(', ')
607
+ return `divergent from ${statePath} (${fields}); run \`decision-router setup --target ${target} --apply\``
608
+ }
609
+
610
+ function parseSelectionTarget(target) {
611
+ if (target === 'local' || target === 'auto') return { mode: target }
612
+ const [provider, model, ...extra] = String(target).split('/')
613
+ if (extra.length || !isKnownCandidate(provider, model)) {
614
+ throw new DecisionRouterUsageError('Selection must name one supported provider/model pair')
615
+ }
616
+ return { mode: 'explicit', provider, model }
617
+ }
618
+
619
+ function parseNamedFlags(args, expected) {
620
+ const result = Object.create(null)
621
+ for (let index = 0; index < args.length; index += 1) {
622
+ const flag = args[index]
623
+ if (!expected.includes(flag) || Object.hasOwn(result, flag)) {
624
+ throw new DecisionRouterUsageError(USAGE)
625
+ }
626
+ const value = args[index + 1]
627
+ if (value === undefined || value.startsWith('--')) throw new DecisionRouterUsageError(USAGE)
628
+ result[flag] = value
629
+ index += 1
630
+ }
631
+ return result
632
+ }
633
+
634
+ function parseSetupOptions(args, forbidApply) {
635
+ const result = Object.create(null)
636
+ let index = 0
637
+ while (index < args.length) {
638
+ const flag = args[index]
639
+ if (flag === '--apply') {
640
+ if (forbidApply) {
641
+ throw new DecisionRouterUsageError('preview never writes; use `setup --apply`')
642
+ }
643
+ if (result['--apply'] === true) throw new DecisionRouterUsageError(USAGE)
644
+ result['--apply'] = true
645
+ index += 1
646
+ continue
647
+ }
648
+ if (flag === '--json' || flag === '--accept-migration') {
649
+ if (result[flag] === true) throw new DecisionRouterUsageError(USAGE)
650
+ result[flag] = true
651
+ index += 1
652
+ continue
653
+ }
654
+ if (flag === '--target' || flag === '--selection') {
655
+ const value = args[index + 1]
656
+ if (value === undefined || value.startsWith('--') || Object.hasOwn(result, flag)) {
657
+ throw new DecisionRouterUsageError(USAGE)
658
+ }
659
+ result[flag] = value
660
+ index += 2
661
+ continue
662
+ }
663
+ throw new DecisionRouterUsageError(USAGE)
664
+ }
665
+ return result
666
+ }
667
+
668
+ function saveConfig(env, update) {
669
+ const current = readUserDecisionRouterConfig({ env })
670
+ const next = updateUserDecisionRouterConfig(current, update)
671
+ writeUserDecisionRouterConfig(next, { env })
672
+ }
673
+
674
+ function openLedger(env) {
675
+ return openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath(env) })
676
+ }
677
+
678
+ function parseCaps(args) {
679
+ const firstFlag = args.findIndex((arg) => arg.startsWith('--'))
680
+ const targetArgs = firstFlag === -1 ? args : args.slice(0, firstFlag)
681
+ const optionArgs = firstFlag === -1 ? [] : args.slice(firstFlag)
682
+ const missing = ['--monthly-usd', '--per-decision-usd'].filter(
683
+ (flag) => !optionArgs.includes(flag),
684
+ )
685
+ if (missing.length > 0) {
686
+ throw new DecisionRouterUsageError('Both --monthly-usd and --per-decision-usd are required')
687
+ }
688
+ const flags = parseNamedOptions(optionArgs, ['--monthly-usd', '--per-decision-usd'])
689
+ return {
690
+ monthly: parseUsdMicros(flags['--monthly-usd']),
691
+ perDecision: parseUsdMicros(flags['--per-decision-usd']),
692
+ rest: targetArgs,
693
+ }
694
+ }
695
+
696
+ function parseNamedOptions(args, expected) {
697
+ if (args.length !== expected.length * 2)
698
+ throw new DecisionRouterUsageError('Missing or extra command options')
699
+ const result = Object.create(null)
700
+ for (let index = 0; index < args.length; index += 2) {
701
+ const key = args[index]
702
+ const value = args[index + 1]
703
+ if (!expected.includes(key) || Object.hasOwn(result, key) || !value || value.startsWith('--')) {
704
+ throw new DecisionRouterUsageError('Invalid or duplicate command option')
705
+ }
706
+ result[key] = value
707
+ }
708
+ if (expected.some((key) => !Object.hasOwn(result, key)))
709
+ throw new DecisionRouterUsageError('Missing command option')
710
+ return result
711
+ }
712
+
713
+ function parseUsdMicros(value) {
714
+ if (typeof value !== 'string' || !/^(0|[1-9]\d*)(?:\.\d{1,6})?$/.test(value)) {
715
+ throw new DecisionRouterUsageError(
716
+ 'USD cap must be a non-negative decimal with at most six fractional digits',
717
+ )
718
+ }
719
+ const [whole, fraction = ''] = value.split('.')
720
+ const micros = Number(whole) * 1_000_000 + Number(fraction.padEnd(6, '0'))
721
+ if (!Number.isSafeInteger(micros))
722
+ throw new DecisionRouterUsageError('USD cap exceeds the supported range')
723
+ return micros
724
+ }
725
+
726
+ function isKnownCandidate(provider, model) {
727
+ return (
728
+ typeof provider === 'string' &&
729
+ typeof model === 'string' &&
730
+ DECISION_ROUTER_MODELS[provider]?.includes(model)
731
+ )
732
+ }
733
+
734
+ function isMonth(value) {
735
+ return typeof value === 'string' && /^\d{4}-(0[1-9]|1[0-2])$/.test(value)
736
+ }
737
+
738
+ function candidateKey(provider, model) {
739
+ return `${provider}/${model}`
740
+ }
741
+
742
+ function formatSelection(selection) {
743
+ if (selection.mode === 'explicit') return `${selection.provider}/${selection.model}`
744
+ return selection.mode
745
+ }
746
+
747
+ function formatCandidate(candidate) {
748
+ return `${candidate.provider}/${candidate.model}`
749
+ }
750
+
751
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
752
+ runDecisionRouterCommand(process.argv.slice(2)).catch((error) => {
753
+ console.error(
754
+ `Error: ${error instanceof Error ? error.message : 'Decision-router command failed'}`,
755
+ )
756
+ process.exitCode = 1
757
+ })
758
+ }