pantheon-opencode 1.5.0-beta.2 → 1.5.0-beta.20

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 (107) hide show
  1. package/.pantheon/code-mode/manifest.json +21 -0
  2. package/AGENTS.md +14 -63
  3. package/CHANGELOG.md +1260 -0
  4. package/README.md +162 -23
  5. package/README.pt-BR.md +104 -19
  6. package/bin/pantheon-init.mjs +178 -21
  7. package/commands/pantheon.md +1 -35
  8. package/package.json +23 -15
  9. package/plugin.json +1 -1
  10. package/pyproject.toml +62 -0
  11. package/scripts/code_mode_server.py +431 -55
  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 +12 -45
  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 +536 -164
  22. package/scripts/package-evidence.mjs +242 -0
  23. package/scripts/probe-pantheon-cost.mjs +10 -1
  24. package/scripts/release-beta-version.mjs +56 -60
  25. package/scripts/sync-artifacts.mjs +169 -0
  26. package/scripts/sync-tui.mjs +129 -64
  27. package/scripts/test-opencode-v1-v2-sandbox.sh +79 -161
  28. package/scripts/validation-policy.mjs +7 -7
  29. package/scripts/version-check.mjs +113 -108
  30. package/scripts/versioning.mjs +230 -86
  31. package/src/agents/apollo.md +1 -0
  32. package/src/agents/gaia.md +1 -0
  33. package/src/agents/mnemosyne.md +1 -1
  34. package/src/agents/zeus.md +11 -54
  35. package/src/instructions/memory-protocol.instructions.md +6 -3
  36. package/src/instructions/zeus-anti-stall.instructions.md +2 -4
  37. package/src/instructions/zeus-council-synthesis.instructions.md +3 -28
  38. package/src/instructions/zeus-timeout-retry.instructions.md +3 -28
  39. package/src/mcp/code_mode_server.py +431 -55
  40. package/src/mcp/mcp_persistence_server.py +536 -164
  41. package/src/mcp/toon_codec.py +2 -4
  42. package/src/pantheon/background-job-board.ts +47 -5
  43. package/src/pantheon/{delegation-compaction.ts → compaction-context.ts} +10 -100
  44. package/src/pantheon/cost-command.ts +309 -44
  45. package/src/pantheon/delegation-enforce.ts +59 -14
  46. package/src/pantheon/file-persistence-salvage.ts +64 -0
  47. package/src/pantheon/file-persistence.ts +194 -45
  48. package/src/pantheon/goal-loop.ts +1 -1
  49. package/src/pantheon/goal-store.ts +1 -1
  50. package/src/pantheon/idle-continuation.ts +4 -6
  51. package/src/pantheon/model-command.ts +1 -2
  52. package/src/pantheon/native-task-status.ts +139 -0
  53. package/src/pantheon/presets.d.mts +0 -20
  54. package/src/pantheon/presets.mjs +0 -64
  55. package/src/pantheon/session-guard.ts +2 -2
  56. package/src/pantheon/session-id.ts +30 -0
  57. package/src/pantheon/shared-board.ts +37 -0
  58. package/src/pantheon/task-result-guard.ts +106 -0
  59. package/src/pantheon/todo-enforcer.ts +3 -3
  60. package/src/pantheon/tool-ceiling.ts +159 -0
  61. package/src/pantheon/tool-context.ts +23 -0
  62. package/src/pantheon/v2-bridge.ts +1 -4
  63. package/src/plugin-v2.ts +8 -21
  64. package/src/plugin.ts +83 -251
  65. package/src/plugins/pantheon-hooks.ts +51 -0
  66. package/src/plugins/tui/dist/server.d.ts +1 -1
  67. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  68. package/src/plugins/tui/dist/server.js +1 -1
  69. package/src/plugins/tui/dist/server.js.map +1 -1
  70. package/src/plugins/tui/dist/tui.d.ts +261 -77
  71. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  72. package/src/plugins/tui/dist/tui.js +640 -234
  73. package/src/plugins/tui/dist/tui.js.map +1 -1
  74. package/src/plugins/tui/package-lock.json +2 -2
  75. package/src/plugins/tui/package.json +2 -2
  76. package/src/plugins/tui/src/index.tsx +872 -226
  77. package/src/routing.yml +0 -16
  78. package/src/skills/context-compression/SKILL.md +1 -1
  79. package/scripts/generate-preset-docs.mjs +0 -300
  80. package/scripts/generate-prompts.sh +0 -222
  81. package/scripts/hash_verify.py +0 -192
  82. package/scripts/install/component.mjs +0 -24
  83. package/scripts/install/migrate-config.mjs +0 -302
  84. package/scripts/test-context-compression.sh +0 -169
  85. package/src/pantheon/auto-wake.ts +0 -89
  86. package/src/pantheon/chat-reminders.ts +0 -9
  87. package/src/pantheon/comment-checker.ts +0 -48
  88. package/src/pantheon/compaction-assert.ts +0 -160
  89. package/src/pantheon/cost-tracker.ts +0 -108
  90. package/src/pantheon/delegate-manager.ts +0 -669
  91. package/src/pantheon/delegation-classifier.ts +0 -307
  92. package/src/pantheon/delegation-finalize.ts +0 -374
  93. package/src/pantheon/delegation-notify.ts +0 -212
  94. package/src/pantheon/delegation-toast.ts +0 -73
  95. package/src/pantheon/delegation.ts +0 -1120
  96. package/src/pantheon/dispatch-guard.ts +0 -109
  97. package/src/pantheon/permission-eval.ts +0 -284
  98. package/src/pantheon/preemptive-compact.ts +0 -76
  99. package/src/pantheon/retry-policy.ts +0 -212
  100. package/src/pantheon/step-cap.ts +0 -110
  101. package/src/pantheon/token-opt.ts +0 -781
  102. package/src/pantheon/toon-codec.ts +0 -481
  103. package/src/pantheon/v2-events.ts +0 -131
  104. package/src/pantheon/v2-hooks.ts +0 -287
  105. package/src/pantheon/v2-tool-definitions.ts +0 -331
  106. package/src/pantheon/zeus-delegate-with-retry.ts +0 -406
  107. package/src/plugins/tui/dist/tui.tsx +0 -2605
