pantheon-opencode 1.6.1 → 1.6.2-beta.10

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 (169) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +179 -0
  4. package/README.md +268 -20
  5. package/README.pt-BR.md +34 -11
  6. package/bin/pantheon-init.mjs +301 -32
  7. package/package.json +13 -4
  8. package/plugin.json +1 -1
  9. package/prompts/README.md +58 -0
  10. package/prompts/debug-issue.prompt.md +46 -0
  11. package/prompts/dynamic/agora-generated.txt +38 -0
  12. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  13. package/prompts/focus.prompt.md +42 -0
  14. package/prompts/implement-feature.prompt.md +39 -0
  15. package/prompts/optimize-database.prompt.md +58 -0
  16. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  17. package/prompts/plan-architecture.prompt.md +59 -0
  18. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  19. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  20. package/prompts/semantic-summarize.md +50 -0
  21. package/prompts/sketch.prompt.md +91 -0
  22. package/prompts/subtask.prompt.md +131 -0
  23. package/pyproject.toml +1 -1
  24. package/scripts/build-agents-md.mjs +1 -1
  25. package/scripts/decision-router-budget.mjs +780 -0
  26. package/scripts/decision-router-v2-budget.mjs +218 -0
  27. package/scripts/decision-router-v2-egress.mjs +272 -0
  28. package/scripts/decision-router.mjs +758 -0
  29. package/scripts/docs-check-changelog.mjs +5 -3
  30. package/scripts/doctor.mjs +213 -45
  31. package/scripts/install/agents-md.mjs +2 -1
  32. package/scripts/install/component-selection.mjs +9 -4
  33. package/scripts/install/config-migration.mjs +344 -393
  34. package/scripts/install/config-paths.mjs +15 -0
  35. package/scripts/install/decision-layer-preview.mjs +376 -0
  36. package/scripts/install/decision-router-config.mjs +560 -0
  37. package/scripts/install/health-check.mjs +20 -11
  38. package/scripts/install/interactive.mjs +103 -14
  39. package/scripts/install/interrupt.mjs +4 -3
  40. package/scripts/install/mcp-permissions.mjs +164 -0
  41. package/scripts/install/migrate.mjs +123 -72
  42. package/scripts/install/opencode-version.mjs +31 -13
  43. package/scripts/install/opencode-wildcard.mjs +106 -0
  44. package/scripts/install/opencode.mjs +411 -184
  45. package/scripts/install/plan-artifact.mjs +12 -1
  46. package/scripts/install/plan.mjs +8 -1
  47. package/scripts/install/plugin.mjs +18 -1
  48. package/scripts/install/state.mjs +12 -0
  49. package/scripts/install/strings.mjs +22 -0
  50. package/scripts/install/v2-capabilities.mjs +5 -6
  51. package/scripts/install/venv.mjs +34 -17
  52. package/scripts/mcp_resources.py +11 -9
  53. package/scripts/package-evidence.mjs +1 -0
  54. package/scripts/release-notes.mjs +30 -7
  55. package/scripts/restore.mjs +22 -10
  56. package/scripts/sandbox-env.sh +174 -0
  57. package/scripts/setup-v2-config.mjs +1703 -0
  58. package/scripts/setup.mjs +415 -0
  59. package/scripts/sync-tui.mjs +9 -1
  60. package/scripts/test-opencode-v2-sandbox.sh +448 -157
  61. package/scripts/update-skills-lock.mjs +30 -0
  62. package/scripts/versioning.mjs +41 -5
  63. package/skills-lock.json +10 -10
  64. package/src/agents/aphrodite.md +11 -3
  65. package/src/agents/apollo.md +6 -0
  66. package/src/agents/athena.md +7 -1
  67. package/src/agents/demeter.md +6 -2
  68. package/src/agents/gaia.md +5 -0
  69. package/src/agents/hephaestus.md +7 -2
  70. package/src/agents/hermes.md +14 -13
  71. package/src/agents/iris.md +6 -2
  72. package/src/agents/mnemosyne.md +21 -50
  73. package/src/agents/nyx.md +6 -2
  74. package/src/agents/prometheus.md +5 -1
  75. package/src/agents/talos.md +10 -1
  76. package/src/agents/themis.md +5 -1
  77. package/src/agents/zeus.md +61 -65
  78. package/src/instructions/agent-return-format.instructions.md +1 -1
  79. package/src/instructions/memory-protocol.instructions.md +3 -3
  80. package/src/instructions/test-economy.instructions.md +6 -6
  81. package/src/mcp/eval_store.py +11 -4
  82. package/src/mcp/mcp_resources.py +11 -9
  83. package/src/mcp/memory_mcp.py +293 -150
  84. package/src/mcp/pantheon_vision.py +37 -36
  85. package/src/pantheon/cost-command.ts +30 -133
  86. package/src/pantheon/jev-decision-tool.ts +347 -0
  87. package/src/pantheon/jev-decisions.ts +625 -0
  88. package/src/pantheon/local-decision-agents.ts +170 -0
  89. package/src/pantheon/local-decision-budget.ts +1046 -0
  90. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  91. package/src/pantheon/local-decision-prompt.ts +256 -0
  92. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  93. package/src/pantheon/local-decision-router.ts +225 -0
  94. package/src/pantheon/local-decision-skills.ts +281 -0
  95. package/src/pantheon/local-decision-tool.ts +160 -0
  96. package/src/pantheon/local-decision-turn.ts +101 -0
  97. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  98. package/src/pantheon/local-orchestration.ts +322 -0
  99. package/src/pantheon/model-pricing.ts +1 -536
  100. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  101. package/src/pantheon/v2-decision-budget.ts +456 -0
  102. package/src/pantheon/v2-decision-contracts.ts +300 -0
  103. package/src/pantheon/v2-decision-egress.ts +203 -0
  104. package/src/pantheon/v2-decision-events.ts +180 -0
  105. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  106. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  107. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  108. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  109. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  110. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  111. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  112. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  113. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  114. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  115. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  116. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  117. package/src/pantheon/v2-decision-points.ts +242 -0
  118. package/src/pantheon/v2-decision-policy.ts +166 -0
  119. package/src/pantheon/v2-decision-premises.ts +146 -0
  120. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  121. package/src/pantheon/v2-decision-rank.ts +91 -0
  122. package/src/pantheon/v2-decision-registry.ts +391 -0
  123. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  124. package/src/pantheon/v2-decision-shadow.ts +123 -0
  125. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  126. package/src/pantheon/v2-decision-verify.ts +51 -0
  127. package/src/pantheon/v2-hook-engine.ts +307 -0
  128. package/src/pantheon/v2-native-decisions.ts +365 -0
  129. package/src/pantheon/v2-shell-hooks.ts +66 -2
  130. package/src/pantheon/v2-tools.ts +38 -15
  131. package/src/pantheon/v2-vision.ts +34 -29
  132. package/src/pantheon/vision.ts +43 -10
  133. package/src/plugin-v2.ts +449 -79
  134. package/src/plugin.ts +4 -0
  135. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  136. package/src/plugins/tui/dist/server-v2.d.ts +22 -0
  137. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  138. package/src/plugins/tui/dist/server-v2.js +26 -0
  139. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  140. package/src/plugins/tui/dist/tui-v2.d.ts +54 -51
  141. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  142. package/src/plugins/tui/dist/tui-v2.js +762 -529
  143. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  144. package/src/plugins/tui/dist/tui.js +1 -1
  145. package/src/plugins/tui/index-v2.ts +3 -6
  146. package/src/plugins/tui/package-lock.json +17 -2
  147. package/src/plugins/tui/package.json +6 -3
  148. package/src/plugins/tui/src/context-gauge.ts +59 -0
  149. package/src/plugins/tui/src/cost-data.ts +607 -0
  150. package/src/plugins/tui/src/index-v2.tsx +360 -242
  151. package/src/plugins/tui/src/model-pricing.ts +536 -0
  152. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  153. package/src/plugins/tui/src/server-v2.ts +21 -0
  154. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  155. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  156. package/src/plugins/tui/tsdown.config.ts +34 -5
  157. package/src/routing.yml +72 -13
  158. package/src/skills/README.md +4 -0
  159. package/src/skills/agent-coordination/SKILL.md +0 -3
  160. package/src/skills/artifact-management/SKILL.md +0 -3
  161. package/src/skills/auto-continue/SKILL.md +0 -3
  162. package/src/skills/code-review-checklist/SKILL.md +0 -3
  163. package/src/skills/context-compression/SKILL.md +0 -3
  164. package/src/skills/memory-bank/SKILL.md +6 -28
  165. package/src/skills/session-goal/SKILL.md +0 -3
  166. package/src/skills/simplify/SKILL.md +5 -4
  167. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  168. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  169. package/src/pantheon/memory-context.ts +0 -1017
