pantheon-opencode 1.6.0-beta.8 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +126 -346
  4. package/README.md +83 -608
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +366 -132
  7. package/commands/pantheon-audit.md +7 -1
  8. package/commands/pantheon-consolidate.md +1 -1
  9. package/commands/pantheon-deepwork.md +14 -3
  10. package/commands/pantheon-focus.md +17 -0
  11. package/commands/pantheon-vision.md +61 -12
  12. package/package.json +19 -11
  13. package/plugin.json +1 -1
  14. package/pyproject.toml +6 -2
  15. package/scripts/_pantheon_paths.py +24 -0
  16. package/scripts/build-agents-md.mjs +368 -69
  17. package/scripts/changelog-merge.mjs +161 -0
  18. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  19. package/scripts/docs-check-changelog.mjs +204 -0
  20. package/scripts/docs-link-check.mjs +314 -0
  21. package/scripts/docs-media.mjs +157 -0
  22. package/scripts/doctor.mjs +828 -40
  23. package/scripts/install/agents-md.mjs +2 -2
  24. package/scripts/install/backup.mjs +648 -0
  25. package/scripts/install/cli-ui.mjs +303 -72
  26. package/scripts/install/component-selection.mjs +61 -0
  27. package/scripts/install/config-migration.mjs +583 -27
  28. package/scripts/install/exit-codes.mjs +26 -0
  29. package/scripts/install/file-inventory.mjs +555 -0
  30. package/scripts/install/health-check.mjs +31 -25
  31. package/scripts/install/interactive.mjs +78 -383
  32. package/scripts/install/migrate.mjs +49 -25
  33. package/scripts/install/model-picker.mjs +218 -250
  34. package/scripts/install/opencode-version.mjs +83 -21
  35. package/scripts/install/opencode.mjs +1465 -180
  36. package/scripts/install/plan-artifact.mjs +517 -0
  37. package/scripts/install/plan.mjs +475 -0
  38. package/scripts/install/plugin.mjs +251 -30
  39. package/scripts/install/prompt-result.mjs +2 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +60 -4
  43. package/scripts/install/venv.mjs +90 -47
  44. package/scripts/install/verify.mjs +128 -0
  45. package/scripts/install/vision-prompt.mjs +173 -0
  46. package/scripts/install-mcp.mjs +2 -2
  47. package/scripts/manifest-inventory.mjs +49 -3
  48. package/scripts/mcp_persistence.py +1535 -1050
  49. package/scripts/memory_mcp.py +12 -843
  50. package/scripts/node-engine-policy.mjs +85 -0
  51. package/scripts/package-evidence.mjs +10 -2
  52. package/scripts/postinstall.mjs +26 -26
  53. package/scripts/probe-pantheon-cost.mjs +118 -19
  54. package/scripts/prune.mjs +9 -3
  55. package/scripts/reconcile.mjs +325 -0
  56. package/scripts/release-gates.mjs +682 -0
  57. package/scripts/restore.mjs +222 -0
  58. package/scripts/run-node-tests.mjs +24 -8
  59. package/scripts/sync-artifacts.mjs +20 -7
  60. package/scripts/sync-tui.mjs +29 -4
  61. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  62. package/scripts/uninstall.mjs +369 -34
  63. package/scripts/update.mjs +164 -0
  64. package/scripts/validate-node-engine-policy.mjs +13 -0
  65. package/scripts/version-check.mjs +34 -1
  66. package/scripts/versioning.mjs +23 -3
  67. package/scripts/vision-status.mjs +682 -0
  68. package/skills-lock.json +8 -8
  69. package/src/agents/aphrodite.md +13 -10
  70. package/src/agents/apollo.md +4 -5
  71. package/src/agents/athena.md +74 -46
  72. package/src/agents/demeter.md +10 -7
  73. package/src/agents/gaia.md +0 -1
  74. package/src/agents/hephaestus.md +4 -3
  75. package/src/agents/hermes.md +10 -9
  76. package/src/agents/iris.md +6 -1
  77. package/src/agents/mnemosyne.md +14 -15
  78. package/src/agents/nyx.md +4 -4
  79. package/src/agents/prometheus.md +12 -11
  80. package/src/agents/talos.md +6 -0
  81. package/src/agents/zeus.md +84 -56
  82. package/src/instructions/agent-return-format.instructions.md +12 -41
  83. package/src/instructions/memory-protocol.instructions.md +5 -11
  84. package/src/instructions/test-economy.instructions.md +12 -0
  85. package/src/instructions/yagni.instructions.md +6 -15
  86. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  87. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  88. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  89. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  90. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  91. package/src/mcp/_pantheon_paths.py +24 -0
  92. package/src/mcp/mcp_codemap_module.py +86 -18
  93. package/src/mcp/mcp_persistence.py +1535 -1050
  94. package/src/mcp/memory_mcp.py +444 -94
  95. package/src/mcp/pantheon_vision.py +285 -41
  96. package/src/mcp/requirements-mcp.txt +5 -0
  97. package/src/pantheon/context-pruner.ts +541 -0
  98. package/src/pantheon/cost-command.ts +814 -60
  99. package/src/pantheon/goal-loop.ts +11 -8
  100. package/src/pantheon/memory-context.ts +1017 -0
  101. package/src/pantheon/model-agents.ts +19 -0
  102. package/src/pantheon/model-command.ts +218 -56
  103. package/src/pantheon/model-pricing.ts +536 -0
  104. package/src/pantheon/presets.mjs +2 -0
  105. package/src/pantheon/task-result-guard.ts +50 -14
  106. package/src/pantheon/v2-bounded-read.ts +640 -0
  107. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  108. package/src/pantheon/v2-execute-after.ts +135 -24
  109. package/src/pantheon/v2-model-overrides.ts +275 -0
  110. package/src/pantheon/v2-tools.ts +89 -35
  111. package/src/pantheon/v2-unsupported.mjs +2 -3
  112. package/src/pantheon/v2-vision.ts +622 -0
  113. package/src/pantheon/vision-local.ts +531 -0
  114. package/src/pantheon/vision.ts +1160 -115
  115. package/src/plugin-v2.ts +654 -162
  116. package/src/plugin.ts +15 -11
  117. package/src/plugins/tui/dist/tui-v2.d.ts +1036 -0
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -0
  119. package/src/plugins/tui/dist/tui-v2.js +3808 -0
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -0
  121. package/src/plugins/tui/dist/tui.js +4 -4
  122. package/src/plugins/tui/index-v2.ts +6 -0
  123. package/src/plugins/tui/package-lock.json +5416 -1297
  124. package/src/plugins/tui/package.json +14 -10
  125. package/src/plugins/tui/src/index-v2.tsx +4372 -0
  126. package/src/plugins/tui/src/index.tsx +3 -3
  127. package/src/plugins/tui/src/opencode-v2.d.ts +13 -0
  128. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  129. package/src/plugins/tui/tsdown.config.ts +2 -2
  130. package/src/plugins/tui/tui-v2.ts +2 -0
  131. package/src/plugins/tui/tui.ts +3 -0
  132. package/src/routing.yml +50 -5
  133. package/src/skills/agent-coordination/SKILL.md +7 -2
  134. package/src/skills/artifact-management/SKILL.md +5 -1
  135. package/src/skills/auto-continue/SKILL.md +14 -6
  136. package/src/skills/codemap/SKILL.md +1 -1
  137. package/src/skills/memory-bank/SKILL.md +21 -13
  138. package/src/skills/session-goal/SKILL.md +14 -15
  139. package/src/skills/spec-driven-development/SKILL.md +3 -1
  140. package/src/skills/worktrees/SKILL.md +30 -11
  141. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -6,26 +6,20 @@
