pi-goal-delegate 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -0
- package/README.md +74 -40
- package/package.json +1 -1
- package/skills/delegate/SKILL.md +12 -15
- package/src/command.ts +36 -5
- package/src/contract.ts +128 -11
- package/src/events.ts +22 -1
- package/src/index.ts +82 -10
- package/src/registry.ts +78 -22
- package/src/result-schema.ts +132 -0
- package/src/retention.ts +46 -9
- package/src/run.ts +73 -10
- package/src/spawn.ts +5 -1
- package/src/supervisor.mjs +113 -4
- package/src/verify.ts +3 -1
- package/src/worker.ts +128 -59
- package/src/worktree.ts +107 -3
package/src/contract.ts
CHANGED
|
@@ -23,6 +23,45 @@ export const MAX_MAX_TURNS = 500;
|
|
|
23
23
|
export const DEFAULT_TIMEOUT_MINUTES = 60;
|
|
24
24
|
export const MAX_TIMEOUT_MINUTES = 240;
|
|
25
25
|
|
|
26
|
+
/**
|
|
27
|
+
* Delegation depth is the number of further child levels a run tree may create.
|
|
28
|
+
* Zero preserves the original one-level default. An explicit cap enables task
|
|
29
|
+
* decomposition without replacing budget control with unbounded recursion.
|
|
30
|
+
*/
|
|
31
|
+
export const DEFAULT_MAX_DEPTH = 0;
|
|
32
|
+
export const MAX_MAX_DEPTH = 3;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Why a nested run may not set these limits, or undefined when it may.
|
|
36
|
+
*
|
|
37
|
+
* A child inherits the depth and spend budget of the run that started it.
|
|
38
|
+
* Raising one is indistinguishable from removing the bound its parent set, so
|
|
39
|
+
* the rule is one function rather than a copy in each entry point: two copies of
|
|
40
|
+
* "how much of its budget may a child spend" are two answers to one question.
|
|
41
|
+
*/
|
|
42
|
+
export function attenuationRefusal(
|
|
43
|
+
parent: { depth?: number; maxDepth?: number; maxCostUsd?: number },
|
|
44
|
+
request: { maxDepth: number; maxCostUsd: number },
|
|
45
|
+
): string | undefined {
|
|
46
|
+
// A run that no delegation started has no parent budget to honour.
|
|
47
|
+
if (parent.depth === undefined) return undefined;
|
|
48
|
+
const allowedDepth = parent.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
49
|
+
if (request.maxDepth > allowedDepth) {
|
|
50
|
+
return `maxDepth must be at most ${allowedDepth} in this delegation.`;
|
|
51
|
+
}
|
|
52
|
+
const allowedCost = parent.maxCostUsd ?? 0;
|
|
53
|
+
if (allowedCost > 0 && (request.maxCostUsd <= 0 || request.maxCostUsd > allowedCost)) {
|
|
54
|
+
return `maxCostUsd must be greater than 0 and at most ${allowedCost} in this delegation.`;
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** One completion message should normally contain the whole verdict. */
|
|
60
|
+
export const COMPLETION_MESSAGE_LIMIT = 24_000;
|
|
61
|
+
/** A structured result must remain a bounded, model- and codemode-readable value. */
|
|
62
|
+
export const MAX_STRUCTURED_RESULT_CHARS = 64_000;
|
|
63
|
+
export const DEFAULT_VERIFY_TIMEOUT_MS = 120_000;
|
|
64
|
+
|
|
26
65
|
/**
|
|
27
66
|
* How many delegations one session may keep live at once.
|
|
28
67
|
*
|
|
@@ -131,6 +170,9 @@ export type ContainmentVerdict = "gone" | "leaked" | "unproven";
|
|
|
131
170
|
/** What a verify command proved about a completion claim. */
|
|
132
171
|
export type VerificationVerdict = true | false | "not-run";
|
|
133
172
|
|
|
173
|
+
/** JSON data crosses the child/parent protocol; functions and class instances do not. */
|
|
174
|
+
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
|
|
175
|
+
|
|
134
176
|
/** The recorded result of running a run's verify command in the parent. */
|
|
135
177
|
export interface VerificationRecord {
|
|
136
178
|
command: string;
|
|
@@ -178,14 +220,24 @@ export interface RunSpec {
|
|
|
178
220
|
/** The child ran without ambient extensions, skills, MCP servers or context files. */
|
|
179
221
|
isolated?: boolean;
|
|
180
222
|
/**
|
|
181
|
-
* A command
|
|
182
|
-
*
|
|
223
|
+
* A command that gates the child's completion claim and is then independently
|
|
224
|
+
* re-run by the parent. A failed child-side check returns to the child as a
|
|
225
|
+
* tool result; it does not terminate the run. The parent uses the same
|
|
226
|
+
* PI_DELEGATE_ENV_DROP policy as the child.
|
|
183
227
|
*/
|
|
184
228
|
verify?: { command: string };
|
|
229
|
+
/** Optional JSON Schema for the structured value passed to delegate_complete. */
|
|
230
|
+
resultSchema?: Record<string, unknown>;
|
|
231
|
+
/** Zero-based position in the delegation tree. */
|
|
232
|
+
depth?: number;
|
|
233
|
+
/** Maximum absolute depth for this run tree; zero disables nested delegation. */
|
|
234
|
+
maxDepth?: number;
|
|
185
235
|
/** Session to continue instead of starting from the goal alone. */
|
|
186
236
|
resumeSession?: string;
|
|
237
|
+
/** The previous run whose session and, when present, worktree this run continues. */
|
|
238
|
+
resumedFrom?: string;
|
|
187
239
|
/** The child's workspace, when it was created as a git worktree. */
|
|
188
|
-
worktree?: { path: string; branch: string; repo: string };
|
|
240
|
+
worktree?: { path: string; branch: string; repo: string; base?: string };
|
|
189
241
|
/** Cumulative spend cap in USD. 0 disables it. */
|
|
190
242
|
maxCostUsd: number;
|
|
191
243
|
/**
|
|
@@ -297,6 +349,10 @@ export interface RunProgress {
|
|
|
297
349
|
/** Tail of the last assistant text, bounded. */
|
|
298
350
|
lastText: string;
|
|
299
351
|
lastError?: string;
|
|
352
|
+
/** Parent-side copy of the shared circuit-breaker state. */
|
|
353
|
+
breaker: BreakerState;
|
|
354
|
+
toolCallsThisTurn: number;
|
|
355
|
+
noProgressReason?: string;
|
|
300
356
|
/** The child's session header was seen. */
|
|
301
357
|
started: boolean;
|
|
302
358
|
/** The child reached its idle boundary at least once. */
|
|
@@ -311,6 +367,8 @@ export function emptyProgress(): RunProgress {
|
|
|
311
367
|
toolErrors: 0,
|
|
312
368
|
usage: emptyUsage(),
|
|
313
369
|
lastText: "",
|
|
370
|
+
breaker: emptyBreaker(),
|
|
371
|
+
toolCallsThisTurn: 0,
|
|
314
372
|
started: false,
|
|
315
373
|
settledOnce: false,
|
|
316
374
|
};
|
|
@@ -397,6 +455,39 @@ export type BreakerVerdict =
|
|
|
397
455
|
| { kind: "warn"; reason: string }
|
|
398
456
|
| { kind: "stop"; status: RunStatus; reason: string };
|
|
399
457
|
|
|
458
|
+
type Canonical = string | number | boolean | null | Canonical[] | { [key: string]: Canonical };
|
|
459
|
+
|
|
460
|
+
/** Canonical tool-call identity shared by the child and the parent's event observer. */
|
|
461
|
+
export function canonicalCallSignature(toolName: unknown, input: unknown): string {
|
|
462
|
+
const seen = new WeakSet<object>();
|
|
463
|
+
const walk = (value: unknown): Canonical => {
|
|
464
|
+
if (value === null || value === undefined) return null;
|
|
465
|
+
if (Array.isArray(value)) return value.map(walk);
|
|
466
|
+
switch (typeof value) {
|
|
467
|
+
case "string":
|
|
468
|
+
case "boolean":
|
|
469
|
+
return value;
|
|
470
|
+
case "number":
|
|
471
|
+
return Number.isFinite(value) ? value : String(value);
|
|
472
|
+
case "object": {
|
|
473
|
+
if (seen.has(value)) return "[circular]";
|
|
474
|
+
seen.add(value);
|
|
475
|
+
const source = value as Record<string, unknown>;
|
|
476
|
+
const sorted: Record<string, Canonical> = {};
|
|
477
|
+
for (const key of Object.keys(source).sort()) sorted[key] = walk(source[key]);
|
|
478
|
+
return sorted;
|
|
479
|
+
}
|
|
480
|
+
default:
|
|
481
|
+
return String(value);
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
try {
|
|
485
|
+
return `${String(toolName ?? "?")}:${JSON.stringify(walk(input ?? {}))}`;
|
|
486
|
+
} catch {
|
|
487
|
+
return `${String(toolName ?? "?")}:unserialisable`;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
400
491
|
/** Fold one tool result. A success clears the error streak. */
|
|
401
492
|
export function noteToolResult(state: BreakerState, failed: boolean): BreakerVerdict {
|
|
402
493
|
state.consecutiveErrors = failed ? state.consecutiveErrors + 1 : 0;
|
|
@@ -455,6 +546,13 @@ export function noteIdleTurn(state: BreakerState, text: string, toolCallsThisTur
|
|
|
455
546
|
};
|
|
456
547
|
}
|
|
457
548
|
|
|
549
|
+
/** Minutes a run really has: its own cap, or the parent's deadline if nearer. */
|
|
550
|
+
function budgetMinutes(spec: RunSpec): number {
|
|
551
|
+
if (!Number.isFinite(spec.deadline)) return spec.timeoutMinutes;
|
|
552
|
+
const remaining = Math.ceil((spec.deadline - Date.now()) / 60_000);
|
|
553
|
+
return Math.max(1, Math.min(spec.timeoutMinutes, remaining));
|
|
554
|
+
}
|
|
555
|
+
|
|
458
556
|
export function buildGoalPrompt(spec: RunSpec): string {
|
|
459
557
|
const doneWhen = spec.doneWhen?.trim() || "You decide the concrete completion criteria, state them, then meet them.";
|
|
460
558
|
const context = spec.context?.trim() || "(none provided; discover what you need from the repository and the environment)";
|
|
@@ -470,19 +568,31 @@ export function buildGoalPrompt(spec: RunSpec): string {
|
|
|
470
568
|
"",
|
|
471
569
|
"## How this session works",
|
|
472
570
|
"You are a delegated sub-agent working alone on this goal. The user is not present and cannot answer questions.",
|
|
473
|
-
"- Keep working until the goal is verifiably done, then call delegate_complete
|
|
571
|
+
"- Keep working until the goal is verifiably done, then call delegate_complete with summary, evidence, and any requested structured result.",
|
|
474
572
|
"- Evidence means the commands you ran, the files you changed, and the checks that pass. Without evidence the delegation is only a claim.",
|
|
475
573
|
"- Call delegate_blocked(reason, needs) when you cannot proceed without a decision, credential, or fact you cannot obtain.",
|
|
476
574
|
"- If an automatic continuation arrives, do not restate progress: continue the work.",
|
|
477
575
|
"- Keep changes scoped to the goal. Do not start unrelated work.",
|
|
478
576
|
"- Do not ask questions. Either make a defensible decision and note it, or call delegate_blocked.",
|
|
479
|
-
|
|
577
|
+
// A nested run inherits its parent's deadline, so timeoutMinutes is what
|
|
578
|
+
// the parent asked for, not what this child actually has left. Telling a
|
|
579
|
+
// child it has an hour when it has two minutes spends the budget on a
|
|
580
|
+
// plan it cannot finish.
|
|
581
|
+
`- Budget: at most ${spec.maxTurns} model turns and ${budgetMinutes(spec)} minutes.`,
|
|
480
582
|
...(spec.verify
|
|
481
583
|
? [
|
|
482
|
-
`-
|
|
584
|
+
`- Completion is gated by: \`${spec.verify.command}\` in this directory. delegate_complete runs it before ending. If it fails, fix the cause and retry; the parent independently re-runs it after your final claim.`,
|
|
585
|
+
]
|
|
586
|
+
: []),
|
|
587
|
+
...(spec.resultSchema
|
|
588
|
+
? [
|
|
589
|
+
"- delegate_complete requires a structured `result` value satisfying this JSON Schema:",
|
|
590
|
+
"```json",
|
|
591
|
+
JSON.stringify(spec.resultSchema),
|
|
592
|
+
"```",
|
|
483
593
|
]
|
|
484
594
|
: []),
|
|
485
|
-
"(A
|
|
595
|
+
"(A steering message from the parent is delivered between turns. Treat it as direction for the work, not as a new goal.)",
|
|
486
596
|
].join("\n");
|
|
487
597
|
}
|
|
488
598
|
|
|
@@ -493,12 +603,19 @@ export function buildGoalPrompt(spec: RunSpec): string {
|
|
|
493
603
|
* only party that knows the goal changed, and a child that keeps working on last
|
|
494
604
|
* turn's instructions wastes the budget it was given.
|
|
495
605
|
*/
|
|
606
|
+
export function buildSteeringMessage(steering: readonly string[]): string {
|
|
607
|
+
return [
|
|
608
|
+
"# Message from the delegating agent",
|
|
609
|
+
...steering.map((entry) => `- ${entry}`),
|
|
610
|
+
"",
|
|
611
|
+
"Treat this as direction for the work you are already doing. It does not replace the goal.",
|
|
612
|
+
].join("\n");
|
|
613
|
+
}
|
|
614
|
+
|
|
496
615
|
export function buildContinuation(spec: RunSpec, turn: number, steering: readonly string[] = []): string {
|
|
497
616
|
const doneWhen = spec.doneWhen?.trim() || "the stated completion criteria are met";
|
|
498
617
|
return [
|
|
499
|
-
...(steering.length > 0
|
|
500
|
-
? ["# Message from the delegating agent", ...steering.map((entry) => `- ${entry}`), "", "Treat this as direction for the work you are already doing. It does not replace the goal.", ""]
|
|
501
|
-
: []),
|
|
618
|
+
...(steering.length > 0 ? [buildSteeringMessage(steering), ""] : []),
|
|
502
619
|
`Continue working toward the goal. Turn ${turn} of at most ${spec.maxTurns}.`,
|
|
503
620
|
"",
|
|
504
621
|
"# Goal",
|
|
@@ -507,6 +624,6 @@ export function buildContinuation(spec: RunSpec, turn: number, steering: readonl
|
|
|
507
624
|
"# Done when",
|
|
508
625
|
doneWhen,
|
|
509
626
|
"",
|
|
510
|
-
"Rules: keep working until the goal is verifiably done, then call delegate_complete
|
|
627
|
+
"Rules: keep working until the goal is verifiably done, then call delegate_complete with summary, evidence, and any requested structured result. If you are blocked, call delegate_blocked(reason, needs). Do not ask questions.",
|
|
511
628
|
].join("\n");
|
|
512
629
|
}
|
package/src/events.ts
CHANGED
|
@@ -11,7 +11,19 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import { open } from "node:fs/promises";
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
addUsage,
|
|
16
|
+
canonicalCallSignature,
|
|
17
|
+
noteIdleTurn,
|
|
18
|
+
noteToolCall,
|
|
19
|
+
noteToolResult,
|
|
20
|
+
type BreakerVerdict,
|
|
21
|
+
type RunProgress,
|
|
22
|
+
} from "./contract.ts";
|
|
23
|
+
|
|
24
|
+
function noteBreaker(progress: RunProgress, verdict: BreakerVerdict): void {
|
|
25
|
+
if (verdict.kind === "stop") progress.noProgressReason = verdict.reason;
|
|
26
|
+
}
|
|
15
27
|
|
|
16
28
|
const MAX_TEXT = 4000;
|
|
17
29
|
const MAX_LINE = 4 * 1024 * 1024;
|
|
@@ -60,14 +72,22 @@ export function foldEvent(progress: RunProgress, record: unknown): void {
|
|
|
60
72
|
}
|
|
61
73
|
case "turn_start": {
|
|
62
74
|
progress.turns += 1;
|
|
75
|
+
progress.toolCallsThisTurn = 0;
|
|
63
76
|
return;
|
|
64
77
|
}
|
|
65
78
|
case "tool_execution_start": {
|
|
66
79
|
progress.toolCalls += 1;
|
|
80
|
+
progress.toolCallsThisTurn += 1;
|
|
81
|
+
const toolName = typeof event.toolName === "string" ? event.toolName : "";
|
|
82
|
+
const signature = typeof event.signature === "string"
|
|
83
|
+
? event.signature
|
|
84
|
+
: canonicalCallSignature(toolName, event.args);
|
|
85
|
+
noteBreaker(progress, noteToolCall(progress.breaker, signature, toolName));
|
|
67
86
|
return;
|
|
68
87
|
}
|
|
69
88
|
case "tool_execution_end": {
|
|
70
89
|
if (event.isError === true) progress.toolErrors += 1;
|
|
90
|
+
noteBreaker(progress, noteToolResult(progress.breaker, event.isError === true));
|
|
71
91
|
return;
|
|
72
92
|
}
|
|
73
93
|
case "message_end": {
|
|
@@ -101,6 +121,7 @@ export function foldEvent(progress: RunProgress, record: unknown): void {
|
|
|
101
121
|
}
|
|
102
122
|
case "agent_settled": {
|
|
103
123
|
progress.settledOnce = true;
|
|
124
|
+
noteBreaker(progress, noteIdleTurn(progress.breaker, progress.lastText, progress.toolCallsThisTurn));
|
|
104
125
|
return;
|
|
105
126
|
}
|
|
106
127
|
default:
|
package/src/index.ts
CHANGED
|
@@ -30,7 +30,8 @@
|
|
|
30
30
|
* retention.ts reclaim run records by age, count and bytes
|
|
31
31
|
*
|
|
32
32
|
* Artifacts per run: <agentDir>/delegate/<runId>/{spec,meta,state,result,outcome}.json
|
|
33
|
-
* plus child.jsonl, child.log, inbox.jsonl, owner.lock
|
|
33
|
+
* plus child.jsonl, control.jsonl, child.log, inbox.jsonl, owner.lock,
|
|
34
|
+
* and changes.patch for a worktree run with changes.
|
|
34
35
|
*/
|
|
35
36
|
|
|
36
37
|
import { resolve } from "node:path";
|
|
@@ -38,13 +39,17 @@ import { Type } from "typebox";
|
|
|
38
39
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
39
40
|
import { registerDelegateCommand } from "./command.ts";
|
|
40
41
|
import {
|
|
42
|
+
attenuationRefusal,
|
|
41
43
|
DEFAULT_MAX_COST_USD,
|
|
44
|
+
DEFAULT_MAX_DEPTH,
|
|
42
45
|
DEFAULT_MAX_TURNS,
|
|
43
46
|
DEFAULT_TIMEOUT_MINUTES,
|
|
44
47
|
isFailure,
|
|
48
|
+
MAX_MAX_DEPTH,
|
|
45
49
|
MAX_MAX_TURNS,
|
|
46
50
|
MAX_TIMEOUT_MINUTES,
|
|
47
51
|
SPEC_ENV,
|
|
52
|
+
type RunSpec,
|
|
48
53
|
} from "./contract.ts";
|
|
49
54
|
import {
|
|
50
55
|
acquireRegistry,
|
|
@@ -56,6 +61,8 @@ import {
|
|
|
56
61
|
} from "./registry.ts";
|
|
57
62
|
import type { RunRegistry } from "./registry.ts";
|
|
58
63
|
import { formatOutcome, type RunHandle, type RunOutcome } from "./run.ts";
|
|
64
|
+
import { auditResultSchema } from "./result-schema.ts";
|
|
65
|
+
import { readJson } from "./spawn.ts";
|
|
59
66
|
import { gitAvailable } from "./worktree.ts";
|
|
60
67
|
|
|
61
68
|
const STATUS_KEY = "delegate";
|
|
@@ -84,6 +91,20 @@ const worktreeSchema = Type.Object({
|
|
|
84
91
|
path: Type.String(),
|
|
85
92
|
branch: Type.String(),
|
|
86
93
|
repo: Type.String(),
|
|
94
|
+
base: Type.Optional(Type.String()),
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const integrationSchema = Type.Object({
|
|
98
|
+
base: Type.Optional(Type.String()),
|
|
99
|
+
head: Type.String(),
|
|
100
|
+
clean: Type.Boolean(),
|
|
101
|
+
status: Type.String(),
|
|
102
|
+
diffStat: Type.String(),
|
|
103
|
+
patchPath: Type.Optional(Type.String()),
|
|
104
|
+
applyCommand: Type.Optional(Type.String()),
|
|
105
|
+
checkCommand: Type.Optional(Type.String()),
|
|
106
|
+
applyCheck: Type.Optional(Type.Object({ ok: Type.Boolean(), output: Type.String() })),
|
|
107
|
+
error: Type.Optional(Type.String()),
|
|
87
108
|
});
|
|
88
109
|
|
|
89
110
|
const outcomeSchema = Type.Object({
|
|
@@ -98,6 +119,9 @@ const outcomeSchema = Type.Object({
|
|
|
98
119
|
summary: Type.String(),
|
|
99
120
|
evidence: Type.Optional(Type.String()),
|
|
100
121
|
needs: Type.Optional(Type.String()),
|
|
122
|
+
result: Type.Optional(Type.Any()),
|
|
123
|
+
childVerification: Type.Optional(verificationSchema),
|
|
124
|
+
resumedFrom: Type.Optional(Type.String()),
|
|
101
125
|
verified: Type.Union([Type.Boolean(), Type.Literal("not-run")]),
|
|
102
126
|
verification: Type.Optional(verificationSchema),
|
|
103
127
|
sessionFile: Type.Optional(Type.String()),
|
|
@@ -113,6 +137,7 @@ const outcomeSchema = Type.Object({
|
|
|
113
137
|
logCapReached: Type.Optional(Type.Boolean()),
|
|
114
138
|
settledInline: Type.Optional(Type.Boolean()),
|
|
115
139
|
worktree: Type.Optional(worktreeSchema),
|
|
140
|
+
integration: Type.Optional(integrationSchema),
|
|
116
141
|
error: Type.Optional(Type.String()),
|
|
117
142
|
});
|
|
118
143
|
|
|
@@ -167,10 +192,12 @@ export function containmentLine(verdict: string | undefined, leaked: number[] |
|
|
|
167
192
|
}
|
|
168
193
|
|
|
169
194
|
export default function delegateExtension(pi: ExtensionAPI) {
|
|
170
|
-
//
|
|
171
|
-
//
|
|
172
|
-
|
|
173
|
-
|
|
195
|
+
// A child may decompose only when its contract explicitly leaves depth. An
|
|
196
|
+
// unreadable spec fails closed, and old records retain the original depth 0.
|
|
197
|
+
const parentSpecPath = process.env[SPEC_ENV];
|
|
198
|
+
const parentSpecRecord = parentSpecPath ? readJson<RunSpec>(parentSpecPath) : undefined;
|
|
199
|
+
const parentSpec = parentSpecRecord?.kind === "ok" ? parentSpecRecord.value : undefined;
|
|
200
|
+
if (parentSpecPath && (!parentSpec || (parentSpec.depth ?? 0) >= (parentSpec.maxDepth ?? DEFAULT_MAX_DEPTH))) return;
|
|
174
201
|
|
|
175
202
|
// The registry belongs to the session directory. A child's cwd is a property
|
|
176
203
|
// of one run, not of the registry: binding it here would let a
|
|
@@ -181,6 +208,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
181
208
|
thinking: pi.getThinkingLevel(),
|
|
182
209
|
parentModel: modelLabel(ctx),
|
|
183
210
|
activeTools: pi.getActiveTools(),
|
|
211
|
+
depth: parentSpec?.depth,
|
|
212
|
+
maxDepth: parentSpec?.maxDepth,
|
|
213
|
+
deadline: parentSpec?.deadline,
|
|
214
|
+
maxCostUsd: parentSpec?.maxCostUsd,
|
|
184
215
|
deliver: (message) => {
|
|
185
216
|
pi.sendMessage(
|
|
186
217
|
{
|
|
@@ -224,7 +255,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
224
255
|
"When a goal is self-contained and needs multi-turn work in a clean context, call delegate_start. Keep one-shot questions inline.",
|
|
225
256
|
"After delegate_start returns a live handle, end the turn and let the delegate-completion message resume the conversation.",
|
|
226
257
|
"Pass a falsifiable doneWhen and limit context to facts the child cannot discover from the repository.",
|
|
227
|
-
"Pass verify with the exact command that proves the goal
|
|
258
|
+
"Pass verify with the exact command that proves the goal: it gates child completion, and the parent independently re-runs it with the same dropped-environment policy.",
|
|
259
|
+
"Pass resultSchema when a codemode orchestrator needs delegate_complete to return a validated structured result.",
|
|
260
|
+
"Nested delegation is off by default. Set maxDepth (0-3) explicitly; children cannot raise depth, cost, or deadline limits.",
|
|
228
261
|
"When the child needs a cheaper model or a different provider, pass model explicitly.",
|
|
229
262
|
"At most PI_DELEGATE_MAX_LIVE delegations run at once (default 4). A start over the limit is refused with the live runs listed.",
|
|
230
263
|
],
|
|
@@ -244,7 +277,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
244
277
|
verify: Type.Optional(
|
|
245
278
|
Type.String({
|
|
246
279
|
description:
|
|
247
|
-
"A shell command that
|
|
280
|
+
"A shell command that gates delegate_complete in the child and is independently re-run by the parent. Failure returns to the child for repair; a final parent failure is unverified.",
|
|
281
|
+
}),
|
|
282
|
+
),
|
|
283
|
+
resultSchema: Type.Optional(
|
|
284
|
+
Type.Record(Type.String(), Type.Any(), {
|
|
285
|
+
description: "JSON Schema that the structured `result` argument to delegate_complete must satisfy.",
|
|
248
286
|
}),
|
|
249
287
|
),
|
|
250
288
|
maxTurns: Type.Optional(
|
|
@@ -264,7 +302,15 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
264
302
|
maxCostUsd: Type.Optional(
|
|
265
303
|
Type.Number({
|
|
266
304
|
minimum: 0,
|
|
267
|
-
description:
|
|
305
|
+
description:
|
|
306
|
+
"Cumulative spend cap in US dollars for this run, from provider usage cost. It bounds this run, not the whole delegation tree: a child may not exceed its own parent's cap. 0 disables it. Defaults to PI_DELEGATE_MAX_COST_USD.",
|
|
307
|
+
}),
|
|
308
|
+
),
|
|
309
|
+
maxDepth: Type.Optional(
|
|
310
|
+
Type.Integer({
|
|
311
|
+
minimum: 0,
|
|
312
|
+
maximum: MAX_MAX_DEPTH,
|
|
313
|
+
description: "Maximum absolute delegation depth for this run tree. Default 0 disables nested delegation; maximum 3.",
|
|
268
314
|
}),
|
|
269
315
|
),
|
|
270
316
|
model: Type.Optional(
|
|
@@ -317,6 +363,23 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
317
363
|
if (params.worktree && !gitAvailable()) {
|
|
318
364
|
throw new Error("worktree: true needs git on PATH, and git did not run.");
|
|
319
365
|
}
|
|
366
|
+
if (params.resultSchema) {
|
|
367
|
+
const problem = auditResultSchema(params.resultSchema);
|
|
368
|
+
if (problem) throw new Error(problem);
|
|
369
|
+
}
|
|
370
|
+
const inheritedMaxDepth = parentSpec?.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
371
|
+
const requestedMaxDepth = params.maxDepth ?? inheritedMaxDepth;
|
|
372
|
+
if (!Number.isInteger(requestedMaxDepth) || requestedMaxDepth < 0 || requestedMaxDepth > MAX_MAX_DEPTH) {
|
|
373
|
+
throw new Error(`maxDepth must be an integer from 0 to ${MAX_MAX_DEPTH}.`);
|
|
374
|
+
}
|
|
375
|
+
const spendCap = params.maxCostUsd ?? (parentSpec ? (parentSpec.maxCostUsd ?? 0) : maxCostUsd());
|
|
376
|
+
// The attenuation rule lives in contract.ts, so this check and the one
|
|
377
|
+
// registry.start() runs cannot drift into two different answers.
|
|
378
|
+
const refusal = attenuationRefusal(
|
|
379
|
+
{ depth: parentSpec?.depth, maxDepth: parentSpec?.maxDepth, maxCostUsd: parentSpec?.maxCostUsd },
|
|
380
|
+
{ maxDepth: requestedMaxDepth, maxCostUsd: spendCap },
|
|
381
|
+
);
|
|
382
|
+
if (refusal) throw new Error(refusal);
|
|
320
383
|
const cwd = params.cwd ? resolve(ctx.cwd, params.cwd) : ctx.cwd;
|
|
321
384
|
const registry = registryFor(ctx);
|
|
322
385
|
const maxTurns = params.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
@@ -328,7 +391,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
328
391
|
verify: params.verify ? { command: params.verify } : undefined,
|
|
329
392
|
maxTurns,
|
|
330
393
|
timeoutMinutes,
|
|
331
|
-
maxCostUsd:
|
|
394
|
+
maxCostUsd: spendCap,
|
|
395
|
+
resultSchema: params.resultSchema,
|
|
396
|
+
maxDepth: requestedMaxDepth,
|
|
332
397
|
model: params.model,
|
|
333
398
|
tools: params.tools,
|
|
334
399
|
cwd,
|
|
@@ -580,7 +645,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
580
645
|
defaults: {
|
|
581
646
|
maxTurns: DEFAULT_MAX_TURNS,
|
|
582
647
|
timeoutMinutes: DEFAULT_TIMEOUT_MINUTES,
|
|
583
|
-
maxCostUsd: DEFAULT_MAX_COST_USD,
|
|
648
|
+
maxCostUsd: parentSpec?.maxCostUsd ?? DEFAULT_MAX_COST_USD,
|
|
649
|
+
maxDepth: parentSpec?.maxDepth ?? DEFAULT_MAX_DEPTH,
|
|
584
650
|
},
|
|
585
651
|
});
|
|
586
652
|
|
|
@@ -588,6 +654,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
588
654
|
const registry = registryFor(ctx);
|
|
589
655
|
refreshStatus(ctx, registry);
|
|
590
656
|
if (event.reason === "reload") return;
|
|
657
|
+
// A delegated child shares the record root with its parent, and its own
|
|
658
|
+
// session is a short-lived one. Adopting here claimed a workspace run the
|
|
659
|
+
// real session was supposed to report, and consumed its verdict inside a
|
|
660
|
+
// child that exits minutes later; pruning deleted records no child owns.
|
|
661
|
+
// Both belong to the session that owns the machine, not to a child.
|
|
662
|
+
if (parentSpec) return;
|
|
591
663
|
const adopted = await registry.adoptExisting();
|
|
592
664
|
if (adopted.length > 0) {
|
|
593
665
|
try {
|
package/src/registry.ts
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
import { closeSync, openSync, readdirSync, realpathSync, unlinkSync, writeSync } from "node:fs";
|
|
15
15
|
import { resolve } from "node:path";
|
|
16
16
|
import {
|
|
17
|
+
attenuationRefusal,
|
|
18
|
+
COMPLETION_MESSAGE_LIMIT,
|
|
17
19
|
DEFAULT_MAX_COST_USD,
|
|
18
20
|
DEFAULT_MAX_LIVE,
|
|
19
21
|
formatDuration,
|
|
@@ -75,6 +77,11 @@ export interface RegistryHost {
|
|
|
75
77
|
thinking: string;
|
|
76
78
|
parentModel?: string;
|
|
77
79
|
activeTools: readonly string[];
|
|
80
|
+
/** Ambient delegation-tree limits when this registry lives inside a child. */
|
|
81
|
+
depth?: number;
|
|
82
|
+
maxDepth?: number;
|
|
83
|
+
deadline?: number;
|
|
84
|
+
maxCostUsd?: number;
|
|
78
85
|
/** Inject a message that participates in the model's context. */
|
|
79
86
|
deliver: (message: { content: string; summary: string; runIds: string[] }) => void;
|
|
80
87
|
/** Redraw the footer for one registry. Called on settle, so no status goes stale. */
|
|
@@ -102,6 +109,9 @@ export interface StartOptions {
|
|
|
102
109
|
worktree?: boolean;
|
|
103
110
|
/** Cumulative spend cap in USD. Defaults to PI_DELEGATE_MAX_COST_USD. */
|
|
104
111
|
maxCostUsd?: number;
|
|
112
|
+
resultSchema?: Record<string, unknown>;
|
|
113
|
+
/** Maximum absolute delegation depth for the new run tree. */
|
|
114
|
+
maxDepth?: number;
|
|
105
115
|
/** TUI hook: called when live progress changes. */
|
|
106
116
|
onProgress?: (progress: RunProgress, status: RunStatus) => void;
|
|
107
117
|
}
|
|
@@ -263,6 +273,8 @@ export function holderAlive(holder: ClaimHolder): boolean {
|
|
|
263
273
|
|
|
264
274
|
export class RunRegistry {
|
|
265
275
|
private readonly handles = new Map<string, RunHandle>();
|
|
276
|
+
/** Starts admitted synchronously but not yet registered as handles. */
|
|
277
|
+
private reserved = 0;
|
|
266
278
|
private readonly claims = new Map<string, number>();
|
|
267
279
|
private readonly held = new Map<string, RunOutcome>();
|
|
268
280
|
private queue: RunOutcome[] = [];
|
|
@@ -313,10 +325,35 @@ export class RunRegistry {
|
|
|
313
325
|
* environment per call, so a host can raise it without a reload.
|
|
314
326
|
*/
|
|
315
327
|
async start(options: StartOptions): Promise<RunHandle> {
|
|
328
|
+
const inheritedMaxDepth = this.host.maxDepth ?? 0;
|
|
329
|
+
const requestedMaxDepth = options.maxDepth ?? inheritedMaxDepth;
|
|
330
|
+
const spendCap = options.maxCostUsd ?? (this.host.depth !== undefined ? (this.host.maxCostUsd ?? 0) : maxCostUsd());
|
|
331
|
+
const refusal = attenuationRefusal(this.host, { maxDepth: requestedMaxDepth, maxCostUsd: spendCap });
|
|
332
|
+
if (refusal) throw new Error(refusal);
|
|
333
|
+
options = { ...options, maxDepth: requestedMaxDepth, maxCostUsd: spendCap };
|
|
316
334
|
const live = maxLive();
|
|
317
|
-
if (this.runningCount >= live) {
|
|
335
|
+
if (this.runningCount + this.reserved >= live) {
|
|
318
336
|
throw new Error(this.admissionRefusal(live));
|
|
319
337
|
}
|
|
338
|
+
this.reserved += 1;
|
|
339
|
+
// The reservation covers the window between the gate and the handle
|
|
340
|
+
// appearing in `handles`. Once it appears, `runningCount` counts the run:
|
|
341
|
+
// holding both would charge one run two slots for its whole inline window
|
|
342
|
+
// and refuse a start the limit still allows.
|
|
343
|
+
let reserved = true;
|
|
344
|
+
const releaseReservation = () => {
|
|
345
|
+
if (!reserved) return;
|
|
346
|
+
reserved = false;
|
|
347
|
+
this.reserved -= 1;
|
|
348
|
+
};
|
|
349
|
+
try {
|
|
350
|
+
return await this.startReserved(options, releaseReservation);
|
|
351
|
+
} finally {
|
|
352
|
+
releaseReservation();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
private async startReserved(options: StartOptions, releaseReservation: () => void): Promise<RunHandle> {
|
|
320
357
|
const onProgress = options.onProgress;
|
|
321
358
|
const request: StartRequest = {
|
|
322
359
|
goal: options.goal,
|
|
@@ -325,6 +362,10 @@ export class RunRegistry {
|
|
|
325
362
|
maxTurns: options.maxTurns,
|
|
326
363
|
timeoutMinutes: options.timeoutMinutes,
|
|
327
364
|
maxCostUsd: options.maxCostUsd ?? maxCostUsd(),
|
|
365
|
+
resultSchema: options.resultSchema,
|
|
366
|
+
depth: (this.host.depth ?? -1) + 1,
|
|
367
|
+
maxDepth: options.maxDepth ?? 0,
|
|
368
|
+
parentDeadline: this.host.deadline,
|
|
328
369
|
verify: options.verify,
|
|
329
370
|
resumeFrom: options.resumeFrom,
|
|
330
371
|
worktree: options.worktree,
|
|
@@ -349,6 +390,8 @@ export class RunRegistry {
|
|
|
349
390
|
// bounded inline window is still open.
|
|
350
391
|
this.handles.set(handle.runId, handle);
|
|
351
392
|
this.claim([handle.runId]);
|
|
393
|
+
// Admitted is now counted by `runningCount`.
|
|
394
|
+
releaseReservation();
|
|
352
395
|
},
|
|
353
396
|
};
|
|
354
397
|
const handle = await startRun(request);
|
|
@@ -560,31 +603,44 @@ export class RunRegistry {
|
|
|
560
603
|
return;
|
|
561
604
|
}
|
|
562
605
|
for (const outcome of pending) this.delivered.add(outcome.runId);
|
|
563
|
-
const
|
|
564
|
-
|
|
565
|
-
const usage = formatUsage(outcome.usage);
|
|
566
|
-
const head = [
|
|
567
|
-
outcome.runId,
|
|
568
|
-
outcome.status,
|
|
569
|
-
`${outcome.turns} turns`,
|
|
570
|
-
formatDuration(outcome.durationMs),
|
|
571
|
-
usage,
|
|
572
|
-
].filter(Boolean).join(" · ");
|
|
573
|
-
lines.push(`- ${head}`);
|
|
574
|
-
lines.push(` goal: ${shortGoal(outcome.goal, 100)}`);
|
|
575
|
-
if (outcome.summary) lines.push(` result: ${shortGoal(outcome.summary, 400)}`);
|
|
576
|
-
if (outcome.evidence) lines.push(` evidence: ${shortGoal(outcome.evidence, 400)}`);
|
|
577
|
-
}
|
|
578
|
-
const content = [
|
|
606
|
+
const runIds = pending.map((outcome) => outcome.runId);
|
|
607
|
+
const detailed = [
|
|
579
608
|
"# Delegation settled",
|
|
580
609
|
"",
|
|
581
|
-
...
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
610
|
+
...pending.map((outcome) => `## ${outcome.runId}\n${formatOutcome(outcome)}`),
|
|
611
|
+
].join("\n\n");
|
|
612
|
+
let content = detailed;
|
|
613
|
+
if (detailed.length > COMPLETION_MESSAGE_LIMIT) {
|
|
614
|
+
const lines: string[] = [];
|
|
615
|
+
for (const outcome of pending) {
|
|
616
|
+
const usage = formatUsage(outcome.usage);
|
|
617
|
+
const head = [
|
|
618
|
+
outcome.runId,
|
|
619
|
+
outcome.status,
|
|
620
|
+
`${outcome.turns} turns`,
|
|
621
|
+
formatDuration(outcome.durationMs),
|
|
622
|
+
usage,
|
|
623
|
+
].filter(Boolean).join(" · ");
|
|
624
|
+
lines.push(`- ${head}`);
|
|
625
|
+
lines.push(` goal: ${shortGoal(outcome.goal, 100)}`);
|
|
626
|
+
// `summary` and `result` are different fields: a structured result
|
|
627
|
+
// exists when the run carried a schema, and labelling the child's
|
|
628
|
+
// prose as `result` made the two look interchangeable.
|
|
629
|
+
if (outcome.summary) lines.push(` summary: ${shortGoal(outcome.summary, 400)}`);
|
|
630
|
+
if (outcome.evidence) lines.push(` evidence: ${shortGoal(outcome.evidence, 400)}`);
|
|
631
|
+
if (outcome.needs) lines.push(` needs: ${shortGoal(outcome.needs, 400)}`);
|
|
632
|
+
}
|
|
633
|
+
content = [
|
|
634
|
+
"# Delegation settled",
|
|
635
|
+
"",
|
|
636
|
+
...lines,
|
|
637
|
+
"",
|
|
638
|
+
`Call delegate_await({ runIds: [${runIds.map((runId) => JSON.stringify(runId)).join(", ")}] }) for the full outcome, or read the run record under ${delegateRoot()}.`,
|
|
639
|
+
].join("\n");
|
|
640
|
+
}
|
|
585
641
|
const summary = pending.map((outcome) => `${outcome.runId}:${outcome.status}`).join(", ");
|
|
586
642
|
try {
|
|
587
|
-
this.host.deliver({ content, summary, runIds
|
|
643
|
+
this.host.deliver({ content, summary, runIds });
|
|
588
644
|
} catch {
|
|
589
645
|
// The session may be shutting down; the record stays on disk.
|
|
590
646
|
}
|