pantheon-opencode 1.6.3-beta.1 → 1.6.3-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 (54) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +81 -0
  4. package/README.md +20 -2
  5. package/bin/pantheon-init.mjs +15 -27
  6. package/package.json +1 -1
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +1 -1
  9. package/scripts/decision-router-budget.mjs +103 -4
  10. package/scripts/decision-router-v2-budget.mjs +2 -2
  11. package/scripts/decision-router-v2-egress.mjs +0 -2
  12. package/scripts/decision-router.mjs +88 -6
  13. package/scripts/install/decision-router-config.mjs +53 -2
  14. package/scripts/install/interactive.mjs +96 -11
  15. package/scripts/install/opencode.mjs +26 -0
  16. package/scripts/install/plugin.mjs +17 -0
  17. package/scripts/jev-live-probe.mjs +210 -0
  18. package/scripts/skill-search.mjs +242 -0
  19. package/scripts/sync-tui.mjs +11 -0
  20. package/src/agents/aphrodite.md +34 -1
  21. package/src/agents/apollo.md +227 -0
  22. package/src/agents/athena.md +24 -0
  23. package/src/agents/demeter.md +33 -0
  24. package/src/agents/gaia.md +24 -0
  25. package/src/agents/hephaestus.md +24 -0
  26. package/src/agents/hermes.md +33 -0
  27. package/src/agents/iris.md +24 -0
  28. package/src/agents/mnemosyne.md +25 -3
  29. package/src/agents/nyx.md +53 -22
  30. package/src/agents/prometheus.md +242 -1
  31. package/src/agents/talos.md +24 -0
  32. package/src/agents/themis.md +24 -0
  33. package/src/agents/zeus.md +46 -6
  34. package/src/pantheon/j-telemetry-file.ts +96 -0
  35. package/src/pantheon/jev-decision-tool.ts +160 -24
  36. package/src/pantheon/jev-decisions.ts +18 -3
  37. package/src/pantheon/jev-rank-verify.ts +435 -0
  38. package/src/pantheon/jev-risk-gate.ts +1 -0
  39. package/src/pantheon/local-decision-budget.ts +170 -5
  40. package/src/pantheon/local-decision-provider-matrix.ts +0 -1
  41. package/src/pantheon/local-decision-usage-evidence.internal.ts +2 -2
  42. package/src/pantheon/v2-decision-budget.ts +4 -2
  43. package/src/plugin-v2.ts +9 -2
  44. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  45. package/src/plugins/tui/dist/tui-v2.js +457 -4
  46. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  47. package/src/plugins/tui/dist/tui.js +1 -1
  48. package/src/plugins/tui/package-lock.json +2 -2
  49. package/src/plugins/tui/package.json +1 -1
  50. package/src/plugins/tui/src/index-v2.tsx +6 -0
  51. package/src/plugins/tui/src/whats-new-highlights.ts +263 -0
  52. package/src/plugins/tui/src/whats-new-open.ts +80 -0
  53. package/src/plugins/tui/src/whats-new-state.ts +128 -0
  54. package/src/plugins/tui/src/whats-new.tsx +119 -0
package/AGENTS.global.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <!-- pantheon:generated:begin — Pantheon-managed region; regenerated on install/upgrade, never edit inside -->
2
2
  <!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->