6
6
  * CLI. Writes the active preset marker to <presetDir>/.pantheon/active-preset.json
7
7
  * which the plugin (src/plugin.ts) reads on startup via resolveActivePreset().
8
8
  *
9
- * 3-question interactive wizard (askQuestions style):
10
- * 1) perfil (0=herdar do chat [default], go-free/fast/premium/openai) com tabela modelos por papel + provider/baseURL/key + preço
11
- * 2) coleta key mascarada validando PANTHEON_OPENCODE_API_KEY alias OPENCODE_GO_API_KEY e OPENAI_API_KEY
12
- * 3) escopo project|global → writeActivePreset atômico .bak health-check
9
+ * Installer choices use display labels separate from persisted preset IDs.
10
+ * The wizard never reads or validates API keys; it names the required env var.
13
11
  *
14
- * "herdar do chat" (inherit) é o default da Q1: não grava active-preset.json,
12
+ * "Inherit" is the default profile choice and does not write active-preset.json,
15
13
  * então os delegates herdam o modelo do chat pai (herança nativa, sem preset).
16
14
  */
17
- import {
18
- copyFileSync,
19
- existsSync,
20
- mkdirSync,
21
- readFileSync,
22
- renameSync,
23
- writeFileSync,
24
- } from 'node:fs'
15
+ import { lstatSync, mkdirSync, readFileSync } from 'node:fs'
25
16
  import { homedir } from 'node:os'
26
17
  import { join } from 'node:path'
27
18
  import { createInterface } from 'node:readline/promises'