@@ -47,10 +47,21 @@ import {
47
47
  mergeContextSandboxBlocks,
48
48
  migrateMcpEntrypointPaths,
49
49
  migrateV1toV2,
50
+ validateMcpV1toV2Source,
50
51
  } from './config-migration.mjs'
52
+ import { resolveGlobalConfigDirectory } from './config-paths.mjs'
53
+ import { migrateDecisionRouterConfig } from './decision-router-config.mjs'
51
54
  import { componentForInstalledPath, updateFileInventory } from './file-inventory.mjs'
52
55
  import { healthCheck } from './health-check.mjs'
53
- import { detectVersion, runMigrations } from './migrate.mjs'
56
+ import {
57
+ assertMcpGeneratedPermissionsDoNotWeakenExplicitRules,
58
+ assertMcpPermissionNamesUnambiguous,
59
+ assertMcpPermissionScopesDoNotAliasConfiguredServers,
60
+ assertMcpPermissionServerGrantsUnambiguous,
61
+ mcpPermissionAliases,
62
+ normalizeMcpPermissionSegment,
63
+ } from './mcp-permissions.mjs'
64
+ import { runMigrations } from './migrate.mjs'
54
65
  import { describeSharedState } from './opencode-state.mjs'
55
66
  import { DRY_RUN_PROBE_TIMEOUT_MS, resolveOpenCodeVersion } from './opencode-version.mjs'
