pantheon-opencode 1.6.3-beta.9 → 1.7.0-beta.1

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 (69) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +187 -6
  4. package/README.md +7 -1
  5. package/README.pt-BR.md +1 -1
  6. package/bin/pantheon-init.mjs +46 -28
  7. package/package.json +2 -2
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/decision-router-budget.mjs +102 -2
  11. package/scripts/decision-router-v2-budget.mjs +2 -2
  12. package/scripts/decision-router.mjs +82 -25
  13. package/scripts/doctor.mjs +4 -1
  14. package/scripts/install/cli-ui.mjs +2 -1
  15. package/scripts/install/decision-router-config.mjs +12 -4
  16. package/scripts/install/interactive.mjs +45 -28
  17. package/scripts/install/opencode.mjs +151 -30
  18. package/scripts/jev-live-probe.mjs +114 -86
  19. package/scripts/skill-search.mjs +273 -0
  20. package/skills-lock.json +3 -1
  21. package/src/agents/aphrodite.md +34 -1
  22. package/src/agents/apollo.md +227 -0
  23. package/src/agents/athena.md +26 -0
  24. package/src/agents/demeter.md +33 -0
  25. package/src/agents/gaia.md +24 -0
  26. package/src/agents/hephaestus.md +24 -0
  27. package/src/agents/hermes.md +33 -0
  28. package/src/agents/iris.md +24 -0
  29. package/src/agents/mnemosyne.md +25 -3
  30. package/src/agents/nyx.md +50 -22
  31. package/src/agents/prometheus.md +242 -1
  32. package/src/agents/talos.md +24 -0
  33. package/src/agents/themis.md +24 -0
  34. package/src/agents/zeus.md +71 -20
  35. package/src/pantheon/j1-approvals.ts +123 -0
  36. package/src/pantheon/jev-decision-tool.ts +148 -17
  37. package/src/pantheon/jev-decisions.ts +95 -12
  38. package/src/pantheon/jev-escalation.ts +1 -1
  39. package/src/pantheon/jev-quality-score.ts +45 -10
  40. package/src/pantheon/jev-rank-verify.ts +244 -14
  41. package/src/pantheon/jev-risk-gate.ts +82 -12
  42. package/src/pantheon/local-decision-budget.ts +169 -2
  43. package/src/pantheon/local-decision-prompt.ts +2 -0
  44. package/src/pantheon/local-decision-router.ts +16 -0
  45. package/src/pantheon/local-decision-turn.ts +110 -4
  46. package/src/pantheon/local-decision-usage-evidence.internal.ts +2 -2
  47. package/src/pantheon/pantheon-decision-catalog.ts +9 -2
  48. package/src/pantheon/v2-decision-budget.ts +4 -2
  49. package/src/pantheon/v2-tools.ts +42 -0
  50. package/src/plugin-v2.ts +85 -5
  51. package/src/plugins/tui/dist/server-v2.d.ts +14 -6
  52. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  53. package/src/plugins/tui/dist/server-v2.js +16 -9
  54. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  55. package/src/plugins/tui/dist/tui-v2.js +128 -25
  56. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  57. package/src/plugins/tui/dist/tui.js +1 -1
  58. package/src/plugins/tui/package-lock.json +2 -2
  59. package/src/plugins/tui/package.json +1 -1
  60. package/src/plugins/tui/src/server-v2.ts +14 -7
  61. package/src/plugins/tui/src/whats-new-highlights.ts +59 -5
  62. package/src/plugins/tui/src/whats-new-open.ts +41 -1
  63. package/src/plugins/tui/src/whats-new.tsx +61 -8
  64. package/src/routing.yml +2 -0
  65. package/src/skills/README.md +1 -1
  66. package/src/skills/agent-forge/SKILL.md +76 -0
  67. package/src/skills/auto-continue/SKILL.md +12 -163
  68. package/src/skills/auto-continue/references/auto-continue-details.md +175 -0
  69. package/src/skills/prompt-refinery/SKILL.md +60 -0