19
+ import * as clack from '@clack/prompts'
28
20
  import { loadPresetDefs } from '../../src/pantheon/presets.mjs'
21
+ import { ACTIONS, fingerprintOutput, recordChange, snapshot } from './plan.mjs'
22
+ import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
29
23
 
30
24
  /** Preset pricing table (2026 verified). */
31
25
  export const PRESET_PRICE = {
@@ -45,6 +39,45 @@ export const PRESET_PRICE = {
45
39
  label: 'Pago (OpenAI)',
46
40
  detail: 'Direto OpenAI – https://api.openai.com/v1, gpt-5.6 family',
47
41
  },
42
+ 'go-hybrid': {
43
+ label: 'OpenCode Go',
44
+ detail: 'Premium para especialistas centrais; Go rápido para os demais agentes',
45
+ },
46
+ anthropic: {
47
+ label: 'Anthropic',
48
+ detail: 'Direto Anthropic – claude-sonnet-5-5',
49
+ },
50
+ }
51
+
52
+ /** Installer-facing labels and their stable internal preset identifiers. */
53
+ export const INSTALLER_PRESET_CHOICES = [
54
+ { label: 'Inherit', value: 'inherit' },
55
+ { label: 'OpenCode Go', value: 'go-hybrid' },
56
+ { label: 'OpenAI', value: 'openai' },
57
+ { label: 'Anthropic', value: 'anthropic' },
58
+ ]
59
+
60
+ /** Static, safe env-var names for installer guidance; never derive these from credentials or preset metadata. */
61
+ const PRESET_KEY_ENV_GUIDANCE = Object.freeze({
62
+ 'go-free': 'PANTHEON_OPENCODE_API_KEY',
63
+ 'go-fast': 'PANTHEON_OPENCODE_API_KEY',
64
+ 'go-premium': 'PANTHEON_OPENCODE_API_KEY',
65
+ 'go-hybrid': 'PANTHEON_OPENCODE_API_KEY',
66
+ openai: 'OPENAI_API_KEY',
67
+ anthropic: 'ANTHROPIC_API_KEY',
68
+ })
69
+
70
+ /**
71
+ * Build safe installer guidance using only the static preset-to-env-name map.
72
+ * @param {string} name
73
+ * @param {string} [label]
74
+ * @returns {string}
75
+ */
76
+ export function presetKeyEnvGuidance(name, label = name) {
77
+ if (!Object.hasOwn(PRESET_KEY_ENV_GUIDANCE, name)) {
78
+ return 'Configure the required API key in your environment; the installer does not read or validate API keys.'
79
+ }
80
+ return `${label} expects ${PRESET_KEY_ENV_GUIDANCE[name]}. Configure it in your environment; the installer does not read or validate API keys.`
48
81
  }
49
82
 
50
83
  /**
@@ -61,7 +94,8 @@ export function requiredKeyEnvForPreset(name, def) {
61
94
  .filter(Boolean)
62
95
  if (providerEnvs.includes('PANTHEON_OPENCODE_API_KEY')) return 'PANTHEON_OPENCODE_API_KEY'
63
96
  if (providerEnvs.includes('OPENAI_API_KEY')) return 'OPENAI_API_KEY'
64
- return 'PANTHEON_OPENCODE_API_KEY'
97
+ if (providerEnvs.includes('ANTHROPIC_API_KEY')) return 'ANTHROPIC_API_KEY'
98
+ return providerEnvs[0] ?? 'PANTHEON_OPENCODE_API_KEY'
65
99
  }
66
100
 
67
101
  /**
@@ -120,48 +154,42 @@ export function buildPresetTableRow(name, def) {
120
154
  }
121
155
 
122
156
  /**
123
- * Build askQuestions payload for init wizard (3 perguntas).
124
- * Caller can pass this to agent/askQuestions or render via readline.
157
+ * Build the two-question askQuestions payload for model profile and save scope.
158
+ * Values are stable internal identifiers; labels are presentation-only.
125
159
  * @param {Record<string,object>} presetDefs
126
160
  * @returns {Array<object>}
127
161
  */
