pantheon-opencode 1.6.0-beta.10 → 1.6.0-beta.12

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 (71) hide show
  1. package/AGENTS.global.md +42 -18
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +46 -0
  4. package/README.md +122 -38
  5. package/README.pt-BR.md +5 -4
  6. package/bin/pantheon-init.mjs +322 -101
  7. package/package.json +7 -6
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +128 -10
  11. package/scripts/check-plugin-v2-coverage.mjs +7 -7
  12. package/scripts/doctor.mjs +242 -19
  13. package/scripts/install/backup.mjs +648 -0
  14. package/scripts/install/cli-ui.mjs +79 -1
  15. package/scripts/install/exit-codes.mjs +26 -0
  16. package/scripts/install/file-inventory.mjs +555 -0
  17. package/scripts/install/interactive.mjs +15 -1
  18. package/scripts/install/migrate.mjs +32 -6
  19. package/scripts/install/model-picker.mjs +63 -22
  20. package/scripts/install/opencode-version.mjs +9 -1
  21. package/scripts/install/opencode.mjs +761 -63
  22. package/scripts/install/plan-artifact.mjs +517 -0
  23. package/scripts/install/plan.mjs +449 -0
  24. package/scripts/install/plugin.mjs +136 -18
  25. package/scripts/install/shared.mjs +249 -94
  26. package/scripts/install/state.mjs +63 -8
  27. package/scripts/install/strings.mjs +20 -0
  28. package/scripts/install/venv.mjs +25 -6
  29. package/scripts/install/verify.mjs +128 -0
  30. package/scripts/install/vision-prompt.mjs +13 -1
  31. package/scripts/install-mcp.mjs +1 -1
  32. package/scripts/manifest-inventory.mjs +49 -3
  33. package/scripts/mcp_persistence.py +50 -15
  34. package/scripts/node-engine-policy.mjs +74 -0
  35. package/scripts/package-evidence.mjs +6 -0
  36. package/scripts/postinstall.mjs +3 -4
  37. package/scripts/prune.mjs +9 -3
  38. package/scripts/reconcile.mjs +325 -0
  39. package/scripts/restore.mjs +222 -0
  40. package/scripts/uninstall.mjs +258 -34
  41. package/scripts/update.mjs +164 -0
  42. package/scripts/validate-node-engine-policy.mjs +13 -0
  43. package/scripts/version-check.mjs +34 -1
  44. package/scripts/versioning.mjs +9 -1
  45. package/skills-lock.json +4 -4
  46. package/src/agents/iris.md +6 -0
  47. package/src/agents/mnemosyne.md +7 -2
  48. package/src/agents/zeus.md +19 -62
  49. package/src/instructions/agent-return-format.instructions.md +17 -15
  50. package/src/instructions/memory-protocol.instructions.md +3 -2
  51. package/src/instructions/test-economy.instructions.md +21 -0
  52. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  53. package/src/instructions/zeus-council-synthesis.instructions.md +10 -11
  54. package/src/instructions/zeus-memory-operations.instructions.md +11 -6
  55. package/src/instructions/zeus-timeout-retry.instructions.md +28 -9
  56. package/src/mcp/mcp_persistence.py +50 -15
  57. package/src/pantheon/cost-command.ts +5 -2
  58. package/src/pantheon/model-agents.ts +19 -0
  59. package/src/pantheon/model-command.ts +218 -56
  60. package/src/pantheon/v2-model-overrides.ts +275 -0
  61. package/src/pantheon/v2-tools.ts +18 -29
  62. package/src/pantheon/v2-unsupported.mjs +2 -3
  63. package/src/plugin-v2.ts +13 -0
  64. package/src/plugins/tui/dist/tui-v2.js +2 -2
  65. package/src/plugins/tui/dist/tui.js +1 -1
  66. package/src/plugins/tui/package-lock.json +3 -3
  67. package/src/plugins/tui/package.json +2 -2
  68. package/src/skills/artifact-management/SKILL.md +5 -1
  69. package/src/skills/auto-continue/SKILL.md +14 -6
  70. package/src/skills/memory-bank/SKILL.md +5 -1
  71. package/src/skills/worktrees/SKILL.md +30 -11