3
3
  <!-- Source of truth: src/instructions/*.instructions.md + the static sections in this script. -->
4
- <!-- pantheon:agents-md v2 artifact=global generated-at=2026-10-27T08:34:01-03:00 sha=0a6a8e2 -->
4
+ <!-- pantheon:agents-md v2 artifact=global generated-at=2026-11-04T19:23:07-03:00 sha=ad9f855 -->
5
5
 
6
6
  # Pantheon Agent System — OpenCode
7
7
 
package/AGENTS.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <!-- pantheon:generated:begin — Pantheon-managed region; regenerated on install/upgrade, never edit inside -->
2
2
  <!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->
3
3
  <!-- Source of truth: project sections in scripts/build-agents-md.mjs. -->
4
- <!-- pantheon:agents-md v2 artifact=project generated-at=2026-10-27T08:34:01-03:00 sha=0a6a8e2 -->
4
+ <!-- pantheon:agents-md v2 artifact=project generated-at=2026-11-04T19:23:07-03:00 sha=ad9f855 -->
5
5
 
6
6
  # Pantheon — Repository Setup
7
7
 
package/CHANGELOG.md CHANGED
@@ -10,6 +10,87 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
10
10
  <!-- Add new changes here. Running `node scripts/versioning.mjs apply` will
11
11
  move this section to a versioned entry and reset the template below. -->
12
12
 
13
+ ## [v1.6.3-beta.11] - 2026-11-05
14
+
15
+ ## 🆕 What's New
16
+ - Measured MCP usage policy across the roster: durable stores only, milestone checkpoints, one vision pass per image — a governance ladder byte-identical in all 13 specialists, contract-pinned.
17
+ - The skill-discovery pipeline with the trust cascade: installed pool → canonical Anthropic catalog → skills.sh → raw GitHub; Jev ranks, the user reviews and installs.
18
+ - Dead-route holds release (ledger schema v4): the fix for budgets frozen forever by holds of removed routes ($1.00 freed in the field).
19
+ - The roster reform measured: nyx re-scoped to chaos & adversarial, talos aligned to the real hotfix identity, domain-artifact ownership for all 14 agents.
20
+ - Jev validated end to end in the field: N4 dead, verify field-verified, sandbox install 28/28 with all five MCPs live.
21
+
22
+ ### Added
23
+
24
+ - **agents** — The roster reform, measured: the governance ladder (session context → free local selector → one typed Jev question → MCP last resort, with the durable-store, milestone-checkpoint and one-pass-vision rules) now sits byte-identical in all 13 specialist agents, pinned by `tests/agent-mcp-policy.test.mjs`; nyx is re-scoped to its intended chaos & adversarial identity (its observability body duplicated prometheus and left fuzzing uncovered — the observability material moved to prometheus); mnemosyne's description names its memory-MCP curation ownership; the live scorecard's talos scenario now matches the real hotfix-express-lane identity. Post-reform live scorecard: 14/16 exact, 8/8 on the zero-dispatch agents.
25
+ - **skills** — The skill-discovery pipeline: installed pool first (one Jev `mode: "skills"`), then one read-only search across the trust cascade — the canonical `anthropics/skills` catalog first (so `pdf`/`docx`/`mcp-builder` outrank the clones popularity ranking surfaces), the skills.sh index with install counts, then raw GitHub `SKILL.md` code search (8,480 hits where the index offered three) — via `scripts/skill-search.mjs` emitting tier-ordered `{skill, installs, url, source}` JSON, pinned by `tests/skill-search.test.mjs`, then one typed Jev choice question ranking the candidates (only names/counts/descriptions cross — skill contents are untrusted), then the winning candidate is PROPOSED to the user with the project-scoped install command. Pantheon never installs; the review is the user's. The ladder is documented in `docs/reference/native-decisions.md` and carried in `zeus.md`.
26
+ - **routing** — `decision-router holds release --provider <dead> --reason "<why>"`: the administrative correction for holds of routes that no longer exist (they can never reconcile and froze budget forever — the mechanical story behind the mid-month Jev die-offs). Ledger schema v4 adds the immutable `released_holds` archive; live providers are refused, their holds roll off with the period. First field application: the 10 `jev-free` fossils of the removed free route released, $1.00 of reserved budget freed.
27
+ - **mcp** — `bench/mcp-usage-audit.mjs`: the measured native-MCP usage audit (transcript, memory db, persistence kv, bench lines → dated report in `bench/results/`; reports are local-only, they carry bounded session excerpts). First run measured the whole field history: 5.7k memory touches, 2.5k persistence, 84 vision — the verdicts and cost model live in `docs/mcp-tools.md`.
28
+
29
+ - **agents** — The 14-agent domain-artifact analysis (docs/agents/README.md): each specialist owns its domain's durable file — aphrodite keeps docs/ui/conventions.md current whenever the project has a graphical surface, demeter docs/data, hermes docs/api, prometheus docs/infra — read-first, propose-when-missing, update-only-what-you-changed; new exclusive per-agent tools fail the measured bar (grants already enforce the exclusivity that pays).
30
+
31
+
32
+ ### Changed
33
+
34
+ - **agents** — The zeus usage policy is measured, not decorative: `memory_store` takes durable, reusable facts only (session narration goes to a checkpoint or nowhere; per-project namespaces; update instead of duplicate), checkpoints fire at milestones only (never per turn, never re-saving an unchanged key), and vision runs one pass per image (zeus and aphrodite) — each vision call is real gateway spend. The contradictory store phrases that produced the narration excess are gone, pinned by `tests/agent-mcp-policy.test.mjs`.
35
+
36
+ ## [v1.6.3-beta.10] - 2026-11-04
37
+
38
+ ### Fixed
39
+
40
+ - **routing** — The Jev input envelope is enforced: schemaVersion is required (SCHEMA_VERSION_INVALID) and unknown keys are rejected (UNKNOWN_INPUT_KEYS) — the declared contract is now the enforced contract (field report N2/N3).
41
+
42
+ <!-- beta.7–beta.9 were landed together in 548fc6d; separate commits for these releases are absent from repository history. Per-beta attribution follows that commit’s grouped changelog snapshot. -->
43
+
44
+ ## [v1.6.3-beta.9] - 2026-11-04
45
+
46
+ ### Changed
47
+
48
+ - **agents** — The live scorecard now runs the full 13-specialist catalog (was a 5-agent sample); first full-catalog run: 6 exact hits, 2 domain-adjacent judgment calls, measured per agent.
49
+ - **agents** — Zeus gains consolidated MCP call-timing rules: when to recall, when to store, when to checkpoint, when vision fires, and the escalation order (local selector -> Jev -> MCP last resort).
50
+
51
+ ## [v1.6.3-beta.8] - 2026-11-04
52
+
53
+ ### Added
54
+
55
+ - **routing** — The v3.1 **rank** and **verify** primitives on `pantheon_jev_decide`: `mode: "rank"` picks the winner among up to 8 candidates with a fit score (the host answers one scalar per question, so full ordering is impossible — documented); `mode: "verify"` checks 1–4 claims as predicate questions with **BLOCK fail-closed**. Hostile inputs rejected. Zeus-only, same gate chain.
56
+
57
+ ## [v1.6.3-beta.7] - 2026-11-04
58
+
59
+ ### Added
60
+
61
+ - **routing** — `jev-live-probe.mjs`: the operator-run live measurement tool. `--ping` only resolves the configured route locally (exit 0 when valid; no provider call); `--scorecard` runs the 16 configured live scenarios against that route and writes the dated scorecard into `bench/results/`. First live run: 7/8 correct specialist picks via OpenRouter.
62
+
63
+ ## [v1.6.3-beta.6] - 2026-11-04
64
+
65
+ ### Added
66
+
67
+ - **install** — The setup wizard gains a **decision-layer step**: the shadow gates (`PANTHEON_J1_RISK_SCORE`, `PANTHEON_J3_ESCALATION`) and the specialist-caller allowlist (`athena,themis`) become first-class setup choices, written to `~/.config/pantheon/decision-flags.env` (source it from your shell profile). All advisory/shadow; none change behavior by default. Part of the ratified setup modernization.
68
+
69
+ ## [v1.6.3-beta.5] - 2026-11-04
70
+
71
+ ### Fixed
72
+
73
+ - **routing** — The ledger model-key slash fix (vendor ids like `typesafe/jev-1.13`) re-landed after being silently lost in a branch reset: the shipped beta.4 refused the OpenRouter model key with `invalid-model`. Field-verified end to end on the user's host: `advisory:true`, real Jev answer via OpenRouter at $0.00003/decision.
74
+ - **install** — The Jev wizard shows the full live route matrix with credential-state hints (checked hint when `OPENCODE_API_KEY`/`TYPESAFE_API_KEY`/`CLOUDFLARE_API_TOKEN` is in the shell; the exact export when not).
75
+
76
+ ## [v1.6.3-beta.4] - 2026-11-04
77
+
78
+ ### Added
79
+
80
+ - **routing** — `decision-router setup-model cloudflare-workers-jev/clef --account-id=<id>` provisions the Cloudflare Workers AI custom provider entry (accountId + `models.clef`, type `"decision"`); the token rides `CLOUDFLARE_API_TOKEN` in the host environment. Docs record the OpenAI Decisions protocol and the what's-new TUI window as deliberately unwired candidates.
81
+
82
+ ## [v1.6.3-beta.3] - 2026-11-04
83
+
84
+ ### Fixed
85
+
86
+ - **routing** — The OpenRouter-hosted Jev route settles end to end: the usage-evidence validator and the budget ledger now admit the `openrouter` accounting provider and vendor-slash model ids (`typesafe/jev-1.13`). Field-verified on the user's host: Zeus → `pantheon_jev_decide` (mode skills) → real Jev answer via the stored OpenRouter credential, $0.00003 per decision, usage reconciled.
87
+
88
+ ## [v1.6.3-beta.2] - 2026-11-04
89
+
90
+ ### Removed
91
+
92
+ - **routing** — The Console Jev **free variant** route (`opencode-console-jev-free` / `jev-1.13-free`) is removed from the matrix, the wizard, and the ledger: the free tier is rate-limited hard enough to 429 mid-work (field-measured), which is exactly the failure mode a decision route must not have. Existing configs selecting it degrade to skip with a fix hint pointing at the Zen-credited route (`OPENCODE_API_KEY`) or the TypeSafe direct route.
93
+
13
94
  ## [v1.6.3-beta.1] - 2026-11-04
14
95
 
15
96
  ### Added
package/README.md CHANGED
@@ -112,7 +112,11 @@ see [Quick Start](docs/QUICKSTART.md).
112
112
  preset/source, git state, and a `Context` block (tokens, a percent gauge,
113
113
  `$<spent> spent`, and a muted `cache <n>% · <n.n> tok/s` line); the native
114
114
  prompt footer keeps its own line, and Pantheon only appends
115
- `▸<preset> · ✦<n> ativos` while delegations are running. The installer
115
+ `▸<preset> · ✦<n> ativos` while delegations are running. When the Pantheon
116
+ version changes since the last TUI start, a one-time dismissable
117
+ "What's new" dialog lists that version's highlights from the shipped
118
+ changelog — once per version, `esc`/`q` dismisses; see
119
+ [What's new window](docs/reference/whats-new.md). The installer
116
120
  selects the `plugins` component by default; in interactive setup you can
117
121
  change the component selection. A component-scoped install includes the TUI
118
122
  only when `plugins` is selected. The TUI ships no quota panel: for provider
@@ -232,7 +236,15 @@ asks, after a delegation completes — one typed round-trip returns an advisory
232
236
  quality score against named criteria plus a needs-review flag. The result
233
237
  content never leaves the machine (shape metrics and criteria only, hostile
234
238
  criteria rejected outright), and the verdict is advisory telemetry plus a
235
- flag: it never blocks, retries, or alters the delegated result.
239
+ flag: it never blocks, retries, or alters the delegated result. Two more
240
+ orchestrator-owned tool modes round out the surface: `mode: "rank"` picks the
241
+ best of 2–8 named candidates for a state in one typed round-trip (it returns
242
+ the winner and that candidate's fit score — the host API answers one scalar
243
+ per question, so no full ordering is returned), and `mode: "verify"` checks
244
+ 1–4 named claims with one predicate question per claim, mapping each answer to
245
+ `PASS` / `FAIL` / `BLOCK` where every refusal, timeout or malformed answer is
246
+ `BLOCK` (fail-closed); claims are bounded caller-provided strings, hostile
247
+ shapes rejected outright, and neither mode adds a telemetry point.
236
248
 
237
249
  The installer may retain a legacy target-specific preference; it does not control
238
250
  runtime routing. `npx pantheon-opencode decision-router ...` manages stored
@@ -418,6 +430,12 @@ the current project root per request while preserving the trusted
418
430
  `PANTHEON_HOME` fallback. See [Memory](docs/MEMORY.md) for store separation and
419
431
  [MCP tools](docs/mcp-tools.md) for details.
420
432
 
433
+ Native-MCP usage is measured, not assumed: `node bench/mcp-usage-audit.mjs`
434
+ writes a dated audit of real memory/persistence/vision/code-mode/resource
435
+ usage (reports stay local — they carry bounded session excerpts), and the
436
+ agent usage policies derived from it are documented in
437
+ [MCP tools](docs/mcp-tools.md).
438
+
421
439
  The release install gate's tool canary loads the installed tarball's V2 plugin
422
440
  entry under OpenCode 2.0.30 and verifies `hashline_edit` registration, Code Mode
423
441
  visibility, and a bounded edit in an isolated project. It does not prove npm
@@ -26,7 +26,6 @@ import { fileURLToPath } from 'node:url'
26
26
  import { configure as configureUi, endGaugeLine, tag } from '../scripts/install/cli-ui.mjs'
27
27
  import { resolveComponentSelection } from '../scripts/install/component-selection.mjs'
28
28
  import { resolveGlobalConfigDirectory } from '../scripts/install/config-paths.mjs'
29
- import { provisionTypesafeHostProvider } from '../scripts/install/decision-router-config.mjs'
30
29
  import { resolveInstallExitCode } from '../scripts/install/exit-codes.mjs'
31
30
  import { createInterruptHandler } from '../scripts/install/interrupt.mjs'
32
31
  import { parseOpenCodeVersion } from '../scripts/install/opencode-version.mjs'
@@ -61,23 +60,6 @@ function readVersion() {
61
60
  }
62
61
  }
63
62
 
64
- /**
65
- * Merge the TypeSafe decision-model provider entry into the user's
66
- * `opencode.json` (never replaces existing keys; a non-JSON file is reported,
67
- * never overwritten). Returns true, or a short failure reason.
68
- */
69
- /**
70
- * Merge (never overwrite) the TypeSafe decision-model entry into the user's
71
- * OpenCode config, so choosing the TypeSafe route in the wizard needs only the
72
- * user's own sign-in afterwards. Delegates to the shared installer module —
73
- * the same provisioner `decision-router setup-model typesafe-jev/...` uses.
74
- * Returns true, or a short failure reason for the installer to print.
75
- */
76
- function provisionTypesafeProvider() {
77
- const result = provisionTypesafeHostProvider({ env: process.env })
78
- return result.ok ? true : result.reason
79
- }
80
-
81
63
  /** Value of a repeatable installer flag from the raw argv, or undefined. */
