pantheon-opencode 1.5.0-beta.1 → 1.5.0-beta.11

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 (83) hide show
  1. package/.pantheon/code-mode/manifest.json +21 -0
  2. package/CHANGELOG.md +1054 -0
  3. package/README.md +171 -16
  4. package/README.pt-BR.md +99 -13
  5. package/bin/pantheon-init.mjs +178 -21
  6. package/package.json +23 -15
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +65 -0
  9. package/scripts/code_mode_server.py +431 -55
  10. package/scripts/cost.mjs +30 -14
  11. package/scripts/dev-tui.sh +48 -0
  12. package/scripts/doctor.mjs +207 -9
  13. package/scripts/install/cli-ui.mjs +17 -11
  14. package/scripts/install/config-migration.mjs +4 -6
  15. package/scripts/install/opencode.mjs +137 -35
  16. package/scripts/install/plugin.mjs +3 -33
  17. package/scripts/install/shared.mjs +43 -2
  18. package/scripts/install/strings.mjs +129 -0
  19. package/scripts/install-mcp.mjs +1 -0
  20. package/scripts/manifest-inventory.mjs +410 -0
  21. package/scripts/mcp_persistence_server.py +537 -128
  22. package/scripts/package-evidence.mjs +242 -0
  23. package/scripts/probe-context-rehydrate.mjs +240 -0
  24. package/scripts/probe-pantheon-cost.mjs +313 -0
  25. package/scripts/release-beta-version.mjs +56 -60
  26. package/scripts/sync-artifacts.mjs +169 -0
  27. package/scripts/sync-tui.mjs +121 -53
  28. package/scripts/test-opencode-v1-v2-sandbox.sh +367 -96
  29. package/scripts/validation-policy.mjs +7 -7
  30. package/scripts/version-check.mjs +113 -108
  31. package/scripts/versioning.mjs +230 -86
  32. package/src/agents/mnemosyne.md +1 -1
  33. package/src/agents/zeus.md +2 -2
  34. package/src/mcp/code_mode_server.py +431 -55
  35. package/src/mcp/mcp_persistence_server.py +537 -128
  36. package/src/pantheon/auto-wake.ts +1 -5
  37. package/src/pantheon/background-job-board.ts +43 -1
  38. package/src/pantheon/compaction-handoff.ts +304 -0
  39. package/src/pantheon/cost-command.ts +345 -62
  40. package/src/pantheon/delegate-manager.ts +390 -8
  41. package/src/pantheon/delegation-finalize.ts +32 -0
  42. package/src/pantheon/delegation.ts +235 -18
  43. package/src/pantheon/file-persistence-salvage.ts +64 -0
  44. package/src/pantheon/file-persistence.ts +194 -45
  45. package/src/pantheon/native-probe.ts +234 -0
  46. package/src/pantheon/native-task-status.ts +139 -0
  47. package/src/pantheon/provider-capabilities.ts +221 -0
  48. package/src/pantheon/provider-stream-tracker.ts +182 -0
  49. package/src/pantheon/shared-board.ts +37 -0
  50. package/src/pantheon/task-result-guard.ts +107 -0
  51. package/src/pantheon/token-opt.ts +146 -12
  52. package/src/pantheon/tool-ceiling.ts +159 -0
  53. package/src/pantheon/v2-events.ts +18 -1
  54. package/src/plugin-v2.ts +2 -14
  55. package/src/plugin.ts +28 -17
  56. package/src/plugins/pantheon-hooks.ts +51 -0
  57. package/src/plugins/tui/dist/server.d.ts +1 -1
  58. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  59. package/src/plugins/tui/dist/server.js +1 -1
  60. package/src/plugins/tui/dist/server.js.map +1 -1
  61. package/src/plugins/tui/dist/tui.d.ts +137 -27
  62. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  63. package/src/plugins/tui/dist/tui.js +459 -163
  64. package/src/plugins/tui/dist/tui.js.map +1 -1
  65. package/src/plugins/tui/dist/tui.tsx +506 -103
  66. package/src/plugins/tui/package-lock.json +2 -2
  67. package/src/plugins/tui/package.json +1 -1
  68. package/src/plugins/tui/src/index.tsx +506 -103
  69. package/.pantheon/code-mode/.gitkeep +0 -0
  70. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-1.json +0 -8
  71. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-10.json +0 -8
  72. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-11.json +0 -8
  73. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-2.json +0 -8
  74. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-3.json +0 -8
  75. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-4.json +0 -8
  76. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-5.json +0 -8
  77. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-6.json +0 -8
  78. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-7.json +0 -8
  79. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-8.json +0 -8
  80. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-9.json +0 -8
  81. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/heartbeat.json +0 -8
  82. package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/session.json +0 -11
  83. package/src/pantheon/delegate-task-adapter.ts +0 -444