@@ -914,15 +914,35 @@ def _validate_delegations(delegations: object) -> None:
914
914
 
915
915
  def _validate_tail(tail: object, payload_bytes: int | None = None) -> list[str]:
916
916
  """Validate bounded serialized tail lines."""
917
- if not isinstance(tail, list) or len(tail) > MAX_TAIL_ITEMS:
918
- raise ValueError("tail exceeds its size limit")
917
+ if not isinstance(tail, list):
918
+ raise ValueError("tail must be an array")
919
+ if len(tail) > MAX_TAIL_ITEMS:
920
+ raise ValueError(
921
+ f"tail has {len(tail)} items; maximum is {MAX_TAIL_ITEMS}; "
922
+ "remove tail entries or omit tail"
923
+ )
919
924
  for line in tail:
920
- if not isinstance(line, str) or len(line.encode()) > MAX_TAIL_LINE_LENGTH:
921
- raise ValueError("tail entries exceed their size limit")
925
+ if not isinstance(line, str):
926
+ raise ValueError("tail entries must be strings")
927
+ line_bytes = len(line.encode())
928
+ if line_bytes > MAX_TAIL_LINE_LENGTH:
929
+ raise ValueError(
930
+ f"tail entries are {line_bytes:,} UTF-8 bytes; maximum is "
931
+ f"{MAX_TAIL_LINE_LENGTH:,}; remove or shorten tail entries, "
932
+ "or omit tail"
933
+ )
922
934
  if payload_bytes is not None and payload_bytes > MAX_CONTEXT_CONTENT_BYTES:
923
- raise ValueError("tail payload exceeds its size limit")
924
- if sum(len(line.encode()) for line in tail) > MAX_CONTEXT_CONTENT_BYTES:
925
- raise ValueError("tail payload exceeds its size limit")
935
+ raise ValueError(
936
+ f"tail payload is {payload_bytes:,} UTF-8 bytes; maximum is "
937
+ f"{MAX_CONTEXT_CONTENT_BYTES:,}; remove tail entries or omit tail"
938
+ )
939
+ tail_bytes = sum(len(line.encode()) for line in tail)
940
+ if tail_bytes > MAX_CONTEXT_CONTENT_BYTES:
941
+ raise ValueError(
942
+ f"tail contains {tail_bytes:,} UTF-8 bytes across strings; maximum "
943
+ f"is {MAX_CONTEXT_CONTENT_BYTES:,} bytes; remove tail entries or "
944
+ "omit tail"
945
+ )
926
946
  return tail
927
947
 
928
948
 