@@ -65,6 +65,7 @@ export function decisionRouterHelp() {
65
65
  ' setup [options] computed artifact diff; writes only with --apply',
66
66
  ' preview alias of `setup` (never writes)',
67
67
  ' holds unresolved reservations, read-only',
68
+ ' holds release --provider <p> --reason "<why>" archive+release dead-route holds',
68
69
  '',
69
70
  'Explicit actions (each one changes exactly one thing):',
70
71
  ' select local|auto|<provider>/<model> record a selection; enables nothing',
@@ -75,7 +76,7 @@ export function decisionRouterHelp() {
75
76
  ' period confirm --current none|YYYY-MM --next YYYY-MM',
76
77
  '',
77
78
  'Guided (each does the whole chain in one command):',
78
- ' 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>]',
79
80
  ' select + enable + consent + caps + period in one write,',
80
81
  ' then print the verification summary',
81
82
  ' doctor read-only diagnosis of the native decision route with',
@@ -280,6 +281,49 @@ export async function runDecisionRouterCommand(
280
281
  return
281
282
  }
282
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
+
283
327
  if (command === 'period') {
284
328
  const [action, ...periodArgs] = rest
285
329
  if (action !== 'confirm')
@@ -326,6 +370,29 @@ export async function runDecisionRouterCommand(
326
370
  const { provider, model } = selection
327
371
  const candidate = { provider, model }
328
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
+
329
396
  // One update names selection, enablement, candidates and (unless refused)
330
397
  // consent together: selecting a different target revokes consent unless
331
398
  // the same update names it, so this single write is the consent act.
@@ -340,26 +407,11 @@ export async function runDecisionRouterCommand(
340
407
  noConsent ? 'Egress consent NOT recorded (--no-consent).' : 'Egress consent recorded: yes.',
341
408
  )
342
409
 
343
- // The Cloudflare route needs a custom entry with the accountId (the
344
- // host's embedded cloudflare-workers-ai module reads the token from
345
- // CLOUDFLARE_API_TOKEN and the account from the entry options).
346
- if (provider === 'cloudflare-workers-jev') {
347
- const accountId = flagArgs.find((arg) => arg.startsWith('--account-id='))
348
- const provision = provisionCloudflareHostProvider({
349
- accountId: accountId?.split('=')[1],
350
- env,
351
- })
352
- if (provision.ok) {
353
- stdout(
354
- `Cloudflare provider entry merged into ${provision.path} (accountId + models.clef, type "decision"). ` +
355
- 'The token comes from CLOUDFLARE_API_TOKEN (Workers AI-scoped token) in the host environment.',
356
- )
357
- } else {
358
- stdout(
359
- `⚠ Cloudflare provider entry NOT merged: ${provision.reason}` +
360
- ' — pass --account-id=<32-hex Cloudflare account id>.',
361
- )
362
- }
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
+ )
363
415
  }
364
416
 
365
417
  // The TypeSafe route needs a host-side provider entry the decisions API
@@ -642,11 +694,16 @@ function formatInstallState(config, target) {
642
694
 
643
695
  function parseSelectionTarget(target) {
644
696
  if (target === 'local' || target === 'auto') return { mode: target }
645
- const [provider, model, ...extra] = String(target).split('/')
646
- if (extra.length || !isKnownCandidate(provider, model)) {
647
- 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
+ }
648
705
  }
649
- return { mode: 'explicit', provider, model }
706
+ throw new DecisionRouterUsageError('Selection must name one supported provider/model pair')
650
707
  }
651
708
 
652
709
  function parseNamedFlags(args, expected) {
@@ -1750,11 +1750,14 @@ export function checkPluginVersionDrift(args) {
1750
1750
  * @returns {boolean}
1751
1751
  */
1752
1752
  function isV2PluginRef(ref) {
1753
+ // QA beta.20: the installer's V2 writer emits `{ package, options }` —
1754
+ // `package` must be probed FIRST or a perfectly healthy config reads as
1755
+ // "no V2 generation registered" (a false negative the field hit).
1753
1756
  const candidate =
1754
1757
  typeof ref === 'string'
1755
1758
  ? ref
1756
1759
  : ref && typeof ref === 'object'
1757
- ? (ref.path ?? ref.source ?? ref.id ?? ref.name)
1760
+ ? (ref.package ?? ref.path ?? ref.source ?? ref.id ?? ref.name)
1758
1761
  : undefined
1759
1762
  return typeof candidate === 'string' && candidate.includes('plugin-v2')
1760
1763
  }
@@ -386,8 +386,9 @@ export function printWorktreeGuidance({
386
386
  projectRoot = process.cwd(),
387
387
  interactive = false,
388
388
  dryRun = false,
389
+ enabled = true,
389
390
  } = {}) {
390
- if (!interactive || dryRun || !tty()) return
391
+ if (!interactive || dryRun || !tty() || enabled === false) return
391
392
 
392
393
  const recommendation = getWorktreeRecommendation(projectRoot)
393
394
  const rows = [
@@ -656,10 +656,18 @@ export function provisionCloudflareHostProvider({ accountId, env = process.env }
656
656
  data.providers ??= {}
657
657
  data.providers['cloudflare-workers-ai'] ??= {}
658
658
  data.providers['cloudflare-workers-ai'].options ??= {}
659
- data.providers['cloudflare-workers-ai'].options.accountId ??= trimmed
660
- data.providers['cloudflare-workers-ai'].models ??= {}
661
- if (data.providers['cloudflare-workers-ai'].models['clef'] === undefined) {
662
- data.providers['cloudflare-workers-ai'].models['clef'] = {
659
+ const provider = data.providers['cloudflare-workers-ai']
660
+ const existingAccountId = provider.options.accountId
661
+ if (existingAccountId != null && String(existingAccountId).trim() !== '') {
662
+ if (String(existingAccountId).trim().toLowerCase() !== trimmed.toLowerCase()) {
663
+ return { ok: false, reason: 'existing accountId conflicts with --account-id' }
664
+ }
665
+ } else {
666
+ provider.options.accountId = trimmed
667
+ }
668
+ provider.models ??= {}
669
+ if (provider.models.clef === undefined) {
670
+ provider.models.clef = {
663
671
  name: 'Clef (Cloudflare Workers AI)',
664
672
  type: 'decision',
665
673
  }
@@ -56,8 +56,8 @@ export async function promptReview(
56
56
  /**
57
57
  * Collect interactive setup choices before the installer begins any writes.
58
58
  *
59
- * @param {{ components?: string[], defaultComponents?: string[], noMcp?: boolean, prompts?: typeof clack, isTTY?: boolean, getDecisionRouterConfig?: (target: string) => unknown }} [options]
60
- * @returns {Promise<{ components?: Set<string>, target?: string, decisionRouterConfig?: object, canceled?: boolean, cancelPoint?: string }>}
59
+ * @param {{ components?: string[], defaultComponents?: string[], noMcp?: boolean, prompts?: typeof clack, isTTY?: boolean, env?: Record<string, string | undefined>, getDecisionRouterConfig?: (target: string) => unknown }} [options]
60
+ * @returns {Promise<{ components?: Set<string>, target?: string, decisionRouterConfig?: object, decisionModelActivation?: object | null, decisionModelDeferredSetup?: object | null, canceled?: boolean, cancelPoint?: string }>}
61
61
  *
62
62
  * `cancelPoint` names the setup choice where the user stopped (`components` or
63
63
  * `target`), so the caller can print one explainable line and persist the same
@@ -67,6 +67,7 @@ export async function runInteractiveInstall({
67
67
  components = [],
68
68
  defaultComponents = [],
69
69
  noMcp = false,
70
+ env = process.env,
70
71
  getDecisionRouterConfig = () => DEFAULT_DECISION_ROUTER_CONFIG,
71
72
  prompts = clack,
72
73
  isTTY = isTerminal(),
@@ -92,7 +93,7 @@ export async function runInteractiveInstall({
92
93
 
93
94
  const componentOptions = [
94
95
  { label: 'agents', value: 'agents', hint: 'Agent configurations and routing (14 agents)' },
95
- { label: 'skills', value: 'skills', hint: `Reusable skill workflows (${20} skills)` },
96
+ { label: 'skills', value: 'skills', hint: `Reusable skill workflows (${22} skills)` },
96
97
  { label: 'instructions', value: 'instructions', hint: 'AGENTS.md and instructional files' },
97
98
  { label: 'prompts', value: 'prompts', hint: 'Prompt templates for agents' },
98
99
  { label: 'commands', value: 'commands', hint: 'OpenCode command shortcuts' },
@@ -138,7 +139,7 @@ export async function runInteractiveInstall({
138
139
  // that setup-model writes.
139
140
  const jevActivation = await prompts.select({
140
141
  message:
141
- 'Configure the Jev decision model now? (advisory tool for Zeus; one write: selection, consent, caps, period — USD caps are required)',
142
+ 'Configure the Jev decision model now? (Console, OpenRouter, and TypeSafe activate here; Cloudflare is provisioned after install)',
142
143
  options: [
143
144
  {
144
145
  label: 'Skip (default)',
@@ -148,7 +149,7 @@ export async function runInteractiveInstall({
148
149
  {
149
150
  label: 'OpenCode Console Jev (stock)',
150
151
  value: 'opencode-console-jev/jev-1.13',
151
- hint: consoleJevHint(process.env),
152
+ hint: consoleJevHint(env),
152
153
  },
153
154
  {
154
155
  label: 'OpenRouter-hosted Jev',
@@ -158,12 +159,12 @@ export async function runInteractiveInstall({
158
159
  {
159
160
  label: 'TypeSafe Jev (direct)',
160
161
  value: 'typesafe-jev/jev-1.14.0',
161
- hint: typesafeJevHint(process.env),
162
+ hint: typesafeJevHint(env),
162
163
  },
163
164
  {
164
- label: 'Cloudflare Clef',
165
+ label: 'Cloudflare Clef (provision after install)',
165
166
  value: 'cloudflare-workers-jev/clef',
166
- hint: cloudflareJevHint(process.env),
167
+ hint: cloudflareJevHint(env),
167
168
  },
168
169
  ],
169
170
  initialValue: 'skip',
@@ -177,7 +178,8 @@ export async function runInteractiveInstall({
177
178
  // file the user sources (the host reads these at plugin registration from
178
179
  // its own environment — the installer never edits shell profiles silently).
179
180
  const jevFlags = await prompts.multiselect({
180
- message: 'Decision layer extras (all advisory/shadow; none change behavior by default):',
181
+ message:
182
+ 'Decision layer extras (shadow gates are observe-only; specialist access is explicit):',
181
183
  options: [
182
184
  {
183
185
  label: 'J1 risk-score shadow gate',
@@ -191,7 +193,7 @@ export async function runInteractiveInstall({
191
193
  },
192
194
  {
193
195
  label: 'Specialist callers: athena + themis (explicit questions)',
194
- value: 'CALLERS=athena,themis',
196
+ value: 'PANTHEON_JEV_SPECIALIST_CALLERS=athena,themis',
195
197
  hint: 'Allowlisted specialists may ask bounded Jev questions mid-task; presets stay Zeus-only',
196
198
  },
197
199
  ],
@@ -201,26 +203,23 @@ export async function runInteractiveInstall({
201
203
  if (cancelPrompt(prompts, jevFlags, 'decisionFlags')) {
202
204
  return { canceled: true, cancelPoint: 'decisionFlags' }
203
205
  }
204
- if (Array.isArray(jevFlags) && jevFlags.length > 0) {
205
- const flagsDir = join(process.env.XDG_CONFIG_HOME || `${process.env.HOME}/.config`, 'pantheon')
206
- mkdirSync(flagsDir, { recursive: true, mode: 0o700 })
207
- const flagsPath = join(flagsDir, 'decision-flags.env')
208
- const lines = jevFlags.map((flag) => `export ${flag}`).join('\n')
209
- writeFileSync(
210
- flagsPath,
211
- `# Pantheon decision layer — source from your shell profile
212
- ${lines}
213
- `,
214
- )
215
- }
216
- // Only known targets activate; anything else (a stale stub, a renamed
217
- // option) degrades to skip instead of configuring a wrong route.
218
- const KNOWN_JEV_TARGETS = new Set(['opencode-console-jev/jev-1.13', 'typesafe-jev/jev-1.14.0'])
206
+ // Cloudflare needs an account-specific host provider entry. It remains an
207
+ // explicit deferred choice; setup-model must receive --account-id before any
208
+ // route is enabled.
209
+ const KNOWN_JEV_TARGETS = new Set([
210
+ 'opencode-console-jev/jev-1.13',
211
+ 'openrouter-jev/typesafe/jev-1.13',
212
+ 'typesafe-jev/jev-1.14.0',
213
+ ])
214
+ const cloudflareDeferred = jevActivation === 'cloudflare-workers-jev/clef'
219
215
  const activationChoice =
220
216
  typeof jevActivation === 'string' && KNOWN_JEV_TARGETS.has(jevActivation)
221
217
  ? jevActivation
222
218
  : 'skip'
223
219
  let decisionModelActivation = null
220
+ const decisionModelDeferredSetup = cloudflareDeferred
221
+ ? { target: 'cloudflare-workers-jev/clef' }
222
+ : null
224
223
  if (activationChoice !== 'skip') {
225
224
  // Caps prompts degrade to the recommended defaults when the prompt
226
225
  // implementation has no text input (stubbed tests, restricted TTYs).
@@ -247,11 +246,28 @@ ${lines}
247
246
  }
248
247
  }
249
248
 
249
+ // Empty/absent caller allowlist is intentionally Zeus-only. Persist that
250
+ // default too, so rerunning the wizard cannot leave a prior allowlist active.
251
+ const selectedFlags = Array.isArray(jevFlags) ? jevFlags : []
252
+ const hasCallerFlag = selectedFlags.some((flag) =>
253
+ flag.startsWith('PANTHEON_JEV_SPECIALIST_CALLERS='),
254
+ )
255
+ const flagsDir = join(env.XDG_CONFIG_HOME || `${env.HOME}/.config`, 'pantheon')
256
+ mkdirSync(flagsDir, { recursive: true, mode: 0o700 })
257
+ const flagsPath = join(flagsDir, 'decision-flags.env')
258
+ const lines = selectedFlags.map((flag) => `export ${flag}`)
259
+ if (!hasCallerFlag) lines.push('export PANTHEON_JEV_SPECIALIST_CALLERS=')
260
+ writeFileSync(
261
+ flagsPath,
262
+ `# Pantheon decision layer — source from your shell profile\n${lines.join('\n')}\n`,
263
+ )
264
+
250
265
  return {
251
266
  components: selectedComponents,
252
267
  target,
253
268
  decisionRouterConfig: createDecisionRouterConfig(DECISION_ROUTER_PROVIDERS[0], false),
254
269
  decisionModelActivation,
270
+ decisionModelDeferredSetup,
255
271
  }
256
272
  }
257
273
 
@@ -273,7 +289,8 @@ function typesafeJevHint(env = process.env) {
273
289
  }
274
290
 
275
291
  function cloudflareJevHint(env = process.env) {
276
- return env.CLOUDFLARE_API_TOKEN
277
- ? '✓ CLOUDFLARE_API_TOKEN detected — pass --account-id at setup-model'
278
- : 'Workers AI-scoped CLOUDFLARE_API_TOKEN + accountId; setup-model merges the entry'
292
+ const tokenHint = env.CLOUDFLARE_API_TOKEN
293
+ ? 'CLOUDFLARE_API_TOKEN detected'
294
+ : 'requires a Workers AI-scoped CLOUDFLARE_API_TOKEN'
295
+ return `${tokenHint}; not activated by this wizard. After install run: npx pantheon-opencode decision-router setup-model cloudflare-workers-jev/clef --account-id=<32-hex-id> --monthly-usd 5 --per-decision-usd 0.10`
279
296
  }
@@ -624,13 +624,38 @@ function mergeMissing(target, source) {
624
624
  * `src/plugin.ts` or `src/plugins/pantheon-hooks.ts` is not evidence that the
625
625
  * plugin belongs to Pantheon and must be preserved verbatim.
626
626
  */
627
+ /**
628
+ * Field report (beta.13 §2): a plugin registration into the npx cache
629
+ * (`/_npx/<hash>/`) is VOLATILE — other npx-booted MCPs (playwright, rea)
630
+ * recycle that tree while the host is running, and the plugin dies
631
+ * intermittently with ENOENT. When THIS installer itself runs from the cache,
632
+ * the freshly registered path must be the stable global install instead when
633
+ * one exists; otherwise the registration stays volatile and says so.
634
+ */
635
+ export function resolveStablePantheonRoot(root = ROOT) {
636
+ const normalized = root.replaceAll('\\', '/')
637
+ if (!normalized.includes('/_npx/')) return { root, volatile: false }
638
+ const globalCandidate = resolve(
639
+ dirname(process.execPath),
640
+ '..',
641
+ 'lib',
642
+ 'node_modules',
643
+ 'pantheon-opencode',
644
+ )
645
+ if (existsSync(join(globalCandidate, 'src', 'plugin-v2', 'index.ts'))) {
646
+ return { root: globalCandidate, volatile: false }
647
+ }
648
+ return { root, volatile: true }
649
+ }
650
+
627
651
  export function resolveInstalledPlugin(plugin) {
628
652
  if (typeof plugin !== 'string') return plugin
629
653
  const normalized = normalizePluginRef(plugin)
630
- if (PANTHEON_PLUGIN_IDENTITIES.has(normalized)) return join(ROOT, normalized)
654
+ const stable = resolveStablePantheonRoot()
655
+ if (PANTHEON_PLUGIN_IDENTITIES.has(normalized)) return join(stable.root, normalized)
631
656
  // Legacy V2 file ref (pre-directory-contract): migrate to the installed
632
657
  // plugin directory so the beta loader accepts the entry.
633
- if (normalized === PANTHEON_V2_LEGACY_FILE) return join(ROOT, PANTHEON_V2_PLUGIN)
658
+ if (normalized === PANTHEON_V2_LEGACY_FILE) return join(stable.root, PANTHEON_V2_PLUGIN)
634
659
  const identity = managedPluginIdentity(plugin)
635
660
  if (identity !== null && isAbsolute(normalized)) {
636
661
  return INSTALLED_PANTHEON_PLUGIN_PATHS.get(identity) ?? plugin
@@ -1427,6 +1452,8 @@ export function setupRuntimePhase(
1427
1452
  error(S.runtimeFailed(err.message))
1428
1453
  warning(S.runtimeSkippedMcp)
1429
1454
  stats.warnings += 1
1455
+ if (!Array.isArray(stats.warningMessages)) stats.warningMessages = []
1456
+ stats.warningMessages.push(S.runtimeSkippedMcp)
1430
1457
  stats.errors += 1
1431
1458
  return false
1432
1459
  }
@@ -1646,6 +1673,8 @@ async function installPass(
1646
1673
  )
1647
1674
  /** Wizard-confirmed Jev activation (target + caps), surfaced on the result. */
1648
1675
  let decisionModelActivation = null
1676
+ /** Cloudflare needs a user-supplied account ID, so the wizard defers it. */
1677
+ let decisionModelDeferredSetup = null
1649
1678
  const stats = summary.opencode
1650
1679
  // Per-call baseline. `stats` is the module-level cumulative summary, so the
1651
1680
  // consistency guard must compare against THIS call's delta, not the total.
@@ -1804,6 +1833,7 @@ async function installPass(
1804
1833
  },
1805
1834
  prompts: opts.deps?.prompts,
1806
1835
  isTTY: opts.deps?.isTTY,
1836
+ env: opts.deps?.env ?? opts.env ?? process.env,
1807
1837
  })
1808
1838
 
1809
1839
  // Resolve the location from the SELECTION before any cancel return: a
@@ -1840,6 +1870,7 @@ async function installPass(
1840
1870
  decisionRouterConfig = migrateDecisionRouterConfig(result.decisionRouterConfig)
1841
1871
  opts.decisionRouterConfig = decisionRouterConfig
1842
1872
  decisionModelActivation = result.decisionModelActivation ?? null
1873
+ decisionModelDeferredSetup = result.decisionModelDeferredSetup ?? null
1843
1874
  if (!dryRun && _lastRun) _lastRun.target = target
1844
1875
  }
1845
1876
 
@@ -2402,6 +2433,10 @@ async function installPass(
2402
2433
  // payload and the host config are already in place.
2403
2434
  warning(`Could not disable the builtin Context sidebar block: ${cause.message}`)
2404
2435
  stats.warnings++
2436
+ if (!Array.isArray(stats.warningMessages)) stats.warningMessages = []
2437
+ stats.warningMessages.push(
2438
+ `Could not disable the builtin Context sidebar block: ${cause.message}`,
2439
+ )
2405
2440
  }
2406
2441
  }
2407
2442
  if (componentSet.has('plugins')) advancePhase()
@@ -2565,20 +2600,6 @@ async function installPass(
2565
2600
  // A. Parse canonical agent config from src/agents/*.md frontmatter
2566
2601
  // and merge into opencode.json config.
2567
2602
  // --------------------------------------------------------------------
2568
- function getAgentSources(agentPrefix) {
2569
- const agentsDir = join(ROOT, 'src', 'agents')
2570
- if (!existsSync(agentsDir)) return {}
2571
- const sources = {}
2572
- const files = readdirSync(agentsDir).filter(
2573
- (f) => (f.endsWith('.agent.md') || f.endsWith('.md')) && f.toLowerCase() !== 'readme.md',
2574
- )
2575
- for (const f of files) {
2576
- const name = f.replace(/\.(agent\.)?md$/, '')
2577
- sources[name] = `${agentPrefix}/${name}.md`
2578
- }
2579
- return sources
2580
- }
2581
-
2582
2603
  function readAgentConfigFromCanonical() {
2583
2604
  const agentsDir = join(ROOT, 'src', 'agents')
2584
2605
  if (!existsSync(agentsDir)) return {}
@@ -2626,11 +2647,31 @@ async function installPass(
2626
2647
  return config
2627
2648
  }
2628
2649
 
2650
+ // Provenance prefix per install shape (D3-scoped: project installs write it;
2651
+ // global installs NEVER do — the cwd-relative path vanishes agents there).
2652
+ const agentPrefixForSource = isGlobalConfigDir(target)
2653
+ ? null
2654
+ : version === 'v2'
2655
+ ? 'agents'
2656
+ : '.opencode/agents'
2657
+ const agentSources = {}
2658
+ if (agentPrefixForSource !== null) {
2659
+ const agentsDir = join(ROOT, 'src', 'agents')
2660
+ if (existsSync(agentsDir)) {
2661
+ const files = readdirSync(agentsDir).filter(
2662
+ (f) => (f.endsWith('.agent.md') || f.endsWith('.md')) && f.toLowerCase() !== 'readme.md',
2663
+ )
2664
+ for (const f of files) {
2665
+ const name = f.replace(/\.(agent\.)?md$/, '')
2666
+ agentSources[name] = `${agentPrefixForSource}/${name}.md`
2667
+ }
2668
+ }
2669
+ }
2670
+ const isGlobalTarget = isGlobalConfigDir(target)
2671
+
2629
2672
  const configuredMcpServersForPolicies =
2630
2673
  version === 'v2' ? configuredMcpServerNames(config.mcp) : []
2631
2674
  const canonicalAgentConfig = readAgentConfigFromCanonical()
2632
- const agentSources = getAgentSources(agentPrefix)
2633
-
2634
2675
  if (config.agent === undefined) config.agent = {}
2635
2676
 
2636
2677
  if (config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)) {
@@ -2643,7 +2684,39 @@ async function installPass(
2643
2684
  // Preserve user-customized fields (model, provider, mcp, etc.)
2644
2685
  const existing = config.agent[agentName]
2645
2686
  if (!existing || typeof existing !== 'object' || Array.isArray(existing)) continue
2646
- if (agentSources[agentName]) existing.source = agentSources[agentName]
2687
+ // HEAL + provenance (field beta.14→26): `source` is cwd-relative and
2688
+ // host 2.2.5 resolves it against the SESSION cwd — so it is written
2689
+ // ONLY for project installs (the session cwd IS the project) and
2690
+ // NEVER for global installs, where the relative path pointed outside
2691
+ // the config dir and made every agent vanish ("Agent not found:
2692
+ // zeus"). Global entries also get a stale GLOBAL source healed away.
2693
+ if (isGlobalTarget) delete existing.source
2694
+ else if (agentSources[agentName] && !isGlobalTarget)
2695
+ existing.source = agentSources[agentName]
2696
+
2697
+ // The sibling opencode.jsonc merges with PRIORITY on this host and is
2698
+ // user-managed (the installer never rewrites it wholesale) — but OUR
2699
+ // stale `source` field poisons the merged view exactly the same way
2700
+ // (field beta.25: the config dir healed, the jsonc kept the roster
2701
+ // invisible outside it). Targeted strip of the exact pattern only.
2702
+ try {
2703
+ const jsoncPath = join(target, 'opencode.jsonc')
2704
+ if (existsSync(jsoncPath)) {
2705
+ const raw = readFileSync(jsoncPath, 'utf8')
2706
+ let healed = raw.replace(/,?\s*"source":\s*"agents\/[A-Za-z0-9_-]+\.md"/g, '')
2707
+ // A source-first entry leaves `"name": {,` — repair the orphan.
2708
+ healed = healed.replace(/("[A-Za-z0-9_-]+": \{),/g, '$1')
2709
+ if (healed !== raw) {
2710
+ writeFileSync(jsoncPath, healed)
2711
+ warning(
2712
+ 'Healed the sibling opencode.jsonc: removed stale cwd-relative agent "source" fields ' +
2713
+ '(the field that made agents vanish outside the config dir). Review the file if you hand-edit it.',
2714
+ )
2715
+ }
2716
+ }
2717
+ } catch {
2718
+ // The jsonc is user data; a failed heal is reported by doctor instead.
2719
+ }
2647
2720
  for (const field of MANAGED_FIELDS) {
2648
2721
  if (field in agentCfg) {
2649
2722
  existing[field] = JSON.parse(JSON.stringify(agentCfg[field]))
@@ -2654,7 +2727,7 @@ async function installPass(
2654
2727
  } else {
2655
2728
  // ── New agent ──
2656
2729
  const newAgent = {}
2657
- if (agentSources[agentName]) newAgent.source = agentSources[agentName]
2730
+ if (!isGlobalTarget && agentSources[agentName]) newAgent.source = agentSources[agentName]
2658
2731
  if (agentCfg.description) newAgent.description = agentCfg.description
2659
2732
 
2660
2733
  // Copy all framework-managed fields from canonical config
@@ -2784,11 +2857,39 @@ async function installPass(
2784
2857
  // `npm install`. Copying every entry across would turn "silently ignored"
2785
2858
  // into "config fails to load", so only loadable entries move; the rest stay
2786
2859
  // where they are and the warning names the exact failure mode.
2860
+ // Preflight (runs for pure-V2 configs too — a stale or volatile Pantheon
2861
+ // registration must be named even when the singular `plugin` key is long
2862
+ // gone). Field report beta.13 §2: an EXISTING `_npx` path is worse than a
2863
+ // missing one — it passes the existsSync check at install time and dies
2864
+ // intermittently later, so volatility is named and the re-registration
2865
+ // below repoints to the stable tree.
2866
+ if (Array.isArray(config.plugins)) {
2867
+ for (const ref of config.plugins) {
2868
+ const refPath = typeof ref === 'string' ? ref : ref?.package
2869
+ if (typeof refPath !== 'string' || managedPluginIdentity(refPath) === null) continue
2870
+ const absolute = isAbsolute(refPath) ? refPath : resolve(target, refPath)
2871
+ if (!existsSync(absolute)) {
2872
+ warning(
2873
+ `Existing Pantheon registration points to ${refPath}, which no longer exists` +
2874
+ (refPath.includes('_npx/')
2875
+ ? ' (the npx cache recycled that copy) — re-registering to the freshly installed tree'
2876
+ : ' — re-registering to the freshly installed tree'),
2877
+ )
2878
+ } else if (refPath.replaceAll('\\', '/').includes('/_npx/')) {
2879
+ warning(
2880
+ `Existing Pantheon registration points into the volatile npx cache (${refPath}) — ` +
2881
+ 'other npx-booted MCPs recycle that tree and kill the plugin mid-session; ' +
2882
+ 're-registering to a stable tree',
2883
+ )
2884
+ }
2885
+ }
2886
+ }
2787
2887
  if (Array.isArray(config.plugin)) {
2788
2888
  // Strip Pantheon refs FIRST, exactly as the V1 branch does: a stale V1
2789
2889
  // .ts path is not a registrable entry on this host and must not be moved.
2790
2890
  config.plugin = removePantheonPluginReferences(config.plugin)
2791
2891
  if (!Array.isArray(config.plugins)) config.plugins = []
2892
+
2792
2893
  const migrated = []
2793
2894
  const blocked = []
2794
2895
  for (const plugin of config.plugin) {
@@ -2860,6 +2961,14 @@ async function installPass(
2860
2961
  // Legacy refs (npm shorthand, the old src/plugin-v2.ts file path) are
2861
2962
  // recognized via managedPluginIdentity and already stripped above, so
2862
2963
  // they migrate here.
2964
+ const stableRoot = resolveStablePantheonRoot()
2965
+ if (stableRoot.volatile) {
2966
+ warning(
2967
+ 'This installer runs from the npx cache and no stable global install of ' +
2968
+ 'pantheon-opencode was found; the plugin registration will point into the ' +
2969
+ 'volatile cache and can break mid-session. Fix: npm install -g pantheon-opencode, then re-run init.',
2970
+ )
2971
+ }
2863
2972
  const resolvedV2 = resolveInstalledPlugin(PANTHEON_V2_PLUGIN)
2864
2973
  config.plugins = config.plugins.filter(
2865
2974
  (plugin) => pluginReferenceIdentity(plugin) !== pluginReferenceIdentity(resolvedV2),
@@ -3067,6 +3176,8 @@ async function installPass(
3067
3176
  for (const message of mcp.warnings ?? []) {
3068
3177
  warning(message)
3069
3178
  stats.warnings += 1
3179
+ if (!Array.isArray(stats.warningMessages)) stats.warningMessages = []
3180
+ stats.warningMessages.push(message)
3070
3181
  }
3071
3182
  }
3072
3183
 
@@ -3397,19 +3508,27 @@ async function installPass(
3397
3508
  process.stdout.write(` [OK] ${created} component(s) installed\n`)
3398
3509
  if (skipped > 0)
3399
3510
  process.stdout.write(` ${colors.dim('\u2014')} ${skipped} already up-to-date\n`)
3400
- if (warnings > 0)
3511
+ // The warning TEXT restates here — the count alone sent users to doctor to
3512
+ // learn what had already scrolled past.
3513
+ for (const message of stats.warningMessages ?? []) {
3514
+ process.stdout.write(` [WARN] ${message}\n`)
3515
+ }
3516
+ if (warnings > 0 && (stats.warningMessages ?? []).length === 0) {
3517
+ process.stdout.write(` [WARN] ${warnings} warning(s)\n`)
3518
+ }
3519
+ if (warnings > 0) {
3401
3520
  process.stdout.write(
3402
- ` [WARN] ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
3521
+ ` ${colors.dim("Run 'pantheon-opencode doctor' for the full health check")}\n`,
3403
3522
  )
3523
+ }
3404
3524
  process.stdout.write('\n')
3405
- process.stdout.write(` ${colors.bold('Next steps:')}\n`)
3406
- process.stdout.write(` ${colors.dim('\u2022')} Configure agents in opencode.json\n`)
3407
- process.stdout.write(` ${colors.dim('\u2022')} Run 'pantheon-opencode doctor' to verify\n`)
3408
- process.stdout.write(
3409
- ` ${colors.dim('\u2022')} Run 'opencode' to start using Pantheon agents\n`,
3410
- )
3411
- process.stdout.write('\n')
3412
- printWorktreeGuidance({ projectRoot: process.cwd(), interactive: true })
3525
+ // Worktree guidance is a project-install concept: a global install run
3526
+ // from $HOME derived a nonsense `<home>/.pantheon-worktrees/<user>` path.
3527
+ printWorktreeGuidance({
3528
+ projectRoot: process.cwd(),
3529
+ interactive: true,
3530
+ enabled: !(opts.global ?? isGlobalConfigDir(target)),
3531
+ })
3413
3532
  }
3414
3533
 
3415
3534
  // Beta 11 Setup phase 3: report whether this call APPLIED, so the caller can
@@ -3433,6 +3552,7 @@ async function installPass(
3433
3552
  configAdvisories,
3434
3553
  v2Capabilities: version === 'v2' ? v2Capabilities() : null,
3435
3554
  decisionModelActivation,
3555
+ decisionModelDeferredSetup,
3436
3556
  pluginOptions: v2PluginOptions,
3437
3557
  }
3438
3558
  : {
@@ -3440,6 +3560,7 @@ async function installPass(
3440
3560
  applied: true,
3441
3561
  reason: 'applied',
3442
3562
  decisionModelActivation,
3563
+ decisionModelDeferredSetup,
3443
3564
  target,
3444
3565
  runtimeEffects,
3445
3566
  openCodeVersion: version,