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
@@ -1,4 +1,4 @@
1
- /** Caller/target policy for V2's permission.evaluate hook. */
1
+ /** V2 caller/target policy and one-shot host tool-origin correlation. */
2
2
 
3
3
  export const PANTHEON_AGENTS: ReadonlySet<string> = new Set([
4
4
  'zeus',
@@ -19,17 +19,132 @@ export const PANTHEON_AGENTS: ReadonlySet<string> = new Set([
19
19
 
20
20
  export interface V2PermissionEvent {
21
21
  sessionID?: unknown
22
+ action?: unknown
22
23
  resources?: unknown
23
- /** Optional event identity is checked but never used as authority. */
24
+ /** Optional event identity is cross-checked against the host tool event. */
24
25
  agent?: unknown
26
+ source?: unknown
25
27
  /** Mutable decision fields exposed by OpenCode V2's evaluate hook. */
26
28
  effect?: unknown
27
29
  message?: unknown
28
30
  }
29
31
 
32
+ export interface V2SubagentOrigin {
33
+ sessionID: string
34
+ messageID: string
35
+ callID: string
36
+ caller: string
37
+ target: string
38
+ }
39
+
40
+ interface StoredV2SubagentOrigin extends V2SubagentOrigin {
41
+ capturedAt: number
42
+ }
43
+
44
+ const ORIGIN_TTL_MS = 60_000
45
+ const MAX_PENDING_ORIGINS = 256
46
+
47
+ function originKey(sessionID: string, messageID: string, callID: string): string {
48
+ return JSON.stringify([sessionID, messageID, callID])
49
+ }
50
+
51
+ function nonEmptyString(value: unknown): string | undefined {
52
+ if (typeof value !== 'string') return undefined
53
+ const trimmed = value.trim()
54
+ return trimmed.length === 0 ? undefined : trimmed
55
+ }
56
+
57
+ /**
58
+ * One-shot correlation between the host's tool.execute.before event and the
59
+ * permission evaluation emitted from inside that same native tool call.
60
+ * Entries are short-lived and bounded; missing, stale, or uncorrelated origin
61
+ * data can only make admission fail closed.
62
+ */
63
+ export class V2SubagentOriginRegistry {
64
+ private readonly entries = new Map<string, StoredV2SubagentOrigin>()
65
+
66
+ capture(rawEvent: unknown, now = Date.now()): V2SubagentOrigin | undefined {
67
+ this.prune(now)
68
+ if (rawEvent === null || typeof rawEvent !== 'object' || Array.isArray(rawEvent)) {
69
+ return undefined
70
+ }
71
+ const event = rawEvent as {
72
+ tool?: unknown
73
+ sessionID?: unknown
74
+ messageID?: unknown
75
+ id?: unknown
76
+ agent?: unknown
77
+ input?: unknown
78
+ }
79
+ if (event.tool !== 'subagent' || event.input === null || typeof event.input !== 'object') {
80
+ return undefined
81
+ }
82
+ const input = event.input as { agent?: unknown }
83
+ const sessionID = nonEmptyString(event.sessionID)
84
+ const messageID = nonEmptyString(event.messageID)
85
+ const callID = nonEmptyString(event.id)
86
+ const caller = agentName(event.agent)
87
+ const target = agentName(input.agent)
88
+ if (
89
+ sessionID === undefined ||
90
+ messageID === undefined ||
91
+ callID === undefined ||
92
+ caller === undefined ||
93
+ target === undefined ||
94
+ !PANTHEON_AGENTS.has(target) ||
95
+ this.entries.size >= MAX_PENDING_ORIGINS
96
+ ) {
97
+ return undefined
98
+ }
99
+
100
+ const origin = { sessionID, messageID, callID, caller, target }
101
+ this.entries.set(originKey(sessionID, messageID, callID), { ...origin, capturedAt: now })
102
+ return origin
103
+ }
104
+
105
+ /** Remove and return the matching origin, so one tool event authorizes once. */
106
+ consume(event: V2PermissionEvent, now = Date.now()): V2SubagentOrigin | undefined {
107
+ this.prune(now)
108
+ const source = event.source as { type?: unknown; messageID?: unknown; id?: unknown } | undefined
109
+ if (source?.type !== 'tool') return undefined
110
+ const sessionID = nonEmptyString(event.sessionID)
111
+ const messageID = nonEmptyString(source.messageID)
112
+ const callID = nonEmptyString(source.id)
113
+ if (sessionID === undefined || messageID === undefined || callID === undefined) return undefined
114
+ const key = originKey(sessionID, messageID, callID)
115
+ const origin = this.entries.get(key)
116
+ this.entries.delete(key)
117
+ if (origin === undefined) return undefined
118
+ const { capturedAt: _capturedAt, ...result } = origin
119
+ return result
120
+ }
121
+
122
+ /** Cleanup when a subagent tool exits without reaching permission.evaluate. */
123
+ forget(rawEvent: unknown): void {
124
+ if (rawEvent === null || typeof rawEvent !== 'object' || Array.isArray(rawEvent)) return
125
+ const event = rawEvent as {
126
+ tool?: unknown
127
+ sessionID?: unknown
128
+ messageID?: unknown
129
+ id?: unknown
130
+ }
131
+ if (event.tool !== 'subagent') return
132
+ const sessionID = nonEmptyString(event.sessionID)
133
+ const messageID = nonEmptyString(event.messageID)
134
+ const callID = nonEmptyString(event.id)
135
+ if (sessionID === undefined || messageID === undefined || callID === undefined) return
136
+ this.entries.delete(originKey(sessionID, messageID, callID))
137
+ }
138
+
139
+ private prune(now: number): void {
140
+ for (const [key, origin] of this.entries) {
141
+ if (now - origin.capturedAt > ORIGIN_TTL_MS) this.entries.delete(key)
142
+ }
143
+ }
144
+ }
145
+
30
146
  export interface AuthoritativeSession {
31
147
  id?: unknown
32
- agent?: unknown
33
148
  parentID?: unknown
34
149
  }
35
150
 
@@ -56,6 +171,7 @@ export function evaluateV2Delegation(
56
171
  event: V2PermissionEvent,
57
172
  session: AuthoritativeSession | undefined,
58
173
  existingStatus?: unknown,
174
+ origin?: V2SubagentOrigin,
59
175
  ): V2DelegationDecision {
60
176
  if (existingStatus === 'deny') return 'preserve-deny'
61
177
 
@@ -65,19 +181,30 @@ export function evaluateV2Delegation(
65
181
  const targets = rawTargets.filter((target): target is string => target !== undefined)
66
182
  const pantheonTargets = targets.filter((target) => PANTHEON_AGENTS.has(target))
67
183
  if (pantheonTargets.length === 0) return 'passthrough'
184
+ if (event.action !== 'subagent' || targets.length !== 1 || origin === undefined) return 'deny'
68
185
  const sessionID = typeof event.sessionID === 'string' ? event.sessionID : undefined
69
- const caller = agentName(session?.agent)
186
+ const caller = agentName(origin.caller)
70
187
  if (
71
188
  sessionID === undefined ||
72
189
  session === undefined ||
73
190
  session.id !== sessionID ||
74
- caller === undefined
191
+ caller === undefined ||
192
+ origin.sessionID !== sessionID ||
193
+ origin.target !== pantheonTargets[0]
194
+ ) {
195
+ return 'deny'
196
+ }
197
+ const source = event.source as { type?: unknown; messageID?: unknown; id?: unknown } | undefined
198
+ if (
199
+ source?.type !== 'tool' ||
200
+ source.messageID !== origin.messageID ||
201
+ source.id !== origin.callID
75
202
  ) {
76
203
  return 'deny'
77
204
  }
78
205
  const eventCaller = agentName(event.agent)
79
206
  if (eventCaller !== undefined && eventCaller !== caller) return 'deny'
80
- if (session.parentID !== undefined && session.parentID !== null && session.parentID !== '') {
207
+ if (session.parentID !== undefined && session.parentID !== null) {
81
208
  return 'deny'
82
209
  }
83
210
 
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * V1 (`src/plugin.ts`) wires a single `tool.execute.after` handler that runs,
6
6
  * in order:
7
- * 1. task-result-guard — an empty native `task()` result becomes an explicit
7
+ * 1. task-result-guard — an empty child-dispatch result becomes an explicit
8
8
  * error so the parent LLM cannot read silence as success;
9
9
  * 2. context-sandbox — oversized read/grep/glob/webfetch output is truncated
10
10
  * with a marker + metadata;
@@ -40,7 +40,11 @@ import {
40
40
  DEFAULT_CONFIG as SANDBOX_DEFAULT_CONFIG,
41
41
  } from './context-sandbox.ts'
42
42
  import { createReadEnhancer } from './hashline/read-enhancer.ts'
43
- import { createTaskResultGuard } from './task-result-guard.ts'
43
+ import {
44
+ createTaskResultGuard,
45
+ HOST_EMPTY_RESULT_TEXT,
46
+ isChildDispatchTool,
47
+ } from './task-result-guard.ts'
44
48
 
45
49
  /** The `Tool.Result` fields this adapter reads and writes back. */
46
50
  export interface V2ToolResult {
@@ -69,22 +73,41 @@ export interface V2ExecuteAfterOptions {
69
73
  }
70
74
 
71
75
  /** Which `Tool.Result` field carries the (mutable) text this adapter enhances. */
72
- type TextField = 'output' | 'content' | 'content-array'
76
+ type TextField = 'output' | 'content' | 'content-array' | 'child-output-envelope'
73
77
 
74
78
  /**
75
79
  * Extract the mutable text from a `Tool.Result`.
76
80
  *
77
- * Preference order mirrors what a session renders: a declared string `output`
78
- * first, then a string `content`, then the concatenation of `content` text
79
- * parts. A `content` array containing non-text (file) parts is deliberately NOT
80
- * enhanced — replacing it would corrupt the structured payload, so it is
81
- * reported as unextractable and the whole event becomes a no-op.
81
+ * Prefer non-empty `output`, then `content`, and use an empty `output` only as
82
+ * a fallback. A content array containing non-text (file) parts is deliberately
83
+ * not enhanced because replacing it would corrupt the structured payload.
82
84
  *
83
85
  * @returns `{ text, field }` or `null` when there is nothing to enhance.
84
86
  */
85
- function extractText(result: V2ToolResult): { text: string; field: TextField } | null {
86
- if (typeof result.output === 'string') return { text: result.output, field: 'output' }
87
- if (typeof result.content === 'string') return { text: result.content, field: 'content' }
87
+ function extractText(
88
+ result: V2ToolResult,
89
+ tool: string,
90
+ ): { text: string; field: TextField } | null {
91
+ // OpenCode 2.0.30's native `subagent` result wraps the effective output in
92
+ // result.output.output, while result.content also carries a display wrapper.
93
+ // Prefer that child-only envelope over the non-empty wrapper text, otherwise
94
+ // the exact host empty-result sentinel is hidden from the task guard.
95
+ const childOutput =
96
+ isChildDispatchTool(tool) &&
97
+ result.output !== null &&
98
+ typeof result.output === 'object' &&
99
+ !Array.isArray(result.output)
100
+ ? (result.output as { output?: unknown }).output
101
+ : undefined
102
+ if (typeof childOutput === 'string' && childOutput.trim() !== '') {
103
+ return { text: childOutput, field: 'child-output-envelope' }
104
+ }
105
+ if (typeof result.output === 'string' && result.output.trim() !== '') {
106
+ return { text: result.output, field: 'output' }
107
+ }
108
+ if (typeof result.content === 'string' && result.content.trim() !== '') {
109
+ return { text: result.content, field: 'content' }
110
+ }
88
111
  if (Array.isArray(result.content)) {
89
112
  const parts = result.content
90
113
  const allText = parts.every(
@@ -94,22 +117,98 @@ function extractText(result: V2ToolResult): { text: string; field: TextField } |
94
117
  const text = parts
95
118
  .map((part) => (typeof part === 'string' ? part : ((part as { text?: string }).text ?? '')))
96
119
  .join('\n')
97
- return { text, field: 'content-array' }
120
+ if (text.trim() !== '') return { text, field: 'content-array' }
121
+ }
122
+ if (typeof result.output === 'string') return { text: result.output, field: 'output' }
123
+ if (typeof childOutput === 'string') {
124
+ return { text: childOutput, field: 'child-output-envelope' }
98
125
  }
99
126
  return null
100
127
  }
101
128
 
102
- /**
103
- * Write enhanced text back into the SAME field it came from, preserving the
104
- * result's other fields.
105
- */
106
- function writeText(result: V2ToolResult, field: TextField, text: string): void {
129
+ /** Whether content includes an attachment or meaningful object-form text. */
130
+ function hasMeaningfulStructuredContent(content: unknown): boolean {
131
+ if (Array.isArray(content)) {
132
+ return content.some((part) => {
133
+ if (typeof part === 'string') return false
134
+ return (
135
+ part === null || typeof part !== 'object' || (part as { type?: unknown }).type !== 'text'
136
+ )
137
+ })
138
+ }
139
+
140
+ if (content !== null && typeof content === 'object') {
141
+ const part = content as { type?: unknown; text?: unknown }
142
+ return part.type === 'text'
143
+ ? typeof part.text === 'string' && part.text.trim() !== ''
144
+ : Object.keys(content).length > 0
145
+ }
146
+
147
+ return false
148
+ }
149
+
150
+ /** Keep the duplicate child content view synchronized without changing attachments. */
151
+ function rewriteChildContentMirror(
152
+ content: unknown,
153
+ originalText: string,
154
+ replacement: string,
155
+ ): unknown {
156
+ const isHostPlaceholder = originalText.trim() === HOST_EMPTY_RESULT_TEXT
157
+ const matches = (value: unknown): value is string =>
158
+ typeof value === 'string' &&
159
+ (isHostPlaceholder
160
+ ? value.includes(HOST_EMPTY_RESULT_TEXT)
161
+ : originalText.trim() === '' && value.trim() === '')
162
+
163
+ if (typeof content === 'string') return matches(content) ? replacement : content
164
+ if (Array.isArray(content)) {
165
+ return content.map((part) => {
166
+ if (typeof part === 'string') return matches(part) ? replacement : part
167
+ if (
168
+ part !== null &&
169
+ typeof part === 'object' &&
170
+ (part as { type?: unknown }).type === 'text' &&
171
+ matches((part as { text?: unknown }).text)
172
+ ) {
173
+ return { ...part, text: replacement }
174
+ }
175
+ return part
176
+ })
177
+ }
178
+ if (
179
+ content !== null &&
180
+ typeof content === 'object' &&
181
+ (content as { type?: unknown }).type === 'text' &&
182
+ matches((content as { text?: unknown }).text)
183
+ ) {
184
+ return { ...content, text: replacement }
185
+ }
186
+ return content
187
+ }
188
+
189
+ /** Write enhanced text back into its original result field. */
190
+ function writeText(
191
+ result: V2ToolResult,
192
+ field: TextField,
193
+ text: string,
194
+ originalText: string,
195
+ tool: string,
196
+ ): void {
107
197
  if (field === 'output') {
108
198
  result.output = text
109
199
  } else if (field === 'content') {
110
200
  result.content = text
111
- } else {
201
+ } else if (field === 'content-array') {
112
202
  result.content = [{ type: 'text', text }]
203
+ } else {
204
+ const envelope = result.output as { output?: unknown }
205
+ envelope.output = text
206
+ }
207
+ // Native subagent results expose both an output envelope and display content.
208
+ // Keep the parent-visible text aligned, replacing only blank text or text
209
+ // containing the exact known host sentinel; all non-text parts are preserved.
210
+ if (isChildDispatchTool(tool) && field !== 'content' && field !== 'content-array') {
211
+ result.content = rewriteChildContentMirror(result.content, originalText, text)
113
212
  }
114
213
  }
115
214
 
@@ -141,11 +240,23 @@ export function createV2ExecuteAfter(
141
240
  const sessionID = typeof payload.sessionID === 'string' ? payload.sessionID : ''
142
241
  const callID = typeof payload.id === 'string' ? payload.id : ''
143
242
 
144
- const extracted = extractText(result as V2ToolResult)
145
- // A `task` result may carry no text at all — that IS the empty-result
146
- // failure the guard exists to surface, so synthesize an empty string and
147
- // let the guard replace it. Other tools with no text are a no-op.
148
- if (extracted === null && tool !== 'task') return
243
+ const extracted = extractText(result as V2ToolResult, tool)
244
+ // Preserve meaningful non-text structured payloads (file/image/etc.) and
245
+ // non-empty object-form text parts. Empty text-only content, whether an
246
+ // array of text parts or a single object-form text part, must reach the
247
+ // child-dispatch guard below instead of bypassing it.
248
+ const resultContent = (result as V2ToolResult).content
249
+ if (
250
+ hasMeaningfulStructuredContent(resultContent) &&
251
+ (extracted === null || extracted.text.trim() === '')
252
+ ) {
253
+ return
254
+ }
255
+ // Child-dispatch results with no text or structured payload are empty;
256
+ // other tools with no text remain a no-op. The label set is the guard's
257
+ // own set, so a label the guard handles cannot be dropped before the
258
+ // guard sees it.
259
+ if (extracted === null && !isChildDispatchTool(tool)) return
149
260
  const original = extracted === null ? { text: '', field: 'output' as TextField } : extracted
150
261
 
151
262
  const input = { tool, sessionID, callID, args: payload.input }
@@ -159,7 +270,7 @@ export function createV2ExecuteAfter(
159
270
  await readEnhancer(input, output)
160
271
 
161
272
  if (output.output !== original.text) {
162
- writeText(result as V2ToolResult, original.field, output.output)
273
+ writeText(result as V2ToolResult, original.field, output.output, original.text, tool)
163
274
  }
164
275
  // Surface sandbox metadata onto the result (merge, never replace). It is
165
276
  // only present when the sandbox actually truncated something.
@@ -0,0 +1,275 @@
1
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { KNOWN_AGENTS } from './model-agents.ts'
4
+ import { capabilityEntry, normalizeCapability } from './presets.mjs'
5
+
6
+ export interface V2ModelOverride {
7
+ model: string
8
+ variant?: 'low' | 'medium' | 'high'
9
+ }
10
+
11
+ export interface V2ModelConfiguration {
12
+ overrides: Record<string, V2ModelOverride>
13
+ legacyPresetMarker: { source: 'env' | 'file' } | null
14
+ warnings: string[]
15
+ }
16
+
17
+ export interface V2AgentDraftLike {
18
+ list(): readonly { id: string }[]
19
+ update(id: string, update: (agent: { id: string; model?: unknown }) => void): void
20
+ }
21
+
22
+ interface AgentModelLike {
23
+ id: string
24
+ model?: unknown
25
+ }
26
+
27
+ const MODEL_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:+-]*$/
28
+ const VARIANTS = new Set(['low', 'medium', 'high'])
29
+ const KNOWN_AGENTS_SET = new Set<string>(KNOWN_AGENTS)
30
+
31
+ function isRecord(value: unknown): value is Record<string, unknown> {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
33
+ }
34
+
35
+ function isVariant(value: unknown): value is NonNullable<V2ModelOverride['variant']> {
36
+ return typeof value === 'string' && VARIANTS.has(value)
37
+ }
38
+
39
+ function isSupportedModelChoice(model: unknown, variant: unknown): model is string {
40
+ if (typeof model !== 'string' || !MODEL_REF_PATTERN.test(model)) return false
41
+ if (variant !== undefined && !isVariant(variant)) return false
42
+ try {
43
+ capabilityEntry(model)
44
+ if (variant === undefined) return true
45
+ const normalized = normalizeCapability(model, variant)
46
+ return !normalized.clamped && normalized.variant === variant
47
+ } catch {
48
+ return false
49
+ }
50
+ }
51
+
52
+ interface PresetFileSystem {
53
+ openSync(path: string, flags: number): number
54
+ fstatSync(fileDescriptor: number): { isFile(): boolean }
55
+ readFileSync(fileDescriptor: number, encoding: 'utf8'): string
56
+ closeSync(fileDescriptor: number): void
57
+ }
58
+
59
+ class SecurePresetReadUnavailableError extends Error {
60
+ constructor() {
61
+ super('Secure preset-file opening is unavailable')
62
+ }
63
+ }
64
+
65
+ class NonRegularPresetFileError extends Error {
66
+ constructor() {
67
+ super('Preset file is not a regular file')
68
+ }
69
+ }
70
+
71
+ /** Open and read a regular preset file without following links or blocking on special files. */
72
+ export function readV2PresetFile(
73
+ candidate: string,
74
+ fileSystem: PresetFileSystem = { openSync, fstatSync, readFileSync, closeSync },
75
+ ): string {
76
+ const noFollowFlag = constants.O_NOFOLLOW
77
+ const nonBlockFlag = constants.O_NONBLOCK
78
+ if (
79
+ noFollowFlag === undefined ||
80
+ noFollowFlag === 0 ||
81
+ nonBlockFlag === undefined ||
82
+ nonBlockFlag === 0
83
+ ) {
84
+ throw new SecurePresetReadUnavailableError()
85
+ }
86
+
87
+ let fileDescriptor: number | undefined
88
+ try {
89
+ fileDescriptor = fileSystem.openSync(
90
+ candidate,
91
+ constants.O_RDONLY | noFollowFlag | nonBlockFlag,
92
+ )
93
+ if (!fileSystem.fstatSync(fileDescriptor).isFile()) {
94
+ throw new NonRegularPresetFileError()
95
+ }
96
+ return fileSystem.readFileSync(fileDescriptor, 'utf8')
97
+ } finally {
98
+ if (fileDescriptor !== undefined) fileSystem.closeSync(fileDescriptor)
99
+ }
100
+ }
101
+
102
+ function parseOverrides(
103
+ value: Record<string, unknown>,
104
+ warnings: string[],
105
+ ): Record<string, V2ModelOverride> {
106
+ const parsed: Record<string, V2ModelOverride> = {}
107
+ for (const [agent, raw] of Object.entries(value)) {
108
+ if (!KNOWN_AGENTS_SET.has(agent)) {
109
+ warnings.push(
110
+ 'Override entry ignored for an unsupported agent; use one of the canonical Pantheon agent IDs.',
111
+ )
112
+ continue
113
+ }
114
+ const entry = isRecord(raw) ? raw : undefined
115
+ const hasVariant = entry !== undefined && Object.hasOwn(entry, 'variant')
116
+ const variant = hasVariant ? entry?.variant : entry?.reasoning_effort
117
+ const model = entry?.model
118
+ if (!entry || (hasVariant && !isVariant(variant)) || !isSupportedModelChoice(model, variant)) {
119
+ warnings.push(
120
+ 'Override entry ignored because its model or variant is unsupported; choose a supported model and reasoning variant.',
121
+ )
122
+ continue
123
+ }
124
+ const override: V2ModelOverride = { model }
125
+ if (isVariant(variant)) override.variant = variant
126
+ parsed[agent] = override
127
+ }
128
+ return parsed
129
+ }
130
+
131
+ function defaultCandidates(): string[] {
132
+ return [join(process.cwd(), '.pantheon', 'active-preset.json')]
133
+ }
134
+
135
+ /** Read explicit per-agent project overrides only; global files are ignored in V2. */
136
+ export function readV2ModelConfiguration(
137
+ options: { candidates?: string[]; env?: NodeJS.ProcessEnv } = {},
138
+ ): V2ModelConfiguration {
139
+ const env = options.env ?? process.env
140
+ const envName = env.PANTHEON_MODEL_PRESET?.trim()
141
+ let fileMarkerPresent = false
142
+ const configurations: Array<Record<string, V2ModelOverride>> = []
143
+ const warnings: string[] = []
144
+ let readFailure = false
145
+
146
+ // `model-command` passes project before global candidates. Keep this reader
147
+ // project-only even if a caller supplies the legacy candidate list.
148
+ const candidates = options.candidates ?? defaultCandidates()
149
+ for (const candidate of candidates.slice(0, 1)) {
150
+ let rawContent: string
151
+ try {
152
+ rawContent = readV2PresetFile(candidate)
153
+ } catch (error: unknown) {
154
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue
155
+ if (error instanceof SecurePresetReadUnavailableError) {
156
+ warnings.push(
157
+ 'V2 project model configuration cannot be read securely on this platform; manual overrides were not applied.',
158
+ )
159
+ readFailure = true
160
+ break
161
+ }
162
+ if (
163
+ error instanceof NonRegularPresetFileError ||
164
+ (error instanceof Error && 'code' in error && error.code === 'ELOOP')
165
+ ) {
166
+ warnings.push(
167
+ 'V2 project model configuration is not a regular file or is a symlink; check active-preset.json. Manual overrides were not applied.',
168
+ )
169
+ readFailure = true
170
+ break
171
+ }
172
+ warnings.push(
173
+ 'V2 project model configuration could not be read; check active-preset.json file access. Manual overrides were not applied.',
174
+ )
175
+ readFailure = true
176
+ break
177
+ }
178
+
179
+ let raw: unknown
180
+ try {
181
+ raw = JSON.parse(rawContent)
182
+ } catch {
183
+ warnings.push(
184
+ 'V2 project model configuration contains invalid JSON; correct active-preset.json. Manual overrides were not applied.',
185
+ )
186
+ readFailure = true
187
+ break
188
+ }
189
+ if (!isRecord(raw)) {
190
+ warnings.push(
191
+ 'V2 project model configuration has an invalid shape; correct active-preset.json. Manual overrides were not applied.',
192
+ )
193
+ readFailure = true
194
+ break
195
+ }
196
+
197
+ if (Object.hasOwn(raw, 'preset')) fileMarkerPresent = true
198
+ let parsedOverrides: Record<string, V2ModelOverride> = {}
199
+ if (Object.hasOwn(raw, 'overrides')) {
200
+ if (!isRecord(raw.overrides)) {
201
+ warnings.push(
202
+ 'V2 project model configuration has an invalid `overrides` object; expected an object in active-preset.json. The project file contributed no manual overrides.',
203
+ )
204
+ } else if (Object.hasOwn(raw.overrides, 'agents')) {
205
+ if (!isRecord(raw.overrides.agents)) {
206
+ warnings.push(
207
+ 'V2 project model configuration has invalid `overrides.agents`; expected an object in active-preset.json. The project file contributed no manual overrides.',
208
+ )
209
+ } else {
210
+ parsedOverrides = parseOverrides(raw.overrides.agents, warnings)
211
+ }
212
+ }
213
+ }
214
+ configurations.push(parsedOverrides)
215
+ }
216
+
217
+ const envMarkerPresent = typeof envName === 'string' && envName.length > 0
218
+ const markerSource: 'env' | 'file' | null = envMarkerPresent
219
+ ? 'env'
220
+ : fileMarkerPresent
221
+ ? 'file'
222
+ : null
223
+
224
+ // A project-file read/parse failure fails closed. Malformed entries warn but
225
+ // leave other valid project entries available.
226
+ const overrides: Record<string, V2ModelOverride> = {}
227
+ if (!readFailure) {
228
+ Object.assign(overrides, configurations[0] ?? {})
229
+ }
230
+ return {
231
+ overrides,
232
+ legacyPresetMarker: markerSource === null ? null : { source: markerSource },
233
+ warnings,
234
+ }
235
+ }
236
+
237
+ /** Apply one explicit model override while leaving all other agent settings intact. */
238
+ export function applyV2ModelOverride(
239
+ agent: AgentModelLike,
240
+ override: V2ModelOverride | undefined,
241
+ ): void {
242
+ if (
243
+ !KNOWN_AGENTS_SET.has(agent.id) ||
244
+ !override ||
245
+ !isSupportedModelChoice(override.model, override.variant)
246
+ ) {
247
+ return
248
+ }
249
+ const separator = override.model.indexOf('/')
250
+ const previous = isRecord(agent.model) ? agent.model : {}
251
+ const model: Record<string, unknown> = {
252
+ ...previous,
253
+ providerID: override.model.slice(0, separator),
254
+ id: override.model.slice(separator + 1),
255
+ }
256
+ if (override.variant !== undefined) {
257
+ model.variant = override.variant
258
+ } else {
259
+ delete model.variant
260
+ }
261
+ agent.model = model
262
+ }
263
+
264
+ /** Apply explicit overrides to matching agents and leave unmatched host defaults untouched. */
265
+ export function applyV2ModelOverrides(
266
+ draft: V2AgentDraftLike,
267
+ overrides: Record<string, V2ModelOverride>,
268
+ ): void {
269
+ for (const agent of draft.list()) {
270
+ if (!KNOWN_AGENTS_SET.has(agent.id)) continue
271
+ const override = overrides[agent.id]
272
+ if (!override) continue
273
+ draft.update(agent.id, (current) => applyV2ModelOverride(current, override))
274
+ }
275
+ }