@@ -1020,8 +1040,14 @@ def _collect_context_content_errors(
1020
1040
  if not isinstance(content, str):
1021
1041
  errors.shape(prefix, "a string", content)
1022
1042
  return
1023
- if len(content.encode()) > MAX_CONTEXT_CONTENT_BYTES:
1024
- errors.add(prefix, f"exceeds the {MAX_CONTEXT_CONTENT_BYTES}-byte limit")
1043
+ content_bytes = len(content.encode())
1044
+ if content_bytes > MAX_CONTEXT_CONTENT_BYTES:
1045
+ errors.add(
1046
+ prefix,
1047
+ f"is {content_bytes:,} UTF-8 bytes; maximum is "
1048
+ f"{MAX_CONTEXT_CONTENT_BYTES:,} bytes. Reduce content or omit "
1049
+ "optional tail if it contributes",
1050
+ )
1025
1051
  return
1026
1052
  try:
1027
1053
  parsed = json.loads(content)
@@ -1030,11 +1056,10 @@ def _collect_context_content_errors(
1030
1056
  # it as a checkpoint. It is still bounded above.
1031
1057
  return
1032
1058
  if isinstance(parsed, list) and key == "tail":
1033
- if len(parsed) > MAX_TAIL_ITEMS or any(
1034
- not isinstance(line, str) or len(line.encode()) > MAX_TAIL_LINE_LENGTH
1035
- for line in parsed
1036
- ):
1037
- errors.add(f"{prefix}.tail", "exceeds its size limit")
1059
+ try:
1060
+ _validate_tail(parsed)
1061
+ except ValueError as exc:
1062
+ errors.reroot(prefix, str(exc))
1038
1063
  return
1039
1064
  if not isinstance(parsed, dict):
1040
1065
  # The message already names 'content': do not prepend the path again.
@@ -1164,6 +1189,11 @@ def _upsert_context_entry(
1164
1189
  name="context_save",
1165
1190
  description="Save a context checkpoint for a session/phase. "
1166
1191
  "Stores structured JSON in persistence KV with a key-specific TTL. "
1192
+ "The serialized content is limited to 65,536 UTF-8 bytes. An included "
1193
+ "tail may contain at most 100 strings, each at most 4,096 UTF-8 bytes, "
1194
+ "with at most 65,536 UTF-8 bytes across all tail strings. Oversized "
1195
+ "content or tail is rejected, never truncated; remove or omit optional "
1196
+ "tail data when applicable. "
1167
1197
  "content is a JSON STRING; when it parses to an object, 'goal', 'phase', "
1168
1198
  "'delegations' and 'heartbeat' must each be JSON OBJECTS and 'tail' must "
1169
1199
  "be a JSON ARRAY. 'phase' is an object {current,total,name} — NOT a phase "
@@ -1180,7 +1210,12 @@ async def context_save(
1180
1210
  str,
1181
1211
  Field(
1182
1212
  description=(
1183
- "JSON checkpoint string. When it parses to an object, 'goal', "
1213
+ "JSON checkpoint string, limited to 65,536 UTF-8 bytes. An "
1214
+ "included 'tail' may contain at most 100 strings, each at "
1215
+ "most 4,096 UTF-8 bytes, with at most 65,536 UTF-8 bytes "
1216
+ "across all tail strings. Oversized input is rejected, never "
1217
+ "truncated; remove or omit optional 'tail' when applicable. "
1218
+ "When it parses to an object, 'goal', "
1184
1219
  "'phase', 'delegations' and 'heartbeat' must be objects and "
1185
1220
  "'tail' must be an array; all are optional. 'phase' is an "
1186
1221
  "object {current,total,name}, not a counter. Example: "
@@ -129,7 +129,7 @@ const costArgs = {
129
129
  .min(1)
130
130
  .max(365)
131
131
  .optional()
132
- .describe('Number of days of delegation history to include (default 7).'),
132
+ .describe('Number of rolling 24-hour days of history to include (default 7).'),
133
133
  } satisfies z.ZodRawShape
134
134
 
135
135
  /** The XDG state directory every real host installation writes its ledger to. */
@@ -459,6 +459,9 @@ function renderMarkdown(query: CostQuery, days: number): string {
459
459
  const header = `## Token usage by agent and phase (last ${days} days)`
460
460
  const footer = [
461
461
  formatCoverage(coverage, days),
462
+ 'Window: rolling 24-hour days from query time (not calendar days or session boundaries).',
463
+ 'Aggregation: per agent and phase; phase may be unknown on V2.',
464
+ 'Limits: not grouped by session, task, model, or provider; tokens only (no dollar costs), so this cannot establish model-specific savings or deltas.',
462
465
  `Source: opencode.db (read-only) — table families: ${coverage.sources.join(' + ')} — ${coverage.assistantRows} assistant row(s) scanned`,
463
466
  ].join('\n')
464
467
  if (rows.length === 0) {
@@ -823,7 +826,7 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
823
826
  return {
824
827
  pantheon_cost: {
825
828
  description:
826
- 'Report input, output, and total token usage by agent and phase over the last N days, read from opencode.db (read-only, no monetary values). The report states the coverage window it actually covers.',
829
+ 'Report input, output, and total token usage by agent and phase in a rolling N × 24-hour window from query time (read-only, no monetary values). It is not grouped by session, task, model, or provider; phase may be unknown on V2, so it cannot establish model-specific savings or deltas. The report states the coverage window it actually covers.',
827
830
  args: costArgs,
828
831
  execute,
829
832
  },
@@ -0,0 +1,19 @@
1
+ /** Canonical agent IDs shared by model routing and V2 override validation. */
2
+ export const KNOWN_AGENTS = [
3
+ 'zeus',
4
+ 'athena',
5
+ 'apollo',
6
+ 'hermes',
7
+ 'aphrodite',
8
+ 'demeter',
9
+ 'themis',
10
+ 'prometheus',
11
+ 'hephaestus',
12
+ 'nyx',
13
+ 'gaia',
14
+ 'iris',
15
+ 'mnemosyne',
16
+ 'talos',
17
+ ] as const
18
+
19
+ export type KnownAgent = (typeof KNOWN_AGENTS)[number]
@@ -8,7 +8,7 @@
8
8
  * - set --agent X --model Y --effort Z --scope project|global: validates
9
9
  * via CAPABILITY_TABLE/hasVision and persists atomically with .bak + lock.
10
10
  * - reset --agent X [--scope]: removes override.
11
- * - wizard (no args): askQuestions flow agent → model → effort → scope.
11
+ * - legacy V1 wizard (no args): askQuestions flow agent → model → effort → scope.
12
12
  *
13
13
  * Atomic writes use sibling .bak and temporary-file rename with O_NOFOLLOW
14
14
  * and per-path in-memory lock.
@@ -23,6 +23,7 @@ import { lstat, mkdir, open, rename, unlink } from 'node:fs/promises'
23
23
  import { homedir } from 'node:os'
24
24
  import { basename, dirname, join, resolve } from 'node:path'
25
25
  import { z } from 'zod'
26
+ import { KNOWN_AGENTS } from './model-agents.ts'
26
27
  import {
27
28
  capabilityEntry,
28
29
  hasVision,
@@ -31,6 +32,10 @@ import {
31
32
  resolveActivePreset,
32
33
  } from './presets.mjs'
33
34
  import type { ToolContextLike } from './tool-context.ts'
35
+ import { readV2ModelConfiguration } from './v2-model-overrides.ts'
36
+
37
+ export type { KnownAgent } from './model-agents.ts'
38
+ export { KNOWN_AGENTS } from './model-agents.ts'
34
39
 
35
40
  export type ModelScope = 'project' | 'global'
36
41
  export type ModelAction = 'status' | 'show' | 'set' | 'reset'
@@ -38,24 +43,6 @@ export type ModelAction = 'status' | 'show' | 'set' | 'reset'
38
43
  const MODEL_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:+-]*$/
39
44
  const SAFE_PRESET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
40
45
 
41
- /** 14 canonical agents — must stay in sync with src/routing.yml agents. */
42
- export const KNOWN_AGENTS = [
43
- 'zeus',
44
- 'athena',
45
- 'apollo',
46
- 'hermes',
47
- 'aphrodite',
48
- 'demeter',
49
- 'themis',
50
- 'prometheus',
51
- 'hephaestus',
52
- 'nyx',
53
- 'gaia',
54
- 'iris',
55
- 'mnemosyne',
56
- 'talos',
57
- ] as const
58
- export type KnownAgent = (typeof KNOWN_AGENTS)[number]
59
46
  const KNOWN_AGENTS_SET = new Set<string>(KNOWN_AGENTS)
60
47
 
61
48
  const modelArgs = {
@@ -107,6 +94,10 @@ export interface ModelCommandOptions {
107
94
  ask?: (questions: unknown[]) => Promise<Record<string, unknown>>
108
95
  /** Optional readline injection for wizard fallback. */
109
96
  rl?: { question: (q: string) => Promise<string>; close?: () => void }
97
+ /** V2 ignores static presets and reports/applies only explicit per-agent overrides. */
98
+ v2Mode?: boolean
99
+ /** Filesystem seam for secure V2 preset reads, including post-write verification. */
100
+ v2PresetReadFileSystem?: V2PresetReadFileSystem
110
101
  }
111
102
 
112
103
  export interface ModelTool {
@@ -127,6 +118,22 @@ interface ReadFileResult {
127
118
  data: unknown
128
119
  }
129
120
 
121
+ interface V2PresetReadStats {
122
+ isFile(): boolean
123
+ mode: number
124
+ }
125
+
126
+ interface V2PresetReadHandle {
127
+ stat(): Promise<V2PresetReadStats>
128
+ readFile(encoding: 'utf8'): Promise<string>
129
+ close(): Promise<void>
130
+ }
131
+
132
+ /** Filesystem operations injectable for focused V2 race-safety tests. */
133
+ export interface V2PresetReadFileSystem {
134
+ open(path: string, flags: number): Promise<V2PresetReadHandle>
135
+ }
136
+
130
137
  interface AgentStatus {
131
138
  agent: string
132
139
  model: string | undefined
@@ -375,6 +382,75 @@ async function readActivePresetRaw(path: string, label: string): Promise<ReadFil
375
382
  }
376
383
  }
377
384
 
385
+ /** Read V2 mutation state from one nonblocking, no-follow file descriptor. */
386
+ export async function readV2ActivePresetRaw(
387
+ path: string,
388
+ label: string,
389
+ fileSystem: V2PresetReadFileSystem = {
390
+ open: async (filePath, flags) => open(filePath, flags),
391
+ },
392
+ ): Promise<ReadFileResult> {
393
+ const noFollowFlag = constants.O_NOFOLLOW
394
+ const nonBlockFlag = constants.O_NONBLOCK
395
+ if (
396
+ noFollowFlag === undefined ||
397
+ noFollowFlag === 0 ||
398
+ nonBlockFlag === undefined ||
399
+ nonBlockFlag === 0
400
+ ) {
401
+ throw new ModelCommandError(
402
+ `${label} cannot be read securely on this platform; configuration was not changed`,
403
+ )
404
+ }
405
+
406
+ let file: V2PresetReadHandle | undefined
407
+ try {
408
+ file = await fileSystem.open(path, constants.O_RDONLY | noFollowFlag | nonBlockFlag)
409
+ const openedStats = await file.stat()
410
+ if (!openedStats.isFile()) {
411
+ throw new ModelCommandError(
412
+ `${label} must be a regular file and must not be a symlink; configuration was not changed`,
413
+ )
414
+ }
415
+ const content = await file.readFile('utf8')
416
+ try {
417
+ const parsed: unknown = JSON.parse(content)
418
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
419
+ return {
420
+ exists: true,
421
+ valid: false,
422
+ data: null,
423
+ content,
424
+ mode: openedStats.mode & PERMISSION_MASK,
425
+ }
426
+ }
427
+ return {
428
+ exists: true,
429
+ valid: true,
430
+ data: parsed as Record<string, unknown>,
431
+ content,
432
+ mode: openedStats.mode & PERMISSION_MASK,
433
+ }
434
+ } catch {
435
+ return {
436
+ exists: true,
437
+ valid: false,
438
+ data: null,
439
+ content,
440
+ mode: openedStats.mode & PERMISSION_MASK,
441
+ }
442
+ }
443
+ } catch (error: unknown) {
444
+ if (errorCode(error) === 'ENOENT') return { exists: false, valid: true, data: null }
445
+ if (errorCode(error) === 'ELOOP') {
446
+ throw new ModelCommandError(`${label} must not be a symlink; configuration was not changed`)
447
+ }
448
+ throw error
449
+ } finally {
450
+ await file?.close().catch(() => undefined)
451
+ }
452
+ }
453
+
378
454
  function normalizeAgentName(value: string): string {
379
455
  return value.trim().toLowerCase()
380
456
  }
@@ -464,11 +540,14 @@ async function writeActivePresetAtomically(
464
540
 
465
541
  function ensureActivePresetShape(
466
542
  raw: Record<string, unknown> | null,
467
- fallbackPreset: string,
543
+ fallbackPreset?: string,
468
544
  ): Record<string, unknown> {
469
545
  const out: Record<string, unknown> = raw && typeof raw === 'object' ? { ...raw } : {}
470
546
  if (typeof out.version !== 'number') out.version = 1
471
- if (typeof out.preset !== 'string' || (out.preset as string).trim() === '') {
547
+ if (
548
+ fallbackPreset !== undefined &&
549
+ (typeof out.preset !== 'string' || (out.preset as string).trim() === '')
550
+ ) {
472
551
  out.preset = fallbackPreset
473
552
  }
474
553
  if (typeof out.source !== 'string') out.source = 'cli'
@@ -516,34 +595,39 @@ async function updateActivePreset(
516
595
 
517
596
  const path = presetPathForScope(options, scope)
518
597
  return withPathLock(path, async () => {
519
- const current = await readActivePresetRaw(path, 'configuration file')
598
+ const current = options.v2Mode
599
+ ? await readV2ActivePresetRaw(path, 'configuration file', options.v2PresetReadFileSystem)
600
+ : await readActivePresetRaw(path, 'configuration file')
520
601
  if (current.exists && !current.valid) {
521
602
  throw new ModelCommandError(`${scope} preset file contains invalid JSON; file preserved`)
522
603
  }
523
604
 
524
- const env = envValue(options)
525
- let fallbackPreset = defaultFallbackPreset()
526
- // Prefer env preset if set and known
527
- const envPreset = env.PANTHEON_MODEL_PRESET?.trim()
528
- if (envPreset && envPreset !== '' && envPreset !== 'none') {
529
- try {
530
- const defs = loadPresetDefs()
531
- if (Object.hasOwn(defs, envPreset)) fallbackPreset = envPreset
532
- } catch {
533
- // ignore
534
- }
535
- } else if (
536
- current.data &&
537
- typeof current.data === 'object' &&
538
- (current.data as Record<string, unknown>).preset
539
- ) {
540
- const existing = (current.data as Record<string, unknown>).preset as string
541
- if (
542
- typeof existing === 'string' &&
543
- existing.trim() !== '' &&
544
- SAFE_PRESET_NAME.test(existing.trim())
605
+ let fallbackPreset: string | undefined
606
+ if (!options.v2Mode) {
607
+ const env = envValue(options)
608
+ fallbackPreset = defaultFallbackPreset()
609
+ // Prefer env preset if set and known (V1 legacy behavior only).
610
+ const envPreset = env.PANTHEON_MODEL_PRESET?.trim()
611
+ if (envPreset && envPreset !== '' && envPreset !== 'none') {
612
+ try {
613
+ const defs = loadPresetDefs()
614
+ if (Object.hasOwn(defs, envPreset)) fallbackPreset = envPreset
615
+ } catch {
616
+ // ignore
617
+ }
618
+ } else if (
619
+ current.data &&
620
+ typeof current.data === 'object' &&
621
+ (current.data as Record<string, unknown>).preset
545
622
  ) {
546
- fallbackPreset = existing.trim()
623
+ const existing = (current.data as Record<string, unknown>).preset as string
624
+ if (
625
+ typeof existing === 'string' &&
626
+ existing.trim() !== '' &&
627
+ SAFE_PRESET_NAME.test(existing.trim())
628
+ ) {
629
+ fallbackPreset = existing.trim()
630
+ }
547
631
  }
548
632
  }
549
633
 
@@ -603,13 +687,25 @@ async function updateActivePreset(
603
687
 
604
688
  // health-check: verify file parses and preset resolves
605
689
  try {
606
- const written = await readRegularFile(path, 'configuration file')
607
- if (written) JSON.parse(written.content)
690
+ if (options.v2Mode) {
691
+ const written = await readV2ActivePresetRaw(
692
+ path,
693
+ 'configuration file',
694
+ options.v2PresetReadFileSystem,
695
+ )
696
+ if (written.exists && written.content !== undefined) JSON.parse(written.content)
697
+ } else {
698
+ const written = await readRegularFile(path, 'configuration file')
699
+ if (written) JSON.parse(written.content)
700
+ }
608
701
  } catch {
609
702
  options.logger?.warn?.('health-check: active-preset.json verification failed')
610
703
  }
611
704
 
612
- const base = `Model override set (${scope}): ${agentKey} → ${model} (effort: ${variantInfo.variant ?? 'none'}). Restart OpenCode for the change to take effect.`
705
+ const activation = options.v2Mode
706
+ ? 'V2 reads this override during the next agent-config transform on a subsequent OpenCode configuration load; the current session is unchanged.'
707
+ : 'Restart OpenCode for the change to take effect.'
708
+ const base = `Model override set (${scope}): ${agentKey} → ${model} (effort: ${variantInfo.variant ?? 'none'}). ${activation}`
613
709
  return visionWarning ? `${base}\n${visionWarning}` : base
614
710
  } else {
615
711
  // reset
@@ -620,7 +716,10 @@ async function updateActivePreset(
620
716
  // Clean up empty overrides.agents to keep file tidy, but keep overrides object
621
717
  // Remove empty overrides if no agents and no providers etc? Keep minimal.
622
718
  await writeActivePresetAtomically(path, shaped, current)
623
- return `Model override removed (${scope}): ${agentKey}. Restart OpenCode for the change to take effect.`
719
+ const activation = options.v2Mode
720
+ ? 'V2 reads overrides during the next agent-config transform on a subsequent OpenCode configuration load; the current session is unchanged.'
721
+ : 'Restart OpenCode for the change to take effect.'
722
+ return `Model override removed (${scope}): ${agentKey}. ${activation}`
624
723
  }
625
724
  })
626
725
  }
@@ -630,6 +729,7 @@ async function updateActivePreset(
630
729
  async function resolvePerAgentStatus(options: ModelCommandOptions): Promise<{
631
730
  presetName: string | null
632
731
  presetSource: string | null
732
+ legacyPresetMarker: { source: 'env' | 'file' } | null
633
733
  agents: AgentStatus[]
634
734
  warnings: string[]
635
735
  }> {
@@ -637,6 +737,36 @@ async function resolvePerAgentStatus(options: ModelCommandOptions): Promise<{
637
737
  const candidates = activePresetCandidatesList(options)
638
738
  const warnings: string[] = []
639
739
 
740
+ if (options.v2Mode) {
741
+ const configuration = readV2ModelConfiguration({ candidates, env })
742
+ warnings.push(...configuration.warnings)
743
+ const agents = KNOWN_AGENTS.map((agent): AgentStatus => {
744
+ const override = configuration.overrides[agent]
745
+ let vision: boolean | undefined
746
+ if (override?.model) {
747
+ try {
748
+ vision = hasVision(override.model)
749
+ } catch {
750
+ vision = undefined
751
+ }
752
+ }
753
+ return {
754
+ agent,
755
+ model: override?.model,
756
+ effort: override?.variant,
757
+ origin: override ? 'override' : 'none',
758
+ vision,
759
+ }
760
+ })
761
+ return {
762
+ presetName: null,
763
+ presetSource: null,
764
+ legacyPresetMarker: configuration.legacyPresetMarker,
765
+ agents,
766
+ warnings,
767
+ }
768
+ }
769
+
640
770
  // Use presets.mjs resolver (sync) for canonical resolution, but capture warnings
641
771
  const logger: ModelCommandLogger = {
642
772
  warn: (m) => warnings.push(m),
@@ -702,16 +832,37 @@ async function resolvePerAgentStatus(options: ModelCommandOptions): Promise<{
702
832
  return {
703
833
  presetName: (resolved as { name?: string } | null)?.name ?? null,
704
834
  presetSource: (resolved as { source?: string } | null)?.source ?? null,
835
+ legacyPresetMarker: null,
705
836
  agents,
706
837
  warnings,
707
838
  }
708
839
  }
709
840
 
710
841
  async function renderStatus(options: ModelCommandOptions): Promise<string> {
711
- const { presetName, presetSource, agents, warnings } = await resolvePerAgentStatus(options)
842
+ const { presetName, presetSource, legacyPresetMarker, agents, warnings } =
843
+ await resolvePerAgentStatus(options)
712
844
  const lines: string[] = []
713
- lines.push('Pantheon model configuration per-agent (restart OpenCode after changes):')
714
- if (presetName) {
845
+ lines.push(
846
+ options.v2Mode
847
+ ? 'Pantheon model configuration per-agent (configured values only; not a readout of the model serving a completion):'
848
+ : 'Pantheon model configuration per-agent (restart OpenCode after changes):',
849
+ )
850
+ if (options.v2Mode) {
851
+ lines.push('V2 manual override scope: project only; global overrides are not read or applied.')
852
+ if (legacyPresetMarker) {
853
+ const markerSource =
854
+ legacyPresetMarker.source === 'env' ? 'PANTHEON_MODEL_PRESET' : 'active-preset.json'
855
+ lines.push(
856
+ `Legacy preset marker present in ${markerSource} — ignored in V2; static presets are retired.`,
857
+ )
858
+ } else {
859
+ lines.push('Legacy preset marker: none (static presets are retired and ignored in V2).')
860
+ }
861
+ lines.push('Host default remains unchanged when no manual override is set.')
862
+ lines.push(
863
+ 'Manual project-scoped per-agent overrides are read by the V2 agent transform on the next OpenCode configuration load; the current session is unchanged.',
864
+ )
865
+ } else if (presetName) {
715
866
  const originLabel =
716
867
  presetSource === 'env' ? 'env' : presetSource === 'file' ? 'preset' : presetSource
717
868
  lines.push(`active preset: ${presetName} (${presetSource ?? 'unknown'})`)
@@ -736,7 +887,7 @@ async function renderStatus(options: ModelCommandOptions): Promise<string> {
736
887
  return lines.join('\n')
737
888
  }
738
889
 
739
- // ─── Wizard (askQuestions) ──────────────────────────────────────────────────
890
+ // ─── Legacy V1 wizard (askQuestions) ────────────────────────────────────────
740
891
 
741
892
  export function buildWizardQuestions(): unknown[] {
742
893
  return [
@@ -875,13 +1026,23 @@ async function runWizard(options: ModelCommandOptions): Promise<string> {
875
1026
  }
876
1027
  }
877
1028
 
878
- /** Create the deterministic `pantheon_model` tool used by `/pantheon-model`. */
1029
+ /** Create the `pantheon_model` tool; the interactive wizard is V1-only. */
879
1030
  export function createModelCommand(options: ModelCommandOptions = {}): ModelToolset {
1031
+ const args = options.v2Mode
1032
+ ? {
1033
+ ...modelArgs,
1034
+ action: modelArgs.action.describe(
1035
+ 'Operation: status/show, set, or reset. V1 no-args invocation runs the legacy wizard.',
1036
+ ),
1037
+ }
1038
+ : modelArgs
1039
+
880
1040
  return {
881
1041
  pantheon_model: {
882
- description:
883
- 'Show, set, or reset per-agent model overrides in active-preset.json (project or global). Overrides win over preset; env preset wins over file. Never writes .env or top-level model/small_model.',
884
- args: modelArgs,
1042
+ description: options.v2Mode
1043
+ ? 'Show, set, or reset explicit per-agent project-scoped model overrides in active-preset.json. Global overrides are not read or written in V2; future support requires separate explicit authorization. V2 ignores static preset names and PANTHEON_MODEL_PRESET; no wizard or implicit model selection. Status reports project-scoped configured values only and never writes .env or top-level model/small_model.'
1044
+ : 'Show, set, or reset per-agent model overrides in active-preset.json (project or global). Overrides win over preset; env preset wins over file. Never writes .env or top-level model/small_model.',
1045
+ args,
885
1046
  execute: async (args, _ctx) => {
886
1047
  try {
887
1048
  const hasAction = args.action !== undefined
@@ -890,6 +1051,7 @@ export function createModelCommand(options: ModelCommandOptions = {}): ModelTool
890
1051
 
891
1052
  // Wizard when invoked with no args at all
892
1053
  if (!hasAction && !hasAgentModelEffort) {
1054
+ if (options.v2Mode) return await renderStatus(options)
893
1055
  return await runWizard(options)
894
1056
  }
895
1057