82
64
  function readArgValue(name) {
83
65
  const prefix = `${name}=`
@@ -1032,25 +1014,31 @@ async function main() {
1032
1014
  { stdout: (line) => console.log(` ${line}`) },
1033
1015
  )
1034
1016
  console.log(` ${S.jevConfigured(decisionTarget)}`)
1035
- if (decisionTarget.startsWith('typesafe-jev')) {
1036
- const provisioned = provisionTypesafeProvider()
1037
- console.log(
1038
- provisioned === true
1039
- ? ' TypeSafe provider entry merged into opencode.json (adapter + baseURL + apiKey via {env:TYPESAFE_API_KEY}, type "decision"). Activate: export TYPESAFE_API_KEY=<your TypeSafe key> and restart OpenCode. /connect does not carry custom providers.'
1040
- : ` TypeSafe provider entry NOT merged (${provisioned}); merge it manually — see docs/reference/native-decisions.md.`,
1041
- )
1042
- }
1043
1017
  } catch (error) {
1044
1018
  console.error(
1045
1019
  ` ${S.jevConfigureFailed(error instanceof Error ? error.message : String(error))}`,
1046
1020
  )
1047
1021
  console.error(
1048
- ` Fix later with: npx pantheon-opencode decision-router setup-model ${decisionTarget} --monthly-usd ${monthly} --per-decision-usd ${perDecision}`,
1022
+ ` Fix later with: npx pantheon-opencode decision-router setup-model ${decisionTarget} ${decisionTarget.startsWith('cloudflare-workers-jev/') ? '--account-id=<32-hex-id> ' : ''}--monthly-usd ${monthly} --per-decision-usd ${perDecision}`,
1049
1023
  )
1050
1024
  }