56
67
  import {
@@ -92,16 +103,6 @@ import {
92
103
  import { setupVenv, venvPythonPath } from './venv.mjs'
93
104
  import { assertNoSymlinkAncestors, assertPathWithin, assertSafeRemoval } from './verify.mjs'
94
105
 
95
- const COMPONENT_NAMES = [
96
- 'agents',
97
- 'skills',
98
- 'instructions',
99
- 'prompts',
100
- 'commands',
101
- 'plugins',
102
- 'runtime',
103
- ]
104
-
105
106
  /**
106
107
  * The ordered phases one install invocation really runs, derived from the
107
108
  * FINAL component selection (the interactive wizard may have changed it) and
@@ -134,7 +135,7 @@ export function planInstallPhases({ components, dryRun }) {
134
135
  if (!dryRun) phases.push(S.runningHealthChecks)
135
136
  }
136
137
  phases.push(S.writingConfiguration)
137
- if (selected.has('runtime')) phases.push(S.runningMigrations)
138
+ phases.push(S.runningMigrations)
138
139
  if (!dryRun) phases.push(S.recordingState)
139
140
  return phases
140
141
  }
@@ -393,9 +394,7 @@ const PANTHEON_MCP_SERVER_ENTRIES = Object.freeze([
393
394
  /** The managed server names, in write order. */
394
395
  const PANTHEON_MCP_SERVERS = Object.freeze(PANTHEON_MCP_SERVER_ENTRIES.map((entry) => entry.name))
395
396
 
396
- function normalizeMcpPermissionSegment(value) {
397
- return value.replace(/[^a-zA-Z0-9_]/g, '_')
398
- }
397
+ export { normalizeMcpPermissionSegment, PANTHEON_MCP_SERVERS }
399
398
 
400
399
  /**
401
400
  * Translate an agent's `mcp_tools` frontmatter into per-tool native
@@ -407,7 +406,7 @@ function normalizeMcpPermissionSegment(value) {
407
406
  * @param {Record<string, 'all' | string[]>} mcpTools
408
407
  * @returns {Record<string, 'allow' | 'deny'>}
409
408
  */
410
- export function deriveNativeMcpPermissions(mcpTools) {
409
+ export function deriveNativeMcpPermissions(mcpTools, configuredServers = []) {
411
410
  if (mcpTools === null || typeof mcpTools !== 'object' || Array.isArray(mcpTools)) {
412
411
  throw new TypeError('mcp_tools must be an object keyed by MCP server name')
413
412
  }
@@ -427,21 +426,36 @@ export function deriveNativeMcpPermissions(mcpTools) {
427
426
  ) {
428
427
  throw new TypeError(`mcp_tools.${server} must be "all" or an array of tool names`)
429
428
  }
429
+ }
430
430
 
431
- const serverAliases = new Set([server, normalizeMcpPermissionSegment(server)])
431
+ assertMcpPermissionNamesUnambiguous(servers)
432
+ assertMcpPermissionScopesDoNotAliasConfiguredServers(servers, configuredServers)
433
+ for (const server of servers) {
434
+ const tools = Object.hasOwn(mcpTools, server) ? mcpTools[server] : []
435
+ if (Array.isArray(tools)) assertMcpPermissionNamesUnambiguous(tools)
436
+ }
437
+ assertMcpPermissionServerGrantsUnambiguous(
438
+ [...servers].map((server) => ({
439
+ server,
440
+ tools: Object.hasOwn(mcpTools, server) ? mcpTools[server] : [],
441
+ })),
442
+ )
443
+
444
+ for (const server of servers) {
445
+ const serverAliases = mcpPermissionAliases(server)
432
446
  for (const alias of serverAliases) permissions[`${alias}_*`] = 'deny'
433
447
  }
434
448
 
435
449
  for (const server of servers) {
436
450
  const tools = Object.hasOwn(mcpTools, server) ? mcpTools[server] : []
437
- const serverAliases = new Set([server, normalizeMcpPermissionSegment(server)])
451
+ const serverAliases = mcpPermissionAliases(server)
438
452
  if (tools === 'all') {
439
453
  for (const alias of serverAliases) permissions[`${alias}_*`] = 'allow'
440
454
  continue
441
455
  }
442
456
 
443
457
  for (const tool of tools) {
444
- const toolAliases = new Set([tool, normalizeMcpPermissionSegment(tool)])
458
+ const toolAliases = mcpPermissionAliases(tool)
445
459
  for (const serverAlias of serverAliases) {
446
460
  for (const toolAlias of toolAliases) {
447
461
  permissions[`${serverAlias}_${toolAlias}`] = 'allow'
@@ -453,10 +467,58 @@ export function deriveNativeMcpPermissions(mcpTools) {
453
467
  return permissions
454
468
  }
455
469
 
470
+ /** Merge generated MCP grants only when they do not weaken explicit agent policy. */
471
+ export function mergeAgentMcpPermissions(explicit, mcpTools, configuredServers = []) {
472
+ const generated = deriveNativeMcpPermissions(mcpTools, configuredServers)
473
+ assertMcpGeneratedPermissionsDoNotWeakenExplicitRules(explicit, generated)
474
+ return { ...(explicit ?? {}), ...generated }
475
+ }
476
+
477
+ /** Build a fail-closed skill allowlist from an agent's canonical `skills` list. */
478
+ export function deriveNativeSkillPermissions(skills) {
479
+ if (!Array.isArray(skills)) {
480
+ throw new TypeError('agent skills must be an array of skill IDs')
481
+ }
482
+
483
+ const permissions = { '*': 'deny' }
484
+ const seen = new Set()
485
+ for (const skill of skills) {
486
+ if (typeof skill !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skill)) {
487
+ throw new TypeError(`agent skill ID is invalid: ${String(skill)}`)
488
+ }
489
+ if (seen.has(skill)) throw new TypeError(`agent skill list contains duplicate skill: ${skill}`)
490
+ seen.add(skill)
491
+ permissions[skill] = 'allow'
492
+ }
493
+ return permissions
494
+ }
495
+
496
+ /**
497
+ * Add the canonical skill allowlist to one agent's permission map. An explicit
498
+ * skill policy in canonical frontmatter would make last-match precedence
499
+ * ambiguous, so require that policy to be expressed through `skills:` instead.
500
+ */
501
+ export function mergeAgentSkillPermissions(explicit, skills) {
502
+ if (explicit?.skill !== undefined) {
503
+ throw new TypeError('agent skill access must be declared only through the skills list')
504
+ }
505
+ return { ...(explicit ?? {}), skill: deriveNativeSkillPermissions(skills) }
506
+ }
507
+
456
508
  function deepClone(value) {
457
509
  return JSON.parse(JSON.stringify(value))
458
510
  }
459
511
 
512
+ function configuredMcpServerNames(mcpConfig) {
513
+ if (mcpConfig === null || typeof mcpConfig !== 'object' || Array.isArray(mcpConfig)) return []
514
+ const { hasV2ServersMap, legacyServersToggle } = validateMcpV1toV2Source(mcpConfig)
515
+ return Object.entries(mcpConfig).flatMap(([name, value]) => {
516
+ if (hasV2ServersMap && name === 'servers') return Object.keys(value)
517
+ if (legacyServersToggle && name === 'servers') return []
518
+ return [name]
519
+ })
520
+ }
521
+
460
522
  /**
461
523
  * (Re)generate the code-mode manifest with SHA-256 digests for every bundled
462
524
  * script, and write it to the destination. This is the explicit installation
@@ -782,6 +844,35 @@ export function deduplicatePluginReferences(refs) {
782
844
  })
783
845
  }
784
846
 
847
+ /**
848
+ * Register the copied Pantheon TUI plugin in the V2 `plugins` list.
849
+ *
850
+ * The OpenCode 2.x host does not load a local plugin folder by free discovery —
851
+ * only entries listed in `config.plugins` are loaded (sandbox probe evidence:
852
+ * no entry → the copy's server half never attaches; with the entry the host
853
+ * logs `loading plugin id=…/pantheon-tui`). The server half is what wires the
854
+ * TUI runtime's reactive channel, so without this registration a
855
+ * postinstall/sync that re-copies the payload after `init` leaves a sidebar
856
+ * that mounts dead (the "mudo panel" symptom).
857
+ *
858
+ * Idempotent: the existing entry for the copy (same identity) is retained
859
+ * and kept after the core plugin, while every other entry stays in place.
860
+ * Gated on the copy existing so an install without the plugins component does
861
+ * not register a dangling path.
862
+ *
863
+ * @param {{ plugins?: unknown }} config - the config object about to be written (mutated)
864
+ * @param {{ tuiCopyDir: string }} opts - absolute path of the copied plugin directory
865
+ */
866
+ export function ensureTuiCopyRegistered(config, { tuiCopyDir }) {
867
+ if (!Array.isArray(config.plugins)) config.plugins = []
868
+ if (!existsSync(tuiCopyDir)) return
869
+
870
+ const identity = pluginReferenceIdentity(tuiCopyDir)
871
+ const existing = config.plugins.find((entry) => pluginReferenceIdentity(entry) === identity)
872
+ config.plugins = config.plugins.filter((entry) => pluginReferenceIdentity(entry) !== identity)
873
+ config.plugins.push(existing ?? tuiCopyDir)
874
+ }
875
+
785
876
  /**
786
877
  * Duplicate the V1 top-level `context_sandbox` block into the exact Pantheon V2
787
878
  * plugin entry's `options`, converting a plain-string entry into the
@@ -877,8 +968,9 @@ export function isGlobalConfigDir(target) {
877
968
  *
878
969
  * <configDir>/plugins/pantheon-tui (tui.ts + dist/ + package manifests)
879
970
  *
880
- * V1 registers that copy through tui.json. V2 discovers the local plugin's
881
- * index.ts + tui.ts pair; the V2 shim re-exports dist/tui-v2.js.
971
+ * V1 registers that copy through tui.json. V2 loads the copy only through the
972
+ * `plugins` entry (see ensureTuiCopyRegistered); the V2 shim re-exports
973
+ * dist/tui-v2.js.
882
974
  *
883
975
  * @param {string} configDir - OpenCode config directory (target for global
884
976
  * installs, <target>/.opencode for project installs)
@@ -1149,8 +1241,9 @@ export function applyContextSidebarNegation(
1149
1241
  }
1150
1242
 
1151
1243
  /**
1152
- * Sync the Pantheon TUI plugin payload and V1 registration. V2 discovers the
1153
- * copied local-plugin entrypoints and does not use a project tui.json.
1244
+ * Sync the Pantheon TUI plugin payload and V1 registration. V2 does not use a
1245
+ * project tui.json; it loads the copy's server ONLY through the config
1246
+ * `plugins` entry written by ensureTuiCopyRegistered().
1154
1247
  *
1155
1248
  * Contract (single source of truth):
1156
1249
  * 1. ALWAYS copy src/plugins/tui → <configDir>/plugins/pantheon-tui with the
@@ -1161,8 +1254,9 @@ export function applyContextSidebarNegation(
1161
1254
  * paths, in-package src/plugins/tui dirs, bare plugins/pantheon-tui
1162
1255
  * copies, and npx paths. A stale ref left in the non-target location
1163
1256
  * would still be loaded and break the TUI.
1164
- * 3. V1 registers the copied directory in the selected target. V2 relies on
1165
- * local-plugin discovery and does not write a project tui.json entry.
1257
+ * 3. V1 registers the copied directory in the selected target. V2 does not
1258
+ * write a project tui.json entry; its `plugins` registration is written
1259
+ * by the config merge (ensureTuiCopyRegistered).
1166
1260
  *
1167
1261
  * @param {string} target - install target directory
1168
1262
  * @param {object} [opts]
@@ -1225,9 +1319,10 @@ export function syncTuiRegistration(
1225
1319
  })
1226
1320
  }
1227
1321
 
1228
- // OpenCode V2 discovers local plugins from the config plugins directories;
1229
- // its TUI plugin API is exposed by the sibling tui.ts entrypoint. V1 still
1230
- // requires the explicit tui.json registration.
1322
+ // The V2 host loads the copy's server-side RPC only from the config
1323
+ // `plugins` list — ensureTuiCopyRegistered writes that entry during the
1324
+ // config merge, so no tui.json is written here. V1 still requires the
1325
+ // explicit tui.json registration.
1231
1326
  if (version === 'v2') return 'skipped'
1232
1327
 
1233
1328
  // 3. Register the copied directory in the selected target only.
@@ -1251,6 +1346,8 @@ export function setupRuntimePhase(
1251
1346
  reviewedSnapshots = null,
1252
1347
  onVenvDone = null,
1253
1348
  onHealthDone = null,
1349
+ onRuntimeEffects = null,
1350
+ verbose = false,
1254
1351
  },
1255
1352
  stats,
1256
1353
  deps = {},
@@ -1261,14 +1358,27 @@ export function setupRuntimePhase(
1261
1358
  let stopProgress
1262
1359
  try {
1263
1360
  stopProgress = spinner(S.settingUpRuntime)
1361
+ let setupResult
1264
1362
  try {
1265
- setup(target, {
1363
+ setupResult = setup(target, {
1266
1364
  dryRun,
1267
1365
  force: clean,
1366
+ verbose,
1268
1367
  recorder,
1269
1368
  reviewedRemovals,
1270
1369
  reviewedSnapshots,
1271
1370
  })
1371
+ const pythonExists = existsSync(venvPythonPath(target))
1372
+ const runtimeEffects = setupResult?.runtimeEffects ?? {
1373
+ venv:
1374
+ clean && existsSync(join(target, '.venv'))
1375
+ ? 'recreate'
1376
+ : pythonExists
1377
+ ? 'reuse'
1378
+ : 'create',
1379
+ dependencies: 'install',
1380
+ }
1381
+ onRuntimeEffects?.(runtimeEffects)
1272
1382
  } finally {
1273
1383
  // Count the phase even when setup throws: it DID run (and failed). The
1274
1384
  // failure is reported below as a warning, not as a missing phase.
@@ -1306,6 +1416,7 @@ export function setupRuntimePhase(
1306
1416
  stopProgress = null
1307
1417
  warning(`${health.failed.length} check(s) failed — review above`)
1308
1418
  stats.warnings += health.failed.length
1419
+ stats.errors += 1
1309
1420
  return false
1310
1421
  }
1311
1422
  stopProgress(true)
@@ -1316,6 +1427,7 @@ export function setupRuntimePhase(
1316
1427
  error(S.runtimeFailed(err.message))
1317
1428
  warning(S.runtimeSkippedMcp)
1318
1429
  stats.warnings += 1
1430
+ stats.errors += 1
1319
1431
  return false
1320
1432
  }
1321
1433
  }
@@ -1338,63 +1450,80 @@ export function setupRuntimePhase(
1338
1450
  * order) — the dry-run preview reports exactly these
1339
1451
  */
1340
1452
  export function applyMcpServerEntries(config, { runtimeTarget, venvPython, version = 'v2' }) {
1341
- config.mcp = config.mcp || {}
1342
- // MCP stays a flat named-server map for BOTH V1 and V2: OpenCode 1.18.x has
1343
- // no `mcp.servers` wrapper and rejects one with "Missing key
1344
- // mcp.servers.enabled". config-migration.mjs normalizes any legacy
1345
- // wrapper-shaped entries back to the flat map.
1346
- const healed = migrateMcpEntrypointPaths(config.mcp)
1453
+ if (version === 'v2') {
1454
+ if (Object.hasOwn(config, 'mcp')) validateMcpV1toV2Source(config.mcp)
1455
+ else config.mcp = {}
1456
+ } else {
1457
+ config.mcp = config.mcp || {}
1458
+ }
1459
+ let serverMap = config.mcp
1460
+ if (version === 'v2') {
1461
+ const { hasV2ServersMap, legacyServersToggle } = validateMcpV1toV2Source(config.mcp)
1462
+ const existingServers = config.mcp.servers
1463
+ if (hasV2ServersMap) {
1464
+ serverMap = existingServers
1465
+ } else {
1466
+ serverMap = { ...config.mcp }
1467
+ if (legacyServersToggle) delete serverMap.servers
1468
+ config.mcp = { servers: serverMap }
1469
+ }
1470
+ }
1471
+ const healed = migrateMcpEntrypointPaths(serverMap)
1347
1472
 
1348
1473
  // Only add if not already configured by user.
1349
1474
  const servers = []
1350
1475
  for (const entry of PANTHEON_MCP_SERVER_ENTRIES) {
1351
- if (config.mcp[entry.name]) continue
1352
- config.mcp[entry.name] = {
1476
+ if (serverMap[entry.name]) continue
1477
+ serverMap[entry.name] = {
1353
1478
  type: 'local',
1354
1479
  cwd: runtimeTarget,
1355
1480
  command: [venvPython, entry.script],
1356
- enabled: true,
1481
+ ...(version === 'v1' ? { enabled: true } : {}),
1357
1482
  }
1358
1483
  servers.push(entry.name)
1359
1484
  }
1360
1485
 
1361
- // Default MCP permissions.
1486
+ // V1 compatibility defaults. V2 setup converts user `ask` entries only after
1487
+ // explicit review; the inert legacy defaults are not seeded into V2 configs.
1362
1488
  //
1363
- // WARNING: on OpenCode 2.x, `permission.mcp.<server>` is NOT enforced. The
1364
- // host evaluates an MCP call as the action `<server>_<tool>` with resources
1365
- // ["*"]; `permission.mcp.<server>` and `action:"mcp"` are inert (measured on
1366
- // 2.0.29–2.1.3). These defaults are kept for V1 compatibility, but `ask` does
1367
- // not prompt and `allow` grants nothing it did not already have — every `ask`
1368
- // server below is reported to the user as unenforced. The enforceable form is
1369
- // `{ action: "<server>_*", resource: "*", effect: "deny" }`; `ask` there
1370
- // HIDES the tool instead of asking, so it is never emitted as a default.
1371
- config.permission = config.permission || {}
1372
- config.permission.mcp = config.permission.mcp || {}
1373
- if (!config.permission.mcp['pantheon-resources']) {
1374
- config.permission.mcp['pantheon-resources'] = 'allow'
1375
- }
1376
- if (!config.permission.mcp['pantheon-code-mode']) {
1377
- config.permission.mcp['pantheon-code-mode'] = 'ask'
1378
- }
1379
- if (!config.permission.mcp['pantheon-memory']) {
1380
- config.permission.mcp['pantheon-memory'] = 'allow'
1381
- }
1382
- if (!config.permission.mcp['pantheon-persistence']) {
1383
- config.permission.mcp['pantheon-persistence'] = 'allow'
1384
- }
1385
- if (!config.permission.mcp['pantheon-vision']) {
1386
- config.permission.mcp['pantheon-vision'] = 'ask'
1489
+ // Legacy defaults remain V1-only. V2 requires explicit native permissions;
1490
+ // absent a rule, MCP servers remain accessible without a prompt.
1491
+ if (version === 'v1') {
1492
+ config.permission = config.permission || {}
1493
+ config.permission.mcp = config.permission.mcp || {}
1494
+ if (!config.permission.mcp['pantheon-resources']) {
1495
+ config.permission.mcp['pantheon-resources'] = 'allow'
1496
+ }
1497
+ if (!config.permission.mcp['pantheon-code-mode']) {
1498
+ config.permission.mcp['pantheon-code-mode'] = 'ask'
1499
+ }
1500
+ if (!config.permission.mcp['pantheon-memory']) {
1501
+ config.permission.mcp['pantheon-memory'] = 'allow'
1502
+ }
1503
+ if (!config.permission.mcp['pantheon-persistence']) {
1504
+ config.permission.mcp['pantheon-persistence'] = 'allow'
1505
+ }
1506
+ if (!config.permission.mcp['pantheon-vision']) {
1507
+ config.permission.mcp['pantheon-vision'] = 'ask'
1508
+ }
1387
1509
  }
1388
1510
 
1389
1511
  // Report every `ask` entry, whether just seeded or left by a previous
1390
1512
  // install: the config claims a gate the host does not apply. V1's MCP
1391
1513
  // permission semantics were not measured, so the warning is V2-only.
1392
- const S = strings()
1514
+ const askCount = Object.values(config.permission?.mcp ?? {}).filter(
1515
+ (effect) => effect === 'ask',
1516
+ ).length
1393
1517
  const warnings =
1394
1518
  version === 'v2'
1395
- ? Object.entries(config.permission.mcp)
1396
- .filter(([, effect]) => effect === 'ask')
1397
- .map(([server]) => S.mcpAskNotEnforceable(server))
1519
+ ? [
1520
+ ...(askCount > 0
1521
+ ? [
1522
+ `${askCount} legacy MCP ask rule(s) cannot be enforced; run setup for an explicit policy choice.`,
1523
+ ]
1524
+ : []),
1525
+ 'V2 Pantheon MCP servers without an explicit permission rule remain accessible without a prompt.',
1526
+ ]
1398
1527
  : []
1399
1528
 
1400
1529
  return { healed, warnings, servers }
@@ -1446,7 +1575,7 @@ export async function installOpenCode(
1446
1575
  target,
1447
1576
  dryRun = false,
1448
1577
  clean = false,
1449
- components = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime'],
1578
+ components = ['agents', 'skills', 'instructions', 'commands', 'plugins'],
1450
1579
  opts = {},
1451
1580
  ) {
1452
1581
  // Reset per-call so a stale run can never leak into a fresh failure report.
@@ -1461,6 +1590,15 @@ export async function installOpenCode(
1461
1590
  _activeGauge?.fail(err instanceof Error ? err.message : String(err))
1462
1591
  const run = dryRun ? null : _lastRun
1463
1592
  if (run) {
1593
+ try {
1594
+ err.installOutcome = {
1595
+ target: run.target,
1596
+ applied: run.applied,
1597
+ backupDir: run.backupDir,
1598
+ }
1599
+ } catch {
1600
+ // An exotic frozen error must not hide the installer failure.
1601
+ }
1464
1602
  const S = strings()
1465
1603
  const paths = summarizeChanges(run.entries ?? [])
1466
1604
  .files.filter((f) => f.action !== ACTIONS.UNCHANGED && f.action !== ACTIONS.CONFLICT)
@@ -1487,17 +1625,27 @@ async function installPass(
1487
1625
  target,
1488
1626
  dryRun = false,
1489
1627
  clean = false,
1490
- components = ['agents', 'skills', 'instructions', 'commands', 'plugins', 'runtime'],
1628
+ components = ['agents', 'skills', 'instructions', 'commands', 'plugins'],
1491
1629
  opts = {},
1492
1630
  ) {
1631
+ if (opts.configPreview !== undefined && opts.configPreview !== null && !dryRun) {
1632
+ throw new Error('A setup config preview is accepted only during a dry run.')
1633
+ }
1634
+
1493
1635
  // Default target if not provided (global ~/.config/opencode)
1494
1636
  if (!target) {
1495
- target = join(homedir(), '.config', 'opencode')
1637
+ target = resolveGlobalConfigDirectory(process.env)
1496
1638
  }
1639
+ opts.onTargetResolved?.(target)
1497
1640
 
1498
1641
  const componentSet = new Set(
1499
1642
  opts.noMcp ? components.filter((component) => component !== 'runtime') : components,
1500
1643
  )
1644
+ let decisionRouterConfig = migrateDecisionRouterConfig(
1645
+ opts.decisionRouterConfig ?? readState(target)?.decision_router,
1646
+ )
1647
+ /** Wizard-confirmed Jev activation (target + caps), surfaced on the result. */
1648
+ let decisionModelActivation = null
1501
1649
  const stats = summary.opencode
1502
1650
  // Per-call baseline. `stats` is the module-level cumulative summary, so the
1503
1651
  // consistency guard must compare against THIS call's delta, not the total.
@@ -1506,6 +1654,7 @@ async function installPass(
1506
1654
  let plannedChanges = 0
1507
1655
  let planFiles = []
1508
1656
  let planTotals = null
1657
+ let runtimeEffects = null
1509
1658
  let removalPaths = []
1510
1659
  // MCP servers this pass seeds into opencode.json, in write order. Filled by
1511
1660
  // applyMcpServerEntries so the preview names exactly what the apply writes.
@@ -1533,6 +1682,23 @@ async function installPass(
1533
1682
  const ownRecorder = opts.recorder ? null : createRecorder()
1534
1683
  const preview = dryRun && ownRecorder ? ownRecorder : null
1535
1684
  let recorder = opts.recorder ?? ownRecorder.recorder
1685
+ const baseRecorder = recorder
1686
+ const markAppliedWrite = () => {
1687
+ if (dryRun) return
1688
+ if (_lastRun) {
1689
+ _lastRun.target = target
1690
+ _lastRun.applied = true
1691
+ }
1692
+ if (typeof opts.onWrite === 'function') {
1693
+ opts.onWrite({ target, backupDir: _lastRun?.backupDir ?? null })
1694
+ }
1695
+ }
1696
+ if (!dryRun) {
1697
+ recorder = (change) => {
1698
+ baseRecorder(change)
1699
+ if (['create', 'update', 'remove'].includes(change?.action)) markAppliedWrite()
1700
+ }
1701
+ }
1536
1702
  // Test-only failure seam: throw after N recorded writes so the failure path is
1537
1703
  // deterministic. Never reachable from production callers (opts.deps is not a
1538
1704
  // CLI flag) and never applied to the internal dry plan pass.
@@ -1546,7 +1712,9 @@ async function installPass(
1546
1712
  }
1547
1713
  }
1548
1714
  // Track this apply so the wrapper can report the paths written on a failure.
1549
- if (!dryRun) _lastRun = { target, entries: ownRecorder?.entries ?? [], backupDir: null }
1715
+ if (!dryRun) {
1716
+ _lastRun = { target, entries: ownRecorder?.entries ?? [], backupDir: null, applied: false }
1717
+ }
1550
1718
 
1551
1719
  // V1/V2 dual-version awareness (Phase 3): the installer builds a unified
1552
1720
  // config, then applies V2-native migration (migrateV1toV2) when
@@ -1606,7 +1774,10 @@ async function installPass(
1606
1774
  // this notice cannot drift from what the plugin reports; the notice says
1607
1775
  // so, because the live list is a superset that grows at runtime. Advisory:
1608
1776
  // a V2 install is a supported configuration, not a failure.
1609
- notice(formatV2CapabilityNotice())
1777
+ // Default-quiet: the eleven-fact block is install *detail*, not an action
1778
+ // the user must take, so it prints only under --verbose (the recorded
1779
+ // run-state keeps it either way).
1780
+ if (opts.verbose === true) notice(formatV2CapabilityNotice())
1610
1781
  }
1611
1782
 
1612
1783
  // Interactive mode handling
@@ -1614,21 +1785,23 @@ async function installPass(
1614
1785
  const forceInteractive = opts.interactive === true
1615
1786
  const forceHeadless = opts.headless === true
1616
1787
  const autoYes = opts.yes === true
1617
- const interactive = forceInteractive || (stdinTTY && !forceHeadless)
1788
+ const interactive = !autoYes && (forceInteractive || (stdinTTY && !forceHeadless))
1618
1789
 
1619
1790
  if (interactive && !dryRun) {
1620
1791
  const { runInteractiveInstall } = await import('./interactive.mjs')
1621
1792
  const hasRequestedComponents = Array.isArray(opts.requestedComponents)
1622
1793
  const promptComponents = hasRequestedComponents ? opts.requestedComponents : components
1623
- const promptDefaults = hasRequestedComponents
1624
- ? []
1625
- : opts.noMcp
1626
- ? COMPONENT_NAMES.filter((component) => component !== 'runtime')
1627
- : COMPONENT_NAMES
1794
+ const promptDefaults = (hasRequestedComponents ? opts.requestedComponents : components).filter(
1795
+ (component) => !opts.noMcp || component !== 'runtime',
1796
+ )
1628
1797
  const result = await runInteractiveInstall({
1629
1798
  components: promptComponents,
1630
1799
  defaultComponents: promptDefaults,
1631
1800
  noMcp: opts.noMcp === true,
1801
+ getDecisionRouterConfig: (selection) => {
1802
+ const selectionTarget = selection === 'project' ? process.cwd() : target
1803
+ return readState(selectionTarget)?.decision_router
1804
+ },
1632
1805
  prompts: opts.deps?.prompts,
1633
1806
  isTTY: opts.deps?.isTTY,
1634
1807
  })
@@ -1639,6 +1812,7 @@ async function installPass(
1639
1812
  // recorded target is where the user was installing, not where a file was
1640
1813
  // written (nothing was written either way).
1641
1814
  const selectedTarget = result.target === 'project' ? process.cwd() : target
1815
+ opts.onTargetResolved?.(selectedTarget)
1642
1816
 
1643
1817
  if (result.canceled) {
1644
1818
  // The named point is what makes the message explainable. The interactive
@@ -1655,20 +1829,6 @@ async function installPass(
1655
1829
  }
1656
1830
  }
1657
1831
 
1658
- if (!result.confirmed) {
1659
- // Answering "No" at the pre-install confirmation is not the prompt
1660
- // library's cancel channel, so nothing was printed yet: this is the one
1661
- // message, and it names the point.
1662
- notice(S.canceledAt(S.cancelPoints.confirmation))
1663
- return {
1664
- ...stats,
1665
- applied: false,
1666
- reason: 'canceled',
1667
- cancelPoint: 'confirmation',
1668
- target: selectedTarget,
1669
- }
1670
- }
1671
-
1672
1832
  // Map target selection to actual path
1673
1833
  const newComponents = [...result.components].filter(
1674
1834
  (component) => !opts.noMcp || component !== 'runtime',
@@ -1677,6 +1837,18 @@ async function installPass(
1677
1837
  for (const c of newComponents) componentSet.add(c)
1678
1838
 
1679
1839
  target = selectedTarget
1840
+ decisionRouterConfig = migrateDecisionRouterConfig(result.decisionRouterConfig)
1841
+ opts.decisionRouterConfig = decisionRouterConfig
1842
+ decisionModelActivation = result.decisionModelActivation ?? null
1843
+ if (!dryRun && _lastRun) _lastRun.target = target
1844
+ }
1845
+
1846
+ // Reject invalid or newer persisted migration schemas before planning or
1847
+ // applying any target writes. The migration runner repeats this check at the
1848
+ // actual migration point to catch a marker changed during the install.
1849
+ const migrationPreflight = runMigrations(target, { dryRun: true })
1850
+ if (migrationPreflight.status === 'unsupported' || migrationPreflight.status === 'invalid') {
1851
+ throw new Error(migrationPreflight.message)
1680
1852
  }
1681
1853
 
1682
1854
  // Product defaults live in code (PRODUCT_CONFIG_DEFAULTS). A repository-root
@@ -1711,7 +1883,24 @@ async function installPass(
1711
1883
  // real --dry-run) prints it once.
1712
1884
  if (!opts.planOnly) warning(configAdvisories[0])
1713
1885
  }
1714
- const { config, raw: configRaw } = readJsonConfigWithRaw(targetConfigPath)
1886
+ const { config: diskConfig, raw: configRaw } = readJsonConfigWithRaw(targetConfigPath)
1887
+ let config = diskConfig
1888
+ if (opts.configPreview !== undefined && opts.configPreview !== null) {
1889
+ try {
1890
+ config = JSON.parse(opts.configPreview)
1891
+ if (config === null || typeof config !== 'object' || Array.isArray(config)) {
1892
+ throw new Error('not an object')
1893
+ }
1894
+ } catch {
1895
+ throw new Error('The setup config preview input is invalid.')
1896
+ }
1897
+ }
1898
+ // Validate the original MCP shape before runtime entries can be seeded or a
1899
+ // flat map can be wrapped. Seeding first can turn malformed nested input into
1900
+ // an apparently valid wrapper and let migration silently discard user data.
1901
+ if (version === 'v2' && Object.hasOwn(config, 'mcp')) {
1902
+ validateMcpV1toV2Source(config.mcp)
1903
+ }
1715
1904
  const pantheonConfig =
1716
1905
  pantheonConfigPath !== null && existsSync(pantheonConfigPath)
1717
1906
  ? readJsonConfig(pantheonConfigPath)
@@ -1752,9 +1941,8 @@ async function installPass(
1752
1941
  let planned
1753
1942
  try {
1754
1943
  // Use the LIVE selection: the wizard above may have changed componentSet.
1755
- // An AUTHORIZED apply (`--yes`) is not a preview: compute the plan +
1756
- // snapshots but stay silent. The gate path (no `--yes`) still prints the
1757
- // plan for the review / decline preview.
1944
+ // Every apply computes and shows the concise plan before writing. --yes
1945
+ // suppresses prompts, not the summary or integrity/drift checks.
1758
1946
  planned = await installOpenCode(target, true, clean, [...componentSet], {
1759
1947
  ...opts,
1760
1948
  // Hand the RESOLVED generation to the plan pass. Re-resolving would
@@ -1765,7 +1953,7 @@ async function installPass(
1765
1953
  planTimestamp,
1766
1954
  planOnly: true,
1767
1955
  quiet: autoYes,
1768
- quietPlan: autoYes,
1956
+ quietPlan: false,
1769
1957
  })
1770
1958
  } finally {
1771
1959
  Object.assign(stats, savedStats)
@@ -1780,13 +1968,23 @@ async function installPass(
1780
1968
  target,
1781
1969
  packageRoot: ROOT,
1782
1970
  packageVersion,
1971
+ options: {
1972
+ clean,
1973
+ components: [...components],
1974
+ version,
1975
+ isProject: opts.isProject === true,
1976
+ model: opts.model ?? null,
1977
+ smallModel: opts.smallModel ?? null,
1978
+ preset: opts.preset ?? null,
1979
+ mergeDevConfig: mergeDevConfigOpt,
1980
+ },
1783
1981
  files: planned?.files ?? [],
1784
1982
  snapshots: planned?.snapshots ?? [],
1785
1983
  })
1786
1984
  if (drift.length > 0) {
1787
1985
  warning('Reviewed install plan drifted; no files were written.')
1788
1986
  for (const item of drift) warning(` ${item}`)
1789
- return { ...stats, applied: false, reason: 'drift', drift }
1987
+ return { ...stats, applied: false, reason: 'drift', drift, target }
1790
1988
  }
1791
1989
  }
1792
1990
 
@@ -1807,18 +2005,18 @@ async function installPass(
1807
2005
  // prints nothing, so this is the single place that guarantees the
1808
2006
  // message exists exactly once, and it names the point.
1809
2007
  if (typeof injected === 'function') notice(S.canceledAt(S.cancelPoints.review))
1810
- return { ...stats, applied: false, reason: 'canceled', cancelPoint: 'review' }
2008
+ return { ...stats, applied: false, reason: 'canceled', cancelPoint: 'review', target }
1811
2009
  }
1812
2010
  if (!accepted) {
1813
2011
  // Answering "No" is not a cancel: it used to reach the caller as a
1814
2012
  // silent `reason: 'declined'` and exit 0 with "Nothing applied." and
1815
2013
  // no explanation at all.
1816
2014
  notice(S.declinedAt(S.cancelPoints.review))
1817
- return { ...stats, applied: false, reason: 'declined', cancelPoint: 'review' }
2015
+ return { ...stats, applied: false, reason: 'declined', cancelPoint: 'review', target }
1818
2016
  }
1819
2017
  } else {
1820
2018
  notice(S.planOnlyNoYes)
1821
- return { ...stats, applied: false, reason: 'not-authorized' }
2019
+ return { ...stats, applied: false, reason: 'not-authorized', target }
1822
2020
  }
1823
2021
  }
1824
2022
 
@@ -1836,6 +2034,7 @@ async function installPass(
1836
2034
  applied: false,
1837
2035
  reason: 'drift',
1838
2036
  drift: drifted.map((p) => displayPath(target, p)),
2037
+ target,
1839
2038
  }
1840
2039
  }
1841
2040
  reviewedRemovals = new Set((planned?.removals ?? []).map((filePath) => resolve(filePath)))
@@ -2347,6 +2546,10 @@ async function installPass(
2347
2546
  // UI object into the runtime module.
2348
2547
  onVenvDone: () => advancePhase(S.settingUpRuntime),
2349
2548
  onHealthDone: () => advancePhase(S.runningHealthChecks),
2549
+ onRuntimeEffects: (effects) => {
2550
+ runtimeEffects = effects
2551
+ },
2552
+ verbose: opts.verbose === true,
2350
2553
  },
2351
2554
  stats,
2352
2555
  opts.deps,
@@ -2407,11 +2610,15 @@ async function installPass(
2407
2610
  if (fm.permission) {
2408
2611
  agent.permission = JSON.parse(JSON.stringify(fm.permission))
2409
2612
  }
2613
+ if (fm.skills !== undefined) {
2614
+ agent.permission = mergeAgentSkillPermissions(agent.permission, fm.skills)
2615
+ }
2410
2616
  if (fm.mcp_tools !== undefined) {
2411
- agent.permission = {
2412
- ...(agent.permission ?? {}),
2413
- ...deriveNativeMcpPermissions(fm.mcp_tools),
2414
- }
2617
+ agent.permission = mergeAgentMcpPermissions(
2618
+ agent.permission,
2619
+ fm.mcp_tools,
2620
+ configuredMcpServersForPolicies,
2621
+ )
2415
2622
  }
2416
2623
 
2417
2624
  config[name] = agent
@@ -2419,6 +2626,8 @@ async function installPass(
2419
2626
  return config
2420
2627
  }
2421
2628
 
2629
+ const configuredMcpServersForPolicies =
2630
+ version === 'v2' ? configuredMcpServerNames(config.mcp) : []
2422
2631
  const canonicalAgentConfig = readAgentConfigFromCanonical()
2423
2632
  const agentSources = getAgentSources(agentPrefix)
2424
2633
 
@@ -2655,18 +2864,23 @@ async function installPass(
2655
2864
  config.plugins = config.plugins.filter(
2656
2865
  (plugin) => pluginReferenceIdentity(plugin) !== pluginReferenceIdentity(resolvedV2),
2657
2866
  )
2658
- // ALWAYS the object form, even on a fresh install with nothing to preserve.
2659
- // The host hands a plugin its `options` only from `{ package, options }`,
2660
- // and the opt-in features (`context_pruner`, `memory_injection`) read
2661
- // `ctx.options`. Emitting a bare string — which a fresh install used to do —
2662
- // left those features unreachable for anyone who did not already know the
2663
- // object syntax from the docs, so the shape (with an empty options bag) is
2664
- // written from the start and a user's hand-added keys survive a re-run.
2867
+ // Always use object form, even on a fresh install. The host passes plugin
2868
+ // options only from `{ package, options }`, and `context_pruner` reads
2869
+ // `ctx.options`. A bare string left the option unreachable; an empty object
2870
+ // keeps the contract visible and preserves user-added keys on re-run.
2665
2871
  config.plugins.push({
2666
2872
  package: resolvedV2,
2667
2873
  options: existingV2Options === null ? {} : deepClone(existingV2Options),
2668
2874
  })
2669
2875
 
2876
+ // See ensureTuiCopyRegistered: OpenCode 2.x loads server-side RPC of the
2877
+ // copied TUI plugin ONLY through an explicit `plugins` entry.
2878
+ ensureTuiCopyRegistered(config, {
2879
+ tuiCopyDir: isGlobal
2880
+ ? join(target, 'plugins', 'pantheon-tui')
2881
+ : join(target, '.opencode', 'plugins', 'pantheon-tui'),
2882
+ })
2883
+
2670
2884
  // A path that LOOKS like a Pantheon V2 entry but is not one this package
2671
2885
  // can prove it owns (managedPluginIdentity only recognizes installed copies
2672
2886
  // and this package's own paths) would now be registered twice: the host
@@ -2717,6 +2931,10 @@ async function installPass(
2717
2931
  // --------------------------------------------------------------------
2718
2932
  // C. Merge permissions
2719
2933
  // --------------------------------------------------------------------
2934
+ // A native V2 array is an explicit policy, including an empty one. Do not
2935
+ // append legacy defaults to it: reruns would duplicate rules, and custom V2
2936
+ // configs would gain grants the user did not choose.
2937
+ const hasNativeV2Permissions = version === 'v2' && Array.isArray(config.permissions)
2720
2938
  if (config.permission === undefined) config.permission = {}
2721
2939
  if (
2722
2940
  typeof config.permission === 'object' &&
@@ -2736,7 +2954,11 @@ async function installPass(
2736
2954
  // must not seed the key. It used to anyway, via the unconditional
2737
2955
  // PRODUCT_CONFIG_DEFAULTS.permission merge that sat above this block —
2738
2956
  // which also made this gate dead code.
2739
- if (componentSet.has('skills') && config.permission.skill === undefined) {
2957
+ if (
2958
+ componentSet.has('skills') &&
2959
+ config.permission.skill === undefined &&
2960
+ !hasNativeV2Permissions
2961
+ ) {
2740
2962
  config.permission.skill = { '*': 'allow' }
2741
2963
  }
2742
2964
  // These five are the commands Pantheon's OWN agents must be able to run
@@ -2762,7 +2984,7 @@ async function installPass(
2762
2984
  // NOTE: this grant is NOT gated on the skills component — unlike
2763
2985
  // permission.skill above, agents are installed by the agents component and
2764
2986
  // the test/lint commands are needed whichever components were selected.
2765
- if (config.permission.bash === undefined) {
2987
+ if (config.permission.bash === undefined && !hasNativeV2Permissions) {
2766
2988
  config.permission.bash = {
2767
2989
  'git *': 'allow',
2768
2990
  'npm *': 'allow',
@@ -2914,29 +3136,28 @@ async function installPass(
2914
3136
  advancePhase()
2915
3137
 
2916
3138
  // -----------------------------------------------------------------------
2917
- // 3.5 Run migrations (--components runtime)
3139
+ // 3.5 Run state/schema migrations on every init, independent of runtime
3140
+ // selection. Migration schema has its own marker and remains idempotent.
2918
3141
  // -----------------------------------------------------------------------
2919
- if (componentSet.has('runtime')) {
2920
- const currentVersion = detectVersion(target)
2921
- if (currentVersion) {
2922
- const migrationStep = step(S.runningMigrations)
2923
- const migration = runMigrations(target, currentVersion, {
2924
- dryRun,
2925
- recorder,
2926
- updatedAt: planTimestamp,
2927
- })
2928
- migrationStep(true)
2929
- if (migration.plannedState) projectedState = migration.plannedState
2930
- if (migration.applied > 0) {
2931
- success(`Applied ${migration.applied} migration(s)`)
2932
- for (const msg of migration.messages) {
2933
- bullet(msg, 1)
2934
- }
2935
- }
3142
+ const migrationStep = step(S.runningMigrations)
3143
+ const migration = runMigrations(target, {
3144
+ dryRun,
3145
+ recorder,
3146
+ updatedAt: planTimestamp,
3147
+ })
3148
+ if (migration.status === 'unsupported' || migration.status === 'invalid') {
3149
+ migrationStep(false)
3150
+ throw new Error(migration.message)
3151
+ }
3152
+ migrationStep(true)
3153
+ if (migration.plannedState) projectedState = migration.plannedState
3154
+ if (migration.applied > 0) {
3155
+ success(`Applied ${migration.applied} migration(s)`)
3156
+ for (const msg of migration.messages) {
3157
+ bullet(msg, 1)
2936
3158
  }
2937
- // Counted even when there is nothing to migrate: the phase ran its check.
2938
- advancePhase()
2939
3159
  }
3160
+ advancePhase()
2940
3161
 
2941
3162
  if (opts.preset && dryRun) {
2942
3163
  const { writeActivePreset } = await import('./model-picker.mjs')
@@ -2966,6 +3187,7 @@ async function installPass(
2966
3187
  const packageVersion = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version
2967
3188
  let state = projectedState ?? readState(target)
2968
3189
  if (!state) state = createInitialState(packageVersion, planTimestamp)
3190
+ state.decision_router = decisionRouterConfig
2969
3191
  state.pantheon_version = packageVersion
2970
3192
  state.updated_at = planTimestamp
2971
3193
  state.schema_version = 2
@@ -2997,6 +3219,7 @@ async function installPass(
2997
3219
  // names `applyMcpServerEntries` seeded in THIS pass, in write order (empty
2998
3220
  // when the runtime component is not selected or failed its prerequisites).
2999
3221
  plan.mcpServers = mcpServers
3222
+ if (componentSet.has('runtime')) plan.runtimeEffects = runtimeEffects
3000
3223
  plan.versionAssumed = versionAssumed
3001
3224
  planFiles = plan.files
3002
3225
  planTotals = plan.totals
@@ -3034,9 +3257,8 @@ async function installPass(
3034
3257
  // were written"), never one line per file — the gauge already answered
3035
3258
  // "is it moving?" and per-file detail is opt-in via --verbose. `[DRY-RUN]`
3036
3259
  // marks the header only; it no longer prefixes every line.
3037
- // An internal snapshot pass on the apply path (`quietPlan`, e.g. an
3038
- // authorized `--yes` run) computes the plan and snapshots but must NOT
3039
- // echo it — a real apply is not a dry run.
3260
+ // `--yes` still exposes the concise preview before this apply pass runs;
3261
+ // only explicit quiet callers (JSON/doctor) suppress it.
3040
3262
  if (!opts.quietPlan) {
3041
3263
  const verbose = opts.verbose === true
3042
3264
  const planText = formatChangePlan(target, plan, { perFile: verbose })
@@ -3060,43 +3282,6 @@ async function installPass(
3060
3282
  // entries are only added when the Python runtime is actually healthy)
3061
3283
  // -----------------------------------------------------------------------
3062
3284
 
3063
- if (interactive && !dryRun) {
3064
- endGaugeLine()
3065
- const created = stats.created
3066
- const skipped = stats.skipped
3067
- const errors = stats.errors
3068
- const warnings = stats.warnings ?? 0
3069
-
3070
- process.stdout.write('\n')
3071
- process.stdout.write(
3072
- ` ${colors.bold(
3073
- errors > 0
3074
- ? colors.yellow('Installation completed with errors')
3075
- : colors.green('Installation complete'),
3076
- )}\n`,
3077
- )
3078
- process.stdout.write(
3079
- ` ${colors.dim('\u2500'.repeat(Math.min(process.stdout.columns || 60, 60)))}\n`,
3080
- )
3081
- process.stdout.write(` [OK] ${created} component(s) installed\n`)
3082
- if (skipped > 0)
3083
- process.stdout.write(` ${colors.dim('\u2014')} ${skipped} already up-to-date\n`)
3084
- if (errors > 0) process.stdout.write(` [WARN] ${errors} error(s) encountered\n`)
3085
- if (warnings > 0)
3086
- process.stdout.write(
3087
- ` [WARN] ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
3088
- )
3089
- process.stdout.write('\n')
3090
- process.stdout.write(` ${colors.bold('Next steps:')}\n`)
3091
- process.stdout.write(` ${colors.dim('\u2022')} Configure agents in opencode.json\n`)
3092
- process.stdout.write(` ${colors.dim('\u2022')} Run 'pantheon-opencode doctor' to verify\n`)
3093
- process.stdout.write(
3094
- ` ${colors.dim('\u2022')} Run 'opencode' to start using Pantheon agents\n`,
3095
- )
3096
- process.stdout.write('\n')
3097
- printWorktreeGuidance({ projectRoot: process.cwd(), interactive: true })
3098
- }
3099
-
3100
3285
  // -----------------------------------------------------------------------
3101
3286
  // 5. V1 model preset selection (--components agents). V2 ignores the legacy
3102
3287
  // active-preset marker, so it has no profile wizard or --preset support.
@@ -3104,12 +3289,20 @@ async function installPass(
3104
3289
  // Q1 default "herdar do chat" (inherit) writes no active-preset.json —
3105
3290
  // delegates inherit the parent chat model (native inheritance).
3106
3291
  // -----------------------------------------------------------------------
3107
- if (interactive && stdinTTY && version === 'v1' && !dryRun && !autoYes && !opts.preset) {
3292
+ if (
3293
+ interactive &&
3294
+ stdinTTY &&
3295
+ version === 'v1' &&
3296
+ !dryRun &&
3297
+ !autoYes &&
3298
+ !opts.preset &&
3299
+ stats.errors === 0
3300
+ ) {
3108
3301
  const { runInitWizard } = await import('./model-picker.mjs')
3109
3302
  await runInitWizard({ presetDir: target, logger: console, prompts: opts.deps?.prompts })
3110
3303
  }
3111
3304
 
3112
- if (opts.preset && !dryRun) {
3305
+ if (opts.preset && !dryRun && stats.errors === 0) {
3113
3306
  const { writeActivePreset } = await import('./model-picker.mjs')
3114
3307
  writeActivePreset(target, opts.preset, { source: 'cli', updatedAt: planTimestamp, recorder })
3115
3308
  }
@@ -3121,7 +3314,7 @@ async function installPass(
3121
3314
  // blocks on stdin and the default behavior is unchanged. A failure here
3122
3315
  // must never fail the install: vision stays optional.
3123
3316
  // -----------------------------------------------------------------------
3124
- if (interactive && !dryRun && !autoYes) {
3317
+ if (interactive && !dryRun && !autoYes && stats.errors === 0) {
3125
3318
  const runVisionPrompt =
3126
3319
  opts.deps?.runVisionPrompt ?? (await import('./vision-prompt.mjs')).runVisionPrompt
3127
3320
  try {
@@ -3131,13 +3324,8 @@ async function installPass(
3131
3324
  }
3132
3325
  }
3133
3326
 
3134
- // Fail-closed: accumulated stats.errors (bad sources, missing requirements,
3135
- // failed health checks) must never masquerade as a successful installation.
3136
- if (stats.errors > 0) {
3137
- throw new Error(`installation completed with ${stats.errors} error(s); see output above`)
3138
- }
3139
-
3140
- // Record the component state only after the install has completed. The
3327
+ // Record component state even on a degraded runtime result so doctor and a
3328
+ // later init can distinguish a failed runtime from an installed one. The
3141
3329
  // postinstall marker can predate `init` and start with every component
3142
3330
  // pending; leaving it untouched made a healthy beta install look incomplete
3143
3331
  // to `doctor` forever. Unselected components retain their previous state.
@@ -3148,6 +3336,7 @@ async function installPass(
3148
3336
  throw new Error('Installation state exists but cannot be read; refusing to replace it')
3149
3337
  }
3150
3338
  state ??= createInitialState(packageVersion, planTimestamp)
3339
+ state.decision_router = decisionRouterConfig
3151
3340
  state.pantheon_version = packageVersion
3152
3341
  state.updated_at = planTimestamp
3153
3342
  for (const component of ['agents', 'skills', 'plugins', 'runtime']) {
@@ -3177,10 +3366,17 @@ async function installPass(
3177
3366
  verifiedFiles,
3178
3367
  })
3179
3368
  writeState(target, state, { updatedAt: planTimestamp })
3369
+ markAppliedWrite()
3180
3370
  stateStep(true)
3181
3371
  advancePhase()
3182
3372
  }
3183
3373
 
3374
+ // Fail closed only after the degraded state is persisted. The caller records
3375
+ // the partial application and reports its exact target/recovery backup.
3376
+ if (stats.errors > 0) {
3377
+ throw new Error(`installation completed with ${stats.errors} error(s); see output above`)
3378
+ }
3379
+
3184
3380
  // The apply gauge ends before the human summary; a dry run already closed it
3185
3381
  // before its plan block (`done()` is idempotent). A preview must NOT print
3186
3382
  // the installed banner: bin/pantheon-init prints the preview-only line.
@@ -3188,6 +3384,33 @@ async function installPass(
3188
3384
  if (!interactive && !dryRun && !opts.planOnly) {
3189
3385
  printSummary(target, ['opencode'], stats)
3190
3386
  }
3387
+ if (interactive && !dryRun && !opts.planOnly) {
3388
+ endGaugeLine()
3389
+ const created = stats.created
3390
+ const skipped = stats.skipped
3391
+ const warnings = stats.warnings ?? 0
3392
+ process.stdout.write('\n')
3393
+ process.stdout.write(` ${colors.bold(colors.green('Installation complete'))}\n`)
3394
+ process.stdout.write(
3395
+ ` ${colors.dim('\u2500'.repeat(Math.min(process.stdout.columns || 60, 60)))}\n`,
3396
+ )
3397
+ process.stdout.write(` [OK] ${created} component(s) installed\n`)
3398
+ if (skipped > 0)
3399
+ process.stdout.write(` ${colors.dim('\u2014')} ${skipped} already up-to-date\n`)
3400
+ if (warnings > 0)
3401
+ process.stdout.write(
3402
+ ` [WARN] ${warnings} warning(s) — run 'pantheon-opencode doctor' for details\n`,
3403
+ )
3404
+ 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 })
3413
+ }
3191
3414
 
3192
3415
  // Beta 11 Setup phase 3: report whether this call APPLIED, so the caller can
3193
3416
  // avoid a success banner for a plan-only / unauthorized run. The dry pass also
@@ -3202,19 +3425,23 @@ async function installPass(
3202
3425
  files: planFiles,
3203
3426
  totals: planTotals,
3204
3427
  mcpServers,
3428
+ runtimeEffects,
3205
3429
  removals: removalPaths,
3206
3430
  target,
3207
3431
  openCodeVersion: version,
3208
3432
  versionAssumed,
3209
3433
  configAdvisories,
3210
3434
  v2Capabilities: version === 'v2' ? v2Capabilities() : null,
3435
+ decisionModelActivation,
3211
3436
  pluginOptions: v2PluginOptions,
3212
3437
  }
3213
3438
  : {
3214
3439
  ...stats,
3215
3440
  applied: true,
3216
3441
  reason: 'applied',
3442
+ decisionModelActivation,
3217
3443
  target,
3444
+ runtimeEffects,
3218
3445
  openCodeVersion: version,
3219
3446
  configAdvisories,
3220
3447
  v2Capabilities: version === 'v2' ? v2Capabilities() : null,