pantheon-opencode 1.5.0-beta.1 → 1.5.0-beta.2
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 +3 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/cost.mjs +30 -14
- package/scripts/mcp_persistence_server.py +44 -7
- package/scripts/probe-context-rehydrate.mjs +240 -0
- package/scripts/probe-pantheon-cost.mjs +304 -0
- package/scripts/test-opencode-v1-v2-sandbox.sh +394 -41
- package/src/mcp/mcp_persistence_server.py +44 -7
- package/src/pantheon/cost-command.ts +49 -32
- package/src/pantheon/delegate-manager.ts +285 -0
- package/src/pantheon/token-opt.ts +237 -11
- package/src/plugin-v2.ts +2 -14
- package/src/plugin.ts +3 -8
- package/src/plugins/tui/package.json +1 -1
- package/.pantheon/code-mode/.gitkeep +0 -0
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-1.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-10.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-11.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-2.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-3.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-4.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-5.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-6.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-7.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-8.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/checkpoint-9.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/heartbeat.json +0 -8
- package/.pantheon/code-mode/.pantheon/deepwork/initial-token-40k/session.json +0 -11
- package/src/pantheon/delegate-task-adapter.ts +0 -444
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* Token Command — `pantheon_cost` structural tool: token visibility for
|
|
3
|
+
* delegation traffic, straight from opencode.db.
|
|
4
4
|
*
|
|
5
|
-
* Reads the opencode session database READ-ONLY (sum
|
|
6
|
-
*
|
|
5
|
+
* Reads the opencode session database READ-ONLY (sum tokens by agent and
|
|
6
|
+
* phase over the last N days → markdown table). Zero new dependencies:
|
|
7
7
|
* - primary path: node:sqlite (DatabaseSync, readOnly) — node ≥ 22.5;
|
|
8
|
-
* - fallback: spawn scripts/cost.mjs
|
|
9
|
-
* direct import is unavailable;
|
|
8
|
+
* - CLI fallback: spawn scripts/cost.mjs with its explicit flag-based
|
|
9
|
+
* interface when the direct import is unavailable;
|
|
10
10
|
* - missing/unreadable db → FRIENDLY error string, never a crash (tools
|
|
11
11
|
* return errors as TEXT).
|
|
12
12
|
*
|
|
@@ -29,12 +29,13 @@ import type { ToolContextLike } from './delegation.ts'
|
|
|
29
29
|
|
|
30
30
|
const execFileAsync = promisify(execFile)
|
|
31
31
|
|
|
32
|
-
/** One aggregated
|
|
32
|
+
/** One aggregated token row (per agent and phase). */
|
|
33
33
|
export interface CostRow {
|
|
34
34
|
agent: string
|
|
35
|
-
|
|
35
|
+
phase: string
|
|
36
36
|
tokensInput: number
|
|
37
37
|
tokensOutput: number
|
|
38
|
+
tokensTotal: number
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
export interface CostCommandOptions {
|
|
@@ -123,7 +124,7 @@ function assertCompatibleSchema(db: {
|
|
|
123
124
|
}
|
|
124
125
|
}
|
|
125
126
|
|
|
126
|
-
/** Aggregate
|
|
127
|
+
/** Aggregate tokens by agent and phase via node:sqlite (read-only). */
|
|
127
128
|
async function queryWithNodeSqlite(dbPath: string, days: number): Promise<CostRow[]> {
|
|
128
129
|
const sqlite = await import('node:sqlite')
|
|
129
130
|
const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
|
|
@@ -141,24 +142,28 @@ async function queryWithNodeSqlite(dbPath: string, days: number): Promise<CostRo
|
|
|
141
142
|
}
|
|
142
143
|
}
|
|
143
144
|
|
|
144
|
-
/**
|
|
145
|
+
/** CLI fallback: delegate the same aggregation to scripts/cost.mjs. */
|
|
145
146
|
async function queryWithScript(
|
|
146
147
|
scriptPath: string,
|
|
147
148
|
dbPath: string,
|
|
148
149
|
days: number,
|
|
149
150
|
): Promise<CostRow[]> {
|
|
150
|
-
const { stdout } = await execFileAsync(
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
151
|
+
const { stdout } = await execFileAsync(
|
|
152
|
+
process.execPath,
|
|
153
|
+
[scriptPath, '--db-path', dbPath, '--days', String(days)],
|
|
154
|
+
{
|
|
155
|
+
timeout: 15_000,
|
|
156
|
+
encoding: 'utf8',
|
|
157
|
+
},
|
|
158
|
+
)
|
|
154
159
|
const parsed = JSON.parse(stdout) as { ok: boolean; rows?: CostRow[]; error?: string }
|
|
155
160
|
if (!parsed.ok) throw new Error(parsed.error ?? 'cost.mjs failed')
|
|
156
161
|
return parsed.rows ?? []
|
|
157
162
|
}
|
|
158
163
|
|
|
159
|
-
/** Parse message.data JSON rows and aggregate
|
|
164
|
+
/** Parse message.data JSON rows and aggregate tokens by assistant agent/phase. */
|
|
160
165
|
function aggregateMessages(dataValues: readonly string[]): CostRow[] {
|
|
161
|
-
const
|
|
166
|
+
const byAgentAndPhase = new Map<string, CostRow>()
|
|
162
167
|
for (const value of dataValues) {
|
|
163
168
|
try {
|
|
164
169
|
const outer = JSON.parse(value) as Record<string, unknown>
|
|
@@ -169,45 +174,57 @@ function aggregateMessages(dataValues: readonly string[]): CostRow[] {
|
|
|
169
174
|
if (info.role !== 'assistant') continue
|
|
170
175
|
const agent = typeof info.agent === 'string' && info.agent !== '' ? info.agent : null
|
|
171
176
|
if (agent === null) continue
|
|
172
|
-
const
|
|
177
|
+
const metadata = info.metadata as Record<string, unknown> | undefined
|
|
178
|
+
const phase =
|
|
179
|
+
(typeof info.phase === 'string' && info.phase) ||
|
|
180
|
+
(typeof metadata?.phase === 'string' && metadata.phase) ||
|
|
181
|
+
'unknown'
|
|
173
182
|
const tokens = (info.tokens ?? {}) as Record<string, unknown>
|
|
174
183
|
const tokensInput = Number(tokens.input) || 0
|
|
175
184
|
const tokensOutput = Number(tokens.output) || 0
|
|
176
|
-
const
|
|
177
|
-
acc.
|
|
185
|
+
const key = `${agent}\u0000${phase}`
|
|
186
|
+
const acc = byAgentAndPhase.get(key) ?? {
|
|
187
|
+
agent,
|
|
188
|
+
phase,
|
|
189
|
+
tokensInput: 0,
|
|
190
|
+
tokensOutput: 0,
|
|
191
|
+
tokensTotal: 0,
|
|
192
|
+
}
|
|
178
193
|
acc.tokensInput += tokensInput
|
|
179
194
|
acc.tokensOutput += tokensOutput
|
|
180
|
-
|
|
195
|
+
acc.tokensTotal += tokensInput + tokensOutput
|
|
196
|
+
byAgentAndPhase.set(key, acc)
|
|
181
197
|
} catch {
|
|
182
198
|
// Skip malformed rows — a partial ledger never breaks the report.
|
|
183
199
|
}
|
|
184
200
|
}
|
|
185
|
-
return [...
|
|
201
|
+
return [...byAgentAndPhase.values()].sort((a, b) => b.tokensTotal - a.tokensTotal)
|
|
186
202
|
}
|
|
187
203
|
|
|
188
204
|
/** Render the aggregate as a markdown table with a total row. */
|
|
189
205
|
function renderMarkdown(rows: readonly CostRow[], days: number): string {
|
|
190
206
|
if (rows.length === 0) {
|
|
191
|
-
return `##
|
|
207
|
+
return `## Token usage by agent and phase (last ${days} days)\n\nNo token records in the last ${days} days.`
|
|
192
208
|
}
|
|
193
209
|
const total = rows.reduce(
|
|
194
210
|
(acc, r) => {
|
|
195
|
-
acc.costUsd += r.costUsd
|
|
196
211
|
acc.tokensInput += r.tokensInput
|
|
197
212
|
acc.tokensOutput += r.tokensOutput
|
|
213
|
+
acc.tokensTotal += r.tokensTotal
|
|
198
214
|
return acc
|
|
199
215
|
},
|
|
200
|
-
{
|
|
216
|
+
{ tokensInput: 0, tokensOutput: 0, tokensTotal: 0 },
|
|
201
217
|
)
|
|
202
218
|
const lines = [
|
|
203
|
-
`##
|
|
219
|
+
`## Token usage by agent and phase (last ${days} days)`,
|
|
204
220
|
'',
|
|
205
|
-
'| Agent |
|
|
206
|
-
'
|
|
221
|
+
'| Agent | Phase | Tokens In | Tokens Out | Tokens Total |',
|
|
222
|
+
'|-------|-------|----------:|-----------:|-------------:|',
|
|
207
223
|
...rows.map(
|
|
208
|
-
(r) =>
|
|
224
|
+
(r) =>
|
|
225
|
+
`| ${r.agent} | ${r.phase} | ${r.tokensInput} | ${r.tokensOutput} | ${r.tokensTotal} |`,
|
|
209
226
|
),
|
|
210
|
-
`| **Total** |
|
|
227
|
+
`| **Total** | — | **${total.tokensInput}** | **${total.tokensOutput}** | **${total.tokensTotal}** |`,
|
|
211
228
|
'',
|
|
212
229
|
`Source: opencode.db (read-only)`,
|
|
213
230
|
]
|
|
@@ -218,14 +235,14 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
218
235
|
const scriptPath = new URL('../../scripts/cost.mjs', import.meta.url).pathname
|
|
219
236
|
|
|
220
237
|
const execute = async (args: { days?: number }, _ctx: ToolContextLike): Promise<string> => {
|
|
221
|
-
const days = args
|
|
238
|
+
const days = args?.days ?? 7
|
|
222
239
|
try {
|
|
223
240
|
const dbPath = findExistingDb(options?.dbPath)
|
|
224
241
|
if (dbPath === undefined) {
|
|
225
242
|
const expected = resolveCostDbPath(options)
|
|
226
243
|
return (
|
|
227
244
|
`pantheon_cost failed: opencode.db not found (expected at ${expected}). ` +
|
|
228
|
-
`No
|
|
245
|
+
`No token history is available until opencode has stored session data.`
|
|
229
246
|
)
|
|
230
247
|
}
|
|
231
248
|
const rows = await queryWithNodeSqlite(dbPath, days).catch(async (err: unknown) => {
|
|
@@ -243,7 +260,7 @@ export function createCostCommand(options?: CostCommandOptions): CostCommand {
|
|
|
243
260
|
return {
|
|
244
261
|
pantheon_cost: {
|
|
245
262
|
description:
|
|
246
|
-
'Report
|
|
263
|
+
'Report input, output, and total token usage by agent and phase over the last N days, read from opencode.db (read-only, no monetary values).',
|
|
247
264
|
args: costArgs,
|
|
248
265
|
execute,
|
|
249
266
|
},
|
|
@@ -23,7 +23,14 @@
|
|
|
23
23
|
* @module delegate-manager
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
|
+
import { z } from 'zod'
|
|
26
27
|
import type { BackgroundJobBoard, BackgroundJobRecord } from './background-job-board.ts'
|
|
28
|
+
import type { DelegationToolset } from './delegation.ts'
|
|
29
|
+
import {
|
|
30
|
+
DELEGATION_DEFAULTS,
|
|
31
|
+
type DelegationClient,
|
|
32
|
+
readDelegationReport,
|
|
33
|
+
} from './delegation-finalize.ts'
|
|
27
34
|
import {
|
|
28
35
|
buildStopInstruction,
|
|
29
36
|
cappedSummary,
|
|
@@ -113,6 +120,13 @@ export function isDelegationEnabled(
|
|
|
113
120
|
return (env.PANTHEON_DELEGATION ?? '').trim().toLowerCase() !== 'off'
|
|
114
121
|
}
|
|
115
122
|
|
|
123
|
+
export type DelegateMode = 'native' | 'legacy'
|
|
124
|
+
export function resolveDelegateMode(
|
|
125
|
+
env: Record<string, string | undefined> = process.env,
|
|
126
|
+
): DelegateMode {
|
|
127
|
+
return (env.PANTHEON_DELEGATE_MODE ?? '').trim().toLowerCase() === 'native' ? 'native' : 'legacy'
|
|
128
|
+
}
|
|
129
|
+
|
|
116
130
|
// ─── Helpers ───────────────────────────────────────────────────────────
|
|
117
131
|
|
|
118
132
|
const LINE_MAX = 160
|
|
@@ -382,3 +396,274 @@ export function createDelegateManager(options: DelegateManagerOptions): Delegate
|
|
|
382
396
|
},
|
|
383
397
|
}
|
|
384
398
|
}
|
|
399
|
+
|
|
400
|
+
// Native delegation tools live with the manager so the plugin mounts the
|
|
401
|
+
// manager directly; there is intentionally no adapter or kill-switch wrapper.
|
|
402
|
+
const delegateArgs = {
|
|
403
|
+
prompt: z.string().min(1),
|
|
404
|
+
agent: z.string().min(1),
|
|
405
|
+
description: z.string().optional(),
|
|
406
|
+
read_only: z.boolean().optional(),
|
|
407
|
+
model: z.string().optional(),
|
|
408
|
+
} satisfies z.ZodRawShape
|
|
409
|
+
const readArgs = { id: z.string().min(1) } satisfies z.ZodRawShape
|
|
410
|
+
const listArgs = {} satisfies z.ZodRawShape
|
|
411
|
+
export interface ToolContextLike {
|
|
412
|
+
sessionID: string
|
|
413
|
+
agent?: string
|
|
414
|
+
}
|
|
415
|
+
export interface SessionTaskOptions {
|
|
416
|
+
client: DelegationClient
|
|
417
|
+
board: BackgroundJobBoard
|
|
418
|
+
outputDir?: string
|
|
419
|
+
promptTimeoutMs?: number
|
|
420
|
+
settleTimeoutMs?: number
|
|
421
|
+
}
|
|
422
|
+
export function parseModelRef(model: string): { id: string; providerID: string } | undefined {
|
|
423
|
+
const idx = model.indexOf('/')
|
|
424
|
+
return idx > 0 && idx < model.length - 1
|
|
425
|
+
? { providerID: model.slice(0, idx), id: model.slice(idx + 1) }
|
|
426
|
+
: undefined
|
|
427
|
+
}
|
|
428
|
+
export function extractOutputSection(md: string | undefined): string {
|
|
429
|
+
if (md === undefined) return ''
|
|
430
|
+
const at = md.indexOf('## Output')
|
|
431
|
+
const body = at < 0 ? md : md.slice(at + 9)
|
|
432
|
+
const errAt = body.indexOf('\n**Error**:')
|
|
433
|
+
return (errAt < 0 ? body : body.slice(0, errAt)).trim()
|
|
434
|
+
}
|
|
435
|
+
async function promptAccept(
|
|
436
|
+
client: DelegationClient,
|
|
437
|
+
taskID: string,
|
|
438
|
+
agent: string,
|
|
439
|
+
prompt: string,
|
|
440
|
+
model: string | undefined,
|
|
441
|
+
signal: AbortSignal | undefined,
|
|
442
|
+
timeoutMs: number,
|
|
443
|
+
): Promise<void> {
|
|
444
|
+
const modelRef = model === undefined ? undefined : parseModelRef(model)
|
|
445
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
446
|
+
try {
|
|
447
|
+
await Promise.race([
|
|
448
|
+
client.session
|
|
449
|
+
.promptAsync({
|
|
450
|
+
path: { id: taskID },
|
|
451
|
+
body: {
|
|
452
|
+
agent,
|
|
453
|
+
...(modelRef === undefined ? {} : { model: modelRef }),
|
|
454
|
+
parts: [{ type: 'text', text: prompt }],
|
|
455
|
+
},
|
|
456
|
+
...(signal === undefined ? {} : { signal }),
|
|
457
|
+
})
|
|
458
|
+
.then(undefined, (error: unknown) => {
|
|
459
|
+
throw new Error(
|
|
460
|
+
`promptAsync rejected: ${error instanceof Error ? error.message : String(error)}`,
|
|
461
|
+
)
|
|
462
|
+
}),
|
|
463
|
+
new Promise<never>((_, reject) => {
|
|
464
|
+
timer = setTimeout(
|
|
465
|
+
() => reject(new Error(`promptAsync timed out after ${timeoutMs}ms`)),
|
|
466
|
+
timeoutMs,
|
|
467
|
+
)
|
|
468
|
+
timer.unref?.()
|
|
469
|
+
}),
|
|
470
|
+
])
|
|
471
|
+
} finally {
|
|
472
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
export function createSessionTaskFn(options: SessionTaskOptions): NativeTaskFn {
|
|
476
|
+
const {
|
|
477
|
+
client,
|
|
478
|
+
board,
|
|
479
|
+
outputDir = DELEGATION_DEFAULTS.outputDir,
|
|
480
|
+
promptTimeoutMs = 60_000,
|
|
481
|
+
settleTimeoutMs = DELEGATION_DEFAULTS.timeoutMs,
|
|
482
|
+
} = options
|
|
483
|
+
return async ({ agent, prompt, model, signal, taskID }) => {
|
|
484
|
+
await promptAccept(client, taskID, agent, prompt, model, signal, promptTimeoutMs)
|
|
485
|
+
const terminal = await board.waitForTerminal(taskID, settleTimeoutMs)
|
|
486
|
+
const md = await readDelegationReport(outputDir, terminal)
|
|
487
|
+
return { content: extractOutputSection(md) || terminal.resultSummary || '' }
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
export interface NativeDelegateWiring {
|
|
491
|
+
board: BackgroundJobBoard
|
|
492
|
+
client: DelegationClient
|
|
493
|
+
outputDir?: string
|
|
494
|
+
env?: Record<string, string | undefined>
|
|
495
|
+
isRootSession: (sessionID: string) => boolean
|
|
496
|
+
registerChildSession?: (sessionID: string, parentID: string) => void
|
|
497
|
+
registerReadOnlySession?: (
|
|
498
|
+
sessionID: string,
|
|
499
|
+
info: { agent: string; readOnlyFlag?: boolean },
|
|
500
|
+
) => void
|
|
501
|
+
isReadOnlyAgent?: (agent: string) => boolean
|
|
502
|
+
agentModel?: (agent: string) => string | undefined
|
|
503
|
+
managerOptions?: Partial<
|
|
504
|
+
Omit<DelegateManagerOptions, 'board' | 'task' | 'parentSessionID' | 'env'>
|
|
505
|
+
>
|
|
506
|
+
stepCap?: StepCapTracker
|
|
507
|
+
}
|
|
508
|
+
export interface NativeDelegateToolset {
|
|
509
|
+
pantheon_delegate: {
|
|
510
|
+
description: string
|
|
511
|
+
args: typeof delegateArgs
|
|
512
|
+
execute(args: z.infer<z.ZodObject<typeof delegateArgs>>, ctx: ToolContextLike): Promise<string>
|
|
513
|
+
}
|
|
514
|
+
pantheon_delegation_read: {
|
|
515
|
+
description: string
|
|
516
|
+
args: typeof readArgs
|
|
517
|
+
execute(args: z.infer<z.ZodObject<typeof readArgs>>, ctx: ToolContextLike): Promise<string>
|
|
518
|
+
}
|
|
519
|
+
pantheon_delegation_list: {
|
|
520
|
+
description: string
|
|
521
|
+
args: typeof listArgs
|
|
522
|
+
execute(args: z.infer<z.ZodObject<typeof listArgs>>, ctx: ToolContextLike): Promise<string>
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
function shortFirstLine(text: string, max = 60): string {
|
|
526
|
+
const line =
|
|
527
|
+
text
|
|
528
|
+
.split('\n')
|
|
529
|
+
.map((item) => item.trim())
|
|
530
|
+
.find(Boolean) ?? ''
|
|
531
|
+
return line.length > max ? `${line.slice(0, max - 1)}…` : line
|
|
532
|
+
}
|
|
533
|
+
export function createNativeDelegateTools(wiring: NativeDelegateWiring): NativeDelegateToolset {
|
|
534
|
+
const {
|
|
535
|
+
board,
|
|
536
|
+
client,
|
|
537
|
+
env = process.env,
|
|
538
|
+
isRootSession,
|
|
539
|
+
registerChildSession,
|
|
540
|
+
registerReadOnlySession,
|
|
541
|
+
isReadOnlyAgent,
|
|
542
|
+
agentModel,
|
|
543
|
+
managerOptions = {},
|
|
544
|
+
stepCap,
|
|
545
|
+
} = wiring
|
|
546
|
+
const task = createSessionTaskFn({
|
|
547
|
+
client,
|
|
548
|
+
board,
|
|
549
|
+
...(wiring.outputDir === undefined ? {} : { outputDir: wiring.outputDir }),
|
|
550
|
+
...(managerOptions.timeoutMs === undefined
|
|
551
|
+
? {}
|
|
552
|
+
: { promptTimeoutMs: managerOptions.timeoutMs }),
|
|
553
|
+
})
|
|
554
|
+
const managers = new Map<string, DelegateManager>()
|
|
555
|
+
const managerFor = (parentSessionID: string): DelegateManager => {
|
|
556
|
+
const existing = managers.get(parentSessionID)
|
|
557
|
+
if (existing !== undefined) return existing
|
|
558
|
+
const manager = createDelegateManager({
|
|
559
|
+
...managerOptions,
|
|
560
|
+
board,
|
|
561
|
+
task,
|
|
562
|
+
parentSessionID,
|
|
563
|
+
env,
|
|
564
|
+
...(stepCap === undefined ? {} : { stepCap }),
|
|
565
|
+
})
|
|
566
|
+
managers.set(parentSessionID, manager)
|
|
567
|
+
return manager
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
pantheon_delegate: {
|
|
571
|
+
description: 'Dispatch a background agent as a child session and return a verified receipt.',
|
|
572
|
+
args: delegateArgs,
|
|
573
|
+
execute: async (args, ctx) => {
|
|
574
|
+
if (!isDelegationEnabled(env))
|
|
575
|
+
throw new Error('pantheon delegation disabled (PANTHEON_DELEGATION=off)')
|
|
576
|
+
if (!isRootSession(ctx.sessionID))
|
|
577
|
+
throw new Error(
|
|
578
|
+
`pantheon_delegate rejected: session ${ctx.sessionID} is a sub-session — only root sessions can delegate`,
|
|
579
|
+
)
|
|
580
|
+
const model = args.model ?? agentModel?.(args.agent)
|
|
581
|
+
let childID: string
|
|
582
|
+
try {
|
|
583
|
+
const modelRef = model === undefined ? undefined : parseModelRef(model)
|
|
584
|
+
const created = await client.session.create({
|
|
585
|
+
body: {
|
|
586
|
+
parentID: ctx.sessionID,
|
|
587
|
+
title: args.description ?? shortFirstLine(args.prompt),
|
|
588
|
+
...(modelRef === undefined ? {} : { model: modelRef }),
|
|
589
|
+
},
|
|
590
|
+
})
|
|
591
|
+
childID = created.id
|
|
592
|
+
} catch (error) {
|
|
593
|
+
return `pantheon_delegate failed: session.create rejected: ${error instanceof Error ? error.message : String(error)}`
|
|
594
|
+
}
|
|
595
|
+
registerChildSession?.(childID, ctx.sessionID)
|
|
596
|
+
if (args.read_only === true || isReadOnlyAgent?.(args.agent) === true)
|
|
597
|
+
registerReadOnlySession?.(childID, {
|
|
598
|
+
agent: args.agent,
|
|
599
|
+
...(args.read_only === undefined ? {} : { readOnlyFlag: args.read_only }),
|
|
600
|
+
})
|
|
601
|
+
const receipt = await managerFor(ctx.sessionID).launch({
|
|
602
|
+
agent: args.agent,
|
|
603
|
+
prompt: args.prompt,
|
|
604
|
+
...(args.description === undefined ? {} : { description: args.description }),
|
|
605
|
+
...(args.model === undefined ? {} : { model: args.model }),
|
|
606
|
+
taskID: childID,
|
|
607
|
+
})
|
|
608
|
+
return receipt.line
|
|
609
|
+
},
|
|
610
|
+
},
|
|
611
|
+
pantheon_delegation_read: {
|
|
612
|
+
description: 'Block until a delegation finishes, then return its verified report.',
|
|
613
|
+
args: readArgs,
|
|
614
|
+
execute: async (args, ctx) => {
|
|
615
|
+
if (!isDelegationEnabled(env))
|
|
616
|
+
throw new Error('pantheon delegation disabled (PANTHEON_DELEGATION=off)')
|
|
617
|
+
return managerFor(ctx.sessionID).read(args.id)
|
|
618
|
+
},
|
|
619
|
+
},
|
|
620
|
+
pantheon_delegation_list: {
|
|
621
|
+
description: 'List background delegations.',
|
|
622
|
+
args: listArgs,
|
|
623
|
+
execute: async (_args, ctx) => {
|
|
624
|
+
if (!isDelegationEnabled(env))
|
|
625
|
+
throw new Error('pantheon delegation disabled (PANTHEON_DELEGATION=off)')
|
|
626
|
+
const lines = await managerFor(ctx.sessionID).list()
|
|
627
|
+
return lines.length > 0 ? lines.join('\n') : 'No delegations.'
|
|
628
|
+
},
|
|
629
|
+
},
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
export interface PluginNativeDelegationWiring {
|
|
633
|
+
board: BackgroundJobBoard
|
|
634
|
+
client: DelegationClient
|
|
635
|
+
isRootSession: (sessionID: string) => boolean
|
|
636
|
+
registerChildSession: (sessionID: string, parentID: string) => void
|
|
637
|
+
registerReadOnlySession: (
|
|
638
|
+
sessionID: string,
|
|
639
|
+
info: { agent: string; readOnlyFlag?: boolean },
|
|
640
|
+
) => void
|
|
641
|
+
readOnlyAgents: ReadonlySet<string>
|
|
642
|
+
agentModels: Record<string, string | undefined>
|
|
643
|
+
stepCap: StepCapTracker
|
|
644
|
+
wallClockTimeoutMs?: number
|
|
645
|
+
finalizeDelegation: DelegationToolset['finalizeDelegation']
|
|
646
|
+
}
|
|
647
|
+
export type PluginNativeDelegation = NativeDelegateToolset & {
|
|
648
|
+
finalizeDelegation: DelegationToolset['finalizeDelegation']
|
|
649
|
+
}
|
|
650
|
+
export function buildPluginNativeDelegation(
|
|
651
|
+
wiring: PluginNativeDelegationWiring,
|
|
652
|
+
): PluginNativeDelegation {
|
|
653
|
+
return {
|
|
654
|
+
...createNativeDelegateTools({
|
|
655
|
+
board: wiring.board,
|
|
656
|
+
client: wiring.client,
|
|
657
|
+
isRootSession: wiring.isRootSession,
|
|
658
|
+
registerChildSession: wiring.registerChildSession,
|
|
659
|
+
registerReadOnlySession: wiring.registerReadOnlySession,
|
|
660
|
+
isReadOnlyAgent: (agent) => wiring.readOnlyAgents.has(agent.toLowerCase()),
|
|
661
|
+
agentModel: (agent) => wiring.agentModels[agent.toLowerCase()],
|
|
662
|
+
stepCap: wiring.stepCap,
|
|
663
|
+
...(wiring.wallClockTimeoutMs === undefined
|
|
664
|
+
? {}
|
|
665
|
+
: { managerOptions: { timeoutMs: wiring.wallClockTimeoutMs } }),
|
|
666
|
+
}),
|
|
667
|
+
finalizeDelegation: wiring.finalizeDelegation,
|
|
668
|
+
}
|
|
669
|
+
}
|