1051
1025
  }
1052
1026
  }
1053
1027
 
1028
+ const deferredJevSetup = result.decisionModelDeferredSetup ?? null
1029
+ if (deferredJevSetup?.target === 'cloudflare-workers-jev/clef') {
1030
+ console.log('')
1031
+ console.log(
1032
+ ' Cloudflare Clef was not activated: its host provider entry requires your Cloudflare account ID.',
1033
+ )
1034
+ console.log(
1035
+ ' After install, provision it with: npx pantheon-opencode decision-router setup-model cloudflare-workers-jev/clef --account-id=<32-hex-id> --monthly-usd 5 --per-decision-usd 0.10',
1036
+ )
1037
+ console.log(
1038
+ ' Also set CLOUDFLARE_API_TOKEN to a Workers AI-scoped token in the OpenCode host environment, then restart OpenCode.',
1039
+ )
1040
+ }
1041
+
1054
1042
  // Old-version residue: every `npx pantheon-opencode` invocation materializes
1055
1043
  // a full copy under the npm cache's _npx/ and nothing in npm removes old
1056
1044
  // ones. The registration points at THIS run's copy, so every other copy is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pantheon-opencode",
3
- "version": "1.6.3-beta.1",
3
+ "version": "1.6.3-beta.11",
4
4
  "description": "Multi-agent orchestration for OpenCode \u2014 14 specialized agents, TDD, Themis review gates.",