@@ -0,0 +1,221 @@
1
+ /**
2
+ * Exact provider usage contract and the independent V1/V2 capability probes.
3
+ *
4
+ * This module deliberately does not inspect credentials, call a provider, read
5
+ * the TUI, calculate percentages, or derive token counts from text. A provider
6
+ * is supported only when it supplies the complete numeric contract below.
7
+ *
8
+ * @module provider-capabilities
9
+ */
10
+
11
+ /** The only capability statuses exposed by the usage contract. */
12
+ export const USAGE_STATUS = {
13
+ SUPPORTED: 'SUPPORTED',
14
+ UNSUPPORTED: 'UNSUPPORTED',
15
+ } as const
16
+
17
+ export type UsageStatus = (typeof USAGE_STATUS)[keyof typeof USAGE_STATUS]
18
+
19
+ /** Exact token counters supplied by the provider. No totals are inferred. */
20
+ export interface ExactProviderUsage {
21
+ inputTokens: number
22
+ outputTokens: number
23
+ }
24
+
25
+ /** Exact context limit supplied by the provider. */
26
+ export interface ExactProviderLimit {
27
+ contextTokens: number
28
+ }
29
+
30
+ /**
31
+ * Minimum complete provider payload accepted by either capability probe.
32
+ * `resetAt`, when present, is an exact non-negative numeric provider value;
33
+ * date strings and other reset representations are unsupported.
34
+ */
35
+ export interface ExactProviderUsageData {
36
+ sessionId: string
37
+ providerId: string
38
+ modelId: string
39
+ usage: ExactProviderUsage
40
+ limit: ExactProviderLimit
41
+ resetAt?: number
42
+ }
43
+
44
+ /** Stream event metadata required for de-duplication and freshness ordering. */
45
+ export interface ProviderUsageEvent extends ExactProviderUsageData {
46
+ eventId: string
47
+ partId: string
48
+ /** Optional provider sequence. When supplied, it must be an integer. */
49
+ sequence?: number
50
+ /** Optional provider observation time in milliseconds or another numeric scale. */
51
+ observedAt?: number
52
+ }
53
+
54
+ /** A complete snapshot that has passed the exact contract validation. */
55
+ export interface ProviderUsageSnapshot extends ProviderUsageEvent {}
56
+
57
+ export type CapabilityProbeVersion = 'v1' | 'v2'
58
+
59
+ export type CapabilityProbeReason =
60
+ | 'MISSING_SESSION_ID'
61
+ | 'MISSING_PROVIDER_ID'
62
+ | 'MISSING_MODEL_ID'
63
+ | 'MISSING_USAGE'
64
+ | 'MISSING_LIMIT'
65
+ | 'INVALID_USAGE'
66
+ | 'INVALID_LIMIT'
67
+ | 'INVALID_RESET'
68
+
69
+ export type ProviderCapabilityResult =
70
+ | {
71
+ apiVersion: CapabilityProbeVersion
72
+ status: typeof USAGE_STATUS.SUPPORTED
73
+ data: ExactProviderUsageData
74
+ }
75
+ | {
76
+ apiVersion: CapabilityProbeVersion
77
+ status: typeof USAGE_STATUS.UNSUPPORTED
78
+ reason: CapabilityProbeReason
79
+ }
80
+
81
+ type UnknownRecord = Record<string, unknown>
82
+
83
+ function isRecord(value: unknown): value is UnknownRecord {
84
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
85
+ }
86
+
87
+ function isNonEmptyString(value: unknown): value is string {
88
+ return typeof value === 'string' && value.trim().length > 0
89
+ }
90
+
91
+ function isFiniteNonNegativeNumber(value: unknown): value is number {
92
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
93
+ }
94
+
95
+ function hasOnlyKeys(value: UnknownRecord, allowed: readonly string[]): boolean {
96
+ return Object.keys(value).every((key) => allowed.includes(key))
97
+ }
98
+
99
+ function unsupported(
100
+ apiVersion: CapabilityProbeVersion,
101
+ reason: CapabilityProbeReason,
102
+ ): ProviderCapabilityResult {
103
+ return { apiVersion, status: USAGE_STATUS.UNSUPPORTED, reason }
104
+ }
105
+
106
+ /**
107
+ * Validate the complete exact payload without coercion or estimation.
108
+ *
109
+ * This is intentionally shared only as a validator. V1 and V2 entry points
110
+ * below remain separate capability probes and do not fall back to one another.
111
+ */
112
+ function probeExactData(
113
+ apiVersion: CapabilityProbeVersion,
114
+ input: unknown,
115
+ ): ProviderCapabilityResult {
116
+ if (!isRecord(input)) return unsupported(apiVersion, 'MISSING_SESSION_ID')
117
+
118
+ if (!isNonEmptyString(input.sessionId)) {
119
+ return unsupported(apiVersion, 'MISSING_SESSION_ID')
120
+ }
121
+ if (!isNonEmptyString(input.providerId)) {
122
+ return unsupported(apiVersion, 'MISSING_PROVIDER_ID')
123
+ }
124
+ if (!isNonEmptyString(input.modelId)) {
125
+ return unsupported(apiVersion, 'MISSING_MODEL_ID')
126
+ }
127
+ if (!isRecord(input.usage)) return unsupported(apiVersion, 'MISSING_USAGE')
128
+ if (!isRecord(input.limit)) return unsupported(apiVersion, 'MISSING_LIMIT')
129
+ if (!hasOnlyKeys(input.usage, ['inputTokens', 'outputTokens'])) {
130
+ return unsupported(apiVersion, 'INVALID_USAGE')
131
+ }
132
+ if (!hasOnlyKeys(input.limit, ['contextTokens'])) {
133
+ return unsupported(apiVersion, 'INVALID_LIMIT')
134
+ }
135
+
136
+ const usage = input.usage
137
+ if (!isFiniteNonNegativeNumber(usage.inputTokens)) {
138
+ return unsupported(apiVersion, 'INVALID_USAGE')
139
+ }
140
+ if (!isFiniteNonNegativeNumber(usage.outputTokens)) {
141
+ return unsupported(apiVersion, 'INVALID_USAGE')
142
+ }
143
+
144
+ const limit = input.limit
145
+ if (!isFiniteNonNegativeNumber(limit.contextTokens)) {
146
+ return unsupported(apiVersion, 'INVALID_LIMIT')
147
+ }
148
+
149
+ let resetAt: number | undefined
150
+ if ('reset' in input) return unsupported(apiVersion, 'INVALID_RESET')
151
+ if ('resetAt' in input) {
152
+ const value = input.resetAt
153
+ if (!isFiniteNonNegativeNumber(value)) return unsupported(apiVersion, 'INVALID_RESET')
154
+ resetAt = value
155
+ }
156
+
157
+ const data: ExactProviderUsageData = {
158
+ sessionId: input.sessionId,
159
+ providerId: input.providerId,
160
+ modelId: input.modelId,
161
+ usage: {
162
+ inputTokens: usage.inputTokens,
163
+ outputTokens: usage.outputTokens,
164
+ },
165
+ limit: { contextTokens: limit.contextTokens },
166
+ }
167
+ if (resetAt !== undefined) data.resetAt = resetAt
168
+
169
+ return { apiVersion, status: USAGE_STATUS.SUPPORTED, data }
170
+ }
171
+
172
+ /**
173
+ * Probe the V1 exact payload shape supplied by a caller.
174
+ *
175
+ * V1 does not inherit V2 capability, credentials, cache, or lifecycle data.
176
+ * The caller must pass the exact payload after its host-specific extraction.
177
+ */
178
+ export function probeV1Capability(input: unknown): ProviderCapabilityResult {
179
+ return probeExactData('v1', input)
180
+ }
181
+
182
+ /**
183
+ * Probe the V2 exact payload shape supplied by a caller.
184
+ *
185
+ * V2 is intentionally independent from V1: no V1 event, retry, cache, or
186
+ * fallback value is consulted when the exact payload is absent.
187
+ */
188
+ export function probeV2Capability(input: unknown): ProviderCapabilityResult {
189
+ return probeExactData('v2', input)
190
+ }
191
+
192
+ /** Validate one complete stream event using the same exact data contract. */
193
+ export function validateProviderUsageEvent(input: unknown): ProviderUsageEvent | null {
194
+ if (!isRecord(input)) return null
195
+ if (!isNonEmptyString(input.eventId) || !isNonEmptyString(input.partId)) return null
196
+
197
+ const data = probeExactData('v1', input)
198
+ if (data.status !== USAGE_STATUS.SUPPORTED) return null
199
+
200
+ let sequence: number | undefined
201
+ if ('sequence' in input) {
202
+ const value = input.sequence
203
+ if (!isFiniteNonNegativeNumber(value) || !Number.isInteger(value)) return null
204
+ sequence = value
205
+ }
206
+ let observedAt: number | undefined
207
+ if ('observedAt' in input) {
208
+ const value = input.observedAt
209
+ if (!isFiniteNonNegativeNumber(value)) return null
210
+ observedAt = value
211
+ }
212
+
213
+ const event: ProviderUsageEvent = {
214
+ ...data.data,
215
+ eventId: input.eventId,
216
+ partId: input.partId,
217
+ }
218
+ if (sequence !== undefined) event.sequence = sequence
219
+ if (observedAt !== undefined) event.observedAt = observedAt
220
+ return event
221
+ }
@@ -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,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
+ }