pantheon-opencode 1.4.3 → 1.5.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.pantheon/code-mode/README.md +93 -0
  2. package/.pantheon/code-mode/checkpoint-session.py +7 -0
  3. package/.pantheon/code-mode/checkpoint-session.sh +11 -0
  4. package/.pantheon/code-mode/checkpoint_session.py +481 -0
  5. package/.pantheon/code-mode/compress-inline.py +450 -0
  6. package/.pantheon/code-mode/eval-llm-judge.py +255 -0
  7. package/.pantheon/code-mode/eval-monte-carlo.py +368 -0
  8. package/.pantheon/code-mode/eval-run.py +197 -0
  9. package/.pantheon/code-mode/eval-static.py +321 -0
  10. package/.pantheon/code-mode/example-sync.sh +5 -0
  11. package/.pantheon/code-mode/manifest.json +21 -0
  12. package/.pantheon/code-mode/session-end-save.py +186 -0
  13. package/.pantheon/code-mode/session-end-save.sh +18 -0
  14. package/.pantheon/code-mode/test-allowed.sh +5 -0
  15. package/.pantheon/code-mode/test-auto-continue-checkpoint.sh +179 -0
  16. package/.pantheon/code-mode/test-env.sh +7 -0
  17. package/.pantheon/code-mode/test-prlimit.sh +9 -0
  18. package/.pantheon/code-mode/test-timeout.sh +6 -0
  19. package/CHANGELOG.md +1026 -0
  20. package/README.md +292 -1080
  21. package/README.pt-BR.md +308 -0
  22. package/bin/pantheon-init.mjs +207 -31
  23. package/opencode.json +1 -0
  24. package/package.json +34 -14
  25. package/plugin.json +15 -0
  26. package/pyproject.toml +65 -0
  27. package/scripts/_pantheon_paths.py +48 -7
  28. package/scripts/ci-validate-yaml.py +7 -2
  29. package/scripts/code_mode_server.py +451 -44
  30. package/scripts/cost.mjs +30 -14
  31. package/scripts/doctor.mjs +306 -129
  32. package/scripts/generate-preset-docs.mjs +127 -66
  33. package/scripts/generate-prompts.sh +2 -2
  34. package/scripts/install/cli-ui.mjs +23 -10
  35. package/scripts/install/config-migration.mjs +399 -0
  36. package/scripts/install/health-check.mjs +3 -3
  37. package/scripts/install/model-picker.mjs +72 -23
  38. package/scripts/install/opencode-version.mjs +47 -0
  39. package/scripts/install/opencode.mjs +396 -121
  40. package/scripts/install/plugin.mjs +89 -49
  41. package/scripts/install/shared.mjs +55 -159
  42. package/scripts/install/strings.mjs +129 -0
  43. package/scripts/install-mcp.mjs +45 -232
  44. package/scripts/manifest-inventory.mjs +410 -0
  45. package/scripts/mcp_persistence_server.py +798 -60
  46. package/scripts/mcp_resources_server.py +144 -40
  47. package/scripts/memory_mcp_server.py +2 -2
  48. package/scripts/package-evidence.mjs +242 -0
  49. package/scripts/probe-context-rehydrate.mjs +240 -0
  50. package/scripts/probe-pantheon-cost.mjs +313 -0
  51. package/scripts/recover-zenodo-deposition.mjs +146 -0
  52. package/scripts/release-beta-version.mjs +56 -60
  53. package/scripts/sync-artifacts.mjs +169 -0
  54. package/scripts/sync-tui.mjs +135 -42
  55. package/scripts/test-opencode-v1-v2-sandbox.sh +862 -0
  56. package/scripts/uninstall.mjs +298 -954
  57. package/scripts/validate-zenodo-release.mjs +154 -0
  58. package/scripts/validation-policy.mjs +7 -7
  59. package/scripts/version-check.mjs +113 -108
  60. package/scripts/versioning.mjs +230 -86
  61. package/scripts/zenodo-artifact.mjs +21 -0
  62. package/scripts/zenodo-release-state.mjs +53 -0
  63. package/src/agents/mnemosyne.md +1 -1
  64. package/src/agents/zeus.md +27 -16
  65. package/src/mcp/_pantheon_paths.py +48 -7
  66. package/src/mcp/code_mode_server.py +451 -44
  67. package/src/mcp/eval_store.py +1 -1
  68. package/src/mcp/mcp_persistence_server.py +798 -60
  69. package/src/mcp/mcp_resources_server.py +144 -40
  70. package/src/mcp/pantheon_vision_server.py +1 -1
  71. package/src/mcp/toon_codec.py +491 -0
  72. package/src/pantheon/auto-wake.ts +1 -5
  73. package/src/pantheon/background-job-board.ts +110 -2
  74. package/src/pantheon/compaction-handoff.ts +304 -0
  75. package/src/pantheon/cost-command.ts +356 -69
  76. package/src/pantheon/delegate-manager.ts +766 -0
  77. package/src/pantheon/delegation-classifier.ts +307 -0
  78. package/src/pantheon/delegation-enforce.ts +13 -12
  79. package/src/pantheon/delegation-finalize.ts +406 -0
  80. package/src/pantheon/delegation-notify.ts +212 -0
  81. package/src/pantheon/delegation-toast.ts +73 -0
  82. package/src/pantheon/delegation.ts +1337 -0
  83. package/src/pantheon/file-persistence-salvage.ts +64 -0
  84. package/src/pantheon/file-persistence.ts +194 -45
  85. package/src/pantheon/goal-loop.ts +2 -2
  86. package/src/pantheon/goal-store.ts +1 -1
  87. package/src/pantheon/hashline/tool.ts +2 -2
  88. package/src/pantheon/model-command.ts +2 -1
  89. package/src/pantheon/native-probe.ts +234 -0
  90. package/src/pantheon/native-task-status.ts +139 -0
  91. package/src/pantheon/permission-eval.ts +284 -0
  92. package/src/pantheon/provider-capabilities.ts +221 -0
  93. package/src/pantheon/provider-stream-tracker.ts +182 -0
  94. package/src/pantheon/shared-board.ts +37 -0
  95. package/src/pantheon/step-cap.ts +110 -0
  96. package/src/pantheon/task-result-guard.ts +107 -0
  97. package/src/pantheon/token-opt.ts +689 -0
  98. package/src/pantheon/tool-ceiling.ts +159 -0
  99. package/src/pantheon/toon-codec.ts +481 -0
  100. package/src/pantheon/tui-version-check.ts +1 -3
  101. package/src/pantheon/v2-bridge.ts +129 -0
  102. package/src/pantheon/v2-events.ts +148 -0
  103. package/src/pantheon/v2-hooks.ts +287 -0
  104. package/src/pantheon/v2-tool-definitions.ts +331 -0
  105. package/src/pantheon/zeus-delegate-with-retry.ts +406 -0
  106. package/src/plugin-v2/index.ts +21 -0
  107. package/src/plugin-v2.ts +824 -0
  108. package/src/plugin.ts +261 -51
  109. package/src/plugins/pantheon-hooks.ts +51 -0
  110. package/src/plugins/tui/dist/tui.d.ts +116 -24
  111. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  112. package/src/plugins/tui/dist/tui.js +416 -149
  113. package/src/plugins/tui/dist/tui.tsx +456 -87
  114. package/src/plugins/tui/package-lock.json +51 -51
  115. package/src/plugins/tui/package.json +7 -7
  116. package/src/plugins/tui/src/index.tsx +462 -95
  117. package/src/skills/README.md +0 -2
  118. package/src/pantheon/tool-context.ts +0 -41
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Pure provider stream usage tracker.
3
+ *
4
+ * The tracker stores only complete exact provider snapshots. It has no timers,
5
+ * polling, persistence, TUI dependency, provider client, credential fallback,
6
+ * token/cost estimation, or compaction/FSM integration.
7
+ *
8
+ * @module provider-stream-tracker
9
+ */
10
+
11
+ import {
12
+ type ProviderUsageEvent,
13
+ type ProviderUsageSnapshot,
14
+ USAGE_STATUS,
15
+ type UsageStatus,
16
+ validateProviderUsageEvent,
17
+ } from './provider-capabilities.ts'
18
+
19
+ export type TrackerUpdateReason = 'PUBLISHED' | 'DUPLICATE' | 'STALE' | 'OUT_OF_SCOPE' | 'INVALID'
20
+
21
+ export interface ProviderStreamTrackerOptions {
22
+ /** Optional exact stream scope. Events from another stream are unsupported. */
23
+ sessionId?: string
24
+ providerId?: string
25
+ modelId?: string
26
+ /** Injectable sink called only after a complete snapshot is stored. */
27
+ onSnapshot?: (snapshot: ProviderUsageSnapshot) => void
28
+ }
29
+
30
+ export interface ProviderStreamTrackerResult {
31
+ status: UsageStatus
32
+ published: boolean
33
+ reason: TrackerUpdateReason
34
+ snapshot?: ProviderUsageSnapshot
35
+ }
36
+
37
+ export interface ProviderStreamTracker {
38
+ /** Ingest one raw event without coercion or heuristic recovery. */
39
+ ingest(input: unknown): ProviderStreamTrackerResult
40
+ /** Read one complete snapshot for an isolated session/provider/model stream. */
41
+ getSnapshot(
42
+ sessionId: string,
43
+ providerId: string,
44
+ modelId: string,
45
+ ): ProviderUsageSnapshot | undefined
46
+ /** Read all complete snapshots, each isolated by stream identity. */
47
+ snapshots(): ProviderUsageSnapshot[]
48
+ /** Remove all in-memory stream state. */
49
+ clear(): void
50
+ }
51
+
52
+ interface StreamState {
53
+ snapshot: ProviderUsageSnapshot
54
+ eventIds: Set<string>
55
+ partIds: Set<string>
56
+ orderKind?: 'sequence' | 'observedAt'
57
+ orderValue?: number
58
+ }
59
+
60
+ function streamKey(sessionId: string, providerId: string, modelId: string): string {
61
+ return JSON.stringify([sessionId, providerId, modelId])
62
+ }
63
+
64
+ function copySnapshot(snapshot: ProviderUsageSnapshot): ProviderUsageSnapshot {
65
+ const copy: ProviderUsageSnapshot = {
66
+ eventId: snapshot.eventId,
67
+ partId: snapshot.partId,
68
+ sessionId: snapshot.sessionId,
69
+ providerId: snapshot.providerId,
70
+ modelId: snapshot.modelId,
71
+ usage: { ...snapshot.usage },
72
+ limit: { ...snapshot.limit },
73
+ }
74
+ if (snapshot.resetAt !== undefined) copy.resetAt = snapshot.resetAt
75
+ if (snapshot.sequence !== undefined) copy.sequence = snapshot.sequence
76
+ if (snapshot.observedAt !== undefined) copy.observedAt = snapshot.observedAt
77
+ return copy
78
+ }
79
+
80
+ function result(
81
+ status: UsageStatus,
82
+ reason: TrackerUpdateReason,
83
+ snapshot?: ProviderUsageSnapshot,
84
+ ): ProviderStreamTrackerResult {
85
+ return snapshot === undefined
86
+ ? { status, published: false, reason }
87
+ : { status, published: true, reason, snapshot: copySnapshot(snapshot) }
88
+ }
89
+
90
+ function isInScope(event: ProviderUsageEvent, options: ProviderStreamTrackerOptions): boolean {
91
+ return (
92
+ (options.sessionId === undefined || options.sessionId === event.sessionId) &&
93
+ (options.providerId === undefined || options.providerId === event.providerId) &&
94
+ (options.modelId === undefined || options.modelId === event.modelId)
95
+ )
96
+ }
97
+
98
+ function isStale(event: ProviderUsageEvent, state: StreamState): boolean {
99
+ if (event.sequence !== undefined) {
100
+ if (state.orderKind === 'sequence' && state.orderValue !== undefined) {
101
+ return event.sequence <= state.orderValue
102
+ }
103
+ return false
104
+ }
105
+
106
+ if (event.observedAt !== undefined) {
107
+ if (state.orderKind === 'observedAt' && state.orderValue !== undefined) {
108
+ return event.observedAt <= state.orderValue
109
+ }
110
+ return state.orderKind === 'sequence'
111
+ }
112
+
113
+ return state.orderKind !== undefined
114
+ }
115
+
116
+ function updateOrder(event: ProviderUsageEvent, state: StreamState): void {
117
+ if (event.sequence !== undefined) {
118
+ state.orderKind = 'sequence'
119
+ state.orderValue = event.sequence
120
+ } else if (event.observedAt !== undefined) {
121
+ state.orderKind = 'observedAt'
122
+ state.orderValue = event.observedAt
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Create an in-memory tracker. With no scope options, multiple streams are
128
+ * tracked independently by their session/provider/model identity.
129
+ */
130
+ export function createProviderStreamTracker(
131
+ options: ProviderStreamTrackerOptions = {},
132
+ ): ProviderStreamTracker {
133
+ const streams = new Map<string, StreamState>()
134
+
135
+ return {
136
+ ingest(input: unknown): ProviderStreamTrackerResult {
137
+ const event = validateProviderUsageEvent(input)
138
+ if (event === null) return result(USAGE_STATUS.UNSUPPORTED, 'INVALID')
139
+ if (!isInScope(event, options)) return result(USAGE_STATUS.UNSUPPORTED, 'OUT_OF_SCOPE')
140
+
141
+ const key = streamKey(event.sessionId, event.providerId, event.modelId)
142
+ const state = streams.get(key)
143
+ if (state?.eventIds.has(event.eventId) || state?.partIds.has(event.partId)) {
144
+ return result(USAGE_STATUS.SUPPORTED, 'DUPLICATE')
145
+ }
146
+
147
+ if (state !== undefined && isStale(event, state)) {
148
+ state.eventIds.add(event.eventId)
149
+ state.partIds.add(event.partId)
150
+ return result(USAGE_STATUS.SUPPORTED, 'STALE')
151
+ }
152
+
153
+ const nextState: StreamState = state ?? {
154
+ snapshot: event,
155
+ eventIds: new Set<string>(),
156
+ partIds: new Set<string>(),
157
+ }
158
+ nextState.snapshot = event
159
+ nextState.eventIds.add(event.eventId)
160
+ nextState.partIds.add(event.partId)
161
+ updateOrder(event, nextState)
162
+ streams.set(key, nextState)
163
+
164
+ const snapshot = copySnapshot(event)
165
+ options.onSnapshot?.(snapshot)
166
+ return result(USAGE_STATUS.SUPPORTED, 'PUBLISHED', snapshot)
167
+ },
168
+
169
+ getSnapshot(sessionId: string, providerId: string, modelId: string) {
170
+ const state = streams.get(streamKey(sessionId, providerId, modelId))
171
+ return state === undefined ? undefined : copySnapshot(state.snapshot)
172
+ },
173
+
174
+ snapshots() {
175
+ return [...streams.values()].map((state) => copySnapshot(state.snapshot))
176
+ },
177
+
178
+ clear() {
179
+ streams.clear()
180
+ },
181
+ }
182
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Process-wide BackgroundJobBoard singleton shared by every Pantheon plugin
3
+ * surface (src/plugin.ts V1, src/plugins/pantheon-hooks.ts).
4
+ *
5
+ * WHY globalThis and not a module-level `const`: opencode loads each plugin
6
+ * TWICE from two different filesystem paths (the installed npm package AND
7
+ * the repo source — see src/pantheon/plugin-once.ts). Each load is a separate
8
+ * module instance, so a plain ESM singleton would yield TWO boards: the
9
+ * native-task mirror in pantheon-hooks would register jobs on one instance
10
+ * while the finalize path (session.idle + idle scan in plugin.ts) listens on
11
+ * the other, and the job would never finalize. A globalThis-anchored value is
12
+ * process-global by construction, deduping both module copies.
13
+ *
14
+ * The persistence file and signal dir are RELATIVE paths — the board operates
15
+ * against the opencode project root (the cwd of the plugin process), matching
16
+ * the pre-existing plugin.ts wiring exactly.
17
+ */
18
+ import { BackgroundJobBoard } from './background-job-board.ts'
19
+ import { FilePersistenceAdapter } from './file-persistence.ts'
20
+
21
+ const BOARD_KEY = '__pantheonSharedBoard'
22
+
23
+ /** Construction inputs mirror the original plugin.ts module-scope board. */
24
+ const BOARD_OPTIONS = {
25
+ maxConcurrentPerAgent: 3,
26
+ signalDir: '.pantheon/deepwork/board-signals',
27
+ } as const
28
+
29
+ export function getSharedBoard(): BackgroundJobBoard {
30
+ const host = globalThis as { [BOARD_KEY]?: BackgroundJobBoard }
31
+ const existing = host[BOARD_KEY]
32
+ if (existing instanceof BackgroundJobBoard) return existing
33
+ const board = new BackgroundJobBoard(BOARD_OPTIONS)
34
+ board.setPersistence(new FilePersistenceAdapter('.pantheon/board/state.json'))
35
+ host[BOARD_KEY] = board
36
+ return board
37
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * R4 — Per-agent step caps (max_steps).
3
+ *
4
+ * Pure library. routing.yml `agents.<name>.max_steps` gives each agent a
5
+ * step budget (e.g. explore: 25, reviewer: 25, oracle: 15). When an agent's
6
+ * step count reaches max_steps it is forced to summarize-and-stop: the
7
+ * delegation is either skipped with a capped summary (already at cap) or
8
+ * the prompt is appended with a stop instruction (cap hit mid-dispatch).
9
+ *
10
+ * The tracker is PERMANENT-PER-PROCESS: counters accumulate for the process
11
+ * lifetime and are intentionally NOT reset on successful delegations or
12
+ * session end — a per-session reset would let an agent exceed its process
13
+ * budget over a long session. `reset()` exists as a tested utility for
14
+ * tests and future explicit reset points; no production caller wires it.
15
+ *
16
+ * @module step-cap
17
+ */
18
+
19
+ // ─── Types ─────────────────────────────────────────────────────────────
20
+
21
+ /** Default step budget when routing.yml omits max_steps for an agent. */
22
+ export const DEFAULT_MAX_STEPS = 25
23
+
24
+ // ─── Stop instruction ──────────────────────────────────────────────────
25
+
26
+ /**
27
+ * The forced summarize-and-stop instruction injected into a prompt when an
28
+ * agent's step count reaches max_steps.
29
+ */
30
+ export function buildStopInstruction(agent: string, maxSteps: number): string {
31
+ return (
32
+ `\n\n[STEP CAP REACHED — ${agent} at ${maxSteps} steps] ` +
33
+ `You have reached the maximum step budget for this delegation. ` +
34
+ `STOP working immediately and summarize what was accomplished (and ` +
35
+ `what remains, if any) as your final message. Do not start new work.`
36
+ )
37
+ }
38
+
39
+ /**
40
+ * The text returned when a delegation is skipped because the agent is
41
+ * already at its step cap — marks the delegation as capped and asks for a
42
+ * summary of prior results instead of starting new work.
43
+ */
44
+ export function cappedSummary(agent: string, maxSteps: number): string {
45
+ return (
46
+ `[STEP CAP REACHED] ${agent} has reached its max_steps budget (${maxSteps}). ` +
47
+ `Delegation skipped — no new work was started. ` +
48
+ `Summarize prior results and stop.`
49
+ )
50
+ }
51
+
52
+ // ─── Tracker ───────────────────────────────────────────────────────────
53
+
54
+ /**
55
+ * Per-agent step counters with a max_steps budget. Keyed by lowercase agent
56
+ * name (matching is case-insensitive). Agents without a configured budget
57
+ * are never capped.
58
+ */
59
+ export class StepCapTracker {
60
+ private readonly steps = new Map<string, number>()
61
+ readonly maxStepsByAgent: Readonly<Record<string, number>>
62
+
63
+ constructor(maxStepsByAgent: Readonly<Record<string, number>> = {}) {
64
+ this.maxStepsByAgent = maxStepsByAgent
65
+ }
66
+
67
+ /** The configured budget for an agent, or undefined when uncapped. */
68
+ maxStepsFor(agent: string): number | undefined {
69
+ return this.maxStepsByAgent[agent.toLowerCase()]
70
+ }
71
+
72
+ /** Current step count for an agent. */
73
+ stepCount(agent: string): number {
74
+ return this.steps.get(agent.toLowerCase()) ?? 0
75
+ }
76
+
77
+ /** Whether the agent has reached (or exceeded) its max_steps budget. */
78
+ isCapped(agent: string): boolean {
79
+ const max = this.maxStepsFor(agent)
80
+ if (max === undefined) return false
81
+ return this.stepCount(agent) >= max
82
+ }
83
+
84
+ /**
85
+ * Record one step for an agent. Returns the new count and whether this
86
+ * step hit the cap (capped === true exactly when steps >= maxSteps).
87
+ */
88
+ recordStep(agent: string): {
89
+ steps: number
90
+ capped: boolean
91
+ maxSteps: number | undefined
92
+ } {
93
+ const key = agent.toLowerCase()
94
+ const max = this.maxStepsFor(agent)
95
+ const steps = (this.steps.get(key) ?? 0) + 1
96
+ this.steps.set(key, steps)
97
+ return { steps, capped: max !== undefined && steps >= max, maxSteps: max }
98
+ }
99
+
100
+ /**
101
+ * Reset an agent's step count.
102
+ *
103
+ * Intentionally NOT wired in production: the tracker is permanent-per-
104
+ * process (see module docstring) so agents cannot exceed their process
105
+ * budget via resets. Exists for tests and future explicit reset points.
106
+ */
107
+ reset(agent: string): void {
108
+ this.steps.delete(agent.toLowerCase())
109
+ }
110
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Task Result Guard — detects empty task() results from native opencode
3
+ * subagent calls and converts them to explicit errors.
4
+ *
5
+ * Bug context (reproduced 2026-09-10): task() native creates a child session
6
+ * that inherits the parent transcript. When the payload exceeds the provider's
7
+ * admission limit (e.g. free-tier max_outstanding_uncached_prefill_tokens=1000
8
+ * vs 57k incoming tokens), the stream errors with BackendAdmissionRejected.
9
+ * The error is NOT propagated — the child loop exits normally, the child
10
+ * session goes idle with zero assistant/tool output, and opencode marks the
11
+ * task as `completed` with empty content. The parent LLM receives an empty
12
+ * result and proceeds as if the task succeeded.
13
+ *
14
+ * The guard intercepts this in the `tool.execute.after` hook: when the tool
15
+ * is `task` and the output is empty/whitespace-only, it replaces the output
16
+ * with an explicit error message so the parent sees a failure, not silence.
17
+ *
18
+ * Pure TypeScript — zero runtime dependencies. Meant to be wired into the
19
+ * `combinedAfter` hook chain in plugin.ts alongside the sandbox and read
20
+ * enhancer handlers.
21
+ *
22
+ * @module task-result-guard
23
+ */
24
+
25
+ import { createPantheonLogger } from './logger.ts'
26
+
27
+ const log = createPantheonLogger({ module: 'pantheon-task-result-guard' })
28
+
29
+ // ─── Types ─────────────────────────────────────────────────────────────
30
+
31
+ /** Input shape of the opencode `tool.execute.after` hook. */
32
+ export interface TaskGuardInput {
33
+ tool: string
34
+ sessionID: string
35
+ callID: string
36
+ args: unknown
37
+ }
38
+
39
+ /** Output shape of the opencode `tool.execute.after` hook (mutable). */
40
+ export interface TaskGuardOutput {
41
+ title?: string
42
+ output: string
43
+ metadata?: Record<string, unknown>
44
+ }
45
+
46
+ /** The `tool.execute.after` handler shape. */
47
+ export type TaskResultGuardHandler = (
48
+ input: TaskGuardInput,
49
+ output: TaskGuardOutput,
50
+ ) => Promise<void>
51
+
52
+ export interface TaskResultGuardOptions {
53
+ /** Injectable logger (defaults to the Pantheon file log). */
54
+ logger?: { warn: (message: string) => void }
55
+ }
56
+
57
+ // ─── Constants ─────────────────────────────────────────────────────────
58
+
59
+ /**
60
+ * The error message injected when a task() result is empty.
61
+ * Matches the existing delegation-finalize.ts contract:
62
+ * "Child session produced no assistant or tool output".
63
+ */
64
+ export const EMPTY_TASK_ERROR =
65
+ 'ERROR: task() returned empty output — child session produced no assistant or tool output. ' +
66
+ 'This typically means the provider rejected the request (admission control / rate limit) ' +
67
+ 'or the child session crashed before producing any response. ' +
68
+ 'Consider using pantheon_delegate (clean context) instead of task() for large payloads.'
69
+
70
+ // ─── Implementation ────────────────────────────────────────────────────
71
+
72
+ /**
73
+ * Whether a result carries any text content (whitespace-only counts as empty).
74
+ */
75
+ function isEmptyOutput(output: unknown): boolean {
76
+ if (output == null) return true
77
+ if (typeof output !== 'string') return true
78
+ return output.trim() === ''
79
+ }
80
+
81
+ /**
82
+ * Create a task result guard handler for the `tool.execute.after` hook.
83
+ *
84
+ * When the tool is `task` and the output is empty/whitespace-only, replaces
85
+ * the output with an explicit error message. All other tools pass through
86
+ * untouched.
87
+ *
88
+ * @returns A `ToolExecuteAfterHandler`-compatible async function.
89
+ */
90
+ export function createTaskResultGuard(options?: TaskResultGuardOptions): TaskResultGuardHandler {
91
+ const warn = options?.logger?.warn ?? ((message: string) => log.warn(message))
92
+
93
+ return async (input: TaskGuardInput, output: TaskGuardOutput): Promise<void> => {
94
+ // Only intercept the `task` tool — all others pass through untouched.
95
+ if (input.tool !== 'task') return
96
+
97
+ // Only flag truly empty results — non-empty content is the happy path.
98
+ if (!isEmptyOutput(output.output)) return
99
+
100
+ warn(
101
+ `[task-result-guard] Empty task() result detected on session ${input.sessionID} ` +
102
+ `(callID=${input.callID}). Replacing with explicit error.`,
103
+ )
104
+
105
+ output.output = EMPTY_TASK_ERROR
106
+ }
107
+ }