5
5
  "type": "module",
6
6
  "workspaces": [
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pantheon",
3
3
  "publisher": "ils15",
4
- "version": "1.6.3-beta.1",
4
+ "version": "1.6.3-beta.11",
5
5
  "displayName": "Pantheon",
6
6
  "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 20 skills, and OpenCode support.",
7
7
  "agents": "./src/agents",
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend"
4
4
 
5
5
  [project]
6
6
  name = "pantheon"
7
- version = "1.6.3-beta.1"
7
+ version = "1.6.3-beta.11"
8
8
  description = "Multi-agent orchestration framework"
9
9
  requires-python = ">=3.11"
10
10
  # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those
@@ -18,21 +18,21 @@ function getVerifiedUsageEvidenceDetails(value) {
18
18
  }
19
19
 
20
20
  // src/pantheon/local-decision-budget.ts
21
- var SCHEMA_VERSION = 3;
21
+ var SCHEMA_VERSION = 4;
22
22
  var VERSION_TWO = 2;
23
23
  var APPLICATION_ID = 1346522161;
24
+ var RELEASE_REASON_MAX_LENGTH = 200;
24
25
  var DB_FILENAME = "decision-budget.sqlite";
25
26
  var LOCAL_DECISION_BUDGET_PROVIDERS = Object.freeze([
26
27
  "openai-decisions",
27
28
  "typesafe-jev",
28
29
  "opencode-console",
29
- "jev-free",
30
30
  "openrouter",
31
31
  "vercel-ai-gateway",
32
32
  "cloudflare-workers-ai"
33
33
  ]);
34
34
  var ALLOWED_PROVIDERS = new Set(LOCAL_DECISION_BUDGET_PROVIDERS);
35
- var MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
35
+ var MODEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
36
36
  var RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
37
37
  var CLOCK_ROLLBACK_TOLERANCE_MS = 6e4;
38
38
  function resolveLocalDecisionBudgetDbPath(env = process.env) {
@@ -382,6 +382,70 @@ function openLocalDecisionBudgetLedger(options = {}) {
382
382
  return safeChangeCount(result.changes);
383
383
  });
384
384
  }