@@ -1,1120 +0,0 @@
1
- /**
2
- * Delegation Core (Phase 2) — the three background-delegation tools plus the
3
- * finalize lifecycle hook, built on the BackgroundJobBoard.
4
- *
5
- * Tools (STRUCTURAL shape — matches what opencode expects: `{description,
6
- * args (zod shape), execute(args, ctx)}`; zod is imported directly — the
7
- * `@opencode-ai/plugin` package is a devDep and is NEVER runtime-imported):
8
- * - `pantheon_delegate({prompt, agent, description?})` — create a child
9
- * session (parentID = caller), register it on the board, arm a timeout,
10
- * and fire-and-forget `session.promptAsync` on the child (NO noReply —
11
- * the spike refuted noReply as a push mechanism). Completion is observed
12
- * via `session.idle` on the child and finalized through
13
- * `finalizeDelegation` (exposed on the toolset for the Phase 3 event hook).
14
- * - `pantheon_delegation_read({id})` — block via `board.waitForTerminal`,
15
- * return the report markdown, mark the job reconciled.
16
- * - `pantheon_delegation_list()` — job list with `[unread]` for terminal-
17
- * unreconciled jobs.
18
- *
19
- * Depth guard (root-session detection): the ToolContext carries NO parentID
20
- * (spike), so root detection is configurable. Resolution order:
21
- * 1. `options.isRootSession(sessionID)` custom predicate;
22
- * 2. `options.rootSessions` explicit allowlist, with `options.isChildSession`
23
- * authoritative when supplied by the plugin. SDK session metadata is
24
- * registered from parentID; no prompt/name inference is used.
25
- * 3. default (no rootSessions): any session WE created via
26
- * `session.create` is a sub-session; everything else is treated as
27
- * root for standalone compatibility. The plugin supplies the SDK-backed
28
- * hierarchy at runtime.
29
- *
30
- * Read-only enforcement is Phase 4 — `read_only` is exposed on the delegate
31
- * args and the child session is registered in the read-only registry when the
32
- * delegate is read-only (explicit flag or agent ∈ readOnlyAgents), which the
33
- * plugin's `tool.execute.before` guard enforces.
34
- *
35
- * @module delegation
36
- */
37
-
38
- import { z } from 'zod'
39
-
40
- import type { BackgroundJobBoard, BackgroundJobRecord } from './background-job-board.ts'
41
- import {
42
- classifyStuckAgent,
43
- type DelegationResult,
44
- formatDelegationResult,
45
- } from './delegation-classifier.ts'
46
- import {
47
- isDelegationAllowed,
48
- normalizeDelegationAgent,
49
- readOnlyRegistry,
50
- } from './delegation-enforce.ts'
51
- import {
52
- DELEGATION_DEFAULTS,
53
- type DelegationClient,
54
- type DelegationDeps,
55
- type DelegationMessageBundle,
56
- type DelegationOptions,
57
- type FinalizeInput,
58
- finalizeDelegation as finalizeDelegationReport,
59
- readDelegationReport,
60
- } from './delegation-finalize.ts'
61
- import { finalizeIdleChildrenWithoutMd } from './delegation-notify.ts'
62
- import { createPantheonLogger } from './logger.ts'
63
- import { buildAgentListDescription } from './permission-globs.ts'
64
- import { buildStopInstruction, cappedSummary, DEFAULT_MAX_STEPS } from './step-cap.ts'
65
-
66
- export type {
67
- DelegationClient,
68
- DelegationClientSession,
69
- DelegationMessageBundle,
70
- DelegationOptions,
71
- FinalizeInput,
72
- } from './delegation-finalize.ts'
73
- export { DELEGATION_DEFAULTS } from './delegation-finalize.ts'
74
- export type { IdleChildScanDeps } from './delegation-notify.ts'
75
- export { finalizeIdleChildrenWithoutMd, startIdleChildScan } from './delegation-notify.ts'
76
-
77
- // Fase B3: these are runtime controls, not routing/frontmatter fields. The
78
- // plugin reads them from the environment, while tests and embedders can pass
79
- // the same values through DelegationOptions.
80
- export const B3_DEFAULT_EXCEPTION_BUDGET = 5
81
-
82
- /** Maximum time spent proving that an accepted prompt actually booted. */
83
- export const BOOTSTRAP_TIMEOUT_MS = 5_000
84
- /** Default cadence for the bounded bootstrap probe. */
85
- export const BOOTSTRAP_POLL_INTERVAL_MS = 250
86
-
87
- function readIntegerEnv(
88
- env: Record<string, string | undefined>,
89
- name: string,
90
- fallback: number,
91
- minimum: number,
92
- ): number {
93
- const raw = env[name]?.trim()
94
- if (raw === undefined || raw === '') return fallback
95
- const value = Number(raw)
96
- return Number.isSafeInteger(value) && value >= minimum ? value : fallback
97
- }
98
-
99
- type BootstrapOutcome =
100
- | { status: 'started'; elapsedMs: number; reason: string }
101
- | { status: 'startup_failed' | 'bootstrap_unknown'; elapsedMs: number; reason: string }
102
-
103
- type PromptOutcome =
104
- | { status: 'accepted'; value: unknown }
105
- | { status: 'rejected'; reason: string }
106
- | { status: 'timeout'; reason: string }
107
-
108
- /**
109
- * Bound the SDK request itself, not just the board watchdog. The AbortSignal
110
- * is passed to hosts that support it; the race also protects older hosts that
111
- * ignore the signal and never settle their promise.
112
- */
113
- async function promptWithTimeout(
114
- client: DelegationClient,
115
- input: Parameters<DelegationClient['session']['promptAsync']>[0],
116
- timeoutMs: number,
117
- ): Promise<PromptOutcome> {
118
- const controller = new AbortController()
119
- let timer: NodeJS.Timeout | undefined
120
- const operation = client.session.promptAsync({ ...input, signal: controller.signal }).then(
121
- (value) => ({ status: 'accepted' as const, value }),
122
- (error: unknown) => ({
123
- status: 'rejected' as const,
124
- reason: error instanceof Error ? error.message : String(error),
125
- }),
126
- )
127
- try {
128
- return await Promise.race([
129
- operation,
130
- new Promise<PromptOutcome>((resolve) => {
131
- timer = setTimeout(() => {
132
- controller.abort()
133
- resolve({ status: 'timeout', reason: `promptAsync timed out after ${timeoutMs}ms` })
134
- }, timeoutMs)
135
- timer.unref()
136
- }),
137
- ])
138
- } finally {
139
- if (timer !== undefined) clearTimeout(timer)
140
- }
141
- }
142
-
143
- const RUNNING_SESSION_STATES = new Set(['busy', 'running', 'processing', 'retry', 'pending'])
144
-
145
- async function boundedProbe<T>(operation: Promise<T>, timeoutMs: number): Promise<T | undefined> {
146
- if (timeoutMs <= 0) return undefined
147
- let timer: NodeJS.Timeout | undefined
148
- try {
149
- return await Promise.race([
150
- operation,
151
- new Promise<undefined>((resolve) => {
152
- timer = setTimeout(() => resolve(undefined), timeoutMs)
153
- timer.unref()
154
- }),
155
- ])
156
- } finally {
157
- if (timer !== undefined) clearTimeout(timer)
158
- }
159
- }
160
-
161
- function isRunningSession(value: unknown): boolean {
162
- if (typeof value !== 'object' || value === null) return false
163
- const record = value as Record<string, unknown>
164
- const state = record.status ?? record.state
165
- return typeof state === 'string' && RUNNING_SESSION_STATES.has(state.toLowerCase())
166
- }
167
-
168
- function hasDurableMessage(value: unknown): boolean {
169
- if (!Array.isArray(value)) return false
170
- return value.some((bundle) => {
171
- if (typeof bundle !== 'object' || bundle === null) return false
172
- const info = (bundle as { info?: { role?: unknown } }).info
173
- return info?.role === 'user' || info?.role === 'assistant'
174
- })
175
- }
176
-
177
- async function bootstrapChild(
178
- client: DelegationClient,
179
- childSessionID: string,
180
- accepted: unknown,
181
- options: DelegationOptions,
182
- ): Promise<BootstrapOutcome> {
183
- const now = options.now ?? Date.now
184
- const sleep =
185
- options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
186
- const timeoutMs = options.bootstrapTimeoutMs ?? BOOTSTRAP_TIMEOUT_MS
187
- const intervalMs = options.bootstrapPollIntervalMs ?? BOOTSTRAP_POLL_INTERVAL_MS
188
- const startedAt = now()
189
- const hasMessagesAPI = typeof client.session.messages === 'function'
190
- const hasStatusAPI = typeof client.session.get === 'function'
191
- const acceptedRunning = isRunningSession(accepted)
192
-
193
- if (!hasMessagesAPI && !hasStatusAPI) {
194
- return acceptedRunning
195
- ? {
196
- status: 'started',
197
- elapsedMs: now() - startedAt,
198
- reason: 'prompt accepted by legacy host',
199
- }
200
- : {
201
- status: 'bootstrap_unknown',
202
- elapsedMs: now() - startedAt,
203
- reason:
204
- 'host exposes neither session.messages nor session.get and prompt had no running evidence',
205
- }
206
- }
207
-
208
- let sawProbe = false
209
- while (now() - startedAt < timeoutMs) {
210
- let durable = false
211
- let running = acceptedRunning
212
- const remainingMs = timeoutMs - (now() - startedAt)
213
- if (hasMessagesAPI) {
214
- try {
215
- const messagesAPI = client.session.messages
216
- if (messagesAPI === undefined) continue
217
- const messages = await boundedProbe(
218
- messagesAPI({ path: { id: childSessionID } }),
219
- remainingMs,
220
- )
221
- if (messages !== undefined) {
222
- sawProbe = true
223
- durable = hasDurableMessage(messages)
224
- }
225
- } catch {
226
- // A transient endpoint failure is diagnosed after the bounded window.
227
- }
228
- }
229
- if (hasStatusAPI) {
230
- try {
231
- const statusAPI = client.session.get
232
- if (statusAPI === undefined) continue
233
- const status = await boundedProbe(
234
- statusAPI({ path: { id: childSessionID } }),
235
- timeoutMs - (now() - startedAt),
236
- )
237
- if (status !== undefined) {
238
- running = running || isRunningSession(status)
239
- sawProbe = true
240
- }
241
- } catch {
242
- // Fail closed only after the bounded window; never create an unbounded poll.
243
- }
244
- }
245
- if (durable)
246
- return {
247
- status: 'started',
248
- elapsedMs: now() - startedAt,
249
- reason: 'durable child message observed',
250
- }
251
- if (running)
252
- return {
253
- status: 'started',
254
- elapsedMs: now() - startedAt,
255
- reason: 'child session reports running/processing',
256
- }
257
- await sleep(Math.min(intervalMs, Math.max(0, timeoutMs - (now() - startedAt))))
258
- }
259
- return sawProbe
260
- ? {
261
- status: 'startup_failed',
262
- elapsedMs: now() - startedAt,
263
- reason: `no durable message or running state after ${timeoutMs}ms`,
264
- }
265
- : {
266
- status: 'bootstrap_unknown',
267
- elapsedMs: now() - startedAt,
268
- reason: `bootstrap probes were unavailable after ${timeoutMs}ms`,
269
- }
270
- }
271
-
272
- /** Resolve the two supported read-only delegation exception budgets. */
273
- export function resolveDelegationBudgets(
274
- env: Record<string, string | undefined> = process.env,
275
- ): ReadonlyMap<string, number> {
276
- return new Map([
277
- [
278
- 'athena->apollo',
279
- readIntegerEnv(env, 'PANTHEON_ATHENA_APOLLO_BUDGET', B3_DEFAULT_EXCEPTION_BUDGET, 0),
280
- ],
281
- [
282
- 'hermes->apollo',
283
- readIntegerEnv(env, 'PANTHEON_HERMES_APOLLO_BUDGET', B3_DEFAULT_EXCEPTION_BUDGET, 0),
284
- ],
285
- ])
286
- }
287
-
288
- /** Resolve an optional positive wall-clock timeout from the environment. */
289
- export function resolveDelegationTimeoutMs(
290
- env: Record<string, string | undefined> = process.env,
291
- ): number | undefined {
292
- const raw = env.PANTHEON_DELEGATION_TIMEOUT_MS?.trim()
293
- if (raw === undefined || raw === '') return undefined
294
- const value = Number(raw)
295
- return Number.isSafeInteger(value) && value > 0 ? value : undefined
296
- }
297
-
298
- // ─── Types ─────────────────────────────────────────────────────────────
299
-
300
- // Silence-by-default TUI policy (pantheon-hooks L42-58): console output in a
301
- // plugin renders into the opencode TUI — the "lixo". Errors go to
302
- // .pantheon/logs/hooks.log; console echo is opt-in via PANTHEON_HOOKS_LOG=1.
303
- const log = createPantheonLogger({ module: 'pantheon-delegate' })
304
-
305
- /** Structural view of the tool context opencode passes to execute(). */
306
- export interface ToolContextLike {
307
- sessionID: string
308
- directory?: string
309
- worktree?: string
310
- /**
311
- * The OpenCode SDK's ToolContext declares this as required. It remains
312
- * optional here because the structural test/embedding surface can be
313
- * supplied by older hosts; B3 must skip enforcement when it is absent.
314
- */
315
- agent?: string
316
- }
317
-
318
- /** A delegation tool: description + zod args shape + execute. */
319
- export interface DelegationTool<Args extends z.ZodRawShape = z.ZodRawShape> {
320
- description: string
321
- args: Args
322
- execute(args: z.infer<z.ZodObject<Args>>, ctx: ToolContextLike): Promise<string>
323
- }
324
-
325
- /** The full toolset returned by createDelegationTools(). */
326
- export interface DelegationToolset {
327
- pantheon_delegate: DelegationTool<typeof delegateArgs>
328
- pantheon_delegation_read: DelegationTool<typeof readArgs>
329
- pantheon_delegation_list: DelegationTool<typeof listArgs>
330
- /** Lifecycle hook for the Phase 3 event wiring (session.idle on the child). */
331
- finalizeDelegation: (
332
- childSessionID: string,
333
- opts: FinalizeInput,
334
- ) => Promise<BackgroundJobRecord | undefined>
335
- /** Proactive finalize for idle children without MD reports (Fix 2). */
336
- finalizeIdleChildrenWithoutMd: typeof finalizeIdleChildrenWithoutMd
337
- }
338
-
339
- /** Input for createDelegationTools(). */
340
- export interface CreateDelegationToolsInput {
341
- board: BackgroundJobBoard
342
- client: DelegationClient
343
- options?: DelegationOptions
344
- }
345
-
346
- // ─── Args schemas ──────────────────────────────────────────────────────
347
-
348
- const delegateArgs = {
349
- prompt: z.string().min(1).describe('Task prompt delivered to the background agent.'),
350
- agent: z.string().min(1).describe('Agent name, e.g. "apollo" or "hermes".'),
351
- description: z.string().optional().describe('Human-readable description shown on the job board.'),
352
- read_only: z.boolean().optional().describe('Advisory flag for Phase 4 read-only enforcement.'),
353
- model: z
354
- .string()
355
- .optional()
356
- .describe(
357
- 'Explicit model for the child session (provider/model, e.g. "opencode/deepseek-v4-flash-free").',
358
- ),
359
- } satisfies z.ZodRawShape
360
-
361
- const readArgs = {
362
- id: z.string().min(1).describe('Job alias (e.g. "apo-1") or task ID to read.'),
363
- } satisfies z.ZodRawShape
364
-
365
- const listArgs = {} satisfies z.ZodRawShape
366
-
367
- // ─── State labels ──────────────────────────────────────────────────────
368
-
369
- /** Canonical 14-agent roster (O5 tool-description default). */
370
- export const CANONICAL_AGENTS: readonly string[] = [
371
- 'zeus',
372
- 'athena',
373
- 'apollo',
374
- 'hermes',
375
- 'aphrodite',
376
- 'demeter',
377
- 'themis',
378
- 'prometheus',
379
- 'hephaestus',
380
- 'nyx',
381
- 'gaia',
382
- 'iris',
383
- 'mnemosyne',
384
- 'talos',
385
- ]
386
-
387
- function stateLabel(state: BackgroundJobRecord['state']): string {
388
- switch (state) {
389
- case 'running':
390
- return 'RUNNING'
391
- case 'completed':
392
- return 'OK'
393
- case 'error':
394
- return 'ERR'
395
- case 'startup_failed':
396
- return 'STARTUP FAILED'
397
- case 'startup_unknown':
398
- return 'STARTUP UNKNOWN'
399
- case 'cancelled':
400
- return 'CANCELLED'
401
- case 'reconciled':
402
- return 'RECONCILED'
403
- }
404
- }
405
-
406
- /** Normalize the SDK-provided caller agent without inventing an identity. */
407
- const normalizeToolAgent = normalizeDelegationAgent
408
-
409
- /**
410
- * O5: the delegate tool description. When permission.task rules are
411
- * configured, denied agents are REMOVED from the description entirely (not
412
- * just blocked at call time) — the caller never sees them as invocable.
413
- */
414
- function buildDelegateDescription(options: DelegationOptions): string {
415
- const base =
416
- 'Dispatch a background agent as a child session and register it on the job board. ' +
417
- 'Returns the readable alias (e.g. "apo-1"); read the result with ' +
418
- 'pantheon_delegation_read. Only root sessions may delegate.'
419
- if (options.permissionTask === undefined) return base
420
- const roster = options.agentNames ?? CANONICAL_AGENTS
421
- return `${base} Allowed subagents: ${buildAgentListDescription(options.permissionTask, roster)}.`
422
- }
423
-
424
- // ─── Agent activity sampling ────────────────────────────────────────────
425
- //
426
- // Visibility for `pantheon_delegation_read` / `pantheon_delegation_list`
427
- // (issue: the read blocks silently while the child works). While a read waits
428
- // on `waitForTerminal` it periodically samples the CHILD session's messages
429
- // via the same `client.session.messages` the finalize path uses, and the
430
- // collected lines are appended to the report as `## Agent Activity`.
431
- //
432
- // Fail-open by design: a missing/throwing `session.messages` (or empty
433
- // response) degrades to the current behavior — report without a section —
434
- // and NEVER breaks the read. No streaming/SSE, no persistent timers: the
435
- // poll lives inside the read's existing wait and is cleared when it settles.
436
-
437
- /** Cap for one activity line (~200 chars, spec). */
438
- const ACTIVITY_LINE_MAX = 200
439
- /** How often the read re-samples child activity while waiting (ms). */
440
- const ACTIVITY_POLL_MS = 2000
441
- /** Keep only the latest N readable entries per sample. */
442
- const ACTIVITY_LINES = 3
443
-
444
- /**
445
- * Mutable collector shared between the wait loop and the read result.
446
- * `sampled` distinguishes "messages unavailable/never succeeded" (fail-open
447
- * → NO activity section, current behavior) from "messages OK but nothing
448
- * readable" (→ `_no activity captured_` section).
449
- */
450
- interface ActivityCollector {
451
- /** Readable activity lines captured so far (latest window). */
452
- lines: string[]
453
- /** True once session.messages returned a bundle list at least once. */
454
- sampled: boolean
455
- }
456
-
457
- /** Collapse whitespace and cap a single line at ~200 chars. */
458
- function truncateActivityLine(text: string, max = ACTIVITY_LINE_MAX): string {
459
- const clean = text.replace(/\s+/g, ' ').trim()
460
- if (clean.length <= max) return clean
461
- return `${clean.slice(0, max - 1)}…`
462
- }
463
-
464
- /** Readable tool args from a tool part (SDK ToolPart.metadata.input), or ''. */
465
- function toolArgsFromPart(part: { metadata?: { input?: unknown } }): string {
466
- const meta = part.metadata
467
- const raw = meta !== undefined && 'input' in meta ? meta.input : meta
468
- if (raw === undefined) return ''
469
- try {
470
- const s = typeof raw === 'string' ? raw : JSON.stringify(raw)
471
- return s === '' || s === '{}' ? '' : s
472
- } catch {
473
- return ''
474
- }
475
- }
476
-
477
- /**
478
- * One readable activity line per message bundle — tool calls first (highest
479
- * signal), then the first non-empty text part. Image/attachment/reasoning
480
- * parts are skipped (only `text` and `tool` parts are user-visible).
481
- */
482
- function activityLineFromBundle(bundle: DelegationMessageBundle): string | undefined {
483
- const role = bundle.info?.role
484
- const parts = bundle.parts ?? []
485
- for (const part of parts) {
486
- if (part.type === 'tool' && typeof part.tool === 'string' && part.tool !== '') {
487
- const args = toolArgsFromPart(part)
488
- return truncateActivityLine(`tool: ${part.tool}${args !== '' ? ` ${args}` : ''}`)
489
- }
490
- }
491
- for (const part of parts) {
492
- if (part.type === 'text' && typeof part.text === 'string' && part.text.trim() !== '') {
493
- const label = role === 'user' ? 'user' : 'assistant'
494
- return truncateActivityLine(`${label}: ${part.text.trim()}`)
495
- }
496
- }
497
- return undefined
498
- }
499
-
500
- /**
501
- * Sample the child's latest readable activity into `collector` (replace
502
- * window). Fail-open: unavailable/throwing messages leaves the collector
503
- * untouched (previous lines, or none → `_no activity captured_`), while a
504
- * successful (even empty) response marks the collector as sampled.
505
- */
506
- async function sampleChildActivity(
507
- client: DelegationClient,
508
- childSessionID: string,
509
- collector: ActivityCollector,
510
- ): Promise<void> {
511
- if (typeof client.session.messages !== 'function') return
512
- try {
513
- const bundles = await client.session.messages({ path: { id: childSessionID } })
514
- if (!Array.isArray(bundles)) return
515
- collector.sampled = true
516
- if (bundles.length === 0) return
517
- const fresh = bundles
518
- .map((b) => activityLineFromBundle(b))
519
- .filter((l): l is string => l !== undefined)
520
- .slice(-ACTIVITY_LINES)
521
- if (fresh.length > 0) {
522
- collector.lines.length = 0
523
- collector.lines.push(...fresh)
524
- }
525
- } catch (err: unknown) {
526
- const reason = err instanceof Error ? err.message : String(err)
527
- log.warn(`[pantheon-delegate] activity sample failed (fail-open): ${reason}`)
528
- }
529
- }
530
-
531
- /** Last readable activity line for a child, or undefined when unavailable. */
532
- async function lastChildActivity(
533
- client: DelegationClient,
534
- childSessionID: string,
535
- ): Promise<string | undefined> {
536
- if (typeof client.session.messages !== 'function') return undefined
537
- try {
538
- const bundles = await client.session.messages({ path: { id: childSessionID } })
539
- if (!Array.isArray(bundles)) return undefined
540
- for (let i = bundles.length - 1; i >= 0; i--) {
541
- const bundle = bundles[i]
542
- if (bundle === undefined) continue
543
- const line = activityLineFromBundle(bundle)
544
- if (line !== undefined) return line
545
- }
546
- return undefined
547
- } catch (err: unknown) {
548
- const reason = err instanceof Error ? err.message : String(err)
549
- log.warn(`[pantheon-delegate] last activity fetch failed (fail-open): ${reason}`)
550
- return undefined
551
- }
552
- }
553
-
554
- /**
555
- * Wait for a terminal board state while sampling the child's activity every
556
- * ACTIVITY_POLL_MS (first sample fires immediately — a quick finalize can
557
- * still capture something). The interval is cleared when the wait settles;
558
- * collection never delays the terminal resolution.
559
- */
560
- async function waitForTerminalWithActivity(
561
- board: BackgroundJobBoard,
562
- client: DelegationClient,
563
- taskID: string,
564
- timeoutMs: number,
565
- collector: ActivityCollector,
566
- ): Promise<BackgroundJobRecord> {
567
- void sampleChildActivity(client, taskID, collector)
568
- const timer = setInterval(() => {
569
- void sampleChildActivity(client, taskID, collector)
570
- }, ACTIVITY_POLL_MS)
571
- timer.unref()
572
- try {
573
- return await board.waitForTerminal(taskID, timeoutMs)
574
- } finally {
575
- clearInterval(timer)
576
- }
577
- }
578
-
579
- /** Render the trailing activity section appended to the read result. */
580
- export function formatActivitySection(lines: string[]): string {
581
- if (lines.length === 0) return '## Agent Activity\n\n_no activity captured_'
582
- return `## Agent Activity\n\n${lines.map((l) => `- ${l}`).join('\n')}`
583
- }
584
-
585
- // ─── Model resolution ──────────────────────────────────────────────────
586
-
587
- /** Session model ref accepted by the opencode server's session.create. */
588
- export interface ChildSessionModelRef {
589
- id: string
590
- providerID: string
591
- }
592
-
593
- const MODEL_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:+-]*$/
594
- const MODEL_REF_HINT =
595
- 'Expected a non-empty "provider/model-id" reference with exactly one slash, no whitespace/control characters, backslashes, or path traversal. Remove the override or use that format.'
596
-
597
- type ModelOverrideSource = 'explicit' | 'agentModels'
598
-
599
- function invalidModelOverride(source: ModelOverrideSource): string {
600
- return `pantheon_delegate rejected: invalid ${source} model override. ${MODEL_REF_HINT}`
601
- }
602
-
603
- /**
604
- * Split a `provider/model` model ID (e.g. `opencode/deepseek-v4-flash-free`)
605
- * into the `{ id, providerID }` ref the session.create body expects.
606
- * Returns undefined for malformed or unsafe IDs.
607
- */
608
- function splitModelRef(model: unknown): ChildSessionModelRef | undefined {
609
- if (typeof model !== 'string' || !MODEL_REF_PATTERN.test(model)) return undefined
610
- const slash = model.indexOf('/')
611
- return { providerID: model.slice(0, slash), id: model.slice(slash + 1) }
612
- }
613
-
614
- /**
615
- * Resolve the child session model from explicit or agent-specific overrides.
616
- * When neither override is present, return undefined so OpenCode can apply
617
- * native model inheritance.
618
- */
619
- function resolveChildModel(
620
- options: DelegationOptions,
621
- agent: string,
622
- explicitModel?: string,
623
- ): { model: ChildSessionModelRef | undefined; error: string | undefined } {
624
- // (a) explicit model option on the delegate tool call
625
- if (explicitModel !== undefined) {
626
- const ref = splitModelRef(explicitModel)
627
- if (ref !== undefined) return { model: ref, error: undefined }
628
- return { model: undefined, error: invalidModelOverride('explicit') }
629
- }
630
- const key = agent.toLowerCase()
631
- // (b) agent-specific model override (routing.yml agent entry via agentModels)
632
- const mapped = options.agentModels?.[key]
633
- if (mapped !== undefined) {
634
- const ref = splitModelRef(mapped)
635
- if (ref !== undefined) return { model: ref, error: undefined }
636
- return { model: undefined, error: invalidModelOverride('agentModels') }
637
- }
638
- return { model: undefined, error: undefined }
639
- }
640
-
641
- /**
642
- * Resolve a child model without selecting a provider or model on the caller's
643
- * behalf. OpenCode owns native inheritance when this returns no model; if the
644
- * host requires one, its session.create/promptAsync error is returned with
645
- * the normal diagnostic rather than silently choosing a fallback.
646
- *
647
- * @returns `{ model, error }` — at most one of `model` / `error` is set;
648
- * both may be unset (no model resolved, warn emitted).
649
- */
650
- function resolveUsableChildModel(
651
- options: DelegationOptions,
652
- agent: string,
653
- explicitModel: string | undefined,
654
- ): { model: ChildSessionModelRef | undefined; error: string | undefined } {
655
- const resolved = resolveChildModel(options, agent, explicitModel)
656
- if (resolved.error !== undefined || resolved.model !== undefined) return resolved
657
- options.logger?.warn?.(
658
- `[pantheon-delegate] no model resolved for agent "${agent}" — ` +
659
- 'omitting model so OpenCode can inherit it from the parent session',
660
- )
661
- return resolved
662
- }
663
-
664
- // ─── Factory ───────────────────────────────────────────────────────────
665
-
666
- /**
667
- * Pure helper: collect the IDs of root sessions (parentID === undefined)
668
- * from a session list. Used to SEED the depth-guard allowlist at startup —
669
- * opencode does not replay `session.created` events for sessions that exist
670
- * before plugin load, so a resumed root would never enter `rootSessions`
671
- * and the depth guard would reject its pantheon_delegate calls after a
672
- * restart. Fail-open contract lives at the call site (plugin.ts): a failed
673
- * `session.list()` leaves the registry untouched, never crashes startup.
674
- */
675
- export function collectRootSessionIDs(
676
- sessions: ReadonlyArray<{ id: string; parentID?: string }>,
677
- ): Set<string> {
678
- const roots = new Set<string>()
679
- for (const session of sessions) {
680
- if (session.parentID === undefined) roots.add(session.id)
681
- }
682
- return roots
683
- }
684
-
685
- /**
686
- * Build the delegation toolset. Keeps per-instance state: the set of child
687
- * sessions WE created (depth-guard default) and the per-job timeout timers
688
- * (cleared on finalize, `.unref()`'d so they never hold the process open).
689
- */
690
- export function createDelegationTools(input: CreateDelegationToolsInput): DelegationToolset {
691
- const { board, client } = input
692
- // Runtime matrix enforcement is the safe default for every host. A legacy
693
- // structural embedder must opt out explicitly with `false`; omission must
694
- // never silently widen the delegation surface.
695
- const options: DelegationOptions = { enforceRuntimeMatrix: true, ...(input.options ?? {}) }
696
- const deps: DelegationDeps = { board, client, options }
697
- const outputDir = options.outputDir ?? DELEGATION_DEFAULTS.outputDir
698
- const timeoutMs = options.wallClockTimeoutMs ?? options.timeoutMs ?? DELEGATION_DEFAULTS.timeoutMs
699
- const readTimeoutMs = options.readTimeoutMs ?? DELEGATION_DEFAULTS.readTimeoutMs
700
-
701
- const knownChildren = new Set<string>()
702
- const timers = new Map<string, NodeJS.Timeout>()
703
- // Fase B3: per-parent-session delegation budget tracking, scoped to this
704
- // factory/process instance. Keyed by `${parentSessionID}:${parentAgent}->${targetAgent}`;
705
- // it is not restart-persistent because the factory has no reliable store.
706
- const budgetUsage = new Map<string, number>()
707
-
708
- function isRootSession(sessionID: string): boolean {
709
- if (options.isChildSession?.(sessionID) === true) return false
710
- if (options.isRootSession !== undefined) return options.isRootSession(sessionID)
711
- if (options.rootSessions !== undefined) {
712
- // compaction-134 (fix layer 2): the allowlist alone is NOT
713
- // authoritative. opencode does not replay `session.created` events for
714
- // pre-existing sessions, so after a restart the resumed root never
715
- // entered rootSessions (the plugin seeds it from session.list() at
716
- // startup, but that seed is fail-open). A session is a sub-session
717
- // ONLY if WE created it as a child (knownChildren — filled on every
718
- // pantheon_delegate dispatch). Everything unknown is treated as root:
719
- // resumed/unknown sessions can delegate, while the real depth guard
720
- // (a child of a delegate cannot re-delegate) is preserved.
721
- return options.rootSessions.has(sessionID) || !knownChildren.has(sessionID)
722
- }
723
- return !knownChildren.has(sessionID)
724
- }
725
-
726
- function clearTimer(childSessionID: string): void {
727
- const timer = timers.get(childSessionID)
728
- if (timer !== undefined) {
729
- clearTimeout(timer)
730
- timers.delete(childSessionID)
731
- }
732
- }
733
-
734
- /** Bound finalize: clear the job timer, then run the report + transition. */
735
- async function finalize(
736
- childSessionID: string,
737
- opts: FinalizeInput,
738
- ): Promise<BackgroundJobRecord | undefined> {
739
- clearTimer(childSessionID)
740
- return finalizeDelegationReport(deps, childSessionID, opts)
741
- }
742
-
743
- const pantheon_delegate: DelegationTool<typeof delegateArgs> = {
744
- description: buildDelegateDescription(options),
745
- args: delegateArgs,
746
- execute: async (args, ctx) => {
747
- if (!isRootSession(ctx.sessionID)) {
748
- throw new Error(
749
- `pantheon_delegate rejected: session ${ctx.sessionID} is a sub-session — only root sessions can delegate`,
750
- )
751
- }
752
- if (!board.canDispatch(args.agent)) {
753
- throw new Error(
754
- `pantheon_delegate rejected: concurrency limit reached for agent "${args.agent}" ` +
755
- `(${board.getRunningCount(args.agent)} running)`,
756
- )
757
- }
758
-
759
- // R4: per-agent step caps. An agent already at max_steps is forced to
760
- // summarize-and-stop — the delegation is skipped with a capped summary
761
- // (no session, no board job, no budget consumed). Otherwise record the
762
- // step; when THIS step hits the cap, append the stop instruction to
763
- // the prompt so the agent summarizes and stops instead of continuing.
764
- let effectivePrompt = args.prompt
765
- const stepCap = options.stepCapTracker
766
- if (stepCap !== undefined) {
767
- const maxSteps = stepCap.maxStepsFor(args.agent)
768
- if (stepCap.isCapped(args.agent)) {
769
- return cappedSummary(args.agent, maxSteps ?? DEFAULT_MAX_STEPS)
770
- }
771
- const rec = stepCap.recordStep(args.agent)
772
- if (rec.capped && rec.maxSteps !== undefined) {
773
- effectivePrompt = `${args.prompt}${buildStopInstruction(args.agent, rec.maxSteps)}`
774
- }
775
- }
776
-
777
- // Fase B3: only the two read-only exceptions are budgeted. The official
778
- // SDK provides the current agent on ToolContext. If a structural/older
779
- // host omits it, do NOT infer identity from prompt, target, or process
780
- // state: the budget is explicitly skipped and the delegation continues.
781
- const parentAgent = normalizeToolAgent(ctx.agent)
782
- const targetAgent = args.agent.toLowerCase()
783
- if (
784
- options.enforceRuntimeMatrix === true &&
785
- !isDelegationAllowed(parentAgent, targetAgent, options.permissionTask)
786
- ) {
787
- const reason =
788
- parentAgent === undefined
789
- ? 'ToolContext.agent is unavailable'
790
- : `${parentAgent}->${targetAgent} is not allowed`
791
- options.logger?.warn?.(
792
- `[pantheon-delegate] runtime delegation denied for session ${ctx.sessionID}: ${reason}`,
793
- )
794
- throw new Error(`pantheon_delegate rejected: runtime delegation matrix denied (${reason})`)
795
- }
796
- if (
797
- parentAgent === undefined &&
798
- !options.enforceRuntimeMatrix &&
799
- (options.delegationBudgets?.size ?? 0) > 0
800
- ) {
801
- const message =
802
- `[pantheon-delegate] B3 budget skipped: current agent unavailable for session ${ctx.sessionID}; ` +
803
- `no budget limit applied to ${targetAgent}. Runtime must provide ToolContext.agent ` +
804
- '(the official SDK field) to enforce the configured exception budget.'
805
- ;(options.logger?.warn ?? ((msg: string) => log.warn(msg)))(message)
806
- }
807
- const budgetKey =
808
- parentAgent === undefined ? undefined : `${ctx.sessionID}:${parentAgent}->${targetAgent}`
809
- const budget =
810
- parentAgent === undefined
811
- ? undefined
812
- : options.delegationBudgets?.get(`${parentAgent}->${targetAgent}`)
813
- let budgetReserved = false
814
- if (budgetKey !== undefined && budget !== undefined) {
815
- const used = budgetUsage.get(budgetKey) ?? 0
816
- if (used >= budget) {
817
- throw new Error(
818
- `pantheon_delegate rejected: delegation budget exhausted for ${parentAgent}->${targetAgent} ` +
819
- `(${used}/${budget} dispatches used in this session). ` +
820
- 'Configure the corresponding PANTHEON_*_APOLLO_BUDGET environment variable or DelegationOptions.',
821
- )
822
- }
823
- // Reserve before the first await so concurrent calls cannot overshoot.
824
- budgetUsage.set(budgetKey, used + 1)
825
- budgetReserved = true
826
- }
827
-
828
- // session.create failure → return a clear error as TEXT (tools return
829
- // errors as text, not thrown) and register NO job on the board — an
830
- // unhandled rejection here would otherwise lose the failure entirely.
831
- // Resolution order: explicit delegate model > active-preset agent model
832
- // > omit (native inheritance). small_model is never used for delegated
833
- // children.
834
- const resolved = resolveUsableChildModel(options, args.agent, args.model)
835
- if (resolved.error !== undefined) {
836
- if (budgetReserved && budgetKey !== undefined)
837
- budgetUsage.set(budgetKey, (budgetUsage.get(budgetKey) ?? 1) - 1)
838
- return resolved.error
839
- }
840
- const childModel = resolved.model
841
- let created: { id: string }
842
- try {
843
- created = await client.session.create({
844
- body: {
845
- parentID: ctx.sessionID,
846
- title: args.description ?? effectivePrompt.slice(0, 80),
847
- ...(childModel !== undefined ? { model: childModel } : {}),
848
- },
849
- })
850
- } catch (err: unknown) {
851
- const reason = err instanceof Error ? err.message : String(err)
852
- if (budgetReserved && budgetKey !== undefined) {
853
- budgetUsage.set(budgetKey, Math.max(0, (budgetUsage.get(budgetKey) ?? 1) - 1))
854
- }
855
- return `pantheon_delegate failed to create child session: ${reason}`
856
- }
857
- const childSessionID = created.id
858
- knownChildren.add(childSessionID)
859
- options.registerChildSession?.(childSessionID, ctx.sessionID)
860
-
861
- // Phase 4 read-only enforcement: register the child session in the
862
- // read-only registry when the delegate is read-only — explicit
863
- // `read_only: true` on the call, or the agent ∈ readOnlyAgents
864
- // (case-insensitive). The plugin's tool.execute.before guard then
865
- // denies edit/write/bash/task inside that session.
866
- const readOnly =
867
- args.read_only === true || (options.readOnlyAgents?.has(args.agent.toLowerCase()) ?? false)
868
- if (readOnly) {
869
- const entry: { agent: string; readOnlyFlag?: boolean } = { agent: args.agent }
870
- if (args.read_only !== undefined) entry.readOnlyFlag = args.read_only
871
- readOnlyRegistry.register(childSessionID, entry)
872
- }
873
-
874
- const job = await board.registerLaunch({
875
- taskID: childSessionID,
876
- parentSessionID: ctx.sessionID,
877
- agent: args.agent,
878
- description: args.description ?? effectivePrompt,
879
- objective: effectivePrompt,
880
- })
881
-
882
- // Timeout manager: cleared on finalize, unref'd so the timer never
883
- // keeps the process alive on its own.
884
- const timer = setTimeout(() => {
885
- timers.delete(childSessionID)
886
- void finalize(childSessionID, {
887
- state: 'error',
888
- error: `Delegation [${job.alias}] timed out after ${timeoutMs}ms without reaching a terminal state`,
889
- timedOut: true,
890
- }).catch((err: unknown) => log.error('[pantheon-delegate] timeout finalize failed:', err))
891
- }, timeoutMs)
892
- timer.unref()
893
- timers.set(childSessionID, timer)
894
-
895
- const promptBody = {
896
- agent: args.agent,
897
- ...(childModel !== undefined ? { model: childModel } : {}),
898
- parts: [{ type: 'text' as const, text: effectivePrompt }],
899
- }
900
- const promptOutcome = await promptWithTimeout(
901
- client,
902
- { path: { id: childSessionID }, body: promptBody },
903
- options.promptTimeoutMs ?? options.bootstrapTimeoutMs ?? BOOTSTRAP_TIMEOUT_MS,
904
- )
905
- let bootstrap: BootstrapOutcome
906
- let safeRetry = false
907
- if (promptOutcome.status === 'rejected') {
908
- // A synchronous rejection is the only safe automatic retry signal: the
909
- // host explicitly told us that it did not accept the request.
910
- bootstrap = {
911
- status: 'startup_failed',
912
- elapsedMs: 0,
913
- reason: `promptAsync rejected: ${promptOutcome.reason}`,
914
- }
915
- safeRetry = true
916
- } else if (promptOutcome.status === 'timeout') {
917
- // A timeout is ambiguous: the server may have accepted the prompt even
918
- // though the client never received its response. Never resend it.
919
- bootstrap = { status: 'startup_failed', elapsedMs: 0, reason: promptOutcome.reason }
920
- } else {
921
- bootstrap = await bootstrapChild(client, childSessionID, promptOutcome.value, options)
922
- }
923
- log.info(
924
- `[pantheon-delegate] bootstrap child=${childSessionID} elapsed=${bootstrap.elapsedMs}ms reason=${bootstrap.reason}`,
925
- )
926
- if (bootstrap.status === 'started') {
927
- return (
928
- `Delegated to ${args.agent}: [${job.alias}] (task ${childSessionID}).\n` +
929
- `Read the result with pantheon_delegation_read({ id: "${job.alias}" }).`
930
- )
931
- }
932
-
933
- // Every startup diagnosis is terminal for this child. Only a prompt
934
- // rejection (known not accepted) permits one fresh-session retry;
935
- // accepted-empty, unavailable APIs, and request timeouts do not.
936
- const boardStartupState =
937
- bootstrap.status === 'bootstrap_unknown' ? 'startup_unknown' : 'startup_failed'
938
- await finalize(childSessionID, {
939
- state: boardStartupState,
940
- error: `${bootstrap.status}: ${bootstrap.reason}`,
941
- })
942
- if (!safeRetry) {
943
- const finalResult: DelegationResult = {
944
- status: bootstrap.status,
945
- content: `Child session ${childSessionID} did not start (${bootstrap.reason}).`,
946
- retryCount: 0,
947
- recommendation:
948
- bootstrap.status === 'bootstrap_unknown'
949
- ? 'Inspect the child session in the board/TUI and retry manually only after confirming the prompt was not accepted.'
950
- : 'Inspect the child session/host promptAsync implementation; no automatic retry was attempted because acceptance was ambiguous.',
951
- }
952
- return formatDelegationResult(finalResult)
953
- }
954
-
955
- let retry: { id: string }
956
- try {
957
- retry = await client.session.create({
958
- body: {
959
- parentID: ctx.sessionID,
960
- title: args.description ?? effectivePrompt.slice(0, 80),
961
- ...(childModel !== undefined ? { model: childModel } : {}),
962
- },
963
- })
964
- } catch (err: unknown) {
965
- const reason = err instanceof Error ? err.message : String(err)
966
- return `[STARTUP FAILED] ${bootstrap.status}: ${bootstrap.reason}; retry creation failed: ${reason}`
967
- }
968
- const retryID = retry.id
969
- knownChildren.add(retryID)
970
- options.registerChildSession?.(retryID, ctx.sessionID)
971
- const retryJob = await board.registerLaunch({
972
- taskID: retryID,
973
- parentSessionID: ctx.sessionID,
974
- agent: args.agent,
975
- description: args.description ?? effectivePrompt,
976
- objective: effectivePrompt,
977
- })
978
- const retryTimer = setTimeout(() => {
979
- timers.delete(retryID)
980
- void finalize(retryID, {
981
- state: 'error',
982
- error: `Delegation [${retryJob.alias}] timed out after ${timeoutMs}ms without reaching a terminal state`,
983
- timedOut: true,
984
- }).catch((err: unknown) =>
985
- log.error('[pantheon-delegate] retry timeout finalize failed:', err),
986
- )
987
- }, timeoutMs)
988
- retryTimer.unref()
989
- timers.set(retryID, retryTimer)
990
- const retryPrompt = await promptWithTimeout(
991
- client,
992
- { path: { id: retryID }, body: promptBody },
993
- options.promptTimeoutMs ?? options.bootstrapTimeoutMs ?? BOOTSTRAP_TIMEOUT_MS,
994
- )
995
- let retryBootstrap: BootstrapOutcome
996
- if (retryPrompt.status === 'rejected') {
997
- retryBootstrap = {
998
- status: 'startup_failed',
999
- elapsedMs: 0,
1000
- reason: `retry promptAsync rejected: ${retryPrompt.reason}`,
1001
- }
1002
- } else if (retryPrompt.status === 'timeout') {
1003
- retryBootstrap = { status: 'startup_failed', elapsedMs: 0, reason: retryPrompt.reason }
1004
- } else {
1005
- retryBootstrap = await bootstrapChild(client, retryID, retryPrompt.value, options)
1006
- }
1007
- log.info(
1008
- `[pantheon-delegate] bootstrap retry child=${retryID} elapsed=${retryBootstrap.elapsedMs}ms reason=${retryBootstrap.reason}`,
1009
- )
1010
- if (retryBootstrap.status === 'started') {
1011
- return (
1012
- `Delegated to ${args.agent}: [${retryJob.alias}] (task ${retryID}); retry=1.\n` +
1013
- `Read the result with pantheon_delegation_read({ id: "${retryJob.alias}" }).`
1014
- )
1015
- }
1016
- await finalize(retryID, {
1017
- state: retryBootstrap.status === 'bootstrap_unknown' ? 'startup_unknown' : 'startup_failed',
1018
- error: `startup retry exhausted: ${retryBootstrap.status}: ${retryBootstrap.reason}`,
1019
- })
1020
- const finalResult: DelegationResult = {
1021
- status: retryBootstrap.status,
1022
- content: `Child session ${retryID} did not start (${retryBootstrap.reason}).`,
1023
- retryCount: 1,
1024
- recommendation:
1025
- 'Inspect the child session/host promptAsync implementation; no further automatic retries will be attempted.',
1026
- }
1027
- return formatDelegationResult(finalResult)
1028
- },
1029
- }
1030
-
1031
- const pantheon_delegation_read: DelegationTool<typeof readArgs> = {
1032
- description:
1033
- 'Block until a background delegation finishes (completed/error/cancelled), then return its ' +
1034
- 'report markdown (with a trailing agent-activity section) and mark the job reconciled. ' +
1035
- 'Resolves by alias or task ID.',
1036
- args: readArgs,
1037
- execute: async (args, ctx) => {
1038
- const job = board.resolve(ctx.sessionID, args.id)
1039
- if (!job) {
1040
- return `Unknown delegation "${args.id}" for this session. Use pantheon_delegation_list to see active delegations.`
1041
- }
1042
-
1043
- // Sample the child's messages while waiting so the caller sees what the
1044
- // agent is doing — fail-open: no messages support → report as before.
1045
- const collector: ActivityCollector = { lines: [], sampled: false }
1046
- let terminal: BackgroundJobRecord
1047
- try {
1048
- terminal = await waitForTerminalWithActivity(
1049
- board,
1050
- client,
1051
- job.taskID,
1052
- readTimeoutMs,
1053
- collector,
1054
- )
1055
- } catch {
1056
- return `Timed out after ${readTimeoutMs}ms waiting for delegation "${args.id}" ([${job.alias}]).`
1057
- }
1058
-
1059
- const md = await readDelegationReport(outputDir, terminal)
1060
- if (md === undefined) {
1061
- return `Delegation [${terminal.alias}] reached state ${terminal.state} but no report file was found.`
1062
- }
1063
-
1064
- // Classify the result for stuck-agent detection
1065
- const classification = classifyStuckAgent(md)
1066
- const hasActivity = collector.sampled || collector.lines.length > 0
1067
- const activitySuffix = hasActivity ? `\n\n${formatActivitySection(collector.lines)}` : ''
1068
-
1069
- if (classification.status === 'success') {
1070
- await board.markReconciled(job.taskID)
1071
- // Backward compatible: success reports returned as-is
1072
- if (!hasActivity) return md
1073
- return `${md.replace(/\n+$/, '')}${activitySuffix}`
1074
- }
1075
-
1076
- // Non-success: build structured DelegationResult and format
1077
- const delegationResult: DelegationResult = {
1078
- status: classification.status === 'empty' ? 'empty' : classification.status,
1079
- content: md,
1080
- retryCount: 0,
1081
- partialResult: classification.partialResult,
1082
- recommendation: classification.recommendation,
1083
- }
1084
-
1085
- await board.markReconciled(job.taskID)
1086
- const formatted = formatDelegationResult(delegationResult)
1087
- return `${formatted}${activitySuffix}`
1088
- },
1089
- }
1090
-
1091
- const pantheon_delegation_list: DelegationTool<typeof listArgs> = {
1092
- description:
1093
- 'List background delegations for the current session, with [unread] for finished jobs.',
1094
- args: listArgs,
1095
- execute: async (_args, ctx) => {
1096
- const jobs = board.list(ctx.sessionID)
1097
- if (jobs.length === 0) return 'No background delegations for this session.'
1098
-
1099
- const lines = await Promise.all(
1100
- jobs.map(async (j) => {
1101
- const unread = j.terminalUnreconciled ? ' [unread]' : ''
1102
- const base = ` [${j.alias}] ${j.agent} — ${j.description} — ${stateLabel(j.state)}${unread}`
1103
- // Running jobs get a live `last activity:` line (fail-open fetch).
1104
- if (j.state !== 'running') return base
1105
- const last = await lastChildActivity(client, j.taskID)
1106
- return last === undefined ? base : `${base}\n last activity: ${last}`
1107
- }),
1108
- )
1109
- return `Background Delegations (${jobs.length}):\n${lines.join('\n')}`
1110
- },
1111
- }
1112
-
1113
- return {
1114
- pantheon_delegate,
1115
- pantheon_delegation_read,
1116
- pantheon_delegation_list,
1117
- finalizeDelegation: finalize,
1118
- finalizeIdleChildrenWithoutMd,
1119
- }
1120
- }