pantheon-opencode 1.5.0-beta.14 → 1.5.0-beta.15
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.
- package/CHANGELOG.md +38 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/pyproject.toml +2 -5
- package/src/agents/zeus.md +4 -26
- package/src/pantheon/background-job-board.ts +4 -4
- package/src/pantheon/delegate-manager.ts +95 -10
- package/src/pantheon/delegation-classifier.ts +3 -4
- package/src/pantheon/delegation-finalize.ts +69 -7
- package/src/pantheon/delegation.ts +16 -4
- package/src/pantheon/presets.d.mts +0 -20
- package/src/pantheon/presets.mjs +0 -64
- package/src/pantheon/toon-codec.ts +1 -1
- package/src/plugin-v2.ts +4 -6
- package/src/plugin.ts +6 -6
- package/src/plugins/pantheon-hooks.ts +1 -1
- package/src/plugins/tui/dist/tui.d.ts +43 -36
- package/src/plugins/tui/dist/tui.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui.js +102 -38
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
- package/src/plugins/tui/src/index.tsx +168 -67
- package/src/routing.yml +0 -16
- package/scripts/hash_verify.py +0 -192
- package/scripts/test-context-compression.sh +0 -169
- package/src/pantheon/auto-wake.ts +0 -85
- package/src/pantheon/chat-reminders.ts +0 -9
- package/src/pantheon/comment-checker.ts +0 -48
- package/src/pantheon/compaction-assert.ts +0 -160
- package/src/pantheon/compaction-handoff.ts +0 -304
- package/src/pantheon/cost-tracker.ts +0 -108
- package/src/pantheon/dispatch-guard.ts +0 -109
- package/src/pantheon/permission-eval.ts +0 -284
- package/src/pantheon/preemptive-compact.ts +0 -76
- package/src/pantheon/provider-capabilities.ts +0 -221
- package/src/pantheon/provider-stream-tracker.ts +0 -182
- package/src/pantheon/retry-policy.ts +0 -212
- package/src/pantheon/token-opt.ts +0 -689
- package/src/pantheon/v2-events.ts +0 -148
- package/src/pantheon/v2-hooks.ts +0 -287
- package/src/pantheon/v2-tool-definitions.ts +0 -331
- package/src/pantheon/zeus-delegate-with-retry.ts +0 -406
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Compaction handoff coordinator.
|
|
3
|
-
*
|
|
4
|
-
* Coordinates the handoff of a compaction checkpoint from in-memory state to
|
|
5
|
-
* durable persistence. The coordinator is deliberately dependency-free: it
|
|
6
|
-
* does not import plugin, board, MCP, hooks, or provider modules.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
export interface HandoffRecord {
|
|
10
|
-
digest: string
|
|
11
|
-
payload: string
|
|
12
|
-
version: number
|
|
13
|
-
sessionId: string
|
|
14
|
-
leaseToken: string
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export interface PersistencePort {
|
|
18
|
-
prepare(input: HandoffRecord): Promise<void>
|
|
19
|
-
read(sessionId: string, key: string): Promise<HandoffRecord | null>
|
|
20
|
-
commit(sessionId: string, key: string, record: HandoffRecord): Promise<void>
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface MemoryPort {
|
|
24
|
-
publishImmutable(sessionId: string, key: string, record: HandoffRecord): Promise<void>
|
|
25
|
-
readByIdempotencyKey(key: string): Promise<HandoffRecord | null>
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export type HandoffStatus =
|
|
29
|
-
| 'COMMITTED'
|
|
30
|
-
| 'UNAVAILABLE'
|
|
31
|
-
| 'CONFLICT'
|
|
32
|
-
| 'NOT_SUPPORTED'
|
|
33
|
-
| 'INVALID_INPUT'
|
|
34
|
-
|
|
35
|
-
/** Maximum allowed integer version value. */
|
|
36
|
-
export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
|
|
37
|
-
|
|
38
|
-
/** Maximum encoded payload size in bytes (128 KiB). */
|
|
39
|
-
export const MAX_PAYLOAD_BYTES = 65_536
|
|
40
|
-
|
|
41
|
-
/** Maximum length of URL-safe identifiers. */
|
|
42
|
-
export const MAX_ID_LENGTH = 128
|
|
43
|
-
|
|
44
|
-
const URL_SAFE_PATTERN = /^[A-Za-z0-9._~-]+$/
|
|
45
|
-
const DIGEST_PATTERN = /^[a-f0-9]{64}$/
|
|
46
|
-
|
|
47
|
-
/** Validate a URL-safe identifier: 1-128 chars, no control characters. */
|
|
48
|
-
function isValidIdentifier(value: unknown): value is string {
|
|
49
|
-
if (typeof value !== 'string') {
|
|
50
|
-
return false
|
|
51
|
-
}
|
|
52
|
-
if (value.length < 1 || value.length > MAX_ID_LENGTH) {
|
|
53
|
-
return false
|
|
54
|
-
}
|
|
55
|
-
if (value.length > 0 && !URL_SAFE_PATTERN.test(value)) {
|
|
56
|
-
return false
|
|
57
|
-
}
|
|
58
|
-
return true
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** Validate a lease token: 1-128 chars, no control characters. */
|
|
62
|
-
function isValidLeaseToken(value: unknown): value is string {
|
|
63
|
-
if (typeof value !== 'string') {
|
|
64
|
-
return false
|
|
65
|
-
}
|
|
66
|
-
if (value.length < 1 || value.length > MAX_ID_LENGTH) {
|
|
67
|
-
return false
|
|
68
|
-
}
|
|
69
|
-
for (const char of value) {
|
|
70
|
-
const code = char.charCodeAt(0)
|
|
71
|
-
if (code < 0x20 || code === 0x7f) {
|
|
72
|
-
return false
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
return true
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** Validate a positive integer version within the safe integer range. */
|
|
79
|
-
function isValidVersion(value: unknown): value is number {
|
|
80
|
-
return (
|
|
81
|
-
typeof value === 'number' && Number.isInteger(value) && value > 0 && value <= MAX_SAFE_INTEGER
|
|
82
|
-
)
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** Validate a 64-character lowercase hex digest. */
|
|
86
|
-
function isValidDigest(value: unknown): value is string {
|
|
87
|
-
return typeof value === 'string' && DIGEST_PATTERN.test(value)
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Validate that a payload is UTF-8 encodable and contains no NUL or control
|
|
92
|
-
* characters (tab, LF, and CR are permitted).
|
|
93
|
-
*/
|
|
94
|
-
function isValidPayload(value: unknown): value is string {
|
|
95
|
-
if (typeof value !== 'string') {
|
|
96
|
-
return false
|
|
97
|
-
}
|
|
98
|
-
if (value.length < 1 || value.length > MAX_PAYLOAD_BYTES) {
|
|
99
|
-
return false
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
const bytes = Buffer.byteLength(value, 'utf8')
|
|
103
|
-
if (bytes < 1 || bytes > MAX_PAYLOAD_BYTES) {
|
|
104
|
-
return false
|
|
105
|
-
}
|
|
106
|
-
if (value.includes('\0')) {
|
|
107
|
-
return false
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
for (const char of value) {
|
|
111
|
-
const code = char.charCodeAt(0)
|
|
112
|
-
if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) {
|
|
113
|
-
return false
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
return true
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/**
|
|
120
|
-
* Compute the digest over the exact UTF-8 encoded bytes of a payload.
|
|
121
|
-
*/
|
|
122
|
-
export function computeDigest(payload: string): string {
|
|
123
|
-
const bytes = Buffer.from(payload, 'utf8')
|
|
124
|
-
let hash = ''
|
|
125
|
-
for (const byte of bytes) {
|
|
126
|
-
hash += byte.toString(16).padStart(2, '0')
|
|
127
|
-
}
|
|
128
|
-
return hash
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** Create a result describing a failed validation. */
|
|
132
|
-
function invalid(message: string): { status: 'INVALID_INPUT'; message: string } {
|
|
133
|
-
return { status: 'INVALID_INPUT', message }
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Create a result describing a missing dependency. */
|
|
137
|
-
function notSupported(): { status: 'NOT_SUPPORTED' } {
|
|
138
|
-
return { status: 'NOT_SUPPORTED' }
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/** Create a result describing a conflict. */
|
|
142
|
-
function conflict(message: string): { status: 'CONFLICT'; message: string } {
|
|
143
|
-
return { status: 'CONFLICT', message }
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** Create a result describing an unavailable memory port. */
|
|
147
|
-
function unavailable(message: string): { status: 'UNAVAILABLE'; message: string } {
|
|
148
|
-
return { status: 'UNAVAILABLE', message }
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** Create a successful committed result. */
|
|
152
|
-
function committed(digest: string): { status: 'COMMITTED'; digest: string } {
|
|
153
|
-
return { status: 'COMMITTED', digest }
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Compaction handoff coordinator.
|
|
158
|
-
*
|
|
159
|
-
* The coordinator drives the handoff FSM:
|
|
160
|
-
*
|
|
161
|
-
* no record -> prepare -> PREPARED -> memory.publishImmutable
|
|
162
|
-
* -> memory.readByIdempotencyKey -> persistence.commit -> COMMITTED
|
|
163
|
-
*
|
|
164
|
-
* It never retries after memory becomes unavailable; the PREPARED state is
|
|
165
|
-
* left intact for a later explicit attempt.
|
|
166
|
-
*/
|
|
167
|
-
export class CompactionHandoffCoordinator {
|
|
168
|
-
private readonly persistence: PersistencePort | undefined
|
|
169
|
-
private readonly memory: MemoryPort | undefined
|
|
170
|
-
|
|
171
|
-
constructor(persistence?: PersistencePort, memory?: MemoryPort) {
|
|
172
|
-
this.persistence = persistence
|
|
173
|
-
this.memory = memory
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Attempt to hand off a compaction checkpoint.
|
|
178
|
-
*
|
|
179
|
-
* Returns immediately with INVALID_INPUT if any argument fails validation.
|
|
180
|
-
* Returns NOT_SUPPORTED if either required port is missing.
|
|
181
|
-
* Returns CONFLICT for digest or lease/version mismatches.
|
|
182
|
-
* Returns UNAVAILABLE if the memory port cannot publish/read the record.
|
|
183
|
-
* Returns COMMITTED when the record is durably committed.
|
|
184
|
-
*/
|
|
185
|
-
async prepare(
|
|
186
|
-
sessionId: string,
|
|
187
|
-
idempotencyKey: string,
|
|
188
|
-
leaseToken: string,
|
|
189
|
-
version: number,
|
|
190
|
-
digest: string,
|
|
191
|
-
payload: string,
|
|
192
|
-
): Promise<{ status: HandoffStatus; key?: string; digest?: string; message?: string }> {
|
|
193
|
-
// Validation first: no port calls are made before this block completes.
|
|
194
|
-
if (
|
|
195
|
-
!isValidIdentifier(sessionId) ||
|
|
196
|
-
!isValidIdentifier(idempotencyKey) ||
|
|
197
|
-
!isValidLeaseToken(leaseToken) ||
|
|
198
|
-
!isValidVersion(version) ||
|
|
199
|
-
!isValidDigest(digest) ||
|
|
200
|
-
!isValidPayload(payload)
|
|
201
|
-
) {
|
|
202
|
-
return invalid('Invalid handoff input')
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
if (this.persistence === undefined || this.memory === undefined) {
|
|
206
|
-
return notSupported()
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const _key = `${sessionId}:${idempotencyKey}`
|
|
210
|
-
|
|
211
|
-
// Check for an existing committed record before preparing a new one.
|
|
212
|
-
const existingRecord = await this.persistence.read(sessionId, idempotencyKey)
|
|
213
|
-
if (existingRecord !== null) {
|
|
214
|
-
if (existingRecord.digest === digest && existingRecord.sessionId === sessionId) {
|
|
215
|
-
// Idempotent replay: same digest and session. Verify lease/version match.
|
|
216
|
-
if (existingRecord.leaseToken !== leaseToken || existingRecord.version !== version) {
|
|
217
|
-
return conflict('Stale lease or version')
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// Verify the record is also in memory. If missing, try to recover by publishing once.
|
|
221
|
-
let memoryRecord: HandoffRecord | null = null
|
|
222
|
-
try {
|
|
223
|
-
memoryRecord = await this.memory.readByIdempotencyKey(idempotencyKey)
|
|
224
|
-
} catch {
|
|
225
|
-
return unavailable('Memory port unavailable')
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
if (memoryRecord === null) {
|
|
229
|
-
// Recovery: memory lost the record but persistence has it. Publish once.
|
|
230
|
-
try {
|
|
231
|
-
await this.memory.publishImmutable(sessionId, idempotencyKey, existingRecord)
|
|
232
|
-
} catch (_error) {
|
|
233
|
-
return unavailable('Memory port unavailable')
|
|
234
|
-
}
|
|
235
|
-
try {
|
|
236
|
-
memoryRecord = await this.memory.readByIdempotencyKey(idempotencyKey)
|
|
237
|
-
} catch (_error) {
|
|
238
|
-
return unavailable('Memory port unavailable')
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
if (memoryRecord === null) {
|
|
243
|
-
return unavailable('Record not found in memory')
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
await this.persistence.commit(sessionId, idempotencyKey, existingRecord)
|
|
247
|
-
return committed(memoryRecord.digest)
|
|
248
|
-
}
|
|
249
|
-
// Different digest or session: conflict.
|
|
250
|
-
return conflict('Digest or session mismatch')
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
// Phase 1: prepare in persistence (PREPARED).
|
|
254
|
-
await this.persistence.prepare({ digest, payload, version, sessionId, leaseToken })
|
|
255
|
-
|
|
256
|
-
// Phase 2: publish the record to memory. If memory is unavailable, the
|
|
257
|
-
// coordinator stays in PREPARED and never retries automatically.
|
|
258
|
-
try {
|
|
259
|
-
await this.memory.publishImmutable(sessionId, idempotencyKey, {
|
|
260
|
-
digest,
|
|
261
|
-
payload,
|
|
262
|
-
version,
|
|
263
|
-
sessionId,
|
|
264
|
-
leaseToken,
|
|
265
|
-
})
|
|
266
|
-
} catch (_error) {
|
|
267
|
-
return unavailable('Memory port unavailable')
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// Phase 3: read back from memory by idempotency key.
|
|
271
|
-
let memoryRecord: HandoffRecord | null = null
|
|
272
|
-
try {
|
|
273
|
-
memoryRecord = await this.memory.readByIdempotencyKey(idempotencyKey)
|
|
274
|
-
} catch (_error) {
|
|
275
|
-
return unavailable('Memory port unavailable')
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
if (memoryRecord === null) {
|
|
279
|
-
return unavailable('Record not found in memory')
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// Stale lease or version check.
|
|
283
|
-
if (memoryRecord.leaseToken !== leaseToken || memoryRecord.version !== version) {
|
|
284
|
-
return conflict('Stale lease or version')
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// Idempotent replay: same key and session is a success.
|
|
288
|
-
// The memory record is authoritative for recovery after crash.
|
|
289
|
-
if (memoryRecord.sessionId === sessionId) {
|
|
290
|
-
// Phase 4: commit to persistence.
|
|
291
|
-
try {
|
|
292
|
-
await this.persistence.commit(sessionId, idempotencyKey, memoryRecord)
|
|
293
|
-
} catch (_error) {
|
|
294
|
-
return conflict('Persistence commit failed')
|
|
295
|
-
}
|
|
296
|
-
return committed(memoryRecord.digest)
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// Same key, different digest or session: conflict.
|
|
300
|
-
return conflict('Digest or session mismatch')
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
export default CompactionHandoffCoordinator
|
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cost Tracker (Wave 4, PR #46) — JSONL cost ledger for background
|
|
3
|
-
* delegations. Every delegation that finishes (or times out) records one
|
|
4
|
-
* line; the ledger lives at `.pantheon/costs/delegations.jsonl` and gives
|
|
5
|
-
* Nyx / the /cost command a durable, human-readable cost history.
|
|
6
|
-
*
|
|
7
|
-
* record() APPENDS (appendFile + parent dir auto-create), never rewrites.
|
|
8
|
-
* A missing ledger is an EMPTY ledger — list() → [], summary() → zeros,
|
|
9
|
-
* no crash. Injectable clock not needed: timestamp is caller-provided
|
|
10
|
-
* (ISO 8601), matching the delegation toolset's timestamping style.
|
|
11
|
-
*
|
|
12
|
-
* @module cost-tracker
|
|
13
|
-
*/
|
|
14
|
-
import { appendFile, mkdir, readFile } from 'node:fs/promises'
|
|
15
|
-
import { dirname } from 'node:path'
|
|
16
|
-
|
|
17
|
-
/** One delegation cost event. */
|
|
18
|
-
export interface CostRecord {
|
|
19
|
-
/** Board task ID (e.g. "ses_child_1" or the job alias "apo-1"). */
|
|
20
|
-
taskId: string
|
|
21
|
-
/** Session that owns the delegation — list(sessionID?) filters on this. */
|
|
22
|
-
sessionID?: string
|
|
23
|
-
/** Delegated agent name (e.g. "hermes"). */
|
|
24
|
-
agent: string
|
|
25
|
-
/** Model ID actually used (e.g. "opencode/deepseek-v4-flash"). */
|
|
26
|
-
model: string
|
|
27
|
-
tokensInput: number
|
|
28
|
-
tokensOutput: number
|
|
29
|
-
/** Cost in USD (already computed by the caller). */
|
|
30
|
-
costUsd: number
|
|
31
|
-
/** ISO 8601 timestamp of the record. */
|
|
32
|
-
timestamp: string
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Aggregate across the whole ledger. */
|
|
36
|
-
export interface CostSummary {
|
|
37
|
-
count: number
|
|
38
|
-
totalCostUsd: number
|
|
39
|
-
totalTokensInput: number
|
|
40
|
-
totalTokensOutput: number
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export interface CostTrackerOptions {
|
|
44
|
-
/** Ledger path. Default: ".pantheon/costs/delegations.jsonl". */
|
|
45
|
-
filePath?: string
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export interface CostTracker {
|
|
49
|
-
/** Append one record to the ledger (creates the parent dir on first write). */
|
|
50
|
-
record(entry: CostRecord): Promise<void>
|
|
51
|
-
/** All records, optionally filtered by sessionID. Missing file → []. */
|
|
52
|
-
list(sessionID?: string): Promise<CostRecord[]>
|
|
53
|
-
/** Aggregate totals across the whole ledger. Missing file → zeros. */
|
|
54
|
-
summary(): Promise<CostSummary>
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** Parse the ledger file; missing file → empty array (never throws). */
|
|
58
|
-
async function readLedger(filePath: string): Promise<CostRecord[]> {
|
|
59
|
-
let raw: string
|
|
60
|
-
try {
|
|
61
|
-
raw = await readFile(filePath, 'utf8')
|
|
62
|
-
} catch {
|
|
63
|
-
return []
|
|
64
|
-
}
|
|
65
|
-
const records: CostRecord[] = []
|
|
66
|
-
for (const line of raw.split('\n')) {
|
|
67
|
-
if (line.trim() === '') continue
|
|
68
|
-
try {
|
|
69
|
-
records.push(JSON.parse(line) as CostRecord)
|
|
70
|
-
} catch {
|
|
71
|
-
// Skip malformed lines — a partial ledger never breaks the reader.
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return records
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function createCostTracker(options?: CostTrackerOptions): CostTracker {
|
|
78
|
-
const filePath = options?.filePath ?? '.pantheon/costs/delegations.jsonl'
|
|
79
|
-
|
|
80
|
-
return {
|
|
81
|
-
async record(entry: CostRecord): Promise<void> {
|
|
82
|
-
await mkdir(dirname(filePath), { recursive: true })
|
|
83
|
-
await appendFile(filePath, `${JSON.stringify(entry)}\n`, 'utf8')
|
|
84
|
-
},
|
|
85
|
-
|
|
86
|
-
async list(sessionID?: string): Promise<CostRecord[]> {
|
|
87
|
-
const records = await readLedger(filePath)
|
|
88
|
-
if (sessionID === undefined) return records
|
|
89
|
-
return records.filter((r) => r.sessionID === sessionID)
|
|
90
|
-
},
|
|
91
|
-
|
|
92
|
-
async summary(): Promise<CostSummary> {
|
|
93
|
-
const records = await readLedger(filePath)
|
|
94
|
-
const summary: CostSummary = {
|
|
95
|
-
count: records.length,
|
|
96
|
-
totalCostUsd: 0,
|
|
97
|
-
totalTokensInput: 0,
|
|
98
|
-
totalTokensOutput: 0,
|
|
99
|
-
}
|
|
100
|
-
for (const r of records) {
|
|
101
|
-
summary.totalCostUsd += r.costUsd
|
|
102
|
-
summary.totalTokensInput += r.tokensInput
|
|
103
|
-
summary.totalTokensOutput += r.tokensOutput
|
|
104
|
-
}
|
|
105
|
-
return summary
|
|
106
|
-
},
|
|
107
|
-
}
|
|
108
|
-
}
|
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Dispatch Guard (Wave 4, PR #46) — auto-retry-on-empty for background
|
|
3
|
-
* delegations. Classifies a dispatch result and redispatch once when it
|
|
4
|
-
* came back empty.
|
|
5
|
-
*
|
|
6
|
-
* Failure signature classification:
|
|
7
|
-
* - 'content' — text content present, nothing to do.
|
|
8
|
-
* - 'empty-mode1' — NO content AND NO tokens: the dispatch returned
|
|
9
|
-
* nothing at all (no reply / early abort).
|
|
10
|
-
* - 'empty-mode2' — no text part but tokens present: reasoning happened
|
|
11
|
-
* but the text part was lost — the themis Wave-2
|
|
12
|
-
* failure signature that triggered this guard.
|
|
13
|
-
*
|
|
14
|
-
* Retry cap is HARD at 1 (never 2x). The guard is stateful per instance:
|
|
15
|
-
* one retry budget total. It is a PURE library — it does NOT intercept
|
|
16
|
-
* task() (opencode 1.18.x cannot intercept task completion via hooks, so
|
|
17
|
-
* integration is manual-orchestration; see zeus.md "Empty-Result Retry").
|
|
18
|
-
*
|
|
19
|
-
* @module dispatch-guard
|
|
20
|
-
*/
|
|
21
|
-
|
|
22
|
-
import { createPantheonLogger } from './logger.ts'
|
|
23
|
-
|
|
24
|
-
// Silence-by-default TUI policy (pantheon-hooks L42-58): the default warn
|
|
25
|
-
// fallback logs to .pantheon/logs/hooks.log; console echo is opt-in via
|
|
26
|
-
// PANTHEON_HOOKS_LOG=1. `logger` injection stays for tests.
|
|
27
|
-
const log = createPantheonLogger({ module: 'pantheon-dispatch-guard' })
|
|
28
|
-
|
|
29
|
-
/** A dispatch result — the minimal shape needed to classify emptiness. */
|
|
30
|
-
export interface DispatchResultLike {
|
|
31
|
-
/** Text content of the result (task_result / report markdown). */
|
|
32
|
-
content?: string | null
|
|
33
|
-
/** Input tokens (present when the model actually reasoned). */
|
|
34
|
-
tokensInput?: number
|
|
35
|
-
/** Output tokens (present when the model actually reasoned). */
|
|
36
|
-
tokensOutput?: number
|
|
37
|
-
/** R1: the failure that produced this result (classified by retry-policy). */
|
|
38
|
-
error?: unknown
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Classification of a dispatch result. */
|
|
42
|
-
export type DispatchClassification = 'content' | 'empty-mode1' | 'empty-mode2'
|
|
43
|
-
|
|
44
|
-
export interface DispatchGuardOptions {
|
|
45
|
-
/** Enable auto-retry on empty results. Default: true. */
|
|
46
|
-
retryOnEmpty?: boolean
|
|
47
|
-
/** Injectable logger (defaults to the Pantheon file log, env-gated echo). */
|
|
48
|
-
logger?: { warn: (message: string) => void }
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export interface DispatchGuard {
|
|
52
|
-
/** Classify a result: content, empty-mode1 (nothing), empty-mode2 (reasoning, no text). */
|
|
53
|
-
classifyResult(result: DispatchResultLike): DispatchClassification
|
|
54
|
-
/**
|
|
55
|
-
* Redispatch ONCE when the result is empty and retryOnEmpty is enabled.
|
|
56
|
-
* A retried result that is STILL empty is returned as-is — the cap of 1
|
|
57
|
-
* is never exceeded. Never throws.
|
|
58
|
-
*/
|
|
59
|
-
maybeRetry(
|
|
60
|
-
result: DispatchResultLike,
|
|
61
|
-
redispatch: () => Promise<DispatchResultLike>,
|
|
62
|
-
): Promise<{
|
|
63
|
-
classification: DispatchClassification
|
|
64
|
-
retried: boolean
|
|
65
|
-
result: DispatchResultLike
|
|
66
|
-
}>
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** 1-based retry budget — the hard cap. Never 2x. */
|
|
70
|
-
const MAX_RETRIES = 1
|
|
71
|
-
|
|
72
|
-
/** Whether a result carries any text content (whitespace-only counts as empty). */
|
|
73
|
-
function hasContent(result: DispatchResultLike): boolean {
|
|
74
|
-
return typeof result.content === 'string' && result.content.trim() !== ''
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/** Whether the result carries any token counts (i.e. the model actually ran). */
|
|
78
|
-
function hasTokens(result: DispatchResultLike): boolean {
|
|
79
|
-
return (result.tokensInput ?? 0) > 0 || (result.tokensOutput ?? 0) > 0
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function createDispatchGuard(options?: DispatchGuardOptions): DispatchGuard {
|
|
83
|
-
const retryOnEmpty = options?.retryOnEmpty ?? true
|
|
84
|
-
const warn = options?.logger?.warn ?? ((message: string) => log.warn(message))
|
|
85
|
-
// Per-instance retry budget — the "cap 1" enforcement point.
|
|
86
|
-
let retriesUsed = 0
|
|
87
|
-
|
|
88
|
-
return {
|
|
89
|
-
classifyResult(result: DispatchResultLike): DispatchClassification {
|
|
90
|
-
if (hasContent(result)) return 'content'
|
|
91
|
-
return hasTokens(result) ? 'empty-mode2' : 'empty-mode1'
|
|
92
|
-
},
|
|
93
|
-
|
|
94
|
-
async maybeRetry(result, redispatch) {
|
|
95
|
-
const classification = this.classifyResult(result)
|
|
96
|
-
if (!retryOnEmpty || classification === 'content' || retriesUsed >= MAX_RETRIES) {
|
|
97
|
-
return { classification, retried: false, result }
|
|
98
|
-
}
|
|
99
|
-
retriesUsed += 1
|
|
100
|
-
warn(`dispatch returned ${classification}; retrying once (cap ${MAX_RETRIES})`)
|
|
101
|
-
const retriedResult = await redispatch()
|
|
102
|
-
return {
|
|
103
|
-
classification: this.classifyResult(retriedResult),
|
|
104
|
-
retried: true,
|
|
105
|
-
result: retriedResult,
|
|
106
|
-
}
|
|
107
|
-
},
|
|
108
|
-
}
|
|
109
|
-
}
|