pantheon-opencode 1.4.1 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +175 -147
- package/bin/pantheon-init.mjs +7 -0
- package/commands/pantheon-model.md +34 -0
- package/package.json +2 -2
- package/scripts/generate-preset-docs.mjs +239 -0
- package/scripts/install/model-picker.mjs +367 -2
- package/scripts/install/opencode.mjs +150 -137
- package/src/agents/zeus.md +14 -25
- package/src/pantheon/cost-command.ts +7 -7
- package/src/pantheon/delegation-enforce.ts +12 -13
- package/src/pantheon/goal-loop.ts +2 -2
- package/src/pantheon/goal-store.ts +1 -1
- package/src/pantheon/hashline/tool.ts +2 -2
- package/src/pantheon/model-command.ts +911 -0
- package/src/pantheon/presets.mjs +30 -33
- package/src/pantheon/tool-context.ts +41 -0
- package/src/plugin.ts +45 -193
- package/src/plugins/tui/dist/tui.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/dist/tui.tsx +13 -2
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
- package/src/plugins/tui/src/index.tsx +21 -8
- package/src/plugins/tui/tsdown.config.ts +11 -0
- package/src/routing.yml +71 -123
- package/src/pantheon/delegation-classifier.ts +0 -307
- package/src/pantheon/delegation-finalize.ts +0 -374
- package/src/pantheon/delegation-notify.ts +0 -197
- package/src/pantheon/delegation-toast.ts +0 -73
- package/src/pantheon/delegation.ts +0 -1110
- package/src/pantheon/permission-eval.ts +0 -284
- package/src/pantheon/step-cap.ts +0 -110
- package/src/pantheon/zeus-delegate-with-retry.ts +0 -401
|
@@ -1,1110 +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
|
-
/**
|
|
594
|
-
* Split a `provider/model` model ID (e.g. `opencode/deepseek-v4-flash-free`)
|
|
595
|
-
* into the `{ id, providerID }` ref the session.create body expects.
|
|
596
|
-
* Returns undefined for malformed IDs (no slash, empty segments).
|
|
597
|
-
*/
|
|
598
|
-
function splitModelRef(model: string): ChildSessionModelRef | undefined {
|
|
599
|
-
const slash = model.indexOf('/')
|
|
600
|
-
if (slash <= 0 || slash === model.length - 1) return undefined
|
|
601
|
-
return { providerID: model.slice(0, slash), id: model.slice(slash + 1) }
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
/**
|
|
605
|
-
* Resolve only an explicitly supplied model. A routing profile's `model` is
|
|
606
|
-
* passed through as `options.agentModels`; profiles without one, and agents
|
|
607
|
-
* without a profile, intentionally resolve to undefined so the OpenCode
|
|
608
|
-
* parent session can provide inheritance.
|
|
609
|
-
*/
|
|
610
|
-
function resolveChildModel(
|
|
611
|
-
options: DelegationOptions,
|
|
612
|
-
agent: string,
|
|
613
|
-
explicitModel?: string,
|
|
614
|
-
): ChildSessionModelRef | undefined {
|
|
615
|
-
// (a) explicit model option on the delegate tool call
|
|
616
|
-
if (explicitModel !== undefined && explicitModel !== '') {
|
|
617
|
-
const ref = splitModelRef(explicitModel)
|
|
618
|
-
if (ref !== undefined) return ref
|
|
619
|
-
}
|
|
620
|
-
const key = agent.toLowerCase()
|
|
621
|
-
// (b) routing.yml agent entry wired through options.agentModels
|
|
622
|
-
const mapped = options.agentModels?.[key]
|
|
623
|
-
if (mapped !== undefined && mapped !== '') {
|
|
624
|
-
const ref = splitModelRef(mapped)
|
|
625
|
-
if (ref !== undefined) return ref
|
|
626
|
-
}
|
|
627
|
-
return undefined
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
/**
|
|
631
|
-
* Resolve a child model without selecting a provider or model on the caller's
|
|
632
|
-
* behalf. OpenCode owns model inheritance when this returns no model; if the
|
|
633
|
-
* host requires one, its session.create/promptAsync error is returned with
|
|
634
|
-
* the normal diagnostic rather than silently choosing a fallback.
|
|
635
|
-
*
|
|
636
|
-
* @returns `{ model, error }` — at most one of `model` / `error` is set;
|
|
637
|
-
* both may be unset (no model resolved, warn emitted).
|
|
638
|
-
*/
|
|
639
|
-
function resolveUsableChildModel(
|
|
640
|
-
options: DelegationOptions,
|
|
641
|
-
agent: string,
|
|
642
|
-
explicitModel: string | undefined,
|
|
643
|
-
): { model: ChildSessionModelRef | undefined; error: string | undefined } {
|
|
644
|
-
const model = resolveChildModel(options, agent, explicitModel)
|
|
645
|
-
if (model === undefined) {
|
|
646
|
-
options.logger?.warn?.(
|
|
647
|
-
`[pantheon-delegate] no model resolved for agent "${agent}" — ` +
|
|
648
|
-
'omitting model so OpenCode can inherit it from the parent session',
|
|
649
|
-
)
|
|
650
|
-
return { model: undefined, error: undefined }
|
|
651
|
-
}
|
|
652
|
-
return { model, error: undefined }
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
// ─── Factory ───────────────────────────────────────────────────────────
|
|
656
|
-
|
|
657
|
-
/**
|
|
658
|
-
* Pure helper: collect the IDs of root sessions (parentID === undefined)
|
|
659
|
-
* from a session list. Used to SEED the depth-guard allowlist at startup —
|
|
660
|
-
* opencode does not replay `session.created` events for sessions that exist
|
|
661
|
-
* before plugin load, so a resumed root would never enter `rootSessions`
|
|
662
|
-
* and the depth guard would reject its pantheon_delegate calls after a
|
|
663
|
-
* restart. Fail-open contract lives at the call site (plugin.ts): a failed
|
|
664
|
-
* `session.list()` leaves the registry untouched, never crashes startup.
|
|
665
|
-
*/
|
|
666
|
-
export function collectRootSessionIDs(
|
|
667
|
-
sessions: ReadonlyArray<{ id: string; parentID?: string }>,
|
|
668
|
-
): Set<string> {
|
|
669
|
-
const roots = new Set<string>()
|
|
670
|
-
for (const session of sessions) {
|
|
671
|
-
if (session.parentID === undefined) roots.add(session.id)
|
|
672
|
-
}
|
|
673
|
-
return roots
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
/**
|
|
677
|
-
* Build the delegation toolset. Keeps per-instance state: the set of child
|
|
678
|
-
* sessions WE created (depth-guard default) and the per-job timeout timers
|
|
679
|
-
* (cleared on finalize, `.unref()`'d so they never hold the process open).
|
|
680
|
-
*/
|
|
681
|
-
export function createDelegationTools(input: CreateDelegationToolsInput): DelegationToolset {
|
|
682
|
-
const { board, client } = input
|
|
683
|
-
// Runtime matrix enforcement is the safe default for every host. A legacy
|
|
684
|
-
// structural embedder must opt out explicitly with `false`; omission must
|
|
685
|
-
// never silently widen the delegation surface.
|
|
686
|
-
const options: DelegationOptions = { enforceRuntimeMatrix: true, ...(input.options ?? {}) }
|
|
687
|
-
const deps: DelegationDeps = { board, client, options }
|
|
688
|
-
const outputDir = options.outputDir ?? DELEGATION_DEFAULTS.outputDir
|
|
689
|
-
const timeoutMs = options.wallClockTimeoutMs ?? options.timeoutMs ?? DELEGATION_DEFAULTS.timeoutMs
|
|
690
|
-
const readTimeoutMs = options.readTimeoutMs ?? DELEGATION_DEFAULTS.readTimeoutMs
|
|
691
|
-
|
|
692
|
-
const knownChildren = new Set<string>()
|
|
693
|
-
const timers = new Map<string, NodeJS.Timeout>()
|
|
694
|
-
// Fase B3: per-parent-session delegation budget tracking, scoped to this
|
|
695
|
-
// factory/process instance. Keyed by `${parentSessionID}:${parentAgent}->${targetAgent}`;
|
|
696
|
-
// it is not restart-persistent because the factory has no reliable store.
|
|
697
|
-
const budgetUsage = new Map<string, number>()
|
|
698
|
-
|
|
699
|
-
function isRootSession(sessionID: string): boolean {
|
|
700
|
-
if (options.isChildSession?.(sessionID) === true) return false
|
|
701
|
-
if (options.isRootSession !== undefined) return options.isRootSession(sessionID)
|
|
702
|
-
if (options.rootSessions !== undefined) {
|
|
703
|
-
// compaction-134 (fix layer 2): the allowlist alone is NOT
|
|
704
|
-
// authoritative. opencode does not replay `session.created` events for
|
|
705
|
-
// pre-existing sessions, so after a restart the resumed root never
|
|
706
|
-
// entered rootSessions (the plugin seeds it from session.list() at
|
|
707
|
-
// startup, but that seed is fail-open). A session is a sub-session
|
|
708
|
-
// ONLY if WE created it as a child (knownChildren — filled on every
|
|
709
|
-
// pantheon_delegate dispatch). Everything unknown is treated as root:
|
|
710
|
-
// resumed/unknown sessions can delegate, while the real depth guard
|
|
711
|
-
// (a child of a delegate cannot re-delegate) is preserved.
|
|
712
|
-
return options.rootSessions.has(sessionID) || !knownChildren.has(sessionID)
|
|
713
|
-
}
|
|
714
|
-
return !knownChildren.has(sessionID)
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
function clearTimer(childSessionID: string): void {
|
|
718
|
-
const timer = timers.get(childSessionID)
|
|
719
|
-
if (timer !== undefined) {
|
|
720
|
-
clearTimeout(timer)
|
|
721
|
-
timers.delete(childSessionID)
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
|
|
725
|
-
/** Bound finalize: clear the job timer, then run the report + transition. */
|
|
726
|
-
async function finalize(
|
|
727
|
-
childSessionID: string,
|
|
728
|
-
opts: FinalizeInput,
|
|
729
|
-
): Promise<BackgroundJobRecord | undefined> {
|
|
730
|
-
clearTimer(childSessionID)
|
|
731
|
-
return finalizeDelegationReport(deps, childSessionID, opts)
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
const pantheon_delegate: DelegationTool<typeof delegateArgs> = {
|
|
735
|
-
description: buildDelegateDescription(options),
|
|
736
|
-
args: delegateArgs,
|
|
737
|
-
execute: async (args, ctx) => {
|
|
738
|
-
if (!isRootSession(ctx.sessionID)) {
|
|
739
|
-
throw new Error(
|
|
740
|
-
`pantheon_delegate rejected: session ${ctx.sessionID} is a sub-session — only root sessions can delegate`,
|
|
741
|
-
)
|
|
742
|
-
}
|
|
743
|
-
if (!board.canDispatch(args.agent)) {
|
|
744
|
-
throw new Error(
|
|
745
|
-
`pantheon_delegate rejected: concurrency limit reached for agent "${args.agent}" ` +
|
|
746
|
-
`(${board.getRunningCount(args.agent)} running)`,
|
|
747
|
-
)
|
|
748
|
-
}
|
|
749
|
-
|
|
750
|
-
// R4: per-agent step caps. An agent already at max_steps is forced to
|
|
751
|
-
// summarize-and-stop — the delegation is skipped with a capped summary
|
|
752
|
-
// (no session, no board job, no budget consumed). Otherwise record the
|
|
753
|
-
// step; when THIS step hits the cap, append the stop instruction to
|
|
754
|
-
// the prompt so the agent summarizes and stops instead of continuing.
|
|
755
|
-
let effectivePrompt = args.prompt
|
|
756
|
-
const stepCap = options.stepCapTracker
|
|
757
|
-
if (stepCap !== undefined) {
|
|
758
|
-
const maxSteps = stepCap.maxStepsFor(args.agent)
|
|
759
|
-
if (stepCap.isCapped(args.agent)) {
|
|
760
|
-
return cappedSummary(args.agent, maxSteps ?? DEFAULT_MAX_STEPS)
|
|
761
|
-
}
|
|
762
|
-
const rec = stepCap.recordStep(args.agent)
|
|
763
|
-
if (rec.capped && rec.maxSteps !== undefined) {
|
|
764
|
-
effectivePrompt = `${args.prompt}${buildStopInstruction(args.agent, rec.maxSteps)}`
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
// Fase B3: only the two read-only exceptions are budgeted. The official
|
|
769
|
-
// SDK provides the current agent on ToolContext. If a structural/older
|
|
770
|
-
// host omits it, do NOT infer identity from prompt, target, or process
|
|
771
|
-
// state: the budget is explicitly skipped and the delegation continues.
|
|
772
|
-
const parentAgent = normalizeToolAgent(ctx.agent)
|
|
773
|
-
const targetAgent = args.agent.toLowerCase()
|
|
774
|
-
if (
|
|
775
|
-
options.enforceRuntimeMatrix === true &&
|
|
776
|
-
!isDelegationAllowed(parentAgent, targetAgent, options.permissionTask)
|
|
777
|
-
) {
|
|
778
|
-
const reason =
|
|
779
|
-
parentAgent === undefined
|
|
780
|
-
? 'ToolContext.agent is unavailable'
|
|
781
|
-
: `${parentAgent}->${targetAgent} is not allowed`
|
|
782
|
-
options.logger?.warn?.(
|
|
783
|
-
`[pantheon-delegate] runtime delegation denied for session ${ctx.sessionID}: ${reason}`,
|
|
784
|
-
)
|
|
785
|
-
throw new Error(`pantheon_delegate rejected: runtime delegation matrix denied (${reason})`)
|
|
786
|
-
}
|
|
787
|
-
if (
|
|
788
|
-
parentAgent === undefined &&
|
|
789
|
-
!options.enforceRuntimeMatrix &&
|
|
790
|
-
(options.delegationBudgets?.size ?? 0) > 0
|
|
791
|
-
) {
|
|
792
|
-
const message =
|
|
793
|
-
`[pantheon-delegate] B3 budget skipped: current agent unavailable for session ${ctx.sessionID}; ` +
|
|
794
|
-
`no budget limit applied to ${targetAgent}. Runtime must provide ToolContext.agent ` +
|
|
795
|
-
'(the official SDK field) to enforce the configured exception budget.'
|
|
796
|
-
;(options.logger?.warn ?? ((msg: string) => log.warn(msg)))(message)
|
|
797
|
-
}
|
|
798
|
-
const budgetKey =
|
|
799
|
-
parentAgent === undefined ? undefined : `${ctx.sessionID}:${parentAgent}->${targetAgent}`
|
|
800
|
-
const budget =
|
|
801
|
-
parentAgent === undefined
|
|
802
|
-
? undefined
|
|
803
|
-
: options.delegationBudgets?.get(`${parentAgent}->${targetAgent}`)
|
|
804
|
-
let budgetReserved = false
|
|
805
|
-
if (budgetKey !== undefined && budget !== undefined) {
|
|
806
|
-
const used = budgetUsage.get(budgetKey) ?? 0
|
|
807
|
-
if (used >= budget) {
|
|
808
|
-
throw new Error(
|
|
809
|
-
`pantheon_delegate rejected: delegation budget exhausted for ${parentAgent}->${targetAgent} ` +
|
|
810
|
-
`(${used}/${budget} dispatches used in this session). ` +
|
|
811
|
-
'Configure the corresponding PANTHEON_*_APOLLO_BUDGET environment variable or DelegationOptions.',
|
|
812
|
-
)
|
|
813
|
-
}
|
|
814
|
-
// Reserve before the first await so concurrent calls cannot overshoot.
|
|
815
|
-
budgetUsage.set(budgetKey, used + 1)
|
|
816
|
-
budgetReserved = true
|
|
817
|
-
}
|
|
818
|
-
|
|
819
|
-
// session.create failure → return a clear error as TEXT (tools return
|
|
820
|
-
// errors as text, not thrown) and register NO job on the board — an
|
|
821
|
-
// unhandled rejection here would otherwise lose the failure entirely.
|
|
822
|
-
// Only an explicit delegate model or routing profile model is sent.
|
|
823
|
-
// Otherwise omit it so OpenCode inherits the parent model.
|
|
824
|
-
const resolved = resolveUsableChildModel(options, args.agent, args.model)
|
|
825
|
-
if (resolved.error !== undefined) {
|
|
826
|
-
if (budgetReserved && budgetKey !== undefined)
|
|
827
|
-
budgetUsage.set(budgetKey, (budgetUsage.get(budgetKey) ?? 1) - 1)
|
|
828
|
-
return resolved.error
|
|
829
|
-
}
|
|
830
|
-
const childModel = resolved.model
|
|
831
|
-
let created: { id: string }
|
|
832
|
-
try {
|
|
833
|
-
created = await client.session.create({
|
|
834
|
-
body: {
|
|
835
|
-
parentID: ctx.sessionID,
|
|
836
|
-
title: args.description ?? effectivePrompt.slice(0, 80),
|
|
837
|
-
...(childModel !== undefined ? { model: childModel } : {}),
|
|
838
|
-
},
|
|
839
|
-
})
|
|
840
|
-
} catch (err: unknown) {
|
|
841
|
-
const reason = err instanceof Error ? err.message : String(err)
|
|
842
|
-
if (budgetReserved && budgetKey !== undefined) {
|
|
843
|
-
budgetUsage.set(budgetKey, Math.max(0, (budgetUsage.get(budgetKey) ?? 1) - 1))
|
|
844
|
-
}
|
|
845
|
-
return `pantheon_delegate failed to create child session: ${reason}`
|
|
846
|
-
}
|
|
847
|
-
const childSessionID = created.id
|
|
848
|
-
knownChildren.add(childSessionID)
|
|
849
|
-
options.registerChildSession?.(childSessionID, ctx.sessionID)
|
|
850
|
-
|
|
851
|
-
// Phase 4 read-only enforcement: register the child session in the
|
|
852
|
-
// read-only registry when the delegate is read-only — explicit
|
|
853
|
-
// `read_only: true` on the call, or the agent ∈ readOnlyAgents
|
|
854
|
-
// (case-insensitive). The plugin's tool.execute.before guard then
|
|
855
|
-
// denies edit/write/bash/task inside that session.
|
|
856
|
-
const readOnly =
|
|
857
|
-
args.read_only === true || (options.readOnlyAgents?.has(args.agent.toLowerCase()) ?? false)
|
|
858
|
-
if (readOnly) {
|
|
859
|
-
const entry: { agent: string; readOnlyFlag?: boolean } = { agent: args.agent }
|
|
860
|
-
if (args.read_only !== undefined) entry.readOnlyFlag = args.read_only
|
|
861
|
-
readOnlyRegistry.register(childSessionID, entry)
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
const job = await board.registerLaunch({
|
|
865
|
-
taskID: childSessionID,
|
|
866
|
-
parentSessionID: ctx.sessionID,
|
|
867
|
-
agent: args.agent,
|
|
868
|
-
description: args.description ?? effectivePrompt,
|
|
869
|
-
objective: effectivePrompt,
|
|
870
|
-
})
|
|
871
|
-
|
|
872
|
-
// Timeout manager: cleared on finalize, unref'd so the timer never
|
|
873
|
-
// keeps the process alive on its own.
|
|
874
|
-
const timer = setTimeout(() => {
|
|
875
|
-
timers.delete(childSessionID)
|
|
876
|
-
void finalize(childSessionID, {
|
|
877
|
-
state: 'error',
|
|
878
|
-
error: `Delegation [${job.alias}] timed out after ${timeoutMs}ms without reaching a terminal state`,
|
|
879
|
-
timedOut: true,
|
|
880
|
-
}).catch((err: unknown) => log.error('[pantheon-delegate] timeout finalize failed:', err))
|
|
881
|
-
}, timeoutMs)
|
|
882
|
-
timer.unref()
|
|
883
|
-
timers.set(childSessionID, timer)
|
|
884
|
-
|
|
885
|
-
const promptBody = {
|
|
886
|
-
agent: args.agent,
|
|
887
|
-
...(childModel !== undefined ? { model: childModel } : {}),
|
|
888
|
-
parts: [{ type: 'text' as const, text: effectivePrompt }],
|
|
889
|
-
}
|
|
890
|
-
const promptOutcome = await promptWithTimeout(
|
|
891
|
-
client,
|
|
892
|
-
{ path: { id: childSessionID }, body: promptBody },
|
|
893
|
-
options.promptTimeoutMs ?? options.bootstrapTimeoutMs ?? BOOTSTRAP_TIMEOUT_MS,
|
|
894
|
-
)
|
|
895
|
-
let bootstrap: BootstrapOutcome
|
|
896
|
-
let safeRetry = false
|
|
897
|
-
if (promptOutcome.status === 'rejected') {
|
|
898
|
-
// A synchronous rejection is the only safe automatic retry signal: the
|
|
899
|
-
// host explicitly told us that it did not accept the request.
|
|
900
|
-
bootstrap = {
|
|
901
|
-
status: 'startup_failed',
|
|
902
|
-
elapsedMs: 0,
|
|
903
|
-
reason: `promptAsync rejected: ${promptOutcome.reason}`,
|
|
904
|
-
}
|
|
905
|
-
safeRetry = true
|
|
906
|
-
} else if (promptOutcome.status === 'timeout') {
|
|
907
|
-
// A timeout is ambiguous: the server may have accepted the prompt even
|
|
908
|
-
// though the client never received its response. Never resend it.
|
|
909
|
-
bootstrap = { status: 'startup_failed', elapsedMs: 0, reason: promptOutcome.reason }
|
|
910
|
-
} else {
|
|
911
|
-
bootstrap = await bootstrapChild(client, childSessionID, promptOutcome.value, options)
|
|
912
|
-
}
|
|
913
|
-
log.info(
|
|
914
|
-
`[pantheon-delegate] bootstrap child=${childSessionID} elapsed=${bootstrap.elapsedMs}ms reason=${bootstrap.reason}`,
|
|
915
|
-
)
|
|
916
|
-
if (bootstrap.status === 'started') {
|
|
917
|
-
return (
|
|
918
|
-
`Delegated to ${args.agent}: [${job.alias}] (task ${childSessionID}).\n` +
|
|
919
|
-
`Read the result with pantheon_delegation_read({ id: "${job.alias}" }).`
|
|
920
|
-
)
|
|
921
|
-
}
|
|
922
|
-
|
|
923
|
-
// Every startup diagnosis is terminal for this child. Only a prompt
|
|
924
|
-
// rejection (known not accepted) permits one fresh-session retry;
|
|
925
|
-
// accepted-empty, unavailable APIs, and request timeouts do not.
|
|
926
|
-
const boardStartupState =
|
|
927
|
-
bootstrap.status === 'bootstrap_unknown' ? 'startup_unknown' : 'startup_failed'
|
|
928
|
-
await finalize(childSessionID, {
|
|
929
|
-
state: boardStartupState,
|
|
930
|
-
error: `${bootstrap.status}: ${bootstrap.reason}`,
|
|
931
|
-
})
|
|
932
|
-
if (!safeRetry) {
|
|
933
|
-
const finalResult: DelegationResult = {
|
|
934
|
-
status: bootstrap.status,
|
|
935
|
-
content: `Child session ${childSessionID} did not start (${bootstrap.reason}).`,
|
|
936
|
-
retryCount: 0,
|
|
937
|
-
recommendation:
|
|
938
|
-
bootstrap.status === 'bootstrap_unknown'
|
|
939
|
-
? 'Inspect the child session in the board/TUI and retry manually only after confirming the prompt was not accepted.'
|
|
940
|
-
: 'Inspect the child session/host promptAsync implementation; no automatic retry was attempted because acceptance was ambiguous.',
|
|
941
|
-
}
|
|
942
|
-
return formatDelegationResult(finalResult)
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
let retry: { id: string }
|
|
946
|
-
try {
|
|
947
|
-
retry = await client.session.create({
|
|
948
|
-
body: {
|
|
949
|
-
parentID: ctx.sessionID,
|
|
950
|
-
title: args.description ?? effectivePrompt.slice(0, 80),
|
|
951
|
-
...(childModel !== undefined ? { model: childModel } : {}),
|
|
952
|
-
},
|
|
953
|
-
})
|
|
954
|
-
} catch (err: unknown) {
|
|
955
|
-
const reason = err instanceof Error ? err.message : String(err)
|
|
956
|
-
return `[STARTUP FAILED] ${bootstrap.status}: ${bootstrap.reason}; retry creation failed: ${reason}`
|
|
957
|
-
}
|
|
958
|
-
const retryID = retry.id
|
|
959
|
-
knownChildren.add(retryID)
|
|
960
|
-
options.registerChildSession?.(retryID, ctx.sessionID)
|
|
961
|
-
const retryJob = await board.registerLaunch({
|
|
962
|
-
taskID: retryID,
|
|
963
|
-
parentSessionID: ctx.sessionID,
|
|
964
|
-
agent: args.agent,
|
|
965
|
-
description: args.description ?? effectivePrompt,
|
|
966
|
-
objective: effectivePrompt,
|
|
967
|
-
})
|
|
968
|
-
const retryTimer = setTimeout(() => {
|
|
969
|
-
timers.delete(retryID)
|
|
970
|
-
void finalize(retryID, {
|
|
971
|
-
state: 'error',
|
|
972
|
-
error: `Delegation [${retryJob.alias}] timed out after ${timeoutMs}ms without reaching a terminal state`,
|
|
973
|
-
timedOut: true,
|
|
974
|
-
}).catch((err: unknown) =>
|
|
975
|
-
log.error('[pantheon-delegate] retry timeout finalize failed:', err),
|
|
976
|
-
)
|
|
977
|
-
}, timeoutMs)
|
|
978
|
-
retryTimer.unref()
|
|
979
|
-
timers.set(retryID, retryTimer)
|
|
980
|
-
const retryPrompt = await promptWithTimeout(
|
|
981
|
-
client,
|
|
982
|
-
{ path: { id: retryID }, body: promptBody },
|
|
983
|
-
options.promptTimeoutMs ?? options.bootstrapTimeoutMs ?? BOOTSTRAP_TIMEOUT_MS,
|
|
984
|
-
)
|
|
985
|
-
let retryBootstrap: BootstrapOutcome
|
|
986
|
-
if (retryPrompt.status === 'rejected') {
|
|
987
|
-
retryBootstrap = {
|
|
988
|
-
status: 'startup_failed',
|
|
989
|
-
elapsedMs: 0,
|
|
990
|
-
reason: `retry promptAsync rejected: ${retryPrompt.reason}`,
|
|
991
|
-
}
|
|
992
|
-
} else if (retryPrompt.status === 'timeout') {
|
|
993
|
-
retryBootstrap = { status: 'startup_failed', elapsedMs: 0, reason: retryPrompt.reason }
|
|
994
|
-
} else {
|
|
995
|
-
retryBootstrap = await bootstrapChild(client, retryID, retryPrompt.value, options)
|
|
996
|
-
}
|
|
997
|
-
log.info(
|
|
998
|
-
`[pantheon-delegate] bootstrap retry child=${retryID} elapsed=${retryBootstrap.elapsedMs}ms reason=${retryBootstrap.reason}`,
|
|
999
|
-
)
|
|
1000
|
-
if (retryBootstrap.status === 'started') {
|
|
1001
|
-
return (
|
|
1002
|
-
`Delegated to ${args.agent}: [${retryJob.alias}] (task ${retryID}); retry=1.\n` +
|
|
1003
|
-
`Read the result with pantheon_delegation_read({ id: "${retryJob.alias}" }).`
|
|
1004
|
-
)
|
|
1005
|
-
}
|
|
1006
|
-
await finalize(retryID, {
|
|
1007
|
-
state: retryBootstrap.status === 'bootstrap_unknown' ? 'startup_unknown' : 'startup_failed',
|
|
1008
|
-
error: `startup retry exhausted: ${retryBootstrap.status}: ${retryBootstrap.reason}`,
|
|
1009
|
-
})
|
|
1010
|
-
const finalResult: DelegationResult = {
|
|
1011
|
-
status: retryBootstrap.status,
|
|
1012
|
-
content: `Child session ${retryID} did not start (${retryBootstrap.reason}).`,
|
|
1013
|
-
retryCount: 1,
|
|
1014
|
-
recommendation:
|
|
1015
|
-
'Inspect the child session/host promptAsync implementation; no further automatic retries will be attempted.',
|
|
1016
|
-
}
|
|
1017
|
-
return formatDelegationResult(finalResult)
|
|
1018
|
-
},
|
|
1019
|
-
}
|
|
1020
|
-
|
|
1021
|
-
const pantheon_delegation_read: DelegationTool<typeof readArgs> = {
|
|
1022
|
-
description:
|
|
1023
|
-
'Block until a background delegation finishes (completed/error/cancelled), then return its ' +
|
|
1024
|
-
'report markdown (with a trailing agent-activity section) and mark the job reconciled. ' +
|
|
1025
|
-
'Resolves by alias or task ID.',
|
|
1026
|
-
args: readArgs,
|
|
1027
|
-
execute: async (args, ctx) => {
|
|
1028
|
-
const job = board.resolve(ctx.sessionID, args.id)
|
|
1029
|
-
if (!job) {
|
|
1030
|
-
return `Unknown delegation "${args.id}" for this session. Use pantheon_delegation_list to see active delegations.`
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
// Sample the child's messages while waiting so the caller sees what the
|
|
1034
|
-
// agent is doing — fail-open: no messages support → report as before.
|
|
1035
|
-
const collector: ActivityCollector = { lines: [], sampled: false }
|
|
1036
|
-
let terminal: BackgroundJobRecord
|
|
1037
|
-
try {
|
|
1038
|
-
terminal = await waitForTerminalWithActivity(
|
|
1039
|
-
board,
|
|
1040
|
-
client,
|
|
1041
|
-
job.taskID,
|
|
1042
|
-
readTimeoutMs,
|
|
1043
|
-
collector,
|
|
1044
|
-
)
|
|
1045
|
-
} catch {
|
|
1046
|
-
return `Timed out after ${readTimeoutMs}ms waiting for delegation "${args.id}" ([${job.alias}]).`
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
|
-
const md = await readDelegationReport(outputDir, terminal)
|
|
1050
|
-
if (md === undefined) {
|
|
1051
|
-
return `Delegation [${terminal.alias}] reached state ${terminal.state} but no report file was found.`
|
|
1052
|
-
}
|
|
1053
|
-
|
|
1054
|
-
// Classify the result for stuck-agent detection
|
|
1055
|
-
const classification = classifyStuckAgent(md)
|
|
1056
|
-
const hasActivity = collector.sampled || collector.lines.length > 0
|
|
1057
|
-
const activitySuffix = hasActivity ? `\n\n${formatActivitySection(collector.lines)}` : ''
|
|
1058
|
-
|
|
1059
|
-
if (classification.status === 'success') {
|
|
1060
|
-
await board.markReconciled(job.taskID)
|
|
1061
|
-
// Backward compatible: success reports returned as-is
|
|
1062
|
-
if (!hasActivity) return md
|
|
1063
|
-
return `${md.replace(/\n+$/, '')}${activitySuffix}`
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
// Non-success: build structured DelegationResult and format
|
|
1067
|
-
const delegationResult: DelegationResult = {
|
|
1068
|
-
status: classification.status === 'empty' ? 'empty' : classification.status,
|
|
1069
|
-
content: md,
|
|
1070
|
-
retryCount: 0,
|
|
1071
|
-
partialResult: classification.partialResult,
|
|
1072
|
-
recommendation: classification.recommendation,
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
await board.markReconciled(job.taskID)
|
|
1076
|
-
const formatted = formatDelegationResult(delegationResult)
|
|
1077
|
-
return `${formatted}${activitySuffix}`
|
|
1078
|
-
},
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
const pantheon_delegation_list: DelegationTool<typeof listArgs> = {
|
|
1082
|
-
description:
|
|
1083
|
-
'List background delegations for the current session, with [unread] for finished jobs.',
|
|
1084
|
-
args: listArgs,
|
|
1085
|
-
execute: async (_args, ctx) => {
|
|
1086
|
-
const jobs = board.list(ctx.sessionID)
|
|
1087
|
-
if (jobs.length === 0) return 'No background delegations for this session.'
|
|
1088
|
-
|
|
1089
|
-
const lines = await Promise.all(
|
|
1090
|
-
jobs.map(async (j) => {
|
|
1091
|
-
const unread = j.terminalUnreconciled ? ' [unread]' : ''
|
|
1092
|
-
const base = ` [${j.alias}] ${j.agent} — ${j.description} — ${stateLabel(j.state)}${unread}`
|
|
1093
|
-
// Running jobs get a live `last activity:` line (fail-open fetch).
|
|
1094
|
-
if (j.state !== 'running') return base
|
|
1095
|
-
const last = await lastChildActivity(client, j.taskID)
|
|
1096
|
-
return last === undefined ? base : `${base}\n last activity: ${last}`
|
|
1097
|
-
}),
|
|
1098
|
-
)
|
|
1099
|
-
return `Background Delegations (${jobs.length}):\n${lines.join('\n')}`
|
|
1100
|
-
},
|
|
1101
|
-
}
|
|
1102
|
-
|
|
1103
|
-
return {
|
|
1104
|
-
pantheon_delegate,
|
|
1105
|
-
pantheon_delegation_read,
|
|
1106
|
-
pantheon_delegation_list,
|
|
1107
|
-
finalizeDelegation: finalize,
|
|
1108
|
-
finalizeIdleChildrenWithoutMd,
|
|
1109
|
-
}
|
|
1110
|
-
}
|