385
+ function releaseHoldsForProvider(provider, reason) {
386
+ if (typeof provider !== "string" || provider.length < 1 || provider.length > 64) {
387
+ return { released: 0, freedMicros: 0 };
388
+ }
389
+ if (typeof reason !== "string" || reason.length < 1 || reason.length > RELEASE_REASON_MAX_LENGTH) {
390
+ return { released: 0, freedMicros: 0 };
391
+ }
392
+ return inImmediateTransaction(() => {
393
+ const timestamp = now();
394
+ const rows = db.prepare(
395
+ `SELECT id, provider, model, period_utc, reserved_micros, state, created_at_ms
396
+ FROM reservations WHERE provider = ? AND state IN ('pending', 'uncertain')
397
+ ORDER BY created_at_ms, id`
398
+ ).all(provider);
399
+ if (rows.length === 0) return { released: 0, freedMicros: 0 };
400
+ const archive = db.prepare(
401
+ `INSERT INTO released_holds
402
+ (reservation_id, provider, model, period_utc, reserved_micros, state_at_release,
403
+ reason, created_at_ms, released_at_ms)
404
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
405
+ );
406
+ let freedMicros = 0;
407
+ for (const row of rows) {
408
+ archive.run(
409
+ row.id,
410
+ row.provider,
411
+ row.model,
412
+ row.period_utc,
413
+ row.reserved_micros,
414
+ row.state,
415
+ reason,
416
+ row.created_at_ms,
417
+ timestamp
418
+ );
419
+ freedMicros = safeMicrosTotal(freedMicros + row.reserved_micros);
420
+ }
421
+ const remove = db.prepare(
422
+ `DELETE FROM reservations WHERE provider = ? AND state IN ('pending', 'uncertain')`
423
+ ).run(provider);
424
+ if (safeChangeCount(remove.changes) !== rows.length) {
425
+ throw new Error("Reservation rows changed during release");
426
+ }
427
+ return { released: rows.length, freedMicros };
428
+ });
429
+ }
430
+ function listReleasedHolds(limit) {
431
+ const bound = typeof limit === "number" && Number.isInteger(limit) && limit > 0 ? Math.min(limit, 200) : 20;
432
+ const rows = db.prepare(
433
+ `SELECT reservation_id, provider, model, period_utc, reserved_micros, state_at_release,
434
+ reason, created_at_ms, released_at_ms
435
+ FROM released_holds ORDER BY released_at_ms DESC, reservation_id LIMIT ?`
436
+ ).all(bound);
437
+ return rows.map((row) => ({
438
+ reservationId: row.reservation_id,
439
+ provider: row.provider,
440
+ model: row.model,
441
+ period: row.period_utc,
442
+ reservedMicros: row.reserved_micros,
443
+ stateAtRelease: row.state_at_release === "uncertain" ? "uncertain" : "pending",
444
+ reason: row.reason,
445
+ createdAtMs: row.created_at_ms,
446
+ releasedAtMs: row.released_at_ms
447
+ }));
448
+ }
385
449
  function pruneCompletedPeriods() {
386
450
  return inImmediateTransaction(() => {
387
451
  let currentPeriod;
@@ -437,6 +501,8 @@ function openLocalDecisionBudgetLedger(options = {}) {
437
501
  reconcileVerified,
438
502
  listUncertainReservations,
439
503
  recoverPendingReservations,
504
+ releaseHoldsForProvider,
505
+ listReleasedHolds,
440
506
  pruneCompletedPeriods,
441
507
  close: () => db.close()
442
508
  };
@@ -451,12 +517,16 @@ function ensureSchema(db) {
451
517
  if (applicationId !== 0 || tables.length !== 0) {
452
518
  throw new Error("Refusing to initialize an unrecognized SQLite database");
453
519
  }
454
- createSchemaV3(db);
520
+ createSchemaV4(db);
455
521
  } else if (version === 1 && applicationId === APPLICATION_ID) {
456
522
  migrateVersionOne(db);
457
523
  migrateVersionTwoToThree(db);
524
+ migrateVersionThreeToFour(db);
458
525
  } else if (version === VERSION_TWO && applicationId === APPLICATION_ID) {
459
526
  migrateVersionTwoToThree(db);
527
+ migrateVersionThreeToFour(db);
528
+ } else if (version === 3 && applicationId === APPLICATION_ID) {
529
+ migrateVersionThreeToFour(db);
460
530
  } else if (version !== SCHEMA_VERSION || applicationId !== APPLICATION_ID) {
461
531
  throw new Error("Unsupported or incompatible local decision budget database schema");
462
532
  }
@@ -551,9 +621,38 @@ function migrateVersionTwoToThree(db) {
551
621
  INSERT INTO ledger_state (id, active_period_utc)
552
622
  SELECT id, NULL FROM ledger_state_v2;
553
623
  DROP TABLE ledger_state_v2;
624
+ PRAGMA user_version = 3;
625
+ `);
626
+ }
627
+ function migrateVersionThreeToFour(db) {
628
+ validateVersionThreeSchema(db);
629
+ db.exec(`
630
+ CREATE TABLE released_holds (
631
+ reservation_id TEXT PRIMARY KEY NOT NULL,
632
+ provider TEXT NOT NULL,
633
+ model TEXT NOT NULL,
634
+ period_utc TEXT NOT NULL CHECK (length(period_utc) = 7),
635
+ reserved_micros INTEGER NOT NULL CHECK (reserved_micros > 0),
636
+ state_at_release TEXT NOT NULL CHECK (state_at_release IN ('pending', 'uncertain')),
637
+ reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND ${RELEASE_REASON_MAX_LENGTH}),
638
+ created_at_ms INTEGER NOT NULL,
639
+ released_at_ms INTEGER NOT NULL
640
+ ) STRICT;
641
+ CREATE INDEX released_holds_released_idx ON released_holds (released_at_ms, reservation_id);
554
642
  PRAGMA user_version = ${SCHEMA_VERSION};
555
643
  `);
556
644
  }
645
+ function createSchemaV4(db) {
646
+ createSchemaV3(db);
647
+ migrateVersionThreeToFour(db);
648
+ }
649
+ function validateVersionThreeSchema(db) {
650
+ db.prepare(
651
+ `SELECT id, provider, model, period_utc, reserved_micros, actual_micros, state,
652
+ created_at_ms, updated_at_ms FROM reservations LIMIT 0`
653
+ );
654
+ db.prepare("SELECT id, active_period_utc FROM ledger_state LIMIT 0");
655
+ }
557
656
  function migrateVersionOne(db) {
558
657
  validateVersionOneSchema(db);
559
658
  const providers = db.prepare("SELECT DISTINCT provider FROM reservations UNION SELECT provider FROM provider_caps").all();
@@ -101,7 +101,7 @@ function readDecisionBudgetLedgerFacts(dbPath) {
101
101
  try {
102
102
  const version = db.prepare("PRAGMA user_version").get().user_version;
103
103
  const applicationId = db.prepare("PRAGMA application_id").get().application_id;
104
- if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) {
104
+ if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3 && version !== 4) {
105
105
  return { present: true, readable: false, reason: "unsupported-schema" };
106
106
  }
107
107
  const activeRow = db.prepare("SELECT active_period_utc FROM ledger_state WHERE id = 1").get();
@@ -185,7 +185,7 @@ function listDecisionHoldsReadOnly(dbPath) {
185
185
  try {
186
186
  const applicationId = db.prepare("PRAGMA application_id").get().application_id;
187
187
  const version = db.prepare("PRAGMA user_version").get().user_version;
188
- if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3) return null;
188
+ if (applicationId !== EXPECTED_APPLICATION_ID || version !== 3 && version !== 4) return null;
189
189
  const rows = db.prepare(
190
190
  `SELECT id, provider, model, period_utc, reserved_micros, state
191
191
  FROM reservations WHERE state IN ('pending', 'uncertain')
@@ -14,7 +14,6 @@ var DECISION_ROUTER_MODELS = Object.freeze({
14
14
  "openai-decisions": Object.freeze(["gpt-6-luna"]),
15
15
  "typesafe-jev": Object.freeze(["jev-1.14.0"]),
16
16
  "opencode-console-jev": Object.freeze(["jev-1.13"]),
17
- "opencode-console-jev-free": Object.freeze(["jev-1.13-free"]),
18
17
  // Host-embedded decision modules confirmed in the 2.2.5 binary; the model
19
18
  // ids are the provider-side decision models (see
20
19
  // docs/reference/native-decisions.md for credential acquisition).
@@ -26,7 +25,6 @@ var DECISION_PROVIDER_BUDGET_MAPPING = Object.freeze({
26
25
  "openai-decisions": "openai-decisions",
27
26
  "typesafe-jev": "typesafe-jev",
28
27
  "opencode-console-jev": "opencode-console",
29
- "opencode-console-jev-free": "jev-free",
30
28
  "openrouter-jev": "openrouter",
31
29
  "vercel-gateway-jev": "vercel-ai-gateway",
32
30
  "cloudflare-workers-jev": "cloudflare-workers-ai"
@@ -32,6 +32,7 @@ import {
32
32
  DECISION_ROUTER_MODELS,
33
33
  diffDecisionRouterSurfaces,
34
34
  inspectTypesafeHostProvider,
35
+ provisionCloudflareHostProvider,
35
36
  provisionTypesafeHostProvider,
36
37
  readUserDecisionRouterConfig,
37
38
  resolveUserDecisionRouterConfigPath,
@@ -64,6 +65,7 @@ export function decisionRouterHelp() {
64
65
  ' setup [options] computed artifact diff; writes only with --apply',
65
66
  ' preview alias of `setup` (never writes)',
66
67
  ' holds unresolved reservations, read-only',
68
+ ' holds release --provider <p> --reason "<why>" archive+release dead-route holds',
67
69
  '',
68
70
  'Explicit actions (each one changes exactly one thing):',
69
71
  ' select local|auto|<provider>/<model> record a selection; enables nothing',
@@ -74,7 +76,7 @@ export function decisionRouterHelp() {
74
76
  ' period confirm --current none|YYYY-MM --next YYYY-MM',
75
77
  '',
76
78
  'Guided (each does the whole chain in one command):',
77
- ' setup-model <provider>/<model> --monthly-usd N --per-decision-usd N [--no-consent]',
79
+ ' setup-model <provider>/<model> --monthly-usd N --per-decision-usd N [--no-consent] [--account-id=<32-hex-id>]',
78
80
  ' select + enable + consent + caps + period in one write,',
79
81
  ' then print the verification summary',
80
82
  ' doctor read-only diagnosis of the native decision route with',
@@ -279,6 +281,49 @@ export async function runDecisionRouterCommand(
279
281
  return
280
282
  }
281
283
 
284
+ if (command === 'holds' && rest[0] === 'release') {
285
+ // Administrative correction for holds of routes that no longer exist:
286
+ // a dead provider can never reconcile, so its holds would freeze budget
287
+ // forever. Live providers are refused — their holds roll off with the
288
+ // period. Every released row is archived with the mandatory reason.
289
+ const [, ...releaseArgs] = rest
290
+ const options = parseNamedOptions(releaseArgs, ['--provider', '--reason'])
291
+ const provider = options['--provider']
292
+ const reason = options['--reason']
293
+ if (provider === undefined || reason === undefined) {
294
+ throw new DecisionRouterUsageError(
295
+ 'Usage: decision-router holds release --provider <dead-provider> --reason "<why>"',
296
+ )
297
+ }
298
+ if (Object.hasOwn(DECISION_ROUTER_MODELS, provider)) {
299
+ throw new DecisionRouterUsageError(
300
+ `Provider ${provider} is a live catalog route — its holds are not releasable; ` +
301
+ 'they reconcile or roll off with the budget period.',
302
+ )
303
+ }
304
+ const ledger = openLedger(env)
305
+ try {
306
+ const result = ledger.releaseHoldsForProvider(provider, reason)
307
+ if (result.released === 0) {
308
+ stdout(`No unresolved holds for provider ${provider}.`)
309
+ } else {
310
+ stdout(
311
+ `Released ${result.released} hold(s) of provider ${provider}; ` +
312
+ `freed ${(result.freedMicros / 1_000_000).toFixed(2)} USD of reserved budget.`,
313
+ )
314
+ for (const hold of ledger.listReleasedHolds(5)) {
315
+ stdout(
316
+ `Archived ${hold.reservationId}: provider=${hold.provider} model=${hold.model} ` +
317
+ `state_at_release=${hold.stateAtRelease} reason="${hold.reason}"`,
318
+ )
319
+ }
320
+ }
321
+ } finally {
322
+ ledger.close()
323
+ }
324
+ return
325
+ }
326
+
282
327
  if (command === 'period') {
283
328
  const [action, ...periodArgs] = rest
284
329
  if (action !== 'confirm')
@@ -314,7 +359,9 @@ export async function runDecisionRouterCommand(
314
359
  )
315
360
  }
316
361
  const noConsent = flagArgs.includes('--no-consent')
317
- const capArgs = flagArgs.filter((arg) => arg !== '--no-consent')
362
+ const capArgs = flagArgs.filter(
363
+ (arg) => arg !== '--no-consent' && !arg.startsWith('--account-id='),
364
+ )
318
365
  // Exactly the two caps flags with values; parseCaps validates them and
319
366
  // leaves `rest` empty because setup-model has no positional caps targets.
320
367
  if (capArgs.length !== 4) throw new DecisionRouterUsageError(USAGE)
@@ -323,6 +370,29 @@ export async function runDecisionRouterCommand(
323
370
  const { provider, model } = selection
324
371
  const candidate = { provider, model }
325
372
 
373
+ // Cloudflare's native module requires an account-specific custom host
374
+ // provider entry. Fail before selecting/enabling the route if that entry
375
+ // cannot be provisioned; a warning after activation would leave a route
376
+ // that cannot be resolved by the host.
377
+ let cloudflareProvision = null
378
+ if (provider === 'cloudflare-workers-jev') {
379
+ const accountIdFlag = flagArgs.find((arg) => arg.startsWith('--account-id='))
380
+ if (!accountIdFlag) {
381
+ throw new DecisionRouterUsageError(
382
+ 'Cloudflare route requires --account-id=<32-hex-id>; route was not activated',
383
+ )
384
+ }
385
+ cloudflareProvision = provisionCloudflareHostProvider({
386
+ accountId: accountIdFlag.slice('--account-id='.length),
387
+ env,
388
+ })
389
+ if (!cloudflareProvision.ok) {
390
+ throw new DecisionRouterUsageError(
391
+ `Cloudflare route was not activated: ${cloudflareProvision.reason}`,
392
+ )
393
+ }
394
+ }
395
+
326
396
  // One update names selection, enablement, candidates and (unless refused)
327
397
  // consent together: selecting a different target revokes consent unless
328
398
  // the same update names it, so this single write is the consent act.
@@ -337,6 +407,13 @@ export async function runDecisionRouterCommand(
337
407
  noConsent ? 'Egress consent NOT recorded (--no-consent).' : 'Egress consent recorded: yes.',
338
408
  )
339
409
 
410
+ if (cloudflareProvision) {
411
+ stdout(
412
+ `Cloudflare provider entry merged into ${cloudflareProvision.path} (accountId + models.clef, type "decision"). ` +
413
+ 'The token comes from CLOUDFLARE_API_TOKEN (Workers AI-scoped token) in the host environment.',
414
+ )
415
+ }
416
+
340
417
  // The TypeSafe route needs a host-side provider entry the decisions API
341
418
  // can resolve; the Console routes are host-native and need none. The
342
419
  // merge is additive and idempotent; a failure is a printed warning (the
@@ -617,11 +694,16 @@ function formatInstallState(config, target) {
617
694
 
618
695
  function parseSelectionTarget(target) {
619
696
  if (target === 'local' || target === 'auto') return { mode: target }
620
- const [provider, model, ...extra] = String(target).split('/')
621
- if (extra.length || !isKnownCandidate(provider, model)) {
622
- throw new DecisionRouterUsageError('Selection must name one supported provider/model pair')
697
+ const value = String(target)
698
+ for (const provider of Object.keys(DECISION_ROUTER_MODELS)) {
699
+ const prefix = `${provider}/`
700
+ if (!value.startsWith(prefix)) continue
701
+ const model = value.slice(prefix.length)
702
+ if (DECISION_ROUTER_MODELS[provider].includes(model)) {
703
+ return { mode: 'explicit', provider, model }
704
+ }
623
705
  }
624
- return { mode: 'explicit', provider, model }
706
+ throw new DecisionRouterUsageError('Selection must name one supported provider/model pair')
625
707
  }
626
708
 
627
709
  function parseNamedFlags(args, expected) {