pantheon-opencode 1.5.0-beta.9 → 1.5.1

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