128
162
  export function buildInitQuestions(presetDefs) {
129
- const names = Object.keys(presetDefs)
130
- const presetOptions = [
131
- {
132
- label: 'inherit',
133
- description: 'Herda modelo do chat pai — não grava active-preset.json (herança nativa)',
134
- },
135
- ...names.map((n) => ({
136
- label: n,
137
- description: buildPresetTableRow(n, presetDefs[n]),
138
- })),
139
- ]
163
+ const presetOptions = INSTALLER_PRESET_CHOICES.filter(
164
+ ({ value }) => value === 'inherit' || presetDefs[value],
165
+ ).map(({ label, value }) => ({
166
+ label,
167
+ value,
168
+ description:
169
+ value === 'inherit'
170
+ ? 'Use the model selected in the current chat; do not save an active preset.'
171
+ : (presetDefs[value].description ?? buildPresetTableRow(value, presetDefs[value])),
172
+ }))
140
173
  return [
141
174
  {
142
- header: 'Perfil de modelos',
143
- question:
144
- 'Escolha o perfil (0=herdar do chat [default], go-free/fast/premium/openai) — tabela: perfil | provider/baseURL/key | preço | modelos por papel',
175
+ header: 'Model profile',
176
+ question: 'Choose the default model profile for Pantheon agents.',
145
177
  options: presetOptions,
146
178
  multiSelect: false,
147
179
  },
148
180
  {
149
- header: 'API Key',
150
- question:
151
- 'Informe a chave (coleta mascarada). Validação: PANTHEON_OPENCODE_API_KEY (alias OPENCODE_GO_API_KEY aceito) para Go; OPENAI_API_KEY para openai. Não escreve .env.',
152
- kind: 'password',
153
- },
154
- {
155
- header: 'Escopo',
156
- question: 'Onde salvar o preset ativo?',
181
+ header: 'Install scope',
182
+ question: 'Where should the active preset be saved?',
157
183
  options: [
158
184
  {
159
- label: 'project',
160
- description: './.pantheon/active-preset.json (escopo do projeto, seguro)',
185
+ label: 'Project',
186
+ value: 'project',
187
+ description: './.pantheon/active-preset.json',
161
188
  },
162
189
  {
163
- label: 'global',
164
- description: '~/.config/opencode/.pantheon/active-preset.json (global)',
190
+ label: 'Global',
191
+ value: 'global',
192
+ description: '~/.config/opencode/.pantheon/active-preset.json',
165
193
  },
166
194
  ],
167
195
  multiSelect: false,
@@ -176,12 +204,16 @@ export function buildInitQuestions(presetDefs) {
176
204
  * @param {string} [source] 'cli' | 'interactive'
177
205
  * @returns {{version: number, preset: string, source: string, updated_at: string}}
178
206
  */
179
- export function buildActivePresetFile(presetName, source = 'cli') {
207
+ export function buildActivePresetFile(
208
+ presetName,
209
+ source = 'cli',
210
+ updatedAt = new Date().toISOString(),
211
+ ) {
180
212
  return {
181
213
  version: 1,
182
214
  preset: presetName,
183
215
  source,
184
- updated_at: new Date().toISOString(),
216
+ updated_at: updatedAt,
185
217
  }
186
218
  }
187
219
 
@@ -197,28 +229,70 @@ export function buildActivePresetFile(presetName, source = 'cli') {
197
229
  export function writeActivePreset(
198
230
  presetDir,
199
231
  presetName,
200
- { dryRun = false, source = 'cli', logger = console } = {},
232
+ { dryRun = false, source = 'cli', logger = console, updatedAt, recorder = null } = {},
201
233
  ) {
202
234
  const dir = join(presetDir, '.pantheon')
203
235
  const filePath = join(dir, 'active-preset.json')
204
236
  const backupPath = join(dir, 'active-preset.json.bak')
205
237
 
238
+ const content = `${JSON.stringify(buildActivePresetFile(presetName, source, updatedAt), null, 2)}\n`
239
+ assertNoSymlinkAncestors(filePath)
240
+ assertNoSymlinkAncestors(backupPath)
241
+ assertNoSymlinkAncestors(`${filePath}.tmp-${process.pid}`)
242
+ assertNoSymlinkAncestors(`${backupPath}.tmp-${process.pid}`)
243
+ let current = null
244
+ try {
245
+ const info = lstatSync(filePath)
246
+ if (info.isSymbolicLink() || !info.isFile()) {
247
+ throw new Error(`Refusing to write through non-regular file: ${filePath}`)
248
+ }
249
+ current = readFileSync(filePath)
250
+ } catch (error) {
251
+ if (error?.code !== 'ENOENT') throw error
252
+ }
253
+ if (current !== null) {
254
+ const backupSnapshot = snapshot(backupPath)
255
+ recordChange(
256
+ {
257
+ path: backupPath,
258
+ action: !backupSnapshot.exists
259
+ ? ACTIONS.CREATE
260
+ : backupSnapshot.sha256 === fingerprintOutput(current)
261
+ ? ACTIONS.UNCHANGED
262
+ : ACTIONS.UPDATE,
263
+ bytes: current.length,
264
+ outputFingerprint: fingerprintOutput(current),
265
+ scored: false,
266
+ },
267
+ recorder,
268
+ )
269
+ if (!dryRun && backupSnapshot.sha256 !== fingerprintOutput(current)) {
270
+ writeFileAtomically(backupPath, current)
271
+ }
272
+ }
273
+ const before = snapshot(filePath)
274
+ recordChange(
275
+ {
276
+ path: filePath,
277
+ action: !before.exists
278
+ ? ACTIONS.CREATE
279
+ : current?.toString('utf8') === content
280
+ ? ACTIONS.UNCHANGED
281
+ : ACTIONS.UPDATE,
282
+ bytes: Buffer.byteLength(content, 'utf8'),
283
+ outputFingerprint: fingerprintOutput(content),
284
+ },
285
+ recorder,
286
+ )
206
287
  if (dryRun) {
207
288
  logger.log?.(`[dry-run] Would write model preset "${presetName}" to ${filePath}`)
208
289
  return { written: false, path: filePath, backupPath: null }
209
290
  }
210
291
 
211
292
  mkdirSync(dir, { recursive: true })
212
- let backupMade = false
213
- if (existsSync(filePath)) {
214
- copyFileSync(filePath, backupPath)
215
- backupMade = true
216
- }
217
- writeFileSync(
218
- `${filePath}.tmp-${process.pid}`,
219
- `${JSON.stringify(buildActivePresetFile(presetName, source), null, 2)}\n`,
220
- )
221
- renameSync(`${filePath}.tmp-${process.pid}`, filePath)
293
+ assertNoSymlinkAncestors(filePath)
294
+ assertNoSymlinkAncestors(backupPath)
295
+ writeFileAtomically(filePath, content)
222
296
  // health-check: verify file is readable and valid JSON with preset
223
297
  try {
224
298
  const content = readFileSync(filePath, 'utf8')
@@ -227,19 +301,7 @@ export function writeActivePreset(
227
301
  } catch (err) {
228
302
  logger.warn?.(`health-check: active-preset.json verification failed: ${err.message}`)
229
303
  }
230
- return { written: true, path: filePath, backupPath: backupMade ? backupPath : null }
231
- }
232
-
233
- /**
234
- * Masked input helper: reads line without echoing (fallback to plain question).
235
- * @param {import('node:readline/promises').Interface} rli
236
- * @param {string} prompt
237
- * @returns {Promise<string>}
238
- */
239
- async function questionMasked(rli, prompt) {
240
- // Node readline doesn't support masking natively; we try to use raw mode.
241
- // Fallback: plain question (test env will provide mock).
242
- return await rli.question(prompt)
304
+ return { written: true, path: filePath, backupPath: current !== null ? backupPath : null }
243
305
  }
244
306
 
245
307
  /**
@@ -305,16 +367,9 @@ export async function runModelPicker({
305
367
  }
306
368
 
307
369
  /**
308
- * 3-question init wizard via askQuestions (or readline fallback).
309
- * Steps:
310
- * 1) perfil (0=herdar do chat [default], go-free/fast/premium/openai) com tabela
311
- * 2) coleta key mascarada validando PANTHEON_OPENCODE_API_KEY alias OPENCODE_GO_API_KEY e OPENAI_API_KEY
312
- * 3) escopo project|global → writeActivePreset atômico .bak health-check
313
- *
314
- * "herdar do chat" (inherit) é o default da Q1: não grava active-preset.json,
315
- * então os delegates herdam o modelo do chat pai (herança nativa, sem preset).
370
+ * Collect the V1 model profile and save scope, without reading API keys.
316
371
  *
317
- * @param {{presetDir?: string, target?: string, presets?: object, env?: Record<string,string|undefined>, dryRun?: boolean, logger?: object, ask?: Function, rl?: object}} [opts]
372
+ * @param {{presetDir?: string, target?: string, presets?: object, env?: Record<string,string|undefined>, dryRun?: boolean, logger?: object, ask?: Function, prompts?: object}} [opts]
318
373
  * @returns {Promise<{preset:string, scope:string}|null>}
319
374
  */
320
375
  export async function runInitWizard({
@@ -325,19 +380,15 @@ export async function runInitWizard({
325
380
  dryRun = false,
326
381
  logger = console,
327
382
  ask,
328
- rl,
383
+ prompts = clack,
329
384
  } = {}) {
330
385
  const defs = presets ?? loadPresetDefs()
331
- const names = Object.keys(defs)
332
- if (names.length === 0) {
333
- logger.warn?.('Model presets: no presets defined in routing.yml')
386
+ const questions = buildInitQuestions(defs)
387
+ if (questions[0].options.length === 1) {
388
+ logger.warn?.('Model presets: no selectable presets defined in routing.yml')
334
389
  return null
335
390
  }
336
391
 
337
- // Build questions payload for askQuestions
338
- const questions = buildInitQuestions(defs)
339
-
340
- // If ask is provided (OpenCode agent/askQuestions), use it
341
392
  let answers
342
393
  if (typeof ask === 'function') {
343
394
  try {
@@ -347,166 +398,83 @@ export async function runInitWizard({
347
398
  return null
348
399
  }
349
400
  } else {
350
- // Fallback: readline 3-step wizard
351
- const rli = rl ?? createInterface({ input: process.stdin, output: process.stdout })
352
- const closeAfter = !rl
353
- try {
354
- // Q1: perfil (0 = herdar do chat, default)
355
- const list = [
356
- ' 0) inherit — Herda modelo do chat pai (não grava active-preset.json)',
357
- ...names.map((n, i) => ` ${i + 1}) ${buildPresetTableRow(n, defs[n])}`),
358
- ].join('\n')
359
- const a1 = await rli.question(
360
- `\n[1/3] Perfil de modelos (0=herdar do chat [default], number or name):\n${list}\n> `,
361
- )
362
- const t1 = (a1 ?? '').trim()
363
- let presetName = null
364
- if (t1 === '' || t1 === '0' || t1 === 'inherit' || t1.toLowerCase() === 'none') {
365
- presetName = 'inherit'
366
- } else if (names.includes(t1)) {
367
- presetName = t1
368
- } else {
369
- const idx = Number(t1)
370
- if (Number.isInteger(idx) && idx >= 1 && idx <= names.length) presetName = names[idx - 1]
371
- }
372
- if (!presetName) {
373
- logger.warn?.(`Unknown preset "${t1}" — wizard canceled.`)
374
- return null
375
- }
376
- if (presetName === 'inherit') {
377
- logger.log?.(
378
- 'Herança nativa: delegates herdam o modelo do chat pai — nenhum preset ativo gravado.',
379
- )
380
- return { preset: 'inherit', scope: 'project' }
381
- }
382
-
383
- // Q2: key masked
384
- const requiredEnv = requiredKeyEnvForPreset(presetName, defs[presetName])
385
- const aliasNote =
386
- requiredEnv === 'PANTHEON_OPENCODE_API_KEY' ? ' (alias OPENCODE_GO_API_KEY aceito)' : ''
387
- const envConfigured = isKeyConfiguredForPreset(env, presetName, defs[presetName])
388
- let keyAnswer = ''
389
- if (envConfigured) {
390
- logger.log?.(
391
- `Chave ${requiredEnv}${aliasNote} já configurada no ambiente (mascarada: ${maskKey(env[requiredEnv] ?? env.OPENCODE_GO_API_KEY ?? '')}).`,
392
- )
393
- } else {
394
- // masked collection
395
- const prompt = `[2/3] Informe ${requiredEnv}${aliasNote} (entrada mascarada, não escreve .env): `
396
- // Use questionMasked for tests; real TTY would mask
397
- keyAnswer = (await questionMasked(rli, prompt)).trim()
398
- if (keyAnswer === '') {
399
- logger.warn?.(
400
- `Chave vazia para ${requiredEnv} — wizard canceled. Preencha env ${requiredEnv} antes de continuar.`,
401
- )
402
- return null
403
- }
404
- // validate non-empty already; optionally check length
405
- if (!dryRun) {
406
- // For health-check, set in current env (not .env file) for this session
407
- // Prefer primary var
408
- env[requiredEnv] = keyAnswer
409
- logger.log?.(
410
- `Chave coletada (mascarada: ${maskKey(keyAnswer)}). Defina export ${requiredEnv}='${maskKey(keyAnswer)}' no seu shell para persistir (não escrevemos .env).`,
411
- )
412
- }
413
- }
414
-
415
- // Q3: escopo
416
- const a3 = await rli.question(`[3/3] Escopo (project|global, default project): `)
417
- const scopeRaw = (a3 ?? '').trim().toLowerCase()
418
- const scope = scopeRaw === 'global' ? 'global' : 'project'
419
-
420
- answers = { preset: presetName, scope, key: keyAnswer }
421
- } finally {
422
- if (closeAfter) rli.close()
401
+ const select = prompts.select
402
+ const isCancel = prompts.isCancel ?? clack.isCancel
403
+ const preset = await select({
404
+ message: questions[0].question,
405
+ options: questions[0].options.map(({ label, value, description }) => ({
406
+ label,
407
+ value,
408
+ hint: description,
409
+ })),
410
+ initialValue: 'inherit',
411
+ })
412
+ if (isCancel(preset)) {
413
+ prompts.cancel?.('Model selection canceled.')
414
+ return null
423
415
  }
424
- // For fallback path, we already have answers; proceed to write
425
- const presetName = answers.preset
426
- const scope = answers.scope ?? 'project'
427
- const projectDir = presetDir ?? target ?? process.cwd()
428
- const globalDir = (() => {
429
- const home = env.HOME?.trim() || homedir()
430
- const xdg = env.XDG_CONFIG_HOME?.trim() || join(home, '.config')
431
- return join(xdg, 'opencode')
432
- })()
433
- const dir = scope === 'global' ? globalDir : projectDir
434
- if (!dryRun) {
435
- const result = writeActivePreset(dir, presetName, {
436
- dryRun: false,
437
- source: 'interactive',
438
- logger,
416
+ if (preset === 'inherit') {
417
+ answers = { preset, scope: 'project' }
418
+ } else {
419
+ const scope = await select({
420
+ message: questions[1].question,
421
+ options: questions[1].options.map(({ label, value, description }) => ({
422
+ label,
423
+ value,
424
+ hint: description,
425
+ })),
426
+ initialValue: 'project',
439
427
  })
440
- logger.log?.(
441
- `Preset ${presetName} salvo em ${scope} (${result.path})${result.backupPath ? ` backup: ${result.backupPath}` : ''}`,
442
- )
443
- // health-check: verify file
444
- try {
445
- const raw = readFileSync(result.path, 'utf8')
446
- JSON.parse(raw)
447
- logger.log?.('health-check: active-preset.json OK')
448
- } catch (e) {
449
- logger.warn?.(`health-check failed: ${e.message}`)
428
+ if (isCancel(scope)) {
429
+ prompts.cancel?.('Model selection canceled.')
430
+ return null
450
431
  }
451
- } else {
452
- logger.log?.(`[dry-run] Would write preset "${presetName}" scope ${scope}`)
432
+ answers = { preset, scope }
453
433
  }
454
- return { preset: presetName, scope }
455
434
  }
456
435
 
457
- // ask path: answers expected as object with preset/scope/key or array
458
- // Normalize: ask may return {answers: [...]} or direct mapping (also handles {label} objects)
459
- let presetName, scope, keyAnswer
460
- if (Array.isArray(answers)) {
461
- const a0 = answers[0]?.answer ?? answers[0]
462
- const a1 = answers[1]?.answer ?? answers[1]
463
- const a2 = answers[2]?.answer ?? answers[2]
464
- presetName = a0 && typeof a0 === 'object' && 'label' in a0 ? a0.label : a0
465
- keyAnswer = a1 && typeof a1 === 'object' && 'answer' in a1 ? a1.answer : a1
466
- if (keyAnswer && typeof keyAnswer === 'object' && 'label' in keyAnswer)
467
- keyAnswer = keyAnswer.label
468
- scope = a2 && typeof a2 === 'object' && 'label' in a2 ? a2.label : a2
469
- if (scope && typeof scope === 'object' && 'answer' in scope) scope = scope.answer
470
- } else if (answers && typeof answers === 'object') {
471
- presetName = answers.preset ?? answers['0'] ?? answers.q1 ?? answers.presetName
472
- keyAnswer = answers.key ?? answers['1'] ?? answers.q2
473
- scope = answers.scope ?? answers['2'] ?? answers.q3
474
- if (presetName && typeof presetName === 'object' && 'label' in presetName)
475
- presetName = presetName.label
476
- if (presetName && typeof presetName === 'object' && 'answer' in presetName)
477
- presetName = presetName.answer
478
- if (scope && typeof scope === 'object' && 'label' in scope) scope = scope.label
479
- if (scope && typeof scope === 'object' && 'answer' in scope) scope = scope.answer
480
- }
481
- if (typeof presetName === 'string') presetName = presetName.trim()
482
- // Q1 default = herdar do chat: empty/0/inherit/none writes nothing (não grava active-preset.json)
483
- if (!presetName || presetName === '0' || presetName === 'inherit' || presetName === 'none') {
484
- logger.log?.(
485
- 'Herança nativa: delegates herdam o modelo do chat pai — nenhum preset ativo gravado.',
486
- )
487
- return { preset: 'inherit', scope: 'project' }
436
+ const unwrap = (value) => {
437
+ if (value && typeof value === 'object') {
438
+ return unwrap(value.value ?? value.answer ?? value.label)
439
+ }
440
+ return value
488
441
  }
489
- if (!names.includes(presetName)) {
490
- logger.warn?.(`Unknown preset "${presetName}" — wizard canceled.`)
491
- return null
442
+ let presetAnswer
443
+ let scopeAnswer
444
+ const values = answers?.answers ?? answers
445
+ if (Array.isArray(values)) {
446
+ presetAnswer = unwrap(values[0])
447
+ scopeAnswer = unwrap(values[1])
448
+ } else if (values && typeof values === 'object') {
449
+ presetAnswer = unwrap(values.preset ?? values['0'] ?? values.q1)
450
+ scopeAnswer = unwrap(values.scope ?? values['1'] ?? values.q2)
492
451
  }
493
- const requiredEnv = requiredKeyEnvForPreset(presetName, defs[presetName])
494
- const envConfigured = isKeyConfiguredForPreset(
495
- { ...env, ...(keyAnswer ? { [requiredEnv]: keyAnswer } : {}) },
496
- presetName,
497
- defs[presetName],
452
+
453
+ const rawPreset = String(presetAnswer ?? 'inherit').trim()
454
+ const choice = INSTALLER_PRESET_CHOICES.find(
455
+ ({ label, value }) =>
456
+ rawPreset.toLowerCase() === value.toLowerCase() ||
457
+ rawPreset.toLowerCase() === label.toLowerCase(),
498
458
  )
499
- if (!envConfigured) {
500
- logger.warn?.(`Chave ${requiredEnv} não configurada — defina env antes de continuar.`)
459
+ if (!choice) {
460
+ logger.warn?.(`Unknown model profile "${rawPreset}" — wizard canceled.`)
501
461
  return null
502
462
  }
503
- if (keyAnswer && !dryRun) {
504
- env[requiredEnv] = keyAnswer
505
- logger.log?.(
506
- `Chave coletada (mascarada: ${maskKey(String(keyAnswer))}). Não escrevemos .env; export ${requiredEnv} no shell para persistir.`,
507
- )
463
+ if (choice.value === 'inherit') {
464
+ logger.log?.('Using the current chat model; no active preset was saved.')
465
+ return { preset: 'inherit', scope: 'project' }
466
+ }
467
+ if (!defs[choice.value]) {
468
+ logger.warn?.(`Model profile "${choice.label}" is not defined — wizard canceled.`)
469
+ return null
508
470
  }
509
- const finalScope = scope === 'global' ? 'global' : 'project'
471
+
472
+ const scopeChoice = String(unwrap(scopeAnswer) ?? 'project')
473
+ .trim()
474
+ .toLowerCase()
475
+ const finalScope = scopeChoice === 'global' ? 'global' : 'project'
476
+ logger.log?.(presetKeyEnvGuidance(choice.value, choice.label))
477
+
510
478
  const projectDir = presetDir ?? target ?? process.cwd()
511
479
  const globalDir = (() => {
512
480
  const home = env.HOME?.trim() || homedir()
@@ -514,22 +482,22 @@ export async function runInitWizard({
514
482
  return join(xdg, 'opencode')
515
483
  })()
516
484
  const dir = finalScope === 'global' ? globalDir : projectDir
517
- if (!dryRun) {
518
- const result = writeActivePreset(dir, presetName, {
519
- dryRun: false,
520
- source: 'interactive',
521
- logger,
522
- })
523
- logger.log?.(`Preset ${presetName} salvo em ${finalScope} (${result.path})`)
524
- try {
525
- const raw = readFileSync(result.path, 'utf8')
526
- JSON.parse(raw)
527
- logger.log?.('health-check: active-preset.json OK')
528
- } catch (e) {
529
- logger.warn?.(`health-check failed: ${e.message}`)
530
- }
531
- } else {
532
- logger.log?.(`[dry-run] Would write preset "${presetName}" scope ${finalScope}`)
485
+ if (dryRun) {
486
+ logger.log?.(`[dry-run] Would write preset "${choice.value}" scope ${finalScope}`)
487
+ return { preset: choice.value, scope: finalScope }
488
+ }
489
+
490
+ const result = writeActivePreset(dir, choice.value, {
491
+ source: 'interactive',
492
+ logger,
493
+ })
494
+ logger.log?.(`Preset ${choice.value} saved in ${finalScope} (${result.path})`)
495
+ try {
496
+ const parsed = JSON.parse(readFileSync(result.path, 'utf8'))
497
+ if (parsed.preset !== choice.value) throw new Error('preset mismatch')
498
+ logger.log?.('health-check: active-preset.json OK')
499
+ } catch (err) {
500
+ logger.warn?.(`health-check failed: ${err.message}`)
533
501
  }
534
- return { preset: presetName, scope: finalScope }
502
+ return { preset: choice.value, scope: finalScope }
535
503
  }