pantheon-opencode 1.6.0-beta.13 → 1.6.0-beta.14

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.
@@ -6,18 +6,17 @@
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
15
  import { lstatSync, mkdirSync, readFileSync } from 'node:fs'
18
16
  import { homedir } from 'node:os'
19
17
  import { join } from 'node:path'
20
18
  import { createInterface } from 'node:readline/promises'
19
+ import * as clack from '@clack/prompts'
21
20
  import { loadPresetDefs } from '../../src/pantheon/presets.mjs'
22
21
  import { ACTIONS, fingerprintOutput, recordChange, snapshot } from './plan.mjs'
23
22
  import { assertNoSymlinkAncestors, writeFileAtomically } from './verify.mjs'
@@ -40,6 +39,45 @@ export const PRESET_PRICE = {
40
39
  label: 'Pago (OpenAI)',
41
40
  detail: 'Direto OpenAI – https://api.openai.com/v1, gpt-5.6 family',
42
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.`
43
81
  }
44
82
 
45
83
  /**
@@ -56,7 +94,8 @@ export function requiredKeyEnvForPreset(name, def) {
56
94
  .filter(Boolean)
57
95
  if (providerEnvs.includes('PANTHEON_OPENCODE_API_KEY')) return 'PANTHEON_OPENCODE_API_KEY'
58
96
  if (providerEnvs.includes('OPENAI_API_KEY')) return 'OPENAI_API_KEY'
59
- return 'PANTHEON_OPENCODE_API_KEY'
97
+ if (providerEnvs.includes('ANTHROPIC_API_KEY')) return 'ANTHROPIC_API_KEY'
98
+ return providerEnvs[0] ?? 'PANTHEON_OPENCODE_API_KEY'
60
99
  }
61
100
 
62
101
  /**
@@ -115,48 +154,42 @@ export function buildPresetTableRow(name, def) {
115
154
  }
116
155
 
117
156
  /**
118
- * Build askQuestions payload for init wizard (3 perguntas).
119
- * 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.
120
159
  * @param {Record<string,object>} presetDefs
121
160
  * @returns {Array<object>}
122
161
  */
123
162
  export function buildInitQuestions(presetDefs) {
124
- const names = Object.keys(presetDefs)
125
- const presetOptions = [
126
- {
127
- label: 'inherit',
128
- description: 'Herda modelo do chat pai — não grava active-preset.json (herança nativa)',
129
- },
130
- ...names.map((n) => ({
131
- label: n,
132
- description: buildPresetTableRow(n, presetDefs[n]),
133
- })),
134
- ]
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
+ }))
135
173
  return [
136
174
  {
137
- header: 'Perfil de modelos',
138
- question:
139
- '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.',
140
177
  options: presetOptions,
141
178
  multiSelect: false,
142
179
  },
143
180
  {
144
- header: 'API Key',
145
- question:
146
- '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.',
147
- kind: 'password',
148
- },
149
- {
150
- header: 'Escopo',
151
- question: 'Onde salvar o preset ativo?',
181
+ header: 'Install scope',
182
+ question: 'Where should the active preset be saved?',
152
183
  options: [
153
184
  {
154
- label: 'project',
155
- description: './.pantheon/active-preset.json (escopo do projeto, seguro)',
185
+ label: 'Project',
186
+ value: 'project',
187
+ description: './.pantheon/active-preset.json',
156
188
  },
157
189
  {
158
- label: 'global',
159
- description: '~/.config/opencode/.pantheon/active-preset.json (global)',
190
+ label: 'Global',
191
+ value: 'global',
192
+ description: '~/.config/opencode/.pantheon/active-preset.json',
160
193
  },
161
194
  ],
162
195
  multiSelect: false,
@@ -271,18 +304,6 @@ export function writeActivePreset(
271
304
  return { written: true, path: filePath, backupPath: current !== null ? backupPath : null }
272
305
  }
273
306
 
274
- /**
275
- * Masked input helper: reads line without echoing (fallback to plain question).
276
- * @param {import('node:readline/promises').Interface} rli
277
- * @param {string} prompt
278
- * @returns {Promise<string>}
279
- */
280
- async function questionMasked(rli, prompt) {
281
- // Node readline doesn't support masking natively; we try to use raw mode.
282
- // Fallback: plain question (test env will provide mock).
283
- return await rli.question(prompt)
284
- }
285
-
286
307
  /**
287
308
  * Interactive model preset picker. Asks the user to choose a preset; persists
288
309
  * the choice unless dryRun. `rl` may be injected for tests; otherwise a
@@ -346,16 +367,9 @@ export async function runModelPicker({
346
367
  }
347
368
 
348
369
  /**
349
- * 3-question init wizard via askQuestions (or readline fallback).
350
- * Steps:
351
- * 1) perfil (0=herdar do chat [default], go-free/fast/premium/openai) com tabela
352
- * 2) coleta key mascarada validando PANTHEON_OPENCODE_API_KEY alias OPENCODE_GO_API_KEY e OPENAI_API_KEY
353
- * 3) escopo project|global → writeActivePreset atômico .bak health-check
354
- *
355
- * "herdar do chat" (inherit) é o default da Q1: não grava active-preset.json,
356
- * 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.
357
371
  *
358
- * @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]
359
373
  * @returns {Promise<{preset:string, scope:string}|null>}
360
374
  */
361
375
  export async function runInitWizard({
@@ -366,19 +380,15 @@ export async function runInitWizard({
366
380
  dryRun = false,
367
381
  logger = console,
368
382
  ask,
369
- rl,
383
+ prompts = clack,
370
384
  } = {}) {
371
385
  const defs = presets ?? loadPresetDefs()
372
- const names = Object.keys(defs)
373
- if (names.length === 0) {
374
- 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')
375
389
  return null
376
390
  }
377
391
 
378
- // Build questions payload for askQuestions
379
- const questions = buildInitQuestions(defs)
380
-
381
- // If ask is provided (OpenCode agent/askQuestions), use it
382
392
  let answers
383
393
  if (typeof ask === 'function') {
384
394
  try {
@@ -388,166 +398,83 @@ export async function runInitWizard({
388
398
  return null
389
399
  }
390
400
  } else {
391
- // Fallback: readline 3-step wizard
392
- const rli = rl ?? createInterface({ input: process.stdin, output: process.stdout })
393
- const closeAfter = !rl
394
- try {
395
- // Q1: perfil (0 = herdar do chat, default)
396
- const list = [
397
- ' 0) inherit — Herda modelo do chat pai (não grava active-preset.json)',
398
- ...names.map((n, i) => ` ${i + 1}) ${buildPresetTableRow(n, defs[n])}`),
399
- ].join('\n')
400
- const a1 = await rli.question(
401
- `\n[1/3] Perfil de modelos (0=herdar do chat [default], number or name):\n${list}\n> `,
402
- )
403
- const t1 = (a1 ?? '').trim()
404
- let presetName = null
405
- if (t1 === '' || t1 === '0' || t1 === 'inherit' || t1.toLowerCase() === 'none') {
406
- presetName = 'inherit'
407
- } else if (names.includes(t1)) {
408
- presetName = t1
409
- } else {
410
- const idx = Number(t1)
411
- if (Number.isInteger(idx) && idx >= 1 && idx <= names.length) presetName = names[idx - 1]
412
- }
413
- if (!presetName) {
414
- logger.warn?.(`Unknown preset "${t1}" — wizard canceled.`)
415
- return null
416
- }
417
- if (presetName === 'inherit') {
418
- logger.log?.(
419
- 'Herança nativa: delegates herdam o modelo do chat pai — nenhum preset ativo gravado.',
420
- )
421
- return { preset: 'inherit', scope: 'project' }
422
- }
423
-
424
- // Q2: key masked
425
- const requiredEnv = requiredKeyEnvForPreset(presetName, defs[presetName])
426
- const aliasNote =
427
- requiredEnv === 'PANTHEON_OPENCODE_API_KEY' ? ' (alias OPENCODE_GO_API_KEY aceito)' : ''
428
- const envConfigured = isKeyConfiguredForPreset(env, presetName, defs[presetName])
429
- let keyAnswer = ''
430
- if (envConfigured) {
431
- logger.log?.(
432
- `Chave ${requiredEnv}${aliasNote} já configurada no ambiente (mascarada: ${maskKey(env[requiredEnv] ?? env.OPENCODE_GO_API_KEY ?? '')}).`,
433
- )
434
- } else {
435
- // masked collection
436
- const prompt = `[2/3] Informe ${requiredEnv}${aliasNote} (entrada mascarada, não escreve .env): `
437
- // Use questionMasked for tests; real TTY would mask
438
- keyAnswer = (await questionMasked(rli, prompt)).trim()
439
- if (keyAnswer === '') {
440
- logger.warn?.(
441
- `Chave vazia para ${requiredEnv} — wizard canceled. Preencha env ${requiredEnv} antes de continuar.`,
442
- )
443
- return null
444
- }
445
- // validate non-empty already; optionally check length
446
- if (!dryRun) {
447
- // For health-check, set in current env (not .env file) for this session
448
- // Prefer primary var
449
- env[requiredEnv] = keyAnswer
450
- logger.log?.(
451
- `Chave coletada (mascarada: ${maskKey(keyAnswer)}). Defina export ${requiredEnv}='${maskKey(keyAnswer)}' no seu shell para persistir (não escrevemos .env).`,
452
- )
453
- }
454
- }
455
-
456
- // Q3: escopo
457
- const a3 = await rli.question(`[3/3] Escopo (project|global, default project): `)
458
- const scopeRaw = (a3 ?? '').trim().toLowerCase()
459
- const scope = scopeRaw === 'global' ? 'global' : 'project'
460
-
461
- answers = { preset: presetName, scope, key: keyAnswer }
462
- } finally {
463
- 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
464
415
  }
465
- // For fallback path, we already have answers; proceed to write
466
- const presetName = answers.preset
467
- const scope = answers.scope ?? 'project'
468
- const projectDir = presetDir ?? target ?? process.cwd()
469
- const globalDir = (() => {
470
- const home = env.HOME?.trim() || homedir()
471
- const xdg = env.XDG_CONFIG_HOME?.trim() || join(home, '.config')
472
- return join(xdg, 'opencode')
473
- })()
474
- const dir = scope === 'global' ? globalDir : projectDir
475
- if (!dryRun) {
476
- const result = writeActivePreset(dir, presetName, {
477
- dryRun: false,
478
- source: 'interactive',
479
- 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',
480
427
  })
481
- logger.log?.(
482
- `Preset ${presetName} salvo em ${scope} (${result.path})${result.backupPath ? ` backup: ${result.backupPath}` : ''}`,
483
- )
484
- // health-check: verify file
485
- try {
486
- const raw = readFileSync(result.path, 'utf8')
487
- JSON.parse(raw)
488
- logger.log?.('health-check: active-preset.json OK')
489
- } catch (e) {
490
- logger.warn?.(`health-check failed: ${e.message}`)
428
+ if (isCancel(scope)) {
429
+ prompts.cancel?.('Model selection canceled.')
430
+ return null
491
431
  }
492
- } else {
493
- logger.log?.(`[dry-run] Would write preset "${presetName}" scope ${scope}`)
432
+ answers = { preset, scope }
494
433
  }
495
- return { preset: presetName, scope }
496
434
  }
497
435
 
498
- // ask path: answers expected as object with preset/scope/key or array
499
- // Normalize: ask may return {answers: [...]} or direct mapping (also handles {label} objects)
500
- let presetName, scope, keyAnswer
501
- if (Array.isArray(answers)) {
502
- const a0 = answers[0]?.answer ?? answers[0]
503
- const a1 = answers[1]?.answer ?? answers[1]
504
- const a2 = answers[2]?.answer ?? answers[2]
505
- presetName = a0 && typeof a0 === 'object' && 'label' in a0 ? a0.label : a0
506
- keyAnswer = a1 && typeof a1 === 'object' && 'answer' in a1 ? a1.answer : a1
507
- if (keyAnswer && typeof keyAnswer === 'object' && 'label' in keyAnswer)
508
- keyAnswer = keyAnswer.label
509
- scope = a2 && typeof a2 === 'object' && 'label' in a2 ? a2.label : a2
510
- if (scope && typeof scope === 'object' && 'answer' in scope) scope = scope.answer
511
- } else if (answers && typeof answers === 'object') {
512
- presetName = answers.preset ?? answers['0'] ?? answers.q1 ?? answers.presetName
513
- keyAnswer = answers.key ?? answers['1'] ?? answers.q2
514
- scope = answers.scope ?? answers['2'] ?? answers.q3
515
- if (presetName && typeof presetName === 'object' && 'label' in presetName)
516
- presetName = presetName.label
517
- if (presetName && typeof presetName === 'object' && 'answer' in presetName)
518
- presetName = presetName.answer
519
- if (scope && typeof scope === 'object' && 'label' in scope) scope = scope.label
520
- if (scope && typeof scope === 'object' && 'answer' in scope) scope = scope.answer
521
- }
522
- if (typeof presetName === 'string') presetName = presetName.trim()
523
- // Q1 default = herdar do chat: empty/0/inherit/none writes nothing (não grava active-preset.json)
524
- if (!presetName || presetName === '0' || presetName === 'inherit' || presetName === 'none') {
525
- logger.log?.(
526
- 'Herança nativa: delegates herdam o modelo do chat pai — nenhum preset ativo gravado.',
527
- )
528
- 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
529
441
  }
530
- if (!names.includes(presetName)) {
531
- logger.warn?.(`Unknown preset "${presetName}" — wizard canceled.`)
532
- 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)
533
451
  }
534
- const requiredEnv = requiredKeyEnvForPreset(presetName, defs[presetName])
535
- const envConfigured = isKeyConfiguredForPreset(
536
- { ...env, ...(keyAnswer ? { [requiredEnv]: keyAnswer } : {}) },
537
- presetName,
538
- 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(),
539
458
  )
540
- if (!envConfigured) {
541
- logger.warn?.(`Chave ${requiredEnv} não configurada — defina env antes de continuar.`)
459
+ if (!choice) {
460
+ logger.warn?.(`Unknown model profile "${rawPreset}" — wizard canceled.`)
542
461
  return null
543
462
  }
544
- if (keyAnswer && !dryRun) {
545
- env[requiredEnv] = keyAnswer
546
- logger.log?.(
547
- `Chave coletada (mascarada: ${maskKey(String(keyAnswer))}). Não escrevemos .env; export ${requiredEnv} no shell para persistir.`,
548
- )
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
549
470
  }
550
- 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
+
551
478
  const projectDir = presetDir ?? target ?? process.cwd()
552
479
  const globalDir = (() => {
553
480
  const home = env.HOME?.trim() || homedir()
@@ -555,22 +482,22 @@ export async function runInitWizard({
555
482
  return join(xdg, 'opencode')
556
483
  })()
557
484
  const dir = finalScope === 'global' ? globalDir : projectDir
558
- if (!dryRun) {
559
- const result = writeActivePreset(dir, presetName, {
560
- dryRun: false,
561
- source: 'interactive',
562
- logger,
563
- })
564
- logger.log?.(`Preset ${presetName} salvo em ${finalScope} (${result.path})`)
565
- try {
566
- const raw = readFileSync(result.path, 'utf8')
567
- JSON.parse(raw)
568
- logger.log?.('health-check: active-preset.json OK')
569
- } catch (e) {
570
- logger.warn?.(`health-check failed: ${e.message}`)
571
- }
572
- } else {
573
- 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}`)
574
501
  }
575
- return { preset: presetName, scope: finalScope }
502
+ return { preset: choice.value, scope: finalScope }
